From bc849abe2c0e99ae67f208372aa30c6face0eebd Mon Sep 17 00:00:00 2001 From: Boldizsar Mezei Date: Tue, 3 Oct 2023 14:03:13 +0200 Subject: [PATCH] Iota stardust Fixes Fixes Fixes Fixes Fixes Fixes Fixes --- ...ions_tangle-online-unit-tests_emulator.yml | 108 ++-- .../workflows/functions_tangle-unit-tests.yml | 118 +++-- package.json | 2 +- packages/api/package.json | 6 +- packages/api/src/getTopMilestones.ts | 17 +- .../dbUpgrades/1.0.63/creditHighestPayment.ts | 58 --- packages/functions/package.json | 5 +- .../collection/collection-mint.control.ts | 5 +- .../src/controls/credit/credit.controller.ts | 2 +- .../functions/src/controls/nft/nft.deposit.ts | 2 +- .../src/controls/space/space.claim.control.ts | 2 +- .../token-minting/airdrop-minted-token.ts | 5 +- .../token-minting/import-minted-token.ts | 5 +- .../token-minting/token-mint.control.ts | 8 +- .../src/controls/token/token.airdrop.claim.ts | 2 +- .../src/controls/token/token.credit.ts | 3 +- .../src/controls/token/token.order.ts | 2 +- packages/functions/src/index.ts | 4 +- .../src/services/payment/address-service.ts | 2 +- .../services/payment/award/award-service.ts | 4 +- .../payment/nft/nft-deposit-service.ts | 5 +- .../src/services/payment/nft/nft-service.ts | 18 +- .../services/payment/nft/nft-stake-service.ts | 7 +- .../services/payment/payment-processing.ts | 2 +- .../services/payment/space/space-service.ts | 11 +- .../src/services/payment/stake-service.ts | 2 +- .../tangle-service/TangleRequestService.ts | 8 +- .../address/address-validation.service.ts | 6 +- .../award/award.create.service.ts | 5 +- .../award/award.fund.service.ts | 2 +- .../metadataNft/mint-metadata-nft.service.ts | 28 +- .../tangle-service/nft/nft-bid.service.ts | 17 +- .../tangle-service/nft/nft-deposit.service.ts | 2 +- .../nft/nft-purchase.service.ts | 16 +- .../proposal/voting/token.voting.ts | 5 +- .../space/SpaceCreateService.ts | 2 +- .../tangle-service/token/stake.service.ts | 5 +- .../token/token-claim.service.ts | 5 +- .../token/token-trade.service.ts | 5 +- .../token/import-minted-token.service.ts | 10 +- .../services/payment/transaction-service.ts | 42 +- .../src/services/payment/voting-service.ts | 2 +- .../wallet/{smr-wallets => }/AliasWallet.ts | 28 +- .../src/services/wallet/IotaWalletService.ts | 476 ++++++++++++------ .../src/services/wallet/NativeTokenWallet.ts | 12 +- .../src/services/wallet/NftWallet.ts | 49 +- .../src/services/wallet/SmrWalletService.ts | 416 +-------------- .../src/services/wallet/wallet.service.ts | 89 ++++ .../functions/src/services/wallet/wallet.ts | 111 ++-- .../MilestoneTransactionAdapter.ts | 99 ++++ .../SmrMilestoneTransactionAdapter.ts | 109 ---- .../milestone-transactions-triggers/common.ts | 47 +- .../iota-milestone-transaction.trigger.ts | 56 --- ...er.ts => milestone-transaction.trigger.ts} | 41 +- .../token-trading/match-base-token.ts | 5 +- .../token-trading/match-minted-token.ts | 5 +- .../functions/src/triggers/token.trigger.ts | 2 +- .../transaction-trigger/airdrop.claim.ts | 10 +- .../transaction-trigger/matadatNft-minting.ts | 4 +- .../transaction-trigger/proposal.vote.ts | 4 +- .../transaction.trigger.ts | 48 +- .../transaction-trigger/wallet-params.ts | 14 +- .../functions/src/utils/basic-output.utils.ts | 4 +- .../src/utils/bech32-address.helper.ts | 2 +- packages/functions/src/utils/block.utils.ts | 8 +- .../utils/token-minting-utils/alias.utils.ts | 2 +- packages/functions/src/utils/wallet.utils.ts | 65 +-- .../functions/test-tangle/address.spec.ts | 178 ++----- .../award-tangle/award-tangle_1.spec.ts | 10 +- .../award-tangle/award-tangle_2.spec.ts | 83 +-- .../award-tangle/award-tangle_3.spec.ts | 124 ++--- .../award-tangle/award-tangle_4.spec.ts | 126 +++-- .../award-tangle/award-tangle_5.spec.ts | 12 +- .../award-tangle/award-tangle_6.spec.ts | 10 +- .../award-tangle/award-tangle_7.spec.ts | 118 +++++ .../test-tangle/award/award_1.spec.ts | 221 ++++---- .../test-tangle/award/award_10.spec.ts | 8 +- .../test-tangle/award/award_2.spec.ts | 8 +- .../test-tangle/award/award_3.spec.ts | 2 +- .../test-tangle/award/award_4.spec.ts | 10 +- .../test-tangle/award/award_5.spec.ts | 8 +- .../test-tangle/award/award_6.spec.ts | 10 +- .../test-tangle/award/award_7.spec.ts | 8 +- .../test-tangle/award/award_9.spec.ts | 8 +- .../functions/test-tangle/award/common.ts | 4 +- .../test-tangle/base-token-trading/Helper.ts | 8 +- .../base-token-trading_12.spec.ts | 2 +- .../test-tangle/collection-minting/Helper.ts | 19 +- .../collection-minting_4.spec.ts | 2 +- packages/functions/test-tangle/common.ts | 20 +- .../db-roll/credit.highest.spec.ts | 80 --- packages/functions/test-tangle/faucet.ts | 78 ++- .../test-tangle/metadata-nft/Helper.ts | 31 +- .../metadata-nft/mint-metadata-nft_1.spec.ts | 17 +- .../metadata-nft/mint-metadata-nft_2.spec.ts | 168 +++---- .../metadata-nft/mint-metadata-nft_3.spec.ts | 204 ++++---- .../metadata-nft/mint-metadata-nft_4.spec.ts | 159 +++--- .../metadata-nft/mint-metadata-nft_5.spec.ts | 174 ++++--- .../metadata-nft/mint-metadata-nft_6.spec.ts | 138 +++-- .../metadata-nft/mint-metadata-nft_7.spec.ts | 127 +++-- .../test-tangle/minted-nft-trading/Helper.ts | 24 +- .../minted-nft-trading_1.spec.ts | 9 +- .../minted-nft-trading_10.spec.ts | 42 +- .../minted-nft-trading_11.only.spec.ts | 41 +- .../minted-nft-trading_1_b.spec.ts | 124 +++++ .../minted-nft-trading_2.spec.ts | 9 +- .../minted-nft-trading_3.spec.ts | 10 +- .../minted-nft-trading_4.spec.ts | 50 +- .../minted-nft-trading_5.spec.ts | 33 +- .../minted-nft-trading_6.spec.ts | 70 ++- .../minted-nft-trading_7.spec.ts | 161 +++--- .../minted-nft-trading_8.spec.ts | 67 ++- .../minted-token-airdrop/Helper.ts | 8 +- .../minted-token-airdrop_4.spec.ts | 2 +- .../test-tangle/minted-token-trade/Helper.ts | 10 +- .../minted-token-trade_18.spec.ts | 2 +- .../functions/test-tangle/nft-bid/Helper.ts | 15 +- .../test-tangle/nft-bid/nft-bid.otr_1.spec.ts | 2 +- .../test-tangle/nft-bid/nft-bid.otr_2.spec.ts | 2 +- .../test-tangle/nft-bid/nft-bid.otr_3.spec.ts | 47 +- .../test-tangle/nft-bid/nft-bid.otr_4.spec.ts | 2 +- .../test-tangle/nft-set-for-sale/Helper.ts | 15 +- .../nft-set-for-sale_1.spec.ts | 2 +- .../nft-set-for-sale_2.spec.ts | 2 +- .../nft-set-for-sale_3.spec.ts | 2 +- .../test-tangle/nft-staking/Helper.ts | 12 +- .../test-tangle/proposal-tangle/Helper.ts | 10 +- .../test-tangle/space-tangle/Helper.ts | 10 +- .../functions/test-tangle/staking/Helper.ts | 8 +- .../test-tangle/staking/staking_5.spec.ts | 2 +- .../tangleRequest/simple.token.trade.spec.ts | 8 +- .../tangleRequest/tangle-request.spec.ts | 10 +- .../test-tangle/token-import/Helper.ts | 8 +- .../test-tangle/token.based.voting/Helper.ts | 8 +- .../test-tangle/token.claim.minted.spec.ts | 8 +- .../test-tangle/token.mint/Helper.ts | 14 +- .../token.mint/token.mint_3.spec.ts | 10 +- .../trade-base-token-order.spec.ts | 2 +- .../functions/test-tangle/tran.match.spec.ts | 10 +- .../transaction-trigger_1.spec.ts | 2 +- .../transaction-trigger_10.spec.ts | 2 +- .../transaction-trigger_11.spec.ts | 10 +- .../transaction-trigger_12.spec.ts | 55 +- .../transaction-trigger_13.spec.ts | 10 +- .../transaction-trigger_2.spec.ts | 5 +- .../transaction-trigger_3.spec.ts | 5 +- .../transaction-trigger_4.spec.ts | 5 +- .../transaction-trigger_5.spec.ts | 2 +- .../transaction-trigger_6.spec.ts | 2 +- .../transaction-trigger_7.spec.ts | 2 +- .../transaction-trigger_8.spec.ts | 2 +- .../transaction-trigger_9.spec.ts | 2 +- .../withdraw-deposit-nft/Helper.ts | 12 +- .../deposit-withraw-nft_12_a.spec.ts | 7 +- .../deposit-withraw-nft_12_b.spec.ts | 7 +- .../deposit-withraw-nft_13.spec.ts | 7 +- .../deposit-withraw-nft_14.spec.ts | 3 +- .../deposit-withraw-nft_1_a.spec.ts | 3 +- .../deposit-withraw-nft_1_b.spec.ts | 3 +- .../deposit-withraw-nft_1_c.spec.ts | 3 +- packages/functions/test/auth.spec.ts | 41 +- .../functions/test/controls/address.spec.ts | 27 +- packages/functions/test/controls/common.ts | 77 +-- .../test/controls/nft-bidding.spec.ts | 10 +- .../functions/test/controls/order.spec.ts | 35 +- .../token-distribution-auto-trigger.spec.ts | 11 +- .../test/controls/token-distribution.spec.ts | 15 +- .../test/controls/token-trade.buy.spec.ts | 11 +- .../test/controls/token-trade.trigger.spec.ts | 6 +- .../test/controls/token.order.spec.ts | 66 +-- .../token/token.airdrop.claim.spec.ts | 31 +- .../token/token.cancel.pub.sale.spec.ts | 13 +- .../token/token.order.and.claim.air.spec.ts | 13 +- packages/functions/test/milestone.sync.ts | 34 +- packages/functions/test/set-up.ts | 7 +- .../src/api/post/AwardCreateRequest.ts | 2 +- .../src/api/post/CollectionMintRequest.ts | 2 +- .../src/api/post/NftDepositRequest.ts | 2 +- .../src/api/post/NftStakeRequest.ts | 2 +- .../src/api/post/TokenImportRequest.ts | 2 +- .../src/api/post/TokenMintRequest.ts | 2 +- .../api/tangle/AwardCreateTangleRequest.ts | 2 +- packages/interfaces/src/config.ts | 4 +- packages/interfaces/src/models/milestone.ts | 3 +- packages/interfaces/src/utils.ts | 14 + 185 files changed, 2649 insertions(+), 3249 deletions(-) delete mode 100644 packages/database/scripts/dbUpgrades/1.0.63/creditHighestPayment.ts rename packages/functions/src/services/wallet/{smr-wallets => }/AliasWallet.ts (84%) create mode 100644 packages/functions/src/services/wallet/wallet.service.ts create mode 100644 packages/functions/src/triggers/milestone-transactions-triggers/MilestoneTransactionAdapter.ts delete mode 100644 packages/functions/src/triggers/milestone-transactions-triggers/SmrMilestoneTransactionAdapter.ts delete mode 100644 packages/functions/src/triggers/milestone-transactions-triggers/iota-milestone-transaction.trigger.ts rename packages/functions/src/triggers/milestone-transactions-triggers/{smr-milestone-transaction.trigger.ts => milestone-transaction.trigger.ts} (63%) create mode 100644 packages/functions/test-tangle/award-tangle/award-tangle_7.spec.ts delete mode 100644 packages/functions/test-tangle/db-roll/credit.highest.spec.ts create mode 100644 packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts diff --git a/.github/workflows/functions_tangle-online-unit-tests_emulator.yml b/.github/workflows/functions_tangle-online-unit-tests_emulator.yml index 894b50332a..caf6b8ed83 100644 --- a/.github/workflows/functions_tangle-online-unit-tests_emulator.yml +++ b/.github/workflows/functions_tangle-online-unit-tests_emulator.yml @@ -1460,9 +1460,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1497,9 +1497,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1534,9 +1534,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1571,9 +1571,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/db-roll/credit.highest.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_9.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_8.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_9.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1608,9 +1608,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_8.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_7.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_6.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_5.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_6.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1645,9 +1645,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_5.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_4.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_3.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_2.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_3.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1682,9 +1682,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_2.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_12.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_11.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_10.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_11.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1719,9 +1719,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_10.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_1.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_7.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_6.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1756,9 +1756,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_6.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_5.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_4.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_3.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1793,9 +1793,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_3.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_2.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_12.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_10.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_12.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1830,9 +1830,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_10.spec.ts && npm run test-tangle-online:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_1.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_6.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_5.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1867,9 +1867,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_4.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_3.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_2.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_6.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_5.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1904,9 +1904,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_1.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_9.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_8.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_3.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_2.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_1.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1941,9 +1941,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_7.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_6.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_5.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_9.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_8.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1978,9 +1978,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_4.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_3.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_2.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_6.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_5.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2015,8 +2015,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_10.spec.ts && - npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_1.spec.ts + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_3.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_2.spec.ts && + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_10.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2025,3 +2026,38 @@ jobs: name: firestore-data-test-tangle-online-chunk_53 path: ./packages/functions/firestore-data/ retention-days: 1 + chunk_54: + needs: npm-install + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 16.x + - uses: actions/cache@v3 + with: + path: | + node_modules + packages/functions/node_modules + packages/interfaces/node_modules + key: ${{ runner.os }}-modules-${{ hashFiles('**/package.json') }} + - name: Init + run: | + npm run build:functions + npm install -g firebase-tools + - name: Test + working-directory: packages/functions + run: | + export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" + npm run milestone-sync & + firebase emulators:exec " + npm run test-tangle-online:ci -- --findRelatedTests test-tangle/award/award_1.spec.ts + " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data + - name: Archive firestore data + uses: actions/upload-artifact@v3 + if: ${{ failure() }} + with: + name: firestore-data-test-tangle-online-chunk_54 + path: ./packages/functions/firestore-data/ + retention-days: 1 diff --git a/.github/workflows/functions_tangle-unit-tests.yml b/.github/workflows/functions_tangle-unit-tests.yml index fc403cbc0e..80ff91d66c 100644 --- a/.github/workflows/functions_tangle-unit-tests.yml +++ b/.github/workflows/functions_tangle-unit-tests.yml @@ -1458,9 +1458,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1495,9 +1495,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1532,9 +1532,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1569,9 +1569,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/db-roll/credit.highest.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_9.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_8.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_9.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1606,9 +1606,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_8.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_7.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_6.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_5.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_6.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1643,9 +1643,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_5.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_4.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_3.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_2.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_3.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1680,9 +1680,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_2.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_12.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_11.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_10.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_11.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1717,9 +1717,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_10.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/collection-minting/collection-minting_1.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_7.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_6.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1754,9 +1754,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_6.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_5.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_4.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_3.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1791,9 +1791,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_3.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_2.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_12.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_10.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_12.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1828,9 +1828,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_10.spec.ts && npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_1.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_6.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_5.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1865,9 +1865,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_4.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_3.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_2.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_6.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_5.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1902,9 +1902,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_1.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_9.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_8.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_3.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_2.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award-tangle/award-tangle_1.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1939,9 +1939,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_7.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_6.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_5.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_9.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_8.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_7.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -1976,9 +1976,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_4.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_3.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_2.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_6.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_5.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_4.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2013,8 +2013,9 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_10.spec.ts && - npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_1.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_3.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_2.spec.ts && + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_10.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2049,7 +2050,7 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-token-trade/minted-token-trade_15.only.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/award/award_1.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2084,7 +2085,7 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-token-trade/minted-token-trade_15.only.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2119,7 +2120,7 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_9.only.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2154,7 +2155,7 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_8.only.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_9.only.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2189,7 +2190,7 @@ jobs: export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" npm run milestone-sync & firebase emulators:exec " - npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_11.only.spec.ts + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_8.only.spec.ts " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data - name: Archive firestore data uses: actions/upload-artifact@v3 @@ -2198,3 +2199,38 @@ jobs: name: firestore-data-test-tangle-chunk_58 path: ./packages/functions/firestore-data/ retention-days: 1 + chunk_59: + needs: npm-install + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 16.x + - uses: actions/cache@v3 + with: + path: | + node_modules + packages/functions/node_modules + packages/interfaces/node_modules + key: ${{ runner.os }}-modules-${{ hashFiles('**/package.json') }} + - name: Init + run: | + npm run build:functions + npm install -g firebase-tools + - name: Test + working-directory: packages/functions + run: | + export GOOGLE_APPLICATION_CREDENTIALS="./test-service-account-key.json" + npm run milestone-sync & + firebase emulators:exec " + npm run test-tangle:ci -- --findRelatedTests test-tangle/base-token-trading/base-token-trading_11.only.spec.ts + " --project dev --only functions,firestore,storage,ui,auth --export-on-exit=./firestore-data + - name: Archive firestore data + uses: actions/upload-artifact@v3 + if: ${{ failure() }} + with: + name: firestore-data-test-tangle-chunk_59 + path: ./packages/functions/firestore-data/ + retention-days: 1 diff --git a/package.json b/package.json index 6733f1c154..d467b5efb7 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,6 @@ "joi-to-types": "ts-node ./scripts/joi-generator-post.ts && ts-node ./scripts/joi-generator-tangle.ts && npm run prettier" }, "devDependencies": { - "joi-to-typescript": "^4.4.1" + "joi-to-typescript": "4.7.0" } } diff --git a/packages/api/package.json b/packages/api/package.json index daba06eb73..00f01ed840 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -25,12 +25,12 @@ "cors": "^2.8.5", "dayjs": "^1.11.9", "express": "^4.18.2", - "joi": "^17.10.1", + "joi": "17.10.2", "lodash": "^4.17.21", "rxjs": "^7.8.1", "ws": "^8.13.0", - "@iota/iota.js-next": "npm:@iota/iota.js@2.0.0-rc.4", - "@iota/util.js-next": "npm:@iota/util.js@2.0.0-rc.2" + "@iota/iota.js": "npm:@iota/iota.js@2.0.0-rc.4", + "@iota/util.js": "npm:@iota/util.js@2.0.0-rc.2" }, "devDependencies": { "@types/express": "^4.17.17", diff --git a/packages/api/src/getTopMilestones.ts b/packages/api/src/getTopMilestones.ts index 400ee7ca19..78c9ddd782 100644 --- a/packages/api/src/getTopMilestones.ts +++ b/packages/api/src/getTopMilestones.ts @@ -1,5 +1,5 @@ import { build5Db } from '@build-5/database'; -import { COL, Network } from '@build-5/interfaces'; +import { Network, getMilestoneCol } from '@build-5/interfaces'; import { combineLatest, map } from 'rxjs'; import { queryToObservable } from './common'; @@ -11,17 +11,4 @@ export const getTopMilestones = async (_: string) => { }; const networkToQuery = (network: Network) => - build5Db().collection(getMilestoneColForNetwrok(network)).orderBy('createdOn', 'desc').limit(1); - -const getMilestoneColForNetwrok = (network: Network) => { - switch (network) { - case Network.IOTA: - return COL.MILESTONE; - case Network.ATOI: - return COL.MILESTONE_ATOI; - case Network.SMR: - return COL.MILESTONE_SMR; - case Network.RMS: - return COL.MILESTONE_RMS; - } -}; + build5Db().collection(getMilestoneCol(network)).orderBy('createdOn', 'desc').limit(1); diff --git a/packages/database/scripts/dbUpgrades/1.0.63/creditHighestPayment.ts b/packages/database/scripts/dbUpgrades/1.0.63/creditHighestPayment.ts deleted file mode 100644 index 8efe8e31c1..0000000000 --- a/packages/database/scripts/dbUpgrades/1.0.63/creditHighestPayment.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ - -import { COL, Transaction, TransactionPayloadType, TransactionType } from '@build-5/interfaces'; -import dayjs from 'dayjs'; -import { FirebaseApp } from '../../../src/app/app'; -import { Firestore } from '../../../src/firestore/firestore'; - -const PROD_PAYMENT = '0xe50e40db6c583e89733fd1b084e30e1d7b878755' - -export const creditHighestPayment = async ( - app: FirebaseApp, - paymentUid = PROD_PAYMENT, -) => { - const db = new Firestore(app); - - const batch = db.batch(); - - const paymentDocRef = db.doc(`${COL.TRANSACTION}/${paymentUid}`); - const payment = await paymentDocRef.get(); - - if (!payment) { - console.log('Payment does not exist'); - return false; - } - - batch.update(paymentDocRef, { 'payload.invalidPayment': true }); - - // was generated randomly elswhere so getRandomEthAddress is not needed here, - const creditUid = '0x3c368f6d447e5b703fd5b2d3a9d276809d03affe'; - const credit = { - type: TransactionType.CREDIT, - uid: creditUid, - space: payment.space, - member: payment.member, - createdOn: dayjs().toDate(), - network: payment.network, - payload: { - type: TransactionPayloadType.DATA_NO_LONGER_VALID, - amount: payment.payload.amount, - sourceAddress: payment.payload.targetAddress, - targetAddress: payment.payload.sourceAddress, - sourceTransaction: [payment.uid], - nft: payment.payload.nft || null, - reconciled: true, - void: false, - collection: payment.payload.collection || null, - invalidPayment: true, - }, - ignoreWallet: false, - }; - const creditDocRef = db.doc(`${COL.TRANSACTION}/${credit.uid}`); - batch.create(creditDocRef, credit); - - await batch.commit(); - return true; -}; - -export const roll = creditHighestPayment; diff --git a/packages/functions/package.json b/packages/functions/package.json index 3063b3928a..abc0d662bb 100644 --- a/packages/functions/package.json +++ b/packages/functions/package.json @@ -79,11 +79,8 @@ "@build-5/interfaces": "*", "@ffmpeg-installer/ffmpeg": "1.1.0", "@ffprobe-installer/ffprobe": "2.0.0", - "@iota/crypto.js": "1.8.6", "@iota/crypto.js-next": "npm:@iota/crypto.js@2.0.0-rc.2", - "@iota/iota.js": "1.8.6", "@iota/iota.js-next": "npm:@iota/iota.js@2.0.0-rc.4", - "@iota/util.js": "1.8.6", "@iota/util.js-next": "npm:@iota/util.js@2.0.0-rc.2", "@metamask/eth-sig-util": "5.0.2", "algoliasearch": "4.16.0", @@ -100,7 +97,7 @@ "glob": "9.3.4", "interfaces": "^0.0.3", "is-ipfs": "8.0.1", - "joi": "17.10.1", + "joi": "17.10.2", "js-big-decimal": "1.4.1", "jsonwebtoken": "9.0.0", "lodash": "4.17.21", diff --git a/packages/functions/src/controls/collection/collection-mint.control.ts b/packages/functions/src/controls/collection/collection-mint.control.ts index 7c785262eb..6497b43984 100644 --- a/packages/functions/src/controls/collection/collection-mint.control.ts +++ b/packages/functions/src/controls/collection/collection-mint.control.ts @@ -20,8 +20,7 @@ import { AddressTypes, ED25519_ADDRESS_TYPE, INodeInfo } from '@iota/iota.js-nex import dayjs from 'dayjs'; import { last } from 'lodash'; import { build5Db, getSnapshot } from '../../firebase/firestore/build5Db'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../services/wallet/wallet.service'; import { assertMemberHasValidAddress, assertSpaceHasValidAddress } from '../../utils/address.utils'; import { EMPTY_NFT_ID, @@ -82,7 +81,7 @@ export const mintCollectionOrderControl = async (owner: string, params: Collecti .get(); assertSpaceHasValidAddress(royaltySpace, network); - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const targetAddress = await wallet.getNewIotaAddressDetails(); const { storageDeposit: nftsStorageDeposit, nftsToMint } = await getNftsTotalStorageDeposit( diff --git a/packages/functions/src/controls/credit/credit.controller.ts b/packages/functions/src/controls/credit/credit.controller.ts index ce0cc4a6f8..00cf767e8d 100644 --- a/packages/functions/src/controls/credit/credit.controller.ts +++ b/packages/functions/src/controls/credit/credit.controller.ts @@ -12,7 +12,7 @@ import { } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; import { getRandomEthAddress } from '../../utils/wallet.utils'; diff --git a/packages/functions/src/controls/nft/nft.deposit.ts b/packages/functions/src/controls/nft/nft.deposit.ts index 44fa198906..7fd2fa5ade 100644 --- a/packages/functions/src/controls/nft/nft.deposit.ts +++ b/packages/functions/src/controls/nft/nft.deposit.ts @@ -10,7 +10,7 @@ import { } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { getRandomEthAddress } from '../../utils/wallet.utils'; diff --git a/packages/functions/src/controls/space/space.claim.control.ts b/packages/functions/src/controls/space/space.claim.control.ts index 70db37f519..23f40c527c 100644 --- a/packages/functions/src/controls/space/space.claim.control.ts +++ b/packages/functions/src/controls/space/space.claim.control.ts @@ -12,7 +12,7 @@ import { } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { generateRandomAmount } from '../../utils/common.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; diff --git a/packages/functions/src/controls/token-minting/airdrop-minted-token.ts b/packages/functions/src/controls/token-minting/airdrop-minted-token.ts index 16cc8977dc..fdfd2b9482 100644 --- a/packages/functions/src/controls/token-minting/airdrop-minted-token.ts +++ b/packages/functions/src/controls/token-minting/airdrop-minted-token.ts @@ -19,8 +19,7 @@ import dayjs from 'dayjs'; import { chunk } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { CreateAirdropsRequest } from '../../runtime/firebase/token/base/TokenAirdropRequestSchema'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { packBasicOutput } from '../../utils/basic-output.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; @@ -44,7 +43,7 @@ export const airdropMintedTokenControl = async (owner: string, params: CreateAir const drops = params.drops; const totalDropped = drops.reduce((acc, act) => acc + act.count, 0); - const wallet = (await WalletService.newWallet(token.mintingData?.network)) as SmrWallet; + const wallet = await WalletService.newWallet(token.mintingData?.network); const targetAddress = await wallet.getNewIotaAddressDetails(); const nativeToken = { amount: HexHelper.fromBigInt256(bigInt(totalDropped)), diff --git a/packages/functions/src/controls/token-minting/import-minted-token.ts b/packages/functions/src/controls/token-minting/import-minted-token.ts index f6b1870df0..669a862ae0 100644 --- a/packages/functions/src/controls/token-minting/import-minted-token.ts +++ b/packages/functions/src/controls/token-minting/import-minted-token.ts @@ -13,8 +13,7 @@ import { IndexerPluginClient } from '@iota/iota.js-next'; import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { generateRandomAmount } from '../../utils/common.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; @@ -31,7 +30,7 @@ export const importMintedTokenControl = async (owner: string, params: ImportMint throw invalidArgument(WenError.token_already_exists_for_space); } - const wallet = (await WalletService.newWallet(params.network as Network)) as SmrWallet; + const wallet = await WalletService.newWallet(params.network as Network); const indexer = new IndexerPluginClient(wallet.client); const foundryResponse = await indexer.foundry(params.tokenId); diff --git a/packages/functions/src/controls/token-minting/token-mint.control.ts b/packages/functions/src/controls/token-minting/token-mint.control.ts index e0b4aab095..c83dfb47f9 100644 --- a/packages/functions/src/controls/token-minting/token-mint.control.ts +++ b/packages/functions/src/controls/token-minting/token-mint.control.ts @@ -15,8 +15,8 @@ import { import { TransactionHelper } from '@iota/iota.js-next'; import dayjs from 'dayjs'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../services/wallet/wallet'; +import { Wallet } from '../../services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../services/wallet/wallet.service'; import { assertMemberHasValidAddress } from '../../utils/address.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; @@ -52,7 +52,7 @@ export const mintTokenControl = (owner: string, params: TokenMintRequest) => const member = await build5Db().doc(`${COL.MEMBER}/${owner}`).get(); assertMemberHasValidAddress(member, params.network as Network); - const wallet = (await WalletService.newWallet(params.network as Network)) as SmrWallet; + const wallet = await WalletService.newWallet(params.network as Network); const targetAddress = await wallet.getNewIotaAddressDetails(); const totalDistributed = @@ -91,7 +91,7 @@ const getStorageDepositForMinting = async ( token: Token, totalDistributed: number, address: AddressDetails, - wallet: SmrWallet, + wallet: Wallet, ) => { const aliasOutput = createAliasOutput(address, wallet.info); const metadata = await tokenToFoundryMetadata(token); diff --git a/packages/functions/src/controls/token/token.airdrop.claim.ts b/packages/functions/src/controls/token/token.airdrop.claim.ts index a0347c0841..eb53a53dcb 100644 --- a/packages/functions/src/controls/token/token.airdrop.claim.ts +++ b/packages/functions/src/controls/token/token.airdrop.claim.ts @@ -14,7 +14,7 @@ import { import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { generateRandomAmount } from '../../utils/common.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; import { invalidArgument } from '../../utils/error.utils'; diff --git a/packages/functions/src/controls/token/token.credit.ts b/packages/functions/src/controls/token/token.credit.ts index 775d01f269..da5a1380ba 100644 --- a/packages/functions/src/controls/token/token.credit.ts +++ b/packages/functions/src/controls/token/token.credit.ts @@ -2,8 +2,8 @@ import { COL, CreditTokenRequest, DEFAULT_NETWORK, - Member, MIN_IOTA_AMOUNT, + Member, SUB_COL, Token, TokenDistribution, @@ -34,7 +34,6 @@ export const creditTokenControl = async ( await build5Db().runTransaction(async (transaction) => { const tokenDocRef = build5Db().doc(`${COL.TOKEN}/${params.token}`); const distributionDocRef = tokenDocRef.collection(SUB_COL.DISTRIBUTION).doc(owner); - const distribution = await transaction.get(distributionDocRef); if (!distribution || (distribution.totalDeposit || 0) < params.amount) { throw invalidArgument(WenError.not_enough_funds); diff --git a/packages/functions/src/controls/token/token.order.ts b/packages/functions/src/controls/token/token.order.ts index a169567dba..6ff818881b 100644 --- a/packages/functions/src/controls/token/token.order.ts +++ b/packages/functions/src/controls/token/token.order.ts @@ -16,7 +16,7 @@ import { import dayjs from 'dayjs'; import { build5Db } from '../../firebase/firestore/build5Db'; import { assertHasAccess } from '../../services/validators/access'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { assertMemberHasValidAddress, getAddress } from '../../utils/address.utils'; import { isProdEnv } from '../../utils/config.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; diff --git a/packages/functions/src/index.ts b/packages/functions/src/index.ts index 2ec4022a12..3c2e18bd18 100644 --- a/packages/functions/src/index.ts +++ b/packages/functions/src/index.ts @@ -78,11 +78,9 @@ import { collectionWrite } from './triggers/collection.trigger'; import { atoiMilestoneTransactionWrite, iotaMilestoneTransactionWrite, -} from './triggers/milestone-transactions-triggers/iota-milestone-transaction.trigger'; -import { rmsMilestoneTransactionWrite, smrMilestoneTransactionWrite, -} from './triggers/milestone-transactions-triggers/smr-milestone-transaction.trigger'; +} from './triggers/milestone-transactions-triggers/milestone-transaction.trigger'; import { mnemonicWrite } from './triggers/mnemonic.trigger'; import { nftWrite } from './triggers/nft.trigger'; import { onProposalUpdated } from './triggers/proposal.trigger'; diff --git a/packages/functions/src/services/payment/address-service.ts b/packages/functions/src/services/payment/address-service.ts index ee693c1eed..96ed8e9dc4 100644 --- a/packages/functions/src/services/payment/address-service.ts +++ b/packages/functions/src/services/payment/address-service.ts @@ -68,7 +68,7 @@ export class AddressService { const guardians = await spaceDocRef.collection(SUB_COL.GUARDIANS).get(); const proposal = createUpdateSpaceValidatedAddressProposal( order, - match.from.address, + match.from, owner, space!, guardians.length, diff --git a/packages/functions/src/services/payment/award/award-service.ts b/packages/functions/src/services/payment/award/award-service.ts index 28e3ce4b7d..a5253bdef6 100644 --- a/packages/functions/src/services/payment/award/award-service.ts +++ b/packages/functions/src/services/payment/award/award-service.ts @@ -28,7 +28,7 @@ import { createNftOutput } from '../../../utils/collection-minting-utils/nft.uti import { getContentType } from '../../../utils/storage.utils'; import { createAliasOutput } from '../../../utils/token-minting-utils/alias.utils'; import { getRandomEthAddress } from '../../../utils/wallet.utils'; -import { SmrWallet } from '../../wallet/SmrWalletService'; +import { Wallet } from '../../wallet/wallet'; import { TransactionMatch, TransactionService } from '../transaction-service'; export class AwardService { @@ -177,7 +177,7 @@ export const awardToIpfsMetadata = (award: Award) => { return metadata; }; -export const getAwardgStorageDeposits = async (award: Award, token: Token, wallet: SmrWallet) => { +export const getAwardgStorageDeposits = async (award: Award, token: Token, wallet: Wallet) => { const address = await wallet.getNewIotaAddressDetails(); const aliasOutput = createAliasOutput(address, wallet.info); diff --git a/packages/functions/src/services/payment/nft/nft-deposit-service.ts b/packages/functions/src/services/payment/nft/nft-deposit-service.ts index f15c0b5b77..e9279844c6 100644 --- a/packages/functions/src/services/payment/nft/nft-deposit-service.ts +++ b/packages/functions/src/services/payment/nft/nft-deposit-service.ts @@ -38,8 +38,7 @@ import { } from '../../../utils/nft.output.utils'; import { getRandomEthAddress } from '../../../utils/wallet.utils'; import { NftWallet } from '../../wallet/NftWallet'; -import { SmrWallet } from '../../wallet/SmrWalletService'; -import { WalletService } from '../../wallet/wallet'; +import { WalletService } from '../../wallet/wallet.service'; import { TransactionMatch, TransactionService } from '../transaction-service'; export class NftDepositService { constructor(readonly transactionService: TransactionService) {} @@ -277,7 +276,7 @@ export class NftDepositService { throw WenError.nft_not_irc27_compilant; } - const wallet = (await WalletService.newWallet(order.network)) as SmrWallet; + const wallet = await WalletService.newWallet(order.network); const nftWallet = new NftWallet(wallet); const collectionOutput = await nftWallet.getById(nftMetadata.collectionId); const collectionMetadata = getNftOutputMetadata(collectionOutput); diff --git a/packages/functions/src/services/payment/nft/nft-service.ts b/packages/functions/src/services/payment/nft/nft-service.ts index 1483f8254b..91ab751f28 100644 --- a/packages/functions/src/services/payment/nft/nft-service.ts +++ b/packages/functions/src/services/payment/nft/nft-service.ts @@ -6,6 +6,7 @@ import { MilestoneTransactionEntry, Nft, NftAccess, + NftStatus, Transaction, TransactionPayloadType, } from '@build-5/interfaces'; @@ -116,7 +117,7 @@ export class NftService { const tanglePuchase = order.payload.tanglePuchase; const disableWithdraw = order.payload.disableWithdraw; - if (!disableWithdraw && tanglePuchase && AVAILABLE_NETWORKS.includes(order.network!)) { + if (!disableWithdraw && tanglePuchase && nft.status === NftStatus.MINTED) { await this.withdrawNft(order, nft); } } else { @@ -240,10 +241,7 @@ export class NftService { address: previousHighestPay.payload.targetAddress!, amount: previousHighestPay.payload.amount!, }, - from: { - address: previousHighestPay.payload.sourceAddress!, - amount: previousHighestPay.payload.amount!, - }, + from: previousHighestPay.payload.sourceAddress!, }, dateToTimestamp(dayjs(payment.createdOn?.toDate()).subtract(1, 's')), sameOwner, @@ -330,10 +328,7 @@ export class NftService { address: paymentPayload.targetAddress!, amount: paymentPayload.amount!, }, - from: { - address: paymentPayload.sourceAddress!, - amount: paymentPayload.amount!, - }, + from: paymentPayload.sourceAddress!, }); } } @@ -395,10 +390,7 @@ export class NftService { address: highestPay.payload.targetAddress!, amount: highestPay.payload.amount!, }, - from: { - address: highestPay.payload.sourceAddress!, - amount: highestPay.payload.amount!, - }, + from: highestPay.payload.sourceAddress!, }, serverTime(), sameOwner, diff --git a/packages/functions/src/services/payment/nft/nft-stake-service.ts b/packages/functions/src/services/payment/nft/nft-stake-service.ts index 82853d1f07..34923300b1 100644 --- a/packages/functions/src/services/payment/nft/nft-stake-service.ts +++ b/packages/functions/src/services/payment/nft/nft-stake-service.ts @@ -22,8 +22,7 @@ import { cloneDeep, get } from 'lodash'; import { build5Db } from '../../../firebase/firestore/build5Db'; import { dateToTimestamp } from '../../../utils/dateTime.utils'; import { getRandomEthAddress } from '../../../utils/wallet.utils'; -import { SmrWallet } from '../../wallet/SmrWalletService'; -import { WalletService } from '../../wallet/wallet'; +import { WalletService } from '../../wallet/wallet.service'; import { createNftWithdrawOrder } from '../tangle-service/nft/nft-purchase.service'; import { TransactionMatch, TransactionService } from '../transaction-service'; import { NftDepositService } from './nft-deposit-service'; @@ -52,7 +51,7 @@ export class NftStakeService { const { order: withdrawOrder, nftUpdateData } = createNftWithdrawOrder( nft, order.member!, - match.from.address, + match.from, get(order, 'payload.weeks', 0), get(order, 'payload.stakeType', StakeType.DYNAMIC), ); @@ -88,7 +87,7 @@ export class NftStakeService { }; private getNftOutputAmount = async (order: Transaction, tranEntry: MilestoneTransactionEntry) => { - const wallet = (await WalletService.newWallet(order.network)) as SmrWallet; + const wallet = await WalletService.newWallet(order.network); const weeks = get(order, 'payload.weeks', 0); const output = cloneDeep(tranEntry.nftOutput as INftOutput); output.features = output.features?.filter((f) => f.type !== TAG_FEATURE_TYPE); diff --git a/packages/functions/src/services/payment/payment-processing.ts b/packages/functions/src/services/payment/payment-processing.ts index e11a52edc0..c597abd012 100644 --- a/packages/functions/src/services/payment/payment-processing.ts +++ b/packages/functions/src/services/payment/payment-processing.ts @@ -75,7 +75,7 @@ export class ProcessingService { for (const tranOutput of tran.outputs) { if ( build5Transaction?.type !== TransactionType.UNLOCK && - tran.inputs.find((i) => tranOutput.address === i.address) + tran.fromAddresses.includes(tranOutput.address) ) { continue; } diff --git a/packages/functions/src/services/payment/space/space-service.ts b/packages/functions/src/services/payment/space/space-service.ts index 4b60711fa0..67bb185823 100644 --- a/packages/functions/src/services/payment/space/space-service.ts +++ b/packages/functions/src/services/payment/space/space-service.ts @@ -20,8 +20,7 @@ import { import { build5Db } from '../../../firebase/firestore/build5Db'; import { Bech32AddressHelper } from '../../../utils/bech32-address.helper'; import { serverTime } from '../../../utils/dateTime.utils'; -import { SmrWallet } from '../../wallet/SmrWalletService'; -import { WalletService } from '../../wallet/wallet'; +import { WalletService } from '../../wallet/wallet.service'; import { TransactionMatch, TransactionService } from '../transaction-service'; export class SpaceService { @@ -44,11 +43,7 @@ export class SpaceService { const collectionDocRef = build5Db().doc(`${COL.COLLECTION}/${space.collectionId}`); const collection = await collectionDocRef.get(); - const senderIsIssuer = await senderIsCollectionIssuer( - order.network!, - match.from.address, - collection, - ); + const senderIsIssuer = await senderIsCollectionIssuer(order.network!, match.from, collection); if (!senderIsIssuer) { return; } @@ -95,7 +90,7 @@ const senderIsCollectionIssuer = async ( senderBech32: string, collection: Collection, ) => { - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const indexer = new IndexerPluginClient(wallet.client); const hrp = wallet.info.protocol.bech32Hrp; diff --git a/packages/functions/src/services/payment/stake-service.ts b/packages/functions/src/services/payment/stake-service.ts index 2edd0206a1..209d5f33a4 100644 --- a/packages/functions/src/services/payment/stake-service.ts +++ b/packages/functions/src/services/payment/stake-service.ts @@ -56,7 +56,7 @@ export class StakeService { amount: matchAmount, nativeTokens, sourceAddress: order.payload.targetAddress, - targetAddress: match.from.address, + targetAddress: match.from, previousOwnerEntity: Entity.MEMBER, previousOwner: order.member!, ownerEntity: Entity.MEMBER, diff --git a/packages/functions/src/services/payment/tangle-service/TangleRequestService.ts b/packages/functions/src/services/payment/tangle-service/TangleRequestService.ts index 35e06d23c7..ac452e042e 100644 --- a/packages/functions/src/services/payment/tangle-service/TangleRequestService.ts +++ b/packages/functions/src/services/payment/tangle-service/TangleRequestService.ts @@ -47,11 +47,11 @@ export class TangleRequestService { match: TransactionMatch, build5Transaction?: Transaction, ) => { - let owner = match.from.address; + let owner = match.from; let payment: Transaction | undefined; try { - owner = await this.getOwner(match.from.address, order.network!); + owner = await this.getOwner(match.from, order.network!); payment = await this.transactionService.createPayment({ ...order, member: owner }, match); const request = getOutputMetadata(tranEntry.output).request; const response = await this.handleTangleRequest( @@ -128,7 +128,7 @@ export class TangleRequestService { } case TangleRequestType.NFT_PURCHASE: { const service = new TangleNftPurchaseService(this.transactionService); - return await service.handleNftPurchase(tran, tranEntry, owner, request); + return await service.handleNftPurchase(tran, tranEntry, owner, order, request); } case TangleRequestType.NFT_SET_FOR_SALE: { const service = new TangleNftSetForSaleService(this.transactionService); @@ -136,7 +136,7 @@ export class TangleRequestService { } case TangleRequestType.NFT_BID: { const service = new TangleNftBidService(this.transactionService); - return await service.handleNftBid(tran, tranEntry, owner, request); + return await service.handleNftBid(tran, tranEntry, owner, order, request); } case TangleRequestType.CLAIM_MINTED_AIRDROPS: { const service = new TangleTokenClaimService(this.transactionService); diff --git a/packages/functions/src/services/payment/tangle-service/address/address-validation.service.ts b/packages/functions/src/services/payment/tangle-service/address/address-validation.service.ts index 437c6d18b9..bb277f6963 100644 --- a/packages/functions/src/services/payment/tangle-service/address/address-validation.service.ts +++ b/packages/functions/src/services/payment/tangle-service/address/address-validation.service.ts @@ -21,7 +21,7 @@ import { invalidArgument } from '../../../../utils/error.utils'; import { assertValidationAsync } from '../../../../utils/schema.utils'; import { assertIsGuardian } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { validateAddressSchemaObject } from './AddressValidationTangleRequestSchema'; @@ -50,10 +50,6 @@ export class TangleAddressValidationService { action: 'set', }); - if ([Network.IOTA, Network.ATOI].includes(params.network as Network)) { - return { amount: order.payload.amount!, address: order.payload.targetAddress! }; - } - this.transactionService.createUnlockTransaction( order, tran, diff --git a/packages/functions/src/services/payment/tangle-service/award/award.create.service.ts b/packages/functions/src/services/payment/tangle-service/award/award.create.service.ts index 8d0b6b5ace..6750bc51c7 100644 --- a/packages/functions/src/services/payment/tangle-service/award/award.create.service.ts +++ b/packages/functions/src/services/payment/tangle-service/award/award.create.service.ts @@ -25,8 +25,7 @@ import { assertIsSpaceMember } from '../../../../utils/space.utils'; import { getTokenBySymbol } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; import { isStorageUrl } from '../../../joi/common'; -import { SmrWallet } from '../../../wallet/SmrWalletService'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { getAwardgStorageDeposits } from '../../award/award-service'; import { TransactionService } from '../../transaction-service'; import { awardCreateSchema } from './AwardCreateTangleRequestSchema'; @@ -133,7 +132,7 @@ export const createAward = async ( nativeTokenStorageDeposit: 0, funded: false, }; - const wallet = (await WalletService.newWallet(award.network)) as SmrWallet; + const wallet = await WalletService.newWallet(award.network); const storageDeposits = await getAwardgStorageDeposits(award, token, wallet); const awardOwner = { uid: owner, parentId: award.uid, parentCol: COL.AWARD }; diff --git a/packages/functions/src/services/payment/tangle-service/award/award.fund.service.ts b/packages/functions/src/services/payment/tangle-service/award/award.fund.service.ts index f77ce12a8c..936687d5b7 100644 --- a/packages/functions/src/services/payment/tangle-service/award/award.fund.service.ts +++ b/packages/functions/src/services/payment/tangle-service/award/award.fund.service.ts @@ -18,7 +18,7 @@ import { invalidArgument } from '../../../../utils/error.utils'; import { assertValidationAsync } from '../../../../utils/schema.utils'; import { assertIsGuardian } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { awardFundSchema } from './AwardFundTangleRequestSchema'; diff --git a/packages/functions/src/services/payment/tangle-service/metadataNft/mint-metadata-nft.service.ts b/packages/functions/src/services/payment/tangle-service/metadataNft/mint-metadata-nft.service.ts index fc2306d4f1..062bf037f6 100644 --- a/packages/functions/src/services/payment/tangle-service/metadataNft/mint-metadata-nft.service.ts +++ b/packages/functions/src/services/payment/tangle-service/metadataNft/mint-metadata-nft.service.ts @@ -42,8 +42,8 @@ import { createAliasOutput, } from '../../../../utils/token-minting-utils/alias.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { SmrWallet } from '../../../wallet/SmrWalletService'; -import { WalletService } from '../../../wallet/wallet'; +import { Wallet } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionMatch, TransactionService } from '../../transaction-service'; import { metadataNftSchema } from './MetadataNftTangleRequestSchema'; @@ -60,7 +60,7 @@ export class MintMetadataNftService { ) => { const params = await assertValidationAsync(metadataNftSchema, request); - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const targetAddress = await wallet.getNewIotaAddressDetails(); const { nftId, collectionId, aliasId } = await getIds(params, wallet); @@ -144,7 +144,7 @@ export class MintMetadataNftService { }; } -const getAliasOutputAmount = async (owner: string, space: Space, wallet: SmrWallet) => { +const getAliasOutputAmount = async (owner: string, space: Space, wallet: Wallet) => { const targetAddress = await wallet.getNewIotaAddressDetails(); if (isEmpty(space.alias)) { const aliasOutput = createAliasOutput(targetAddress, wallet.info); @@ -165,11 +165,7 @@ const getAliasOutputAmount = async (owner: string, space: Space, wallet: SmrWall return 0; }; -const getCollectionOutputAmount = async ( - aliasId: string, - collectionId: string, - wallet: SmrWallet, -) => { +const getCollectionOutputAmount = async (aliasId: string, collectionId: string, wallet: Wallet) => { if (collectionId === EMPTY_NFT_ID) { const issuerAddress: AddressTypes = { type: ALIAS_ADDRESS_TYPE, aliasId }; const collectionOutput = createNftOutput(issuerAddress, issuerAddress, '', wallet.info); @@ -178,11 +174,7 @@ const getCollectionOutputAmount = async ( return 0; }; -const createMetadataNftOutput = async ( - wallet: SmrWallet, - collectionId: string, - metadata: object, -) => { +const createMetadataNftOutput = async (wallet: Wallet, collectionId: string, metadata: object) => { const targetAddress = await wallet.getNewIotaAddressDetails(); const issuerAddress: AddressTypes = { type: NFT_ADDRESS_TYPE, nftId: collectionId }; const ownerAddress: AddressTypes = { type: ED25519_ADDRESS_TYPE, pubKeyHash: targetAddress.hex }; @@ -222,7 +214,7 @@ const getNftOutputAmount = async ( collectionId: string, nftId: string, metadata: object, - wallet: SmrWallet, + wallet: Wallet, ) => { if (nftId === EMPTY_NFT_ID) { const nftOutput = await createMetadataNftOutput(wallet, collectionId, metadata); @@ -235,7 +227,7 @@ const getNftOutputAmount = async ( throw invalidArgument(WenError.nft_not_deposited); }; -const getIds = async (request: MintMetadataNftTangleRequest, wallet: SmrWallet) => { +const getIds = async (request: MintMetadataNftTangleRequest, wallet: Wallet) => { const indexer = new IndexerPluginClient(wallet.client); const nftId = request.nftId as string; if (nftId) { @@ -256,7 +248,7 @@ const getIds = async (request: MintMetadataNftTangleRequest, wallet: SmrWallet) return { nftId: EMPTY_NFT_ID, collectionId: EMPTY_NFT_ID, aliasId }; }; -const getCollectionId = async (wallet: SmrWallet, indexer: IndexerPluginClient, nftId: string) => { +const getCollectionId = async (wallet: Wallet, indexer: IndexerPluginClient, nftId: string) => { try { const nftOutputId = (await indexer.nft(nftId)).items[0]; const nftOutput = (await wallet.client.output(nftOutputId)).output as INftOutput; @@ -267,7 +259,7 @@ const getCollectionId = async (wallet: SmrWallet, indexer: IndexerPluginClient, }; const getCollectionOutput = async ( - wallet: SmrWallet, + wallet: Wallet, indexer: IndexerPluginClient, collectionId: string, ) => { diff --git a/packages/functions/src/services/payment/tangle-service/nft/nft-bid.service.ts b/packages/functions/src/services/payment/tangle-service/nft/nft-bid.service.ts index f685e46fa0..9ca5134cfd 100644 --- a/packages/functions/src/services/payment/tangle-service/nft/nft-bid.service.ts +++ b/packages/functions/src/services/payment/tangle-service/nft/nft-bid.service.ts @@ -27,10 +27,9 @@ import { assertIpNotBlocked } from '../../../../utils/ip.utils'; import { assertValidationAsync } from '../../../../utils/schema.utils'; import { getSpace } from '../../../../utils/space.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { nftBidSchema } from './NftBidTangleRequestSchema'; -import { AVAILABLE_NETWORKS } from '../../../../controls/common'; export class TangleNftBidService { constructor(readonly transactionService: TransactionService) {} @@ -39,6 +38,7 @@ export class TangleNftBidService { tran: MilestoneTransaction, tranEntry: MilestoneTransactionEntry, owner: string, + tangleOrder: Transaction, request: Record, ): Promise => { const params = await assertValidationAsync(nftBidSchema, request); @@ -47,21 +47,16 @@ export class TangleNftBidService { order.payload.tanglePuchase = true; order.payload.disableWithdraw = params.disableWithdraw || false; + if (tangleOrder.network !== order.network) { + throw invalidArgument(WenError.invalid_network); + } + this.transactionService.push({ ref: build5Db().doc(`${COL.TRANSACTION}/${order.uid}`), data: order, action: 'set', }); - const isMintedNft = AVAILABLE_NETWORKS.includes(order.network!); - if (!isMintedNft) { - return { - status: 'success', - amount: order.payload.amount!, - address: order.payload.targetAddress!, - }; - } - this.transactionService.createUnlockTransaction( order, tran, diff --git a/packages/functions/src/services/payment/tangle-service/nft/nft-deposit.service.ts b/packages/functions/src/services/payment/tangle-service/nft/nft-deposit.service.ts index 69a65b9db2..b71f593e89 100644 --- a/packages/functions/src/services/payment/tangle-service/nft/nft-deposit.service.ts +++ b/packages/functions/src/services/payment/tangle-service/nft/nft-deposit.service.ts @@ -13,7 +13,7 @@ import dayjs from 'dayjs'; import { build5Db } from '../../../../firebase/firestore/build5Db'; import { dateToTimestamp } from '../../../../utils/dateTime.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; export class NftDepositService { diff --git a/packages/functions/src/services/payment/tangle-service/nft/nft-purchase.service.ts b/packages/functions/src/services/payment/tangle-service/nft/nft-purchase.service.ts index a3684756ec..0fcc181392 100644 --- a/packages/functions/src/services/payment/tangle-service/nft/nft-purchase.service.ts +++ b/packages/functions/src/services/payment/tangle-service/nft/nft-purchase.service.ts @@ -25,7 +25,6 @@ import { } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; -import { AVAILABLE_NETWORKS } from '../../../../controls/common'; import { build5Db } from '../../../../firebase/firestore/build5Db'; import { getAddress } from '../../../../utils/address.utils'; import { getNftByMintingId } from '../../../../utils/collection-minting-utils/nft.utils'; @@ -38,7 +37,7 @@ import { assertValidationAsync } from '../../../../utils/schema.utils'; import { getSpace } from '../../../../utils/space.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; import { assertHasAccess } from '../../../validators/access'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { nftPurchaseSchema } from './NftPurchaseTangleRequestSchema'; @@ -49,6 +48,7 @@ export class TangleNftPurchaseService { tran: MilestoneTransaction, tranEntry: MilestoneTransactionEntry, owner: string, + tangleOrder: Transaction, request: Record, ): Promise => { const params = await assertValidationAsync(nftPurchaseSchema, request); @@ -63,9 +63,7 @@ export class TangleNftPurchaseService { action: 'set', }); - const isMintedNft = AVAILABLE_NETWORKS.includes(order.network!); - - if (isMintedNft && tranEntry.amount !== order.payload.amount) { + if (tranEntry.amount !== order.payload.amount || tangleOrder.network !== order.network) { return { status: 'error', amount: order.payload.amount!, @@ -75,14 +73,6 @@ export class TangleNftPurchaseService { }; } - if (!isMintedNft) { - return { - status: 'success', - amount: order.payload.amount!, - address: order.payload.targetAddress!, - }; - } - this.transactionService.createUnlockTransaction( order, tran, diff --git a/packages/functions/src/services/payment/tangle-service/proposal/voting/token.voting.ts b/packages/functions/src/services/payment/tangle-service/proposal/voting/token.voting.ts index e5390c24b8..025586dadf 100644 --- a/packages/functions/src/services/payment/tangle-service/proposal/voting/token.voting.ts +++ b/packages/functions/src/services/payment/tangle-service/proposal/voting/token.voting.ts @@ -15,8 +15,7 @@ import { packBasicOutput } from '../../../../../utils/basic-output.utils'; import { isProdEnv } from '../../../../../utils/config.utils'; import { dateToTimestamp } from '../../../../../utils/dateTime.utils'; import { getRandomEthAddress } from '../../../../../utils/wallet.utils'; -import { SmrWallet } from '../../../../wallet/SmrWalletService'; -import { WalletService } from '../../../../wallet/wallet'; +import { WalletService } from '../../../../wallet/wallet.service'; export const createVoteTransactionOrder = async ( owner: string, @@ -25,7 +24,7 @@ export const createVoteTransactionOrder = async ( token: Token, ): Promise => { const network = isProdEnv() ? Network.SMR : Network.RMS; - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const targetAddress = await wallet.getNewIotaAddressDetails(); const nativeToken = { diff --git a/packages/functions/src/services/payment/tangle-service/space/SpaceCreateService.ts b/packages/functions/src/services/payment/tangle-service/space/SpaceCreateService.ts index c29e5ebf48..a2c1e1eb58 100644 --- a/packages/functions/src/services/payment/tangle-service/space/SpaceCreateService.ts +++ b/packages/functions/src/services/payment/tangle-service/space/SpaceCreateService.ts @@ -9,7 +9,7 @@ import { assertValidationAsync } from '../../../../utils/schema.utils'; import { spaceToIpfsMetadata } from '../../../../utils/space.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; import { isStorageUrl } from '../../../joi/common'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { createSpaceSchemaObject } from './SpaceCreateTangleRequestSchema'; diff --git a/packages/functions/src/services/payment/tangle-service/token/stake.service.ts b/packages/functions/src/services/payment/tangle-service/token/stake.service.ts index 8d9014f330..06b707df94 100644 --- a/packages/functions/src/services/payment/tangle-service/token/stake.service.ts +++ b/packages/functions/src/services/payment/tangle-service/token/stake.service.ts @@ -21,8 +21,7 @@ import { invalidArgument } from '../../../../utils/error.utils'; import { assertValidationAsync } from '../../../../utils/schema.utils'; import { getTokenBySymbol } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { SmrWallet } from '../../../wallet/SmrWalletService'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { depositStakeSchemaObject } from './TokenStakeTangleRequestSchema'; @@ -80,7 +79,7 @@ export const createStakeOrder = async ( } const network = token.mintingData?.network!; - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const targetAddress = await wallet.getNewIotaAddressDetails(); const nativeTokens = [ { diff --git a/packages/functions/src/services/payment/tangle-service/token/token-claim.service.ts b/packages/functions/src/services/payment/tangle-service/token/token-claim.service.ts index cb3b2f5139..0087aa8c57 100644 --- a/packages/functions/src/services/payment/tangle-service/token/token-claim.service.ts +++ b/packages/functions/src/services/payment/tangle-service/token/token-claim.service.ts @@ -24,8 +24,7 @@ import { assertValidationAsync } from '../../../../utils/schema.utils'; import { dropToOutput } from '../../../../utils/token-minting-utils/member.utils'; import { getTokenBySymbol, getUnclaimedDrops } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { SmrWallet } from '../../../wallet/SmrWalletService'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionService } from '../../transaction-service'; import { tokenClaimSchema } from './TokenClaimTangleRequestSchema'; @@ -68,7 +67,7 @@ export const createMintedTokenAirdropCalimOrder = async ( throw invalidArgument(WenError.no_tokens_to_claim); } - const wallet = (await WalletService.newWallet(token.mintingData?.network!)) as SmrWallet; + const wallet = await WalletService.newWallet(token.mintingData?.network!); const targetAddress = await wallet.getNewIotaAddressDetails(); const storageDeposit = drops.reduce((acc, drop) => { const output = dropToOutput(token, drop, targetAddress.bech32, wallet.info); diff --git a/packages/functions/src/services/payment/tangle-service/token/token-trade.service.ts b/packages/functions/src/services/payment/tangle-service/token/token-trade.service.ts index aa7861c6f8..36dad05fcd 100644 --- a/packages/functions/src/services/payment/tangle-service/token/token-trade.service.ts +++ b/packages/functions/src/services/payment/tangle-service/token/token-trade.service.ts @@ -40,8 +40,7 @@ import { getTokenBySymbol, } from '../../../../utils/token.utils'; import { getRandomEthAddress } from '../../../../utils/wallet.utils'; -import { SmrWallet } from '../../../wallet/SmrWalletService'; -import { WalletService } from '../../../wallet/wallet'; +import { WalletService } from '../../../wallet/wallet.service'; import { TransactionMatch, TransactionService } from '../../transaction-service'; import { tradeMintedTokenSchema } from './TokenTradeTangleRequestSchema'; @@ -257,7 +256,7 @@ const getAmount = async (token: Token, count: number, price: number, isSell: boo if (token.status !== TokenStatus.MINTED) { return count; } - const wallet = (await WalletService.newWallet(token.mintingData?.network)) as SmrWallet; + const wallet = await WalletService.newWallet(token.mintingData?.network); const tmpAddress = await wallet.getNewIotaAddressDetails(false); const nativeTokens = [ { amount: HexHelper.fromBigInt256(bigInt(count)), id: token.mintingData?.tokenId! }, diff --git a/packages/functions/src/services/payment/token/import-minted-token.service.ts b/packages/functions/src/services/payment/token/import-minted-token.service.ts index ddd41f77dc..944fdbf071 100644 --- a/packages/functions/src/services/payment/token/import-minted-token.service.ts +++ b/packages/functions/src/services/payment/token/import-minted-token.service.ts @@ -26,8 +26,8 @@ import { build5Storage } from '../../../firebase/storage/build5Storage'; import { getBucket } from '../../../utils/config.utils'; import { migrateUriToSotrage, uriToUrl } from '../../../utils/media.utils'; import { isAliasGovernor } from '../../../utils/token-minting-utils/alias.utils'; -import { SmrWallet } from '../../wallet/SmrWalletService'; -import { WalletService } from '../../wallet/wallet'; +import { Wallet } from '../../wallet/wallet'; +import { WalletService } from '../../wallet/wallet.service'; import { TransactionMatch, TransactionService } from '../transaction-service'; export class ImportMintedTokenService { @@ -44,7 +44,7 @@ export class ImportMintedTokenService { throw WenError.token_does_not_exist; } - const wallet = (await WalletService.newWallet(order.network)) as SmrWallet; + const wallet = await WalletService.newWallet(order.network); const { foundry, alias } = await this.getFoundryOutput(wallet, order, match); const metadata = this.getTokenMetadata(foundry); @@ -124,7 +124,7 @@ export class ImportMintedTokenService { }; private getFoundryOutput = async ( - wallet: SmrWallet, + wallet: Wallet, order: Transaction, match: TransactionMatch, ) => { @@ -140,7 +140,7 @@ export class ImportMintedTokenService { const alias = await indexer.alias(aliasId); const aliasOutput = (await wallet.client.output(alias.items[0])).output; - if (!isAliasGovernor(aliasOutput, match.from.address, wallet.info.protocol.bech32Hrp)) { + if (!isAliasGovernor(aliasOutput, match.from, wallet.info.protocol.bech32Hrp)) { throw WenError.not_alias_governor; } diff --git a/packages/functions/src/services/payment/transaction-service.ts b/packages/functions/src/services/payment/transaction-service.ts index e11781cf13..485d5e423d 100644 --- a/packages/functions/src/services/payment/transaction-service.ts +++ b/packages/functions/src/services/payment/transaction-service.ts @@ -14,6 +14,7 @@ import { TransactionPayloadType, TransactionType, TransactionValidationType, + getMilestoneCol, } from '@build-5/interfaces'; import { ADDRESS_UNLOCK_CONDITION_TYPE, @@ -28,13 +29,13 @@ import * as functions from 'firebase-functions/v2'; import { get, isEmpty, set } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { IDocument, ITransaction } from '../../firebase/firestore/interfaces'; -import { SmrMilestoneTransactionAdapter } from '../../triggers/milestone-transactions-triggers/SmrMilestoneTransactionAdapter'; +import { MilestoneTransactionAdapter } from '../../triggers/milestone-transactions-triggers/MilestoneTransactionAdapter'; import { getOutputMetadata } from '../../utils/basic-output.utils'; import { dateToTimestamp, serverTime } from '../../utils/dateTime.utils'; import { getRandomEthAddress } from '../../utils/wallet.utils'; export interface TransactionMatch { msgId: string; - from: MilestoneTransactionEntry; + from: string; to: MilestoneTransactionEntry; } @@ -81,7 +82,7 @@ export class TransactionService { const data: Transaction = { type: TransactionType.PAYMENT, uid: getRandomEthAddress(), - member: order.member || tran.from.address, + member: order.member || tran.from, space: order.space || '', network: order.network || DEFAULT_NETWORK, payload: { @@ -91,7 +92,7 @@ export class TransactionService { ...nt, amount: Number(nt.amount).toString(), })), - sourceAddress: tran.from.address, + sourceAddress: tran.from, targetAddress: order.payload.targetAddress, reconciled: true, void: false, @@ -233,7 +234,7 @@ export class TransactionService { amount: Number(nt.amount).toString(), })), sourceAddress: tran.to.address, - targetAddress: tran.from.address, + targetAddress: tran.from, sourceTransaction: [payment.uid], nft: payment.payload.nft || null, reconciled: true, @@ -289,7 +290,7 @@ export class TransactionService { amount: Number(nt.amount).toString(), })), sourceAddress: tran.to.address, - targetAddress: tran.from.address, + targetAddress: tran.from, sourceTransaction: [payment.uid], reconciled: true, void: false, @@ -330,7 +331,7 @@ export class TransactionService { payload: { amount: payment.payload.amount, sourceAddress: tran.to.address, - targetAddress: tran.from.address, + targetAddress: tran.from, sourceTransaction: [payment.uid], reconciled: true, void: false, @@ -369,11 +370,11 @@ export class TransactionService { const doc = (await build5Db() .doc(build5Transaction.payload?.milestoneTransactionPath!) .get>())!; - const adapter = new SmrMilestoneTransactionAdapter(order.network!); + const adapter = new MilestoneTransactionAdapter(order.network!); const milestoneTransaction = await adapter.toMilestoneTransaction(doc); - return milestoneTransaction.inputs?.[0]; + return milestoneTransaction.fromAddresses[0]; } - return tran.inputs?.[0]; + return tran.fromAddresses[0]; }; public async isMatch( @@ -389,19 +390,12 @@ export class TransactionService { return; } let found: TransactionMatch | undefined; - const fromAddress: MilestoneTransactionEntry = await this.getFromAddress( - tran, - order, - build5Transaction, - ); + const fromAddress = await this.getFromAddress(tran, order, build5Transaction); if (fromAddress && tran.outputs) { for (const o of tran.outputs) { - // Ignore output that contains input address. Remaining balance. if ( build5Transaction?.type !== TransactionType.UNLOCK && - tran.inputs.find((i) => { - return o.address === i.address; - }) + tran.fromAddresses.includes(o.address) ) { continue; } @@ -428,11 +422,7 @@ export class TransactionService { tranOutput: MilestoneTransactionEntry, build5Transaction?: Transaction, ): Promise { - const fromAddress: MilestoneTransactionEntry = await this.getFromAddress( - tran, - order, - build5Transaction, - ); + const fromAddress = await this.getFromAddress(tran, order, build5Transaction); if (fromAddress) { const match: TransactionMatch = { msgId: tran.messageId, @@ -504,7 +494,9 @@ export class TransactionService { : tranOutput.address, sourceTransaction: [order.uid], expiresOn: expiresOn || dateToTimestamp(dayjs().add(TRANSACTION_AUTO_EXPIRY_MS)), - milestoneTransactionPath: `${COL.MILESTONE}_${network}/${tran.milestone}/${SUB_COL.TRANSACTIONS}/${tran.uid}`, + milestoneTransactionPath: `${getMilestoneCol(network)}/${tran.milestone}/${ + SUB_COL.TRANSACTIONS + }/${tran.uid}`, outputToConsume, customMetadata: getOutputMetadata(tranOutput.output), nftId: tranOutput.nftOutput?.nftId || '', diff --git a/packages/functions/src/services/payment/voting-service.ts b/packages/functions/src/services/payment/voting-service.ts index aa5a45c447..6b994891b0 100644 --- a/packages/functions/src/services/payment/voting-service.ts +++ b/packages/functions/src/services/payment/voting-service.ts @@ -27,7 +27,7 @@ export class VotingService { const values = get(order, 'payload.voteValues', []); const customData = hasValidToken ? { proposalId, values } : undefined; - const storageReturn = match.to.amount >= order.payload.amount! ? match.from.address : undefined; + const storageReturn = match.to.amount >= order.payload.amount! ? match.from : undefined; const credit = await this.transactionService.createCredit( TransactionPayloadType.TOKEN_VOTE, payment, diff --git a/packages/functions/src/services/wallet/smr-wallets/AliasWallet.ts b/packages/functions/src/services/wallet/AliasWallet.ts similarity index 84% rename from packages/functions/src/services/wallet/smr-wallets/AliasWallet.ts rename to packages/functions/src/services/wallet/AliasWallet.ts index 0abe0b80b5..ab7d5c056b 100644 --- a/packages/functions/src/services/wallet/smr-wallets/AliasWallet.ts +++ b/packages/functions/src/services/wallet/AliasWallet.ts @@ -8,19 +8,19 @@ import { TransactionHelper, } from '@iota/iota.js-next'; import { cloneDeep, isEmpty } from 'lodash'; -import { mergeOutputs, packBasicOutput } from '../../../utils/basic-output.utils'; -import { packEssence, packPayload, submitBlock } from '../../../utils/block.utils'; -import { createUnlock } from '../../../utils/smr.utils'; -import { createAliasOutput } from '../../../utils/token-minting-utils/alias.utils'; -import { SmrParams, SmrWallet } from '../SmrWalletService'; -import { MnemonicService } from '../mnemonic'; -import { setConsumedOutputIds } from '../wallet'; +import { mergeOutputs, packBasicOutput } from '../../utils/basic-output.utils'; +import { packEssence, packPayload, submitBlock } from '../../utils/block.utils'; +import { createUnlock } from '../../utils/smr.utils'; +import { createAliasOutput } from '../../utils/token-minting-utils/alias.utils'; +import { MnemonicService } from './mnemonic'; +import { Wallet, WalletParams } from './wallet'; +import { setConsumedOutputIds } from './wallet.service'; export class AliasWallet { - constructor(private readonly wallet: SmrWallet) {} + constructor(private readonly wallet: Wallet) {} - public mintAlias = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public mintAlias = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -49,8 +49,8 @@ export class AliasWallet { ); }; - public changeAliasOwner = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public changeAliasOwner = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const aliasOutputs = await this.getAliasOutputs( @@ -80,8 +80,8 @@ export class AliasWallet { ); }; - public burnAlias = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public burnAlias = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const aliasOutputs = await this.getAliasOutputs( diff --git a/packages/functions/src/services/wallet/IotaWalletService.ts b/packages/functions/src/services/wallet/IotaWalletService.ts index 9a2320492c..006c0e77ae 100644 --- a/packages/functions/src/services/wallet/IotaWalletService.ts +++ b/packages/functions/src/services/wallet/IotaWalletService.ts @@ -1,218 +1,364 @@ -import { KEY_NAME_TANGLE, Network } from '@build-5/interfaces'; -import { Bip32Path } from '@iota/crypto.js'; +import { NativeToken, Timestamp, Transaction } from '@build-5/interfaces'; +import { Bip32Path } from '@iota/crypto.js-next'; import { + ADDRESS_UNLOCK_CONDITION_TYPE, + BASIC_OUTPUT_TYPE, Bech32Helper, ED25519_ADDRESS_TYPE, Ed25519Address, Ed25519Seed, - IKeyPair, - INodeInfo, - IOutputResponse, - IUTXOInput, - SIG_LOCKED_SINGLE_OUTPUT_TYPE, - SingleNodeClient, - UTXO_INPUT_TYPE, - sendAdvanced, -} from '@iota/iota.js'; -import { Converter } from '@iota/util.js'; + IAliasOutput, + IBasicOutput, + IFoundryOutput, + INftOutput, + IndexerPluginClient, + REFERENCE_UNLOCK_TYPE, + TransactionHelper, + UnlockTypes, + addressBalance, +} from '@iota/iota.js-next'; +import { Converter, HexHelper } from '@iota/util.js-next'; +import bigInt from 'big-integer'; import { generateMnemonic } from 'bip39'; -import * as functions from 'firebase-functions/v2'; -import { isEmpty } from 'lodash'; -import { getRandomElement } from '../../utils/common.utils'; +import { cloneDeep, head, isEmpty } from 'lodash'; +import { mergeOutputs, packBasicOutput, subtractHex } from '../../utils/basic-output.utils'; +import { Bech32AddressHelper } from '../../utils/bech32-address.helper'; +import { packEssence, packPayload, submitBlock } from '../../utils/block.utils'; +import { createUnlock } from '../../utils/smr.utils'; +import { NftWallet } from './NftWallet'; import { MnemonicService } from './mnemonic'; -import { AddressDetails, Wallet, WalletParams, setConsumedOutputIds } from './wallet'; -const IOTA_API_ENDPOINTS = [ - 'https://us3.svrs.io/', - 'https://us4.svrs.io/', - 'https://hs5.svrs.io/', - 'https://hs6.svrs.io/', - 'https://chrysalis-nodes.iota.org', -]; - -const ATOI_API_ENDPOINTS = ['https://devnet.svrs.io/']; - -const getEndpointUrl = (network: Network) => { - const urls = network === Network.IOTA ? IOTA_API_ENDPOINTS : ATOI_API_ENDPOINTS; - return getRandomElement(urls); -}; +import { Wallet, WalletParams } from './wallet'; +import { AddressDetails, SendToManyTargets, setConsumedOutputIds } from './wallet.service'; -interface Input { - input: IUTXOInput; - addressKeyPair: IKeyPair; +export interface Expiration { + readonly expiresAt: Timestamp; + readonly returnAddressBech32: string; } -export const getIotaClient = async (network: Network, customUrl?: string) => { - let url = ''; - for (let i = 0; i < 5; ++i) { - url = customUrl || getEndpointUrl(network); - try { - const client = new SingleNodeClient(url); - const healty = await client.health(); - if (healty) { - return { client, info: await client.info() }; - } - } catch (error) { - functions.logger.warn(`Could not connect to client ${network}`, url, error); - } - await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 1000 + 500))); - } - functions.logger.error(`Could not connect to client ${network}`, url); - throw Error(`Could not connect to any client ${network}`); -}; - -export class IotaWallet implements Wallet { - constructor( - public readonly client: SingleNodeClient, - public readonly info: INodeInfo, - private readonly network: Network, - ) {} - +export class IotaWallet extends Wallet { public getBalance = async (addressBech32: string | undefined) => { if (!addressBech32) { return 0; } - return (await this.client.address(addressBech32))?.balance || 0; + const balance = await addressBalance(this.client, addressBech32); + return Number(balance.balance); }; - public getNewIotaAddressDetails = async () => { + public getNewIotaAddressDetails = async (saveMnemonic = true) => { const address = await this.getIotaAddressDetails(generateMnemonic() + ' ' + generateMnemonic()); - await MnemonicService.store(address.bech32, address.mnemonic, this.network); + saveMnemonic && (await MnemonicService.store(address.bech32, address.mnemonic, this.network)); return address; }; public getIotaAddressDetails = async (mnemonic: string): Promise => { - const genesisSeed = Ed25519Seed.fromMnemonic(mnemonic); - const genesisPath = new Bip32Path("m/44'/4218'/0'/0'/0'"); - const genesisWalletSeed = genesisSeed.generateSeedFromPath(genesisPath); - const keyPair = genesisWalletSeed.keyPair(); - const genesisEd25519Address = new Ed25519Address(keyPair.publicKey); - const genesisWalletAddress = genesisEd25519Address.toAddress(); - const hex = Converter.bytesToHex(genesisWalletAddress); + const walletSeed = Ed25519Seed.fromMnemonic(mnemonic); + const walletPath = new Bip32Path("m/44'/4218'/0'/0'/0'"); + const walletAddressSeed = walletSeed.generateSeedFromPath(walletPath); + const keyPair = walletAddressSeed.keyPair(); + const walletEd25519Address = new Ed25519Address(keyPair.publicKey); + const walletAddress = walletEd25519Address.toAddress(); + const hex = Converter.bytesToHex(walletAddress, true); const bech32 = Bech32Helper.toBech32( ED25519_ADDRESS_TYPE, - genesisWalletAddress, - this.info?.bech32HRP!, + walletAddress, + this.info.protocol.bech32Hrp, ); - return { mnemonic, bech32, keyPair, hex }; + return { mnemonic, keyPair, hex, bech32 }; }; - public getAddressDetails = async (bech32: string) => { - const mnemonic = await MnemonicService.get(bech32); + public getAddressDetails = async (bech32: string | undefined) => { + const mnemonic = await MnemonicService.get(bech32 || ''); return this.getIotaAddressDetails(mnemonic); }; - public getOutputs = async (addressHex: string, previouslyConsumedOutputIds: string[] = []) => { - const consumedOutputIds = isEmpty(previouslyConsumedOutputIds) - ? (await this.client.addressEd25519Outputs(addressHex)).outputIds + public getTransactionOutput = async (transactionId: string, outputIndex: number) => { + const outputId = TransactionHelper.outputIdFromTransactionData(transactionId, outputIndex); + return await this.client.output(outputId); + }; + + public bechAddressFromOutput = ( + output: IBasicOutput | IAliasOutput | IFoundryOutput | INftOutput, + ) => { + const hrp = this.info.protocol.bech32Hrp!; + return Bech32AddressHelper.addressFromAddressUnlockCondition( + output.unlockConditions, + hrp, + output.type, + ); + }; + + public getOutputs = async ( + addressBech32: string, + previouslyConsumedOutputIds: string[] = [], + hasStorageDepositReturn: boolean | undefined, + hasTimelock = false, + ) => { + const indexer = new IndexerPluginClient(this.client); + const query = { + addressBech32, + hasStorageDepositReturn, + hasTimelock, + }; + const outputIds = isEmpty(previouslyConsumedOutputIds) + ? (await indexer.basicOutputs(query)).items : previouslyConsumedOutputIds; - const outputs: { [id: string]: IOutputResponse } = {}; - for (const consumedOutputId of consumedOutputIds) { - const output = await this.client.output(consumedOutputId); - if (output.output.type === SIG_LOCKED_SINGLE_OUTPUT_TYPE) { - outputs[consumedOutputId] = output; + const outputs: { [key: string]: IBasicOutput } = {}; + for (const id of outputIds) { + const output = (await this.client.output(id)).output; + if (output.type === BASIC_OUTPUT_TYPE) { + outputs[id] = output; } } return outputs; }; public send = async ( - fromAddress: AddressDetails, + from: AddressDetails, toAddress: string, amount: number, params: WalletParams, - ) => { - const prevConsumedOutputIds = - (await MnemonicService.getData(fromAddress.bech32)).consumedOutputIds || []; - const consumedOutputs = await this.getOutputs(fromAddress.hex, prevConsumedOutputIds); - const totalAmount = Object.values(consumedOutputs).reduce( - (acc, act) => acc + act.output.amount, - 0, - ); - const inputs: Input[] = Object.values(consumedOutputs).map((output) => ({ - input: { - type: UTXO_INPUT_TYPE, - transactionId: output.transactionId, - transactionOutputIndex: output.outputIndex, - }, - addressKeyPair: fromAddress.keyPair, - })); - - const output = { - address: this.convertAddressToHex(toAddress), - addressType: ED25519_ADDRESS_TYPE, + outputToConsume?: string | undefined, + ): Promise => { + const prevConsumedOutputIds = outputToConsume + ? [outputToConsume] + : (await MnemonicService.getData(from.bech32)).consumedOutputIds; + const outputsMap = await this.getOutputs(from.bech32, prevConsumedOutputIds, false); + const output = packBasicOutput( + toAddress, amount, - }; - const remainder = { - address: fromAddress.hex, - addressType: ED25519_ADDRESS_TYPE, - amount: totalAmount - amount, - }; + params.nativeTokens, + this.info, + params.storageDepositReturnAddress, + params.vestingAt, + params.expiration, + params.customMetadata, + params.tag, + ); - await setConsumedOutputIds(fromAddress.bech32, Object.keys(consumedOutputs)); - const { messageId } = await sendAdvanced( - this.client, - inputs, - remainder.amount > 0 ? [output, remainder] : [output], - { - key: Converter.utf8ToBytes(KEY_NAME_TANGLE), - data: Converter.utf8ToBytes(params.data || ''), - }, + const remainders: IBasicOutput[] = []; + + let storageDepositOutputMap: { [key: string]: IBasicOutput } = {}; + if (params.storageDepositSourceAddress) { + const previouslyConsumedOutputIds = + (await MnemonicService.getData(params.storageDepositSourceAddress)).consumedOutputIds || []; + storageDepositOutputMap = await this.getOutputs( + params.storageDepositSourceAddress, + previouslyConsumedOutputIds, + false, + ); + const remainder = mergeOutputs(cloneDeep(Object.values(storageDepositOutputMap))); + remainder.amount = (Number(remainder.amount) - Number(output.amount)).toString(); + if (Number(remainder.amount)) { + remainders.push(remainder); + } + } + const remainder = mergeOutputs(cloneDeep(Object.values(outputsMap))); + remainder.nativeTokens = subtractNativeTokens(remainder, params.nativeTokens); + if (!params.storageDepositSourceAddress) { + remainder.amount = (Number(remainder.amount) - Number(output.amount)).toString(); + } + if (!isEmpty(remainder.nativeTokens) || Number(remainder.amount) > 0) { + remainders.push(remainder); + } + + const inputs = [...Object.keys(outputsMap), ...Object.keys(storageDepositOutputMap)].map( + TransactionHelper.inputFromOutputId, ); - return messageId; + const inputsCommitment = TransactionHelper.getInputsCommitment([ + ...Object.values(outputsMap), + ...Object.values(storageDepositOutputMap), + ]); + + const essence = packEssence(inputs, inputsCommitment, [output, ...remainders], this, params); + const unlocks: UnlockTypes[] = Object.values(outputsMap).map((_, index) => + !index ? createUnlock(essence, from.keyPair) : { type: REFERENCE_UNLOCK_TYPE, reference: 0 }, + ); + if (params.storageDepositSourceAddress) { + const address = await this.getAddressDetails(params.storageDepositSourceAddress); + const storageDepUnlocks: UnlockTypes[] = Object.values(storageDepositOutputMap).map( + (_, index) => + !index + ? createUnlock(essence, address.keyPair) + : { type: REFERENCE_UNLOCK_TYPE, reference: unlocks.length }, + ); + unlocks.push(...storageDepUnlocks); + } + + if (!outputToConsume) { + await setConsumedOutputIds(from.bech32, Object.keys(outputsMap)); + if (params.storageDepositSourceAddress) { + await setConsumedOutputIds( + params.storageDepositSourceAddress, + Object.keys(storageDepositOutputMap), + ); + } + } + return await submitBlock(this, packPayload(essence, unlocks)); }; public sendToMany = async ( from: AddressDetails, - targets: { toAddress: string; amount: number }[], + targets: SendToManyTargets[], params: WalletParams, - ) => { - const consumedOutputIds = (await this.client.addressEd25519Outputs(from.hex)).outputIds; - const outputPromises = consumedOutputIds.map((id) => this.client.output(id)); - const consumedOutputResponses = await Promise.all(outputPromises); - const total = consumedOutputResponses.reduce((acc, act) => acc + act.output.amount, 0); - - const inputs: Input[] = consumedOutputResponses.map((output) => ({ - input: { - type: UTXO_INPUT_TYPE, - transactionId: output.transactionId, - transactionOutputIndex: output.outputIndex, - }, - addressKeyPair: from.keyPair, - })); - - const outputs = targets.map((target) => ({ - address: this.convertAddressToHex(target.toAddress), - addressType: ED25519_ADDRESS_TYPE, - amount: target.amount, - })); - const outputsTotal = outputs.reduce((acc, act) => acc + act.amount, 0); - - const remainderAmount = total - outputsTotal; - const remainder = - remainderAmount > 0 - ? { - address: from.hex, - addressType: ED25519_ADDRESS_TYPE, - amount: remainderAmount, - } - : undefined; - - await setConsumedOutputIds(from.bech32, consumedOutputIds); - const { messageId } = await sendAdvanced( - this.client, + ): Promise => { + const outputsMap = await this.getOutputs(from.bech32, [], false); + const mergedConsumedOutput = mergeOutputs(Object.values(cloneDeep(outputsMap))); + + const outputs = targets.map((target) => + packBasicOutput( + target.toAddress, + target.amount, + target.nativeTokens, + this.info, + undefined, + undefined, + undefined, + target.customMetadata, + ), + ); + const mergedOutputs = mergeOutputs(Object.values(cloneDeep(outputs))); + + const remainderAmount = Number(mergedConsumedOutput.amount) - Number(mergedOutputs.amount); + const remainderNativeTokenAmount = + Number(head(mergedConsumedOutput.nativeTokens)?.amount || 0) - + Number(head(mergedOutputs.nativeTokens)?.amount || 0); + + const remainderNativeTokens = remainderNativeTokenAmount + ? [ + { + id: mergedConsumedOutput.nativeTokens![0].id, + amount: HexHelper.fromBigInt256(bigInt(remainderNativeTokenAmount)), + }, + ] + : []; + + const remainder = packBasicOutput( + from.bech32, + remainderAmount, + remainderNativeTokens, + this.info, + ); + + const inputs = Object.keys(outputsMap).map(TransactionHelper.inputFromOutputId); + const inputsCommitment = TransactionHelper.getInputsCommitment(Object.values(outputsMap)); + + const essence = packEssence( inputs, - remainder ? [...outputs, remainder] : outputs, - { - key: Converter.utf8ToBytes(KEY_NAME_TANGLE), - data: Converter.utf8ToBytes(params.data || ''), - }, + inputsCommitment, + remainderAmount > 0 ? [...outputs, remainder] : outputs, + this, + params, ); - return messageId; + const unlocks: UnlockTypes[] = Object.values(outputsMap).map((_, index) => + !index ? createUnlock(essence, from.keyPair) : { type: REFERENCE_UNLOCK_TYPE, reference: 0 }, + ); + await setConsumedOutputIds(from.bech32, Object.keys(outputsMap)); + return await submitBlock(this, packPayload(essence, unlocks)); }; - private convertAddressToHex(address: string) { - const decodeBench32Target = Bech32Helper.fromBech32(address, this.info?.bech32HRP!); - return Converter.bytesToHex(decodeBench32Target?.addressBytes!); - } + public creditLocked = async (credit: Transaction, params: WalletParams): Promise => { + const mnemonicData = await MnemonicService.getData(credit.payload.sourceAddress!); + const prevSourceConsumedOutputIds = mnemonicData.consumedOutputIds || []; + const sourceConsumedOutputs = await this.getOutputs( + credit.payload.sourceAddress!, + prevSourceConsumedOutputIds, + true, + ); + + const sourceBasicOutputs = Object.values(sourceConsumedOutputs).map((o) => + packBasicOutput(credit.payload.targetAddress!, Number(o.amount), o.nativeTokens, this.info), + ); + + const nftWallet = new NftWallet(this); + const sourceConsumedNftOutputs = await nftWallet.getNftOutputs( + undefined, + credit.payload.sourceAddress, + mnemonicData.consumedNftOutputIds, + ); + const targetAddress = Bech32Helper.addressFromBech32( + credit.payload.targetAddress!, + this.info.protocol.bech32Hrp, + ); + const sourceNftOutputs = Object.values(sourceConsumedNftOutputs).map((nftOutput) => { + const output = cloneDeep(nftOutput); + output.unlockConditions = [{ type: ADDRESS_UNLOCK_CONDITION_TYPE, address: targetAddress }]; + return output; + }); + + const sourceOutputs = [...sourceBasicOutputs, ...sourceNftOutputs]; + + const prevStorageDepConsumedOutputIds = + (await MnemonicService.getData(credit.payload.storageDepositSourceAddress!)) + .consumedOutputIds || []; + const storageDepConsumedOutputs = await this.getOutputs( + credit.payload.storageDepositSourceAddress!, + prevStorageDepConsumedOutputIds, + false, + ); + const storageDepOutputs = Object.values(storageDepConsumedOutputs).map((o) => + packBasicOutput(credit.payload.targetAddress!, Number(o.amount), o.nativeTokens, this.info), + ); + + const inputs = [ + ...Object.keys(sourceConsumedOutputs), + ...Object.keys(sourceConsumedNftOutputs), + ...Object.keys(storageDepConsumedOutputs), + ].map(TransactionHelper.inputFromOutputId); + const inputsCommitment = TransactionHelper.getInputsCommitment([ + ...Object.values(sourceConsumedOutputs), + ...Object.values(sourceConsumedNftOutputs), + ...Object.values(storageDepConsumedOutputs), + ]); + + const essence = packEssence( + inputs, + inputsCommitment, + [...sourceOutputs, ...storageDepOutputs], + this, + params, + ); + + const sourceAddress = await this.getAddressDetails(credit.payload.sourceAddress); + const storageDepositAddess = await this.getAddressDetails( + credit.payload.storageDepositSourceAddress, + ); + + const sourceUnlocks: UnlockTypes[] = Object.keys(sourceOutputs).map((_, i) => + i + ? { type: REFERENCE_UNLOCK_TYPE, reference: 0 } + : createUnlock(essence, sourceAddress.keyPair), + ); + const storageDepositUnlocks: UnlockTypes[] = Object.keys(storageDepConsumedOutputs).map( + (_, i) => + i + ? { type: REFERENCE_UNLOCK_TYPE, reference: sourceUnlocks.length } + : createUnlock(essence, storageDepositAddess.keyPair), + ); + await setConsumedOutputIds( + sourceAddress.bech32, + Object.keys(sourceConsumedOutputs), + Object.keys(sourceConsumedNftOutputs), + ); + await setConsumedOutputIds(storageDepositAddess.bech32, Object.keys(storageDepConsumedOutputs)); + return await submitBlock( + this, + packPayload(essence, [...sourceUnlocks, ...storageDepositUnlocks]), + ); + }; } + +const subtractNativeTokens = (output: IBasicOutput, tokens: NativeToken[] | undefined) => { + if (!output.nativeTokens || !tokens) { + return output.nativeTokens; + } + return cloneDeep(output.nativeTokens || []) + .map((token) => { + const tokenToSubtract = tokens.find((t) => t.id === token.id)?.amount; + if (!tokenToSubtract) { + return token; + } + return { id: token.id, amount: subtractHex(token.amount, tokenToSubtract as string) }; + }) + .filter((nt) => Number(nt.amount) !== 0); +}; diff --git a/packages/functions/src/services/wallet/NativeTokenWallet.ts b/packages/functions/src/services/wallet/NativeTokenWallet.ts index aa112ac307..65ab2138ee 100644 --- a/packages/functions/src/services/wallet/NativeTokenWallet.ts +++ b/packages/functions/src/services/wallet/NativeTokenWallet.ts @@ -19,16 +19,16 @@ import { } from '../../utils/token-minting-utils/foundry.utils'; import { getOwnedTokenTotal } from '../../utils/token-minting-utils/member.utils'; import { getUnclaimedAirdropTotalValue } from '../../utils/token.utils'; -import { SmrParams, SmrWallet } from './SmrWalletService'; +import { AliasWallet } from './AliasWallet'; import { MnemonicService } from './mnemonic'; -import { AliasWallet } from './smr-wallets/AliasWallet'; -import { setConsumedOutputIds } from './wallet'; +import { Wallet, WalletParams } from './wallet'; +import { setConsumedOutputIds } from './wallet.service'; export class NativeTokenWallet { - constructor(private readonly wallet: SmrWallet) {} + constructor(private readonly wallet: Wallet) {} - public mintFoundry = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public mintFoundry = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( diff --git a/packages/functions/src/services/wallet/NftWallet.ts b/packages/functions/src/services/wallet/NftWallet.ts index 025c00bc6b..203f9de27e 100644 --- a/packages/functions/src/services/wallet/NftWallet.ts +++ b/packages/functions/src/services/wallet/NftWallet.ts @@ -50,10 +50,11 @@ import { import { createUnlock } from '../../utils/smr.utils'; import { EMPTY_ALIAS_ID, getAliasBech32Address } from '../../utils/token-minting-utils/alias.utils'; import { awardBadgeToNttMetadata, awardToCollectionMetadata } from '../payment/award/award-service'; -import { SmrParams, SmrWallet } from './SmrWalletService'; +import { AliasWallet } from './AliasWallet'; import { MnemonicService } from './mnemonic'; -import { AliasWallet } from './smr-wallets/AliasWallet'; -import { AddressDetails, setConsumedOutputIds } from './wallet'; +import { Wallet, WalletParams } from './wallet'; +import { AddressDetails, setConsumedOutputIds } from './wallet.service'; + interface MintNftInputParams { readonly aliasOutputId: string; readonly aliasOutput: IAliasOutput; @@ -64,14 +65,14 @@ interface MintNftInputParams { } export class NftWallet { - constructor(private readonly wallet: SmrWallet) {} + constructor(private readonly wallet: Wallet) {} - public mintCollection = async (transaction: Transaction, params: SmrParams) => { + public mintCollection = async (transaction: Transaction, params: WalletParams) => { const sourceIsGov = !transaction.payload.aliasGovAddress || transaction.payload.aliasGovAddress === transaction.payload.sourceAddress; - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -159,8 +160,8 @@ export class NftWallet { return { immutableMetadata: JSON.stringify(collectionMetadata), mutableMetadata: '' }; }; - public mintAwardCollection = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public mintAwardCollection = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -217,8 +218,8 @@ export class NftWallet { return await submitBlock(this.wallet, packPayload(essence, unlocks)); }; - public mintNfts = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public mintNfts = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -317,8 +318,8 @@ export class NftWallet { return await this.wallet.client.blockSubmit(block); }; - public mintNtt = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public mintNtt = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -389,12 +390,12 @@ export class NftWallet { return await this.wallet.client.blockSubmit(block); }; - public mintMetadataNft = async (transaction: Transaction, params: SmrParams) => { + public mintMetadataNft = async (transaction: Transaction, params: WalletParams) => { const sourceIsGov = !transaction.payload.aliasGovAddress || transaction.payload.aliasGovAddress === transaction.payload.sourceAddress; - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -406,7 +407,7 @@ export class NftWallet { const indexer = new IndexerPluginClient(this.wallet.client); const aliasGovAddress = await this.wallet.getAddressDetails( - transaction.payload.aliasGovAddress, + transaction.payload.aliasGovAddress!, ); const aliasGovMnemonic = sourceIsGov ? sourceMnemonic @@ -488,12 +489,12 @@ export class NftWallet { return await submitBlock(this.wallet, packPayload(essence, unlocks)); }; - public updateMetadataNft = async (transaction: Transaction, params: SmrParams) => { + public updateMetadataNft = async (transaction: Transaction, params: WalletParams) => { const sourceIsGov = !transaction.payload.aliasGovAddress || transaction.payload.aliasGovAddress === transaction.payload.sourceAddress; - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const outputsMap = await this.wallet.getOutputs( @@ -506,7 +507,7 @@ export class NftWallet { const indexer = new IndexerPluginClient(this.wallet.client); const aliasGovAddress = await this.wallet.getAddressDetails( - transaction.payload.aliasGovAddress, + transaction.payload.aliasGovAddress!, ); const aliasGovMnemonic = sourceIsGov ? sourceMnemonic @@ -602,7 +603,7 @@ export class NftWallet { address: AddressDetails, input: MintNftInputParams, nftOutputs: INftOutput[], - params: SmrParams, + params: WalletParams, ) => { const inputs = [input.aliasOutputId, input.collectionOutputId, ...input.consumedOutputIds].map( TransactionHelper.inputFromOutputId, @@ -663,7 +664,7 @@ export class NftWallet { return createNftOutput(ownerAddress, issuerAddress, metadata, this.wallet.info); }; - public changeNftOwner = async (transaction: Transaction, params: SmrParams) => { + public changeNftOwner = async (transaction: Transaction, params: WalletParams) => { const sourceMnemonic = await MnemonicService.getData(transaction.payload.sourceAddress); const nftOutputs = await this.getNftOutputs( transaction.payload.nftId || undefined, @@ -673,7 +674,7 @@ export class NftWallet { const nftOutput = Object.values(nftOutputs)[0]; - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const targetAddress = Bech32Helper.addressFromBech32( transaction.payload.targetAddress!, this.wallet.info.protocol.bech32Hrp, @@ -705,8 +706,8 @@ export class NftWallet { ); }; - public lockCollection = async (transaction: Transaction, params: SmrParams) => { - const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress); + public lockCollection = async (transaction: Transaction, params: WalletParams) => { + const sourceAddress = await this.wallet.getAddressDetails(transaction.payload.sourceAddress!); const sourceMnemonic = await MnemonicService.getData(sourceAddress.bech32); const aliasWallet = new AliasWallet(this.wallet); @@ -782,7 +783,7 @@ export class NftWallet { }; } -const getNftMintingAddress = (nfts: Nft[], wallet: SmrWallet) => { +const getNftMintingAddress = (nfts: Nft[], wallet: Wallet) => { const promises = nfts.map(async (nft) => nft.mintingData?.address ? await wallet.getAddressDetails(nft.mintingData?.address) diff --git a/packages/functions/src/services/wallet/SmrWalletService.ts b/packages/functions/src/services/wallet/SmrWalletService.ts index 0b0100c662..69d8a10943 100644 --- a/packages/functions/src/services/wallet/SmrWalletService.ts +++ b/packages/functions/src/services/wallet/SmrWalletService.ts @@ -1,415 +1,3 @@ -import { NativeToken, Network, Timestamp, Transaction } from '@build-5/interfaces'; -import { Bip32Path } from '@iota/crypto.js-next'; -import { - ADDRESS_UNLOCK_CONDITION_TYPE, - BASIC_OUTPUT_TYPE, - Bech32Helper, - ED25519_ADDRESS_TYPE, - Ed25519Address, - Ed25519Seed, - IAliasOutput, - IBasicOutput, - IFoundryOutput, - INftOutput, - INodeInfo, - IndexerPluginClient, - REFERENCE_UNLOCK_TYPE, - SingleNodeClient, - TransactionHelper, - UnlockTypes, - addressBalance, -} from '@iota/iota.js-next'; -import { Converter, HexHelper } from '@iota/util.js-next'; -import bigInt from 'big-integer'; -import { generateMnemonic } from 'bip39'; -import * as functions from 'firebase-functions/v2'; -import { cloneDeep, head, isEmpty } from 'lodash'; -import { mergeOutputs, packBasicOutput, subtractHex } from '../../utils/basic-output.utils'; -import { Bech32AddressHelper } from '../../utils/bech32-address.helper'; -import { packEssence, packPayload, submitBlock } from '../../utils/block.utils'; -import { getRandomElement } from '../../utils/common.utils'; -import { createUnlock } from '../../utils/smr.utils'; -import { NftWallet } from './NftWallet'; -import { MnemonicService } from './mnemonic'; -import { AddressDetails, Wallet, WalletParams, setConsumedOutputIds } from './wallet'; -const RMS_API_ENDPOINTS = ['https://rms1.svrs.io/']; +import { IotaWallet } from './IotaWalletService'; -const SMR_API_ENDPOINTS = ['https://smr1.svrs.io/', 'https://smr3.svrs.io/']; - -export const getEndpointUrl = (network: Network) => { - const urls = network === Network.SMR ? SMR_API_ENDPOINTS : RMS_API_ENDPOINTS; - return getRandomElement(urls); -}; - -export interface Expiration { - readonly expiresAt: Timestamp; - readonly returnAddressBech32: string; -} - -export interface SmrParams extends WalletParams { - readonly storageDepositSourceAddress?: string; - readonly nativeTokens?: NativeToken[]; - readonly storageDepositReturnAddress?: string; - readonly vestingAt?: Timestamp; - readonly expiration?: Expiration; - readonly customMetadata?: Record; - readonly tag?: string; -} - -export const getShimmerClient = async (network: Network) => { - let url = ''; - for (let i = 0; i < 5; ++i) { - url = getEndpointUrl(network); - try { - const client = new SingleNodeClient(url); - const healty = await client.health(); - if (healty) { - return { client, info: await client.info() }; - } - } catch (error) { - functions.logger.warn(`Could not connect to client ${network}`, url, error); - } - await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 1000 + 500))); - } - functions.logger.error(`Could not connect to client ${network}`, url); - throw Error(`Could not connect to any client ${network}`); -}; - -export class SmrWallet implements Wallet { - constructor( - public readonly client: SingleNodeClient, - public readonly info: INodeInfo, - private readonly network: Network, - ) {} - - public getBalance = async (addressBech32: string | undefined) => { - if (!addressBech32) { - return 0; - } - const balance = await addressBalance(this.client, addressBech32); - return Number(balance.balance); - }; - - public getNewIotaAddressDetails = async (saveMnemonic = true) => { - const address = await this.getIotaAddressDetails(generateMnemonic() + ' ' + generateMnemonic()); - saveMnemonic && (await MnemonicService.store(address.bech32, address.mnemonic, this.network)); - return address; - }; - - public getIotaAddressDetails = async (mnemonic: string): Promise => { - const walletSeed = Ed25519Seed.fromMnemonic(mnemonic); - const walletPath = new Bip32Path("m/44'/4218'/0'/0'/0'"); - const walletAddressSeed = walletSeed.generateSeedFromPath(walletPath); - const keyPair = walletAddressSeed.keyPair(); - const walletEd25519Address = new Ed25519Address(keyPair.publicKey); - const walletAddress = walletEd25519Address.toAddress(); - const hex = Converter.bytesToHex(walletAddress, true); - const bech32 = Bech32Helper.toBech32( - ED25519_ADDRESS_TYPE, - walletAddress, - this.info.protocol.bech32Hrp, - ); - - return { mnemonic, keyPair, hex, bech32 }; - }; - - public getAddressDetails = async (bech32: string | undefined) => { - const mnemonic = await MnemonicService.get(bech32 || ''); - return this.getIotaAddressDetails(mnemonic); - }; - - public getTransactionOutput = async (transactionId: string, outputIndex: number) => { - const outputId = TransactionHelper.outputIdFromTransactionData(transactionId, outputIndex); - return await this.client.output(outputId); - }; - - public bechAddressFromOutput = async ( - output: IBasicOutput | IAliasOutput | IFoundryOutput | INftOutput, - ) => { - const hrp = this.info.protocol.bech32Hrp!; - return Bech32AddressHelper.addressFromAddressUnlockCondition( - output.unlockConditions, - hrp, - output.type, - ); - }; - - public getOutputs = async ( - addressBech32: string, - previouslyConsumedOutputIds: string[] = [], - hasStorageDepositReturn: boolean | undefined, - hasTimelock = false, - ) => { - const indexer = new IndexerPluginClient(this.client); - const query = { - addressBech32, - hasStorageDepositReturn, - hasTimelock, - }; - const outputIds = isEmpty(previouslyConsumedOutputIds) - ? (await indexer.basicOutputs(query)).items - : previouslyConsumedOutputIds; - const outputs: { [key: string]: IBasicOutput } = {}; - for (const id of outputIds) { - const output = (await this.client.output(id)).output; - if (output.type === BASIC_OUTPUT_TYPE) { - outputs[id] = output; - } - } - return outputs; - }; - - public send = async ( - from: AddressDetails, - toBech32: string, - amount: number, - params: SmrParams, - outputToConsume?: string, - ) => { - const prevConsumedOutputIds = outputToConsume - ? [outputToConsume] - : (await MnemonicService.getData(from.bech32)).consumedOutputIds; - const outputsMap = await this.getOutputs(from.bech32, prevConsumedOutputIds, false); - const output = packBasicOutput( - toBech32, - amount, - params.nativeTokens, - this.info, - params.storageDepositReturnAddress, - params.vestingAt, - params.expiration, - params.customMetadata, - params.tag, - ); - - const remainders: IBasicOutput[] = []; - - let storageDepositOutputMap: { [key: string]: IBasicOutput } = {}; - if (params.storageDepositSourceAddress) { - const previouslyConsumedOutputIds = - (await MnemonicService.getData(params.storageDepositSourceAddress)).consumedOutputIds || []; - storageDepositOutputMap = await this.getOutputs( - params.storageDepositSourceAddress, - previouslyConsumedOutputIds, - false, - ); - const remainder = mergeOutputs(cloneDeep(Object.values(storageDepositOutputMap))); - remainder.amount = (Number(remainder.amount) - Number(output.amount)).toString(); - if (Number(remainder.amount)) { - remainders.push(remainder); - } - } - const remainder = mergeOutputs(cloneDeep(Object.values(outputsMap))); - remainder.nativeTokens = subtractNativeTokens(remainder, params.nativeTokens); - if (!params.storageDepositSourceAddress) { - remainder.amount = (Number(remainder.amount) - Number(output.amount)).toString(); - } - if (!isEmpty(remainder.nativeTokens) || Number(remainder.amount) > 0) { - remainders.push(remainder); - } - - const inputs = [...Object.keys(outputsMap), ...Object.keys(storageDepositOutputMap)].map( - TransactionHelper.inputFromOutputId, - ); - const inputsCommitment = TransactionHelper.getInputsCommitment([ - ...Object.values(outputsMap), - ...Object.values(storageDepositOutputMap), - ]); - - const essence = packEssence(inputs, inputsCommitment, [output, ...remainders], this, params); - const unlocks: UnlockTypes[] = Object.values(outputsMap).map((_, index) => - !index ? createUnlock(essence, from.keyPair) : { type: REFERENCE_UNLOCK_TYPE, reference: 0 }, - ); - if (params.storageDepositSourceAddress) { - const address = await this.getAddressDetails(params.storageDepositSourceAddress); - const storageDepUnlocks: UnlockTypes[] = Object.values(storageDepositOutputMap).map( - (_, index) => - !index - ? createUnlock(essence, address.keyPair) - : { type: REFERENCE_UNLOCK_TYPE, reference: unlocks.length }, - ); - unlocks.push(...storageDepUnlocks); - } - - if (!outputToConsume) { - await setConsumedOutputIds(from.bech32, Object.keys(outputsMap)); - if (params.storageDepositSourceAddress) { - await setConsumedOutputIds( - params.storageDepositSourceAddress, - Object.keys(storageDepositOutputMap), - ); - } - } - return await submitBlock(this, packPayload(essence, unlocks)); - }; - - public sendToMany = async ( - from: AddressDetails, - targets: { - toAddress: string; - amount: number; - nativeTokens?: NativeToken[]; - customMetadata?: Record; - }[], - params: SmrParams, - ) => { - const outputsMap = await this.getOutputs(from.bech32, [], false); - const mergedConsumedOutput = mergeOutputs(Object.values(cloneDeep(outputsMap))); - - const outputs = targets.map((target) => - packBasicOutput( - target.toAddress, - target.amount, - target.nativeTokens, - this.info, - undefined, - undefined, - undefined, - target.customMetadata, - ), - ); - const mergedOutputs = mergeOutputs(Object.values(cloneDeep(outputs))); - - const remainderAmount = Number(mergedConsumedOutput.amount) - Number(mergedOutputs.amount); - const remainderNativeTokenAmount = - Number(head(mergedConsumedOutput.nativeTokens)?.amount || 0) - - Number(head(mergedOutputs.nativeTokens)?.amount || 0); - - const remainderNativeTokens = remainderNativeTokenAmount - ? [ - { - id: mergedConsumedOutput.nativeTokens![0].id, - amount: HexHelper.fromBigInt256(bigInt(remainderNativeTokenAmount)), - }, - ] - : []; - - const remainder = packBasicOutput( - from.bech32, - remainderAmount, - remainderNativeTokens, - this.info, - ); - - const inputs = Object.keys(outputsMap).map(TransactionHelper.inputFromOutputId); - const inputsCommitment = TransactionHelper.getInputsCommitment(Object.values(outputsMap)); - - const essence = packEssence( - inputs, - inputsCommitment, - remainderAmount > 0 ? [...outputs, remainder] : outputs, - this, - params, - ); - const unlocks: UnlockTypes[] = Object.values(outputsMap).map((_, index) => - !index ? createUnlock(essence, from.keyPair) : { type: REFERENCE_UNLOCK_TYPE, reference: 0 }, - ); - await setConsumedOutputIds(from.bech32, Object.keys(outputsMap)); - return await submitBlock(this, packPayload(essence, unlocks)); - }; - - public creditLocked = async (credit: Transaction, params: SmrParams) => { - const mnemonicData = await MnemonicService.getData(credit.payload.sourceAddress!); - const prevSourceConsumedOutputIds = mnemonicData.consumedOutputIds || []; - const sourceConsumedOutputs = await this.getOutputs( - credit.payload.sourceAddress!, - prevSourceConsumedOutputIds, - true, - ); - - const sourceBasicOutputs = Object.values(sourceConsumedOutputs).map((o) => - packBasicOutput(credit.payload.targetAddress!, Number(o.amount), o.nativeTokens, this.info), - ); - - const nftWallet = new NftWallet(this); - const sourceConsumedNftOutputs = await nftWallet.getNftOutputs( - undefined, - credit.payload.sourceAddress, - mnemonicData.consumedNftOutputIds, - ); - const targetAddress = Bech32Helper.addressFromBech32( - credit.payload.targetAddress!, - this.info.protocol.bech32Hrp, - ); - const sourceNftOutputs = Object.values(sourceConsumedNftOutputs).map((nftOutput) => { - const output = cloneDeep(nftOutput); - output.unlockConditions = [{ type: ADDRESS_UNLOCK_CONDITION_TYPE, address: targetAddress }]; - return output; - }); - - const sourceOutputs = [...sourceBasicOutputs, ...sourceNftOutputs]; - - const prevStorageDepConsumedOutputIds = - (await MnemonicService.getData(credit.payload.storageDepositSourceAddress!)) - .consumedOutputIds || []; - const storageDepConsumedOutputs = await this.getOutputs( - credit.payload.storageDepositSourceAddress!, - prevStorageDepConsumedOutputIds, - false, - ); - const storageDepOutputs = Object.values(storageDepConsumedOutputs).map((o) => - packBasicOutput(credit.payload.targetAddress!, Number(o.amount), o.nativeTokens, this.info), - ); - - const inputs = [ - ...Object.keys(sourceConsumedOutputs), - ...Object.keys(sourceConsumedNftOutputs), - ...Object.keys(storageDepConsumedOutputs), - ].map(TransactionHelper.inputFromOutputId); - const inputsCommitment = TransactionHelper.getInputsCommitment([ - ...Object.values(sourceConsumedOutputs), - ...Object.values(sourceConsumedNftOutputs), - ...Object.values(storageDepConsumedOutputs), - ]); - - const essence = packEssence( - inputs, - inputsCommitment, - [...sourceOutputs, ...storageDepOutputs], - this, - params, - ); - - const sourceAddress = await this.getAddressDetails(credit.payload.sourceAddress); - const storageDepositAddess = await this.getAddressDetails( - credit.payload.storageDepositSourceAddress, - ); - - const sourceUnlocks: UnlockTypes[] = Object.keys(sourceOutputs).map((_, i) => - i - ? { type: REFERENCE_UNLOCK_TYPE, reference: 0 } - : createUnlock(essence, sourceAddress.keyPair), - ); - const storageDepositUnlocks: UnlockTypes[] = Object.keys(storageDepConsumedOutputs).map( - (_, i) => - i - ? { type: REFERENCE_UNLOCK_TYPE, reference: sourceUnlocks.length } - : createUnlock(essence, storageDepositAddess.keyPair), - ); - await setConsumedOutputIds( - sourceAddress.bech32, - Object.keys(sourceConsumedOutputs), - Object.keys(sourceConsumedNftOutputs), - ); - await setConsumedOutputIds(storageDepositAddess.bech32, Object.keys(storageDepConsumedOutputs)); - return await submitBlock( - this, - packPayload(essence, [...sourceUnlocks, ...storageDepositUnlocks]), - ); - }; -} - -const subtractNativeTokens = (output: IBasicOutput, tokens: NativeToken[] | undefined) => { - if (!output.nativeTokens || !tokens) { - return output.nativeTokens; - } - return cloneDeep(output.nativeTokens || []) - .map((token) => { - const tokenToSubtract = tokens.find((t) => t.id === token.id)?.amount; - if (!tokenToSubtract) { - return token; - } - return { id: token.id, amount: subtractHex(token.amount, tokenToSubtract as string) }; - }) - .filter((nt) => Number(nt.amount) !== 0); -}; +export class SmrWallet extends IotaWallet {} diff --git a/packages/functions/src/services/wallet/wallet.service.ts b/packages/functions/src/services/wallet/wallet.service.ts new file mode 100644 index 0000000000..4079ce8caf --- /dev/null +++ b/packages/functions/src/services/wallet/wallet.service.ts @@ -0,0 +1,89 @@ +import { COL, DEFAULT_NETWORK, NativeToken, Network } from '@build-5/interfaces'; +import { SingleNodeClient } from '@iota/iota.js-next'; +import * as functions from 'firebase-functions/v2'; +import { build5Db } from '../../firebase/firestore/build5Db'; +import { getRandomElement } from '../../utils/common.utils'; +import { IotaWallet } from './IotaWalletService'; +import { SmrWallet } from './SmrWalletService'; +import { Wallet } from './wallet'; + +export interface IKeyPair { + publicKey: Uint8Array; + privateKey: Uint8Array; +} + +export interface AddressDetails { + bech32: string; + keyPair: IKeyPair; + hex: string; + mnemonic: string; +} + +export interface SendToManyTargets { + toAddress: string; + amount: number; + customMetadata?: Record; + nativeTokens?: NativeToken[]; +} + +// TODO set IOTA to correct node +const NODES = { + [Network.SMR]: ['https://smr1.svrs.io/', 'https://smr3.svrs.io/'], + [Network.RMS]: ['https://rms1.svrs.io/'], + // [Network.IOTA]: [ + // 'https://us3.svrs.io/', + // 'https://us4.svrs.io/', + // 'https://hs5.svrs.io/', + // 'https://hs6.svrs.io/', + // 'https://chrysalis-nodes.iota.org', + // ], + // [Network.ATOI]: ['https://devnet.svrs.io/'], + [Network.IOTA]: ['https://smr1.svrs.io/', 'https://smr3.svrs.io/'], + [Network.ATOI]: ['https://rms1.svrs.io/'], +}; + +const getClient = async (network: Network) => { + let nodeUrl = ''; + for (let i = 0; i < 5; ++i) { + nodeUrl = getRandomElement(NODES[network]); + try { + const client = new SingleNodeClient(nodeUrl); + const healty = await client.health(); + if (healty) { + return { client, info: await client.info() }; + } + } catch (error) { + functions.logger.warn(`Could not connect to client ${network}`, nodeUrl, error); + } + await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 1000 + 500))); + } + functions.logger.error(`Could not connect to client ${network}`, nodeUrl); + throw Error(`Could not connect to any client ${network}`); +}; + +const wallets: { [network: string]: Wallet } = {}; + +export class WalletService { + public static newWallet = async (network = DEFAULT_NETWORK): Promise => { + const { client, info } = await getClient(network); + if (wallets[network]) { + return wallets[network]; + } + if ([Network.ATOI, Network.IOTA].includes(network)) { + wallets[network] = new IotaWallet(client, info, network); + } else if ([Network.RMS, Network.SMR].includes(network)) { + wallets[network] = new SmrWallet(client, info, network); + } + return wallets[network]; + }; +} + +export const setConsumedOutputIds = ( + address: string, + consumedOutputIds: string[] = [], + consumedNftOutputIds: string[] = [], + consumedAliasOutputIds: string[] = [], +) => + build5Db() + .doc(`${COL.MNEMONIC}/${address}`) + .update({ consumedOutputIds, consumedNftOutputIds, consumedAliasOutputIds }); diff --git a/packages/functions/src/services/wallet/wallet.ts b/packages/functions/src/services/wallet/wallet.ts index 6dbb3bdeab..7786b75f88 100644 --- a/packages/functions/src/services/wallet/wallet.ts +++ b/packages/functions/src/services/wallet/wallet.ts @@ -1,67 +1,64 @@ -import { COL, DEFAULT_NETWORK, Network } from '@build-5/interfaces'; -import { build5Db } from '../../firebase/firestore/build5Db'; -import { IotaWallet, getIotaClient } from './IotaWalletService'; -import { SmrWallet, getShimmerClient } from './SmrWalletService'; - -export interface IKeyPair { - publicKey: Uint8Array; - privateKey: Uint8Array; -} - -export interface AddressDetails { - bech32: string; - keyPair: IKeyPair; - hex: string; - mnemonic: string; -} +import { NativeToken, Network, Timestamp, Transaction } from '@build-5/interfaces'; +import { + IAliasOutput, + IBasicOutput, + IFoundryOutput, + INftOutput, + INodeInfo, + IOutputResponse, + SingleNodeClient, +} from '@iota/iota.js-next'; +import { Expiration } from './IotaWalletService'; +import { AddressDetails, SendToManyTargets } from './wallet.service'; export interface WalletParams { readonly data?: string; + readonly storageDepositSourceAddress?: string; + readonly nativeTokens?: NativeToken[]; + readonly storageDepositReturnAddress?: string; + readonly vestingAt?: Timestamp | null; + readonly expiration?: Expiration; + readonly customMetadata?: Record; + readonly tag?: string; } -export interface SendToManyTargets { - toAddress: string; - amount: number; - customMetadata?: Record; -} - -export interface Wallet { - getBalance: (addressBech32: string) => Promise; - getNewIotaAddressDetails: () => Promise; - getIotaAddressDetails: (mnemonic: string) => Promise; - getAddressDetails: (bech32: string) => Promise; - send: ( - fromAddress: AddressDetails, +export abstract class Wallet { + public abstract getBalance: (addressBech32: string) => Promise; + public abstract getNewIotaAddressDetails: (saveMnemonic?: boolean) => Promise; + public abstract getIotaAddressDetails: (mnemonic: string) => Promise; + public abstract getAddressDetails: (bech32: string) => Promise; + public abstract send: ( + from: AddressDetails, toAddress: string, amount: number, - params: T, + params: WalletParams, + outputToConsume?: string | undefined, ) => Promise; - sendToMany: (from: AddressDetails, targets: SendToManyTargets[], params: T) => Promise; -} + public abstract sendToMany: ( + from: AddressDetails, + targets: SendToManyTargets[], + params: WalletParams, + ) => Promise; + public abstract bechAddressFromOutput: ( + output: IBasicOutput | IAliasOutput | IFoundryOutput | INftOutput, + ) => string; + public abstract getOutputs: ( + addressBech32: string, + previouslyConsumedOutputIds?: string[], + hasStorageDepositReturn?: boolean, + hasTimelock?: boolean, + ) => Promise<{ + [key: string]: IBasicOutput; + }>; + public abstract creditLocked: (credit: Transaction, params: WalletParams) => Promise; + public abstract getTransactionOutput: ( + transactionId: string, + outputIndex: number, + ) => Promise; -export class WalletService { - public static newWallet = async (network = DEFAULT_NETWORK) => { - switch (network) { - case Network.IOTA: - case Network.ATOI: { - const { client, info } = await getIotaClient(network); - return new IotaWallet(client, info, network); - } - case Network.SMR: - case Network.RMS: { - const { client, info } = await getShimmerClient(network); - return new SmrWallet(client, info, network); - } - } - }; + constructor( + public readonly client: SingleNodeClient, + public readonly info: INodeInfo, + public readonly network: Network, + ) {} } - -export const setConsumedOutputIds = ( - address: string, - consumedOutputIds: string[] = [], - consumedNftOutputIds: string[] = [], - consumedAliasOutputIds: string[] = [], -) => - build5Db() - .doc(`${COL.MNEMONIC}/${address}`) - .update({ consumedOutputIds, consumedNftOutputIds, consumedAliasOutputIds }); diff --git a/packages/functions/src/triggers/milestone-transactions-triggers/MilestoneTransactionAdapter.ts b/packages/functions/src/triggers/milestone-transactions-triggers/MilestoneTransactionAdapter.ts new file mode 100644 index 0000000000..aabfd550d7 --- /dev/null +++ b/packages/functions/src/triggers/milestone-transactions-triggers/MilestoneTransactionAdapter.ts @@ -0,0 +1,99 @@ +import { + MilestoneTransaction, + MilestoneTransactionEntry, + Network, + Timestamp, +} from '@build-5/interfaces'; +import { + BASIC_OUTPUT_TYPE, + Bech32Helper, + ED25519_ADDRESS_TYPE, + Ed25519Address, + IBasicOutput, + INftOutput, + ISignatureUnlock, + ITransactionPayload, + NFT_OUTPUT_TYPE, + SIGNATURE_UNLOCK_TYPE, + TransactionHelper, +} from '@iota/iota.js-next'; +import { Converter, HexHelper } from '@iota/util.js-next'; +import { WalletService } from '../../services/wallet/wallet.service'; +import { indexToString } from '../../utils/block.utils'; +import { getTransactionPayloadHex } from '../../utils/smr.utils'; +import { getMilestoneTransactionId } from './common'; + +const VALID_OUTPUTS_TYPES = [BASIC_OUTPUT_TYPE, NFT_OUTPUT_TYPE]; +type VALID_OUTPUT = IBasicOutput | INftOutput; + +export class MilestoneTransactionAdapter { + constructor(private readonly network: Network) {} + + public toMilestoneTransaction = async ( + data: Record, + ): Promise => { + const wallet = await WalletService.newWallet(this.network); + const payload = data.payload as ITransactionPayload; + const outputs = payload.essence.outputs + .filter((o) => VALID_OUTPUTS_TYPES.includes(o.type)) + .map((o) => o); + + const entries: MilestoneTransactionEntry[] = []; + for (let i = 0; i < outputs.length; ++i) { + if (!VALID_OUTPUTS_TYPES.includes(outputs[i].type)) { + continue; + } + const output = outputs[i]; + const address = wallet.bechAddressFromOutput(output); + const entry: MilestoneTransactionEntry = { + amount: Number(output.amount), + address, + nativeTokens: output.nativeTokens || [], + unlockConditions: output.unlockConditions, + outputId: getTransactionPayloadHex(payload) + indexToString(i), + }; + if (output.type === NFT_OUTPUT_TYPE) { + entry.nftOutput = output; + } else if (output.type === BASIC_OUTPUT_TYPE) { + entry.output = output; + } + entries.push(entry); + } + + const fromAddresses: string[] = []; + const unlocks = payload.unlocks.filter((u) => u.type === SIGNATURE_UNLOCK_TYPE); + for (const signatureUnlock of unlocks) { + const senderPublicKey = (signatureUnlock).signature.publicKey; + const pubKeyBytes = Converter.hexToBytes(HexHelper.stripPrefix(senderPublicKey)); + const walletEd25519Address = new Ed25519Address(pubKeyBytes); + const walletAddress = walletEd25519Address.toAddress(); + const senderBech32 = Bech32Helper.toBech32( + ED25519_ADDRESS_TYPE, + walletAddress, + wallet.info.protocol.bech32Hrp, + ); + fromAddresses.push(senderBech32); + } + + const build5TransactionId = await getMilestoneTransactionId(data); + + const consumedOutputIds = payload.essence.inputs.map((input) => + TransactionHelper.outputIdFromTransactionData( + input.transactionId, + input.transactionOutputIndex, + ), + ); + + return { + uid: data.uid as string, + createdOn: data.createdOn as Timestamp, + messageId: data.blockId as string, + milestone: data.milestone as number, + consumedOutputIds, + fromAddresses, + outputs: entries, + processed: data.processed as boolean, + build5TransactionId: build5TransactionId || undefined, + }; + }; +} diff --git a/packages/functions/src/triggers/milestone-transactions-triggers/SmrMilestoneTransactionAdapter.ts b/packages/functions/src/triggers/milestone-transactions-triggers/SmrMilestoneTransactionAdapter.ts deleted file mode 100644 index 5ecb97ccb8..0000000000 --- a/packages/functions/src/triggers/milestone-transactions-triggers/SmrMilestoneTransactionAdapter.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { MilestoneTransaction, MilestoneTransactionEntry, Network } from '@build-5/interfaces'; -import { - BASIC_OUTPUT_TYPE, - Bech32Helper, - ED25519_ADDRESS_TYPE, - Ed25519Address, - IBasicOutput, - INftOutput, - ISignatureUnlock, - IUTXOInput, - NFT_OUTPUT_TYPE, - OutputTypes, - SIGNATURE_UNLOCK_TYPE, - TransactionHelper, - UnlockTypes, -} from '@iota/iota.js-next'; -import { Converter, HexHelper } from '@iota/util.js-next'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; -import { indexToString } from '../../utils/block.utils'; -import { getTransactionPayloadHex } from '../../utils/smr.utils'; -import { getMilestoneTransactionIdForSmr } from './common'; - -const VALID_OUTPUTS_TYPES = [BASIC_OUTPUT_TYPE, NFT_OUTPUT_TYPE]; -type VALID_OUTPUT = IBasicOutput | INftOutput; - -export class SmrMilestoneTransactionAdapter { - constructor(private readonly network: Network) {} - - public toMilestoneTransaction = async ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data: Record, - ): Promise => { - const smrWallet = (await WalletService.newWallet(this.network)) as SmrWallet; - const smrOutputs = (data.payload.essence.outputs as OutputTypes[]) - .filter((o) => VALID_OUTPUTS_TYPES.includes(o.type)) - .map((o) => o); - - const outputs: MilestoneTransactionEntry[] = []; - for (let i = 0; i < smrOutputs.length; ++i) { - if (!VALID_OUTPUTS_TYPES.includes(smrOutputs[i].type)) { - continue; - } - const smrOutput = smrOutputs[i]; - const address = await smrWallet.bechAddressFromOutput(smrOutput); - const output: MilestoneTransactionEntry = { - amount: Number(smrOutput.amount), - address, - nativeTokens: smrOutput.nativeTokens || [], - unlockConditions: smrOutput.unlockConditions, - outputId: getTransactionPayloadHex(data.payload) + indexToString(i), - }; - if (smrOutput.type === NFT_OUTPUT_TYPE) { - output.nftOutput = smrOutput; - } else if (smrOutput.type === BASIC_OUTPUT_TYPE) { - output.output = smrOutput; - } - outputs.push(output); - } - - const inputs: MilestoneTransactionEntry[] = []; - const unlocks = data.payload.unlocks as UnlockTypes[]; - const utxoInputs = data.payload.essence.inputs as IUTXOInput[]; - for (let i = 0; i < utxoInputs.length; ++i) { - const input = utxoInputs[i]; - const output = ( - await smrWallet.getTransactionOutput(input.transactionId, input.transactionOutputIndex) - ).output; - if (!VALID_OUTPUTS_TYPES.includes(output.type)) { - continue; - } - let unlock = unlocks[Math.min(i, unlocks.length - 1)] as UnlockTypes; - while (unlock.type !== SIGNATURE_UNLOCK_TYPE) { - unlock = unlocks[unlock.reference]; - } - const senderPublicKey = (unlock).signature.publicKey; - const pubKeyBytes = Converter.hexToBytes(HexHelper.stripPrefix(senderPublicKey)); - const walletEd25519Address = new Ed25519Address(pubKeyBytes); - const walletAddress = walletEd25519Address.toAddress(); - const senderBech32 = Bech32Helper.toBech32( - ED25519_ADDRESS_TYPE, - walletAddress, - smrWallet.info.protocol.bech32Hrp, - ); - const consumedOutputId = TransactionHelper.outputIdFromTransactionData( - input.transactionId, - input.transactionOutputIndex, - ); - inputs.push({ - amount: Number(output.amount), - address: senderBech32, - outputId: consumedOutputId, - }); - } - - const build5TransactionId = await getMilestoneTransactionIdForSmr(data); - - return { - uid: data.uid, - createdOn: data.createdOn, - messageId: data.blockId, - milestone: data.milestone, - inputs, - outputs, - processed: data.processed, - build5TransactionId: build5TransactionId || undefined, - }; - }; -} diff --git a/packages/functions/src/triggers/milestone-transactions-triggers/common.ts b/packages/functions/src/triggers/milestone-transactions-triggers/common.ts index 7ab285e1a6..52249d7d9a 100644 --- a/packages/functions/src/triggers/milestone-transactions-triggers/common.ts +++ b/packages/functions/src/triggers/milestone-transactions-triggers/common.ts @@ -1,15 +1,11 @@ -import { COL, Network, Transaction, WEN_FUNC_TRIGGER } from '@build-5/interfaces'; -import { ITransactionPayload } from '@iota/iota.js'; -import { ITransactionPayload as ITransactionPayloadNext } from '@iota/iota.js-next'; -import { Converter } from '@iota/util.js'; -import { Converter as ConverterNext } from '@iota/util.js-next'; +import { COL, Transaction, WEN_FUNC_TRIGGER } from '@build-5/interfaces'; +import { ITransactionPayload } from '@iota/iota.js-next'; +import { Converter } from '@iota/util.js-next'; import dayjs from 'dayjs'; import { DocumentOptions } from 'firebase-functions/v2/firestore'; import { isEmpty } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { scale } from '../../scale.settings'; -import { IotaWallet } from '../../services/wallet/IotaWalletService'; -import { WalletService } from '../../services/wallet/wallet'; export const milestoneTriggerConfig = { timeoutSeconds: 300, @@ -19,9 +15,8 @@ export const milestoneTriggerConfig = { export const confirmTransaction = async ( milestoneTransactionPath: string, milestoneTransaction: Record, - network: Network, ) => { - const transactionId = await getMilestoneTransactionId(milestoneTransaction, network); + const transactionId = await getMilestoneTransactionId(milestoneTransaction); if (isEmpty(transactionId)) { return; } @@ -55,39 +50,11 @@ export const unclockMnemonic = async (address: string | undefined) => { }); }; -const getMilestoneTransactionId = (data: Record, network: Network) => { - switch (network) { - case Network.IOTA: - case Network.ATOI: - return getMilestoneTransactionIdForIota(data, network); - default: - return getMilestoneTransactionIdForSmr(data); - } -}; - -export const getMilestoneTransactionIdForSmr = async ( - milestoneTransaction: Record, -) => { +export const getMilestoneTransactionId = async (milestoneTransaction: Record) => { try { - const payload = milestoneTransaction.payload; + const payload = milestoneTransaction.payload; const hexData = payload.essence?.payload?.data || ''; - const metadata = JSON.parse(ConverterNext.hexToUtf8(hexData)); - return (metadata.tranId || '') as string; - } catch (e) { - return ''; - } -}; - -const getMilestoneTransactionIdForIota = async ( - milestoneTransaction: Record, - network: Network, -) => { - try { - const wallet = (await WalletService.newWallet(network)) as IotaWallet; - const messageId = (milestoneTransaction.messageId as string) || ''; - const message = await wallet.client.message(messageId); - const hexData = (message.payload as ITransactionPayload).essence.payload?.data || ''; - const metadata = JSON.parse(Converter.hexToUtf8(hexData) || '{}'); + const metadata = JSON.parse(Converter.hexToUtf8(hexData)); return (metadata.tranId || '') as string; } catch (e) { return ''; diff --git a/packages/functions/src/triggers/milestone-transactions-triggers/iota-milestone-transaction.trigger.ts b/packages/functions/src/triggers/milestone-transactions-triggers/iota-milestone-transaction.trigger.ts deleted file mode 100644 index d0e930aa68..0000000000 --- a/packages/functions/src/triggers/milestone-transactions-triggers/iota-milestone-transaction.trigger.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { COL, Network, SUB_COL } from '@build-5/interfaces'; -import dayjs from 'dayjs'; -import { DocumentSnapshot } from 'firebase-admin/firestore'; -import * as functions from 'firebase-functions/v2'; -import { FirestoreEvent } from 'firebase-functions/v2/firestore'; -import { build5Db } from '../../firebase/firestore/build5Db'; -import { ProcessingService } from '../../services/payment/payment-processing'; -import { confirmTransaction, milestoneTriggerConfig } from './common'; - -const handleMilestoneTransactionWrite = - (network: Network) => - async ( - event: FirestoreEvent< - functions.Change | undefined, - functions.ParamsOf - >, - ) => { - if (!event.data?.after?.data()) { - return; - } - try { - return build5Db().runTransaction(async (transaction) => { - const docRef = build5Db().doc(event.data!.after.ref.path); - const milestoneTransaction = await transaction.get>(docRef); - if (!milestoneTransaction || milestoneTransaction.processed) { - return; - } - await confirmTransaction(event.data!.after.ref.path, milestoneTransaction, network); - - const service = new ProcessingService(transaction); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - await service.processMilestoneTransactions(milestoneTransaction as any); - service.submit(); - - transaction.update(docRef, { processed: true, processedOn: dayjs().toDate() }); - }); - } catch (error) { - functions.logger.error(`${network} transaction error`, event.data!.after.ref.path, error); - } - }; - -export const iotaMilestoneTransactionWrite = functions.firestore.onDocumentWritten( - { - ...milestoneTriggerConfig, - document: `${COL.MILESTONE}/{milestoneId}/${SUB_COL.TRANSACTIONS}/{tranId}`, - }, - handleMilestoneTransactionWrite(Network.IOTA), -); - -export const atoiMilestoneTransactionWrite = functions.firestore.onDocumentWritten( - { - ...milestoneTriggerConfig, - document: `${COL.MILESTONE}_${Network.ATOI}/{milestoneId}/${SUB_COL.TRANSACTIONS}/{tranId}`, - }, - handleMilestoneTransactionWrite(Network.ATOI), -); diff --git a/packages/functions/src/triggers/milestone-transactions-triggers/smr-milestone-transaction.trigger.ts b/packages/functions/src/triggers/milestone-transactions-triggers/milestone-transaction.trigger.ts similarity index 63% rename from packages/functions/src/triggers/milestone-transactions-triggers/smr-milestone-transaction.trigger.ts rename to packages/functions/src/triggers/milestone-transactions-triggers/milestone-transaction.trigger.ts index 022e0b34c2..497a3c36a5 100644 --- a/packages/functions/src/triggers/milestone-transactions-triggers/smr-milestone-transaction.trigger.ts +++ b/packages/functions/src/triggers/milestone-transactions-triggers/milestone-transaction.trigger.ts @@ -1,12 +1,12 @@ -import { COL, Network, SUB_COL } from '@build-5/interfaces'; +import { Network, SUB_COL, getMilestoneCol } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { DocumentSnapshot } from 'firebase-admin/firestore'; import * as functions from 'firebase-functions/v2'; import { FirestoreEvent } from 'firebase-functions/v2/firestore'; import { build5Db } from '../../firebase/firestore/build5Db'; import { ProcessingService } from '../../services/payment/payment-processing'; -import { SmrMilestoneTransactionAdapter } from './SmrMilestoneTransactionAdapter'; -import { confirmTransaction, milestoneTriggerConfig } from './common'; +import { MilestoneTransactionAdapter } from './MilestoneTransactionAdapter'; +import { confirmTransaction } from './common'; import { processConsumedVoteOutputs } from './consumed.vote.outputs'; import { updateTokenSupplyData } from './token.foundry'; @@ -28,9 +28,9 @@ const handleMilestoneTransactionWrite = if (!data || data.processed) { return; } - await confirmTransaction(event.data!.after.ref.path, data, network); + await confirmTransaction(event.data!.after.ref.path, data); await updateTokenSupplyData(data); - const adapter = new SmrMilestoneTransactionAdapter(network); + const adapter = new MilestoneTransactionAdapter(network); const milestoneTransaction = await adapter.toMilestoneTransaction({ ...data, uid: event.params.tranId, @@ -39,10 +39,7 @@ const handleMilestoneTransactionWrite = await service.processMilestoneTransactions(milestoneTransaction); service.submit(); - await processConsumedVoteOutputs( - transaction, - milestoneTransaction.inputs.map((i) => i.outputId!), - ); + await processConsumedVoteOutputs(transaction, milestoneTransaction.consumedOutputIds); return transaction.update(docRef, { processed: true, processedOn: dayjs().toDate() }); }); @@ -51,18 +48,16 @@ const handleMilestoneTransactionWrite = } }; -export const smrMilestoneTransactionWrite = functions.firestore.onDocumentWritten( - { - ...milestoneTriggerConfig, - document: `${COL.MILESTONE}_${Network.SMR}/{milestoneId}/${SUB_COL.TRANSACTIONS}/{tranId}`, - }, - handleMilestoneTransactionWrite(Network.SMR), -); +const getDoc = (network: Network) => + `${getMilestoneCol(network)}/{milestoneId}/${SUB_COL.TRANSACTIONS}/{tranId}`; -export const rmsMilestoneTransactionWrite = functions.firestore.onDocumentWritten( - { - ...milestoneTriggerConfig, - document: `${COL.MILESTONE}_${Network.RMS}/{milestoneId}/${SUB_COL.TRANSACTIONS}/{tranId}`, - }, - handleMilestoneTransactionWrite(Network.RMS), -); +const getHandler = (network: Network) => + functions.firestore.onDocumentWritten( + { document: getDoc(network) }, + handleMilestoneTransactionWrite(network || Network.IOTA), + ); + +export const smrMilestoneTransactionWrite = getHandler(Network.SMR); +export const rmsMilestoneTransactionWrite = getHandler(Network.RMS); +export const iotaMilestoneTransactionWrite = getHandler(Network.IOTA); +export const atoiMilestoneTransactionWrite = getHandler(Network.ATOI); diff --git a/packages/functions/src/triggers/token-trading/match-base-token.ts b/packages/functions/src/triggers/token-trading/match-base-token.ts index b4b0e55806..19493a2d61 100644 --- a/packages/functions/src/triggers/token-trading/match-base-token.ts +++ b/packages/functions/src/triggers/token-trading/match-base-token.ts @@ -18,8 +18,7 @@ import bigDecimal from 'js-big-decimal'; import { isEmpty } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { ITransaction } from '../../firebase/firestore/interfaces'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { getAddress } from '../../utils/address.utils'; import { packBasicOutput } from '../../utils/basic-output.utils'; import { getRoyaltyFees } from '../../utils/royalty.utils'; @@ -145,7 +144,7 @@ const createSmrPayments = async ( tokensToTrade: number, price: number, ): Promise => { - const wallet = (await WalletService.newWallet(buy.sourceNetwork!)) as SmrWallet; + const wallet = await WalletService.newWallet(buy.sourceNetwork!); const tmpAddress = await wallet.getNewIotaAddressDetails(false); const buyOrder = await build5Db() .doc(`${COL.TRANSACTION}/${buy.orderTransactionId}`) diff --git a/packages/functions/src/triggers/token-trading/match-minted-token.ts b/packages/functions/src/triggers/token-trading/match-minted-token.ts index 7fabe64289..91ac499caf 100644 --- a/packages/functions/src/triggers/token-trading/match-minted-token.ts +++ b/packages/functions/src/triggers/token-trading/match-minted-token.ts @@ -17,8 +17,7 @@ import bigInt from 'big-integer'; import bigDecimal from 'js-big-decimal'; import { build5Db } from '../../firebase/firestore/build5Db'; import { ITransaction } from '../../firebase/firestore/interfaces'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { getAddress } from '../../utils/address.utils'; import { packBasicOutput } from '../../utils/basic-output.utils'; import { getRoyaltyFees } from '../../utils/royalty.utils'; @@ -235,7 +234,7 @@ export const matchMintedToken = async ( price: number, triggeredBy: TokenTradeOrderType, ): Promise => { - const wallet = (await WalletService.newWallet(token.mintingData?.network!)) as SmrWallet; + const wallet = await WalletService.newWallet(token.mintingData?.network!); const seller = (await build5Db().doc(`${COL.MEMBER}/${sell.owner}`).get())!; const buyer = (await build5Db().doc(`${COL.MEMBER}/${buy.owner}`).get())!; diff --git a/packages/functions/src/triggers/token.trigger.ts b/packages/functions/src/triggers/token.trigger.ts index d9ec36877c..d4bb5154ee 100644 --- a/packages/functions/src/triggers/token.trigger.ts +++ b/packages/functions/src/triggers/token.trigger.ts @@ -23,7 +23,7 @@ import { isEmpty } from 'lodash'; import { build5Db } from '../firebase/firestore/build5Db'; import { IBatch } from '../firebase/firestore/interfaces'; import { scale } from '../scale.settings'; -import { WalletService } from '../services/wallet/wallet'; +import { WalletService } from '../services/wallet/wallet.service'; import { getAddress } from '../utils/address.utils'; import { downloadMediaAndPackCar, tokenToIpfsMetadata } from '../utils/car.utils'; import { guardedRerun } from '../utils/common.utils'; diff --git a/packages/functions/src/triggers/transaction-trigger/airdrop.claim.ts b/packages/functions/src/triggers/transaction-trigger/airdrop.claim.ts index bbf3814c03..4d029f2836 100644 --- a/packages/functions/src/triggers/transaction-trigger/airdrop.claim.ts +++ b/packages/functions/src/triggers/transaction-trigger/airdrop.claim.ts @@ -20,8 +20,8 @@ import dayjs from 'dayjs'; import { head } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { ITransaction } from '../../firebase/firestore/interfaces'; -import { SmrWallet } from '../../services/wallet/SmrWalletService'; -import { WalletService } from '../../services/wallet/wallet'; +import { Wallet } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { getAddress } from '../../utils/address.utils'; import { dateToTimestamp, serverTime } from '../../utils/dateTime.utils'; import { dropToOutput } from '../../utils/token-minting-utils/member.utils'; @@ -106,7 +106,7 @@ const onMintedAirdropClaim = async (order: Transaction, token: Token) => { const memberDocRef = build5Db().doc(`${COL.MEMBER}/${order.member}`); const member = (await memberDocRef.get())!; - const wallet = (await WalletService.newWallet(token.mintingData?.network!)) as SmrWallet; + const wallet = await WalletService.newWallet(token.mintingData?.network!); let storageDepositUsed = await claimOwnedMintedTokens(order, paymentsId, token, member, wallet); storageDepositUsed += await runInAirdropLoop( @@ -185,7 +185,7 @@ const claimOwnedMintedTokens = ( sourceTransaction: string[], token: Token, member: Member, - wallet: SmrWallet, + wallet: Wallet, ) => build5Db().runTransaction(async (transaction) => { const tokenDocRef = build5Db().doc(`${COL.TOKEN}/${token.uid}`); @@ -234,7 +234,7 @@ const mintedDropToBillPayment = ( token: Token, drop: TokenDrop, member: Member, - wallet: SmrWallet, + wallet: Wallet, ): Transaction => { const memberAddress = getAddress(member, token.mintingData?.network!); const output = dropToOutput(token, drop, memberAddress, wallet.info); diff --git a/packages/functions/src/triggers/transaction-trigger/matadatNft-minting.ts b/packages/functions/src/triggers/transaction-trigger/matadatNft-minting.ts index f69376c169..181b8eb990 100644 --- a/packages/functions/src/triggers/transaction-trigger/matadatNft-minting.ts +++ b/packages/functions/src/triggers/transaction-trigger/matadatNft-minting.ts @@ -20,7 +20,7 @@ import { createMintMetadataCollectionOrder, createMintMetadataNftOrder, } from '../../services/payment/metadataNft-service'; -import { WalletService } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { getAddress } from '../../utils/address.utils'; import { indexToString } from '../../utils/block.utils'; import { dateToTimestamp } from '../../utils/dateTime.utils'; @@ -219,7 +219,7 @@ const onNftUpdated = async (transaction: Transaction) => { }); const wallet = await WalletService.newWallet(transaction.network!); - const balance = await wallet.getBalance(order.payload.targetAddress); + const balance = await wallet.getBalance(order.payload.targetAddress!); const member = await build5Db().doc(`${COL.MEMBER}/${transaction.member}`).get(); const collection = await build5Db().doc(`${COL.COLLECTION}/${nft?.collection}`).get(); diff --git a/packages/functions/src/triggers/transaction-trigger/proposal.vote.ts b/packages/functions/src/triggers/transaction-trigger/proposal.vote.ts index c25d16df5e..5971d7f39c 100644 --- a/packages/functions/src/triggers/transaction-trigger/proposal.vote.ts +++ b/packages/functions/src/triggers/transaction-trigger/proposal.vote.ts @@ -1,12 +1,12 @@ import { COL, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../firebase/firestore/build5Db'; -import { SmrMilestoneTransactionAdapter } from '../milestone-transactions-triggers/SmrMilestoneTransactionAdapter'; +import { MilestoneTransactionAdapter } from '../milestone-transactions-triggers/MilestoneTransactionAdapter'; export const onProposalVoteCreditConfirmed = async (transaction: Transaction) => { const milestoneDoc = (await build5Db() .doc(transaction.payload.walletReference?.milestoneTransactionPath!) .get>())!; - const adapter = new SmrMilestoneTransactionAdapter(transaction.network!); + const adapter = new MilestoneTransactionAdapter(transaction.network!); const milestoneTransaction = await adapter.toMilestoneTransaction(milestoneDoc); const outputId = milestoneTransaction.outputs[0].outputId!; const voteTransactionSnap = await build5Db() diff --git a/packages/functions/src/triggers/transaction-trigger/transaction.trigger.ts b/packages/functions/src/triggers/transaction-trigger/transaction.trigger.ts index c3f20107bf..9fb1b6d971 100644 --- a/packages/functions/src/triggers/transaction-trigger/transaction.trigger.ts +++ b/packages/functions/src/triggers/transaction-trigger/transaction.trigger.ts @@ -18,11 +18,11 @@ import { isEmpty } from 'lodash'; import { build5Db } from '../../firebase/firestore/build5Db'; import { ITransaction } from '../../firebase/firestore/interfaces'; import { scale } from '../../scale.settings'; +import { AliasWallet } from '../../services/wallet/AliasWallet'; import { NativeTokenWallet } from '../../services/wallet/NativeTokenWallet'; import { NftWallet } from '../../services/wallet/NftWallet'; -import { SmrParams, SmrWallet } from '../../services/wallet/SmrWalletService'; -import { AliasWallet } from '../../services/wallet/smr-wallets/AliasWallet'; -import { WalletService } from '../../services/wallet/wallet'; +import { Wallet, WalletParams } from '../../services/wallet/wallet'; +import { WalletService } from '../../services/wallet/wallet.service'; import { getAddress } from '../../utils/address.utils'; import { isEmulatorEnv } from '../../utils/config.utils'; import { serverTime } from '../../utils/dateTime.utils'; @@ -196,17 +196,17 @@ const executeTransaction = async (transactionId: string) => { const transaction = await docRef.get(); const payload = transaction.payload; - const params = await getWalletParams(transaction, transaction.network || DEFAULT_NETWORK); + const params = await getWalletParams(transaction); try { - const walletService = await WalletService.newWallet(transaction.network || DEFAULT_NETWORK); - const sourceAddress = await walletService.getAddressDetails(payload.sourceAddress!); + const wallet = await WalletService.newWallet(transaction.network || DEFAULT_NETWORK); + const sourceAddress = await wallet.getAddressDetails(payload.sourceAddress!); const submit = () => { switch (transaction.type) { case TransactionType.BILL_PAYMENT: case TransactionType.CREDIT: case TransactionType.CREDIT_TANGLE_REQUEST: - return walletService.send( + return wallet.send( sourceAddress, payload.targetAddress!, payload.amount!, @@ -214,28 +214,28 @@ const executeTransaction = async (transactionId: string) => { transaction.payload.outputToConsume, ); case TransactionType.CREDIT_STORAGE_DEPOSIT_LOCKED: - return (walletService as SmrWallet).creditLocked(transaction, params); + return wallet.creditLocked(transaction, params); case TransactionType.MINT_COLLECTION: - return submitCollectionMintTransactions(transaction, walletService as SmrWallet, params); + return submitCollectionMintTransactions(transaction, wallet, params); case TransactionType.MINT_TOKEN: - return submitTokenMintTransactions(transaction, walletService as SmrWallet, params); + return submitTokenMintTransactions(transaction, wallet, params); case TransactionType.AWARD: - return submitCreateAwardTransaction(transaction, walletService as SmrWallet, params); + return submitCreateAwardTransaction(transaction, wallet, params); case TransactionType.METADATA_NFT: - return submitMintMetadataTransaction(transaction, walletService as SmrWallet, params); + return submitMintMetadataTransaction(transaction, wallet, params); case TransactionType.CREDIT_NFT: case TransactionType.WITHDRAW_NFT: { - const nftWallet = new NftWallet(walletService as SmrWallet); + const nftWallet = new NftWallet(wallet); return nftWallet.changeNftOwner(transaction, params); } case TransactionType.UNLOCK: { - return submitUnlockTransaction(transaction, walletService as SmrWallet, params); + return submitUnlockTransaction(transaction, wallet, params); } default: { @@ -264,8 +264,8 @@ const executeTransaction = async (transactionId: string) => { const submitCollectionMintTransactions = ( transaction: Transaction, - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { switch (transaction.payload.type) { case TransactionPayloadType.MINT_ALIAS: { @@ -297,8 +297,8 @@ const submitCollectionMintTransactions = ( const submitTokenMintTransactions = ( transaction: Transaction, - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { switch (transaction.payload.type) { case TransactionPayloadType.MINT_ALIAS: { @@ -322,8 +322,8 @@ const submitTokenMintTransactions = ( const submitCreateAwardTransaction = ( transaction: Transaction, - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { switch (transaction.payload.type) { case TransactionPayloadType.MINT_ALIAS: { @@ -354,8 +354,8 @@ const submitCreateAwardTransaction = ( const submitMintMetadataTransaction = async ( transaction: Transaction, - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { switch (transaction.payload.type) { case TransactionPayloadType.MINT_ALIAS: { @@ -386,8 +386,8 @@ const submitMintMetadataTransaction = async ( const submitUnlockTransaction = async ( transaction: Transaction, - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { switch (transaction.payload.type) { case TransactionPayloadType.UNLOCK_FUNDS: diff --git a/packages/functions/src/triggers/transaction-trigger/wallet-params.ts b/packages/functions/src/triggers/transaction-trigger/wallet-params.ts index 38baf0f57e..a904d6cf68 100644 --- a/packages/functions/src/triggers/transaction-trigger/wallet-params.ts +++ b/packages/functions/src/triggers/transaction-trigger/wallet-params.ts @@ -2,7 +2,6 @@ import { COL, IOTATangleTransaction, NativeToken, - Network, Nft, Transaction, TransactionType, @@ -10,19 +9,10 @@ import { import { HexHelper } from '@iota/util.js-next'; import bigInt from 'big-integer'; import { build5Db } from '../../firebase/firestore/build5Db'; +import { WalletParams } from '../../services/wallet/wallet'; import { isProdEnv } from '../../utils/config.utils'; -export const getWalletParams = (transaction: Transaction, network: Network) => { - switch (network) { - case Network.SMR: - case Network.RMS: - return getShimmerParams(transaction); - default: - return getParams(transaction); - } -}; - -const getShimmerParams = async (transaction: Transaction) => ({ +export const getWalletParams = async (transaction: Transaction): Promise => ({ ...(await getParams(transaction)), nativeTokens: transaction.payload.nativeTokens?.map((nt: NativeToken) => ({ id: nt.id, diff --git a/packages/functions/src/utils/basic-output.utils.ts b/packages/functions/src/utils/basic-output.utils.ts index 7088365843..1faeb58ce8 100644 --- a/packages/functions/src/utils/basic-output.utils.ts +++ b/packages/functions/src/utils/basic-output.utils.ts @@ -23,7 +23,7 @@ import { Converter, HexHelper } from '@iota/util.js-next'; import bigInt from 'big-integer'; import dayjs from 'dayjs'; import { cloneDeep, isEmpty } from 'lodash'; -import { Expiration } from '../services/wallet/SmrWalletService'; +import { Expiration } from '../services/wallet/IotaWalletService'; export const hasNoTimeLock = (output: IBasicOutput) => { const locks = output.unlockConditions.filter( @@ -84,7 +84,7 @@ export const packBasicOutput = ( nativeTokens: INativeToken[] | undefined, info: INodeInfo, retrunAddressBech32?: string, - vestingAt?: Timestamp, + vestingAt?: Timestamp | null, expiration?: Expiration, metadata?: Record, tag?: string, diff --git a/packages/functions/src/utils/bech32-address.helper.ts b/packages/functions/src/utils/bech32-address.helper.ts index ab56178353..b923eb39d0 100644 --- a/packages/functions/src/utils/bech32-address.helper.ts +++ b/packages/functions/src/utils/bech32-address.helper.ts @@ -1,8 +1,8 @@ import { - AddressTypes, ADDRESS_UNLOCK_CONDITION_TYPE, ALIAS_ADDRESS_TYPE, ALIAS_OUTPUT_TYPE, + AddressTypes, BASIC_OUTPUT_TYPE, Bech32Helper, ED25519_ADDRESS_TYPE, diff --git a/packages/functions/src/utils/block.utils.ts b/packages/functions/src/utils/block.utils.ts index 6f11a2737a..604f4bac84 100644 --- a/packages/functions/src/utils/block.utils.ts +++ b/packages/functions/src/utils/block.utils.ts @@ -15,10 +15,10 @@ import { serializeBlock, } from '@iota/iota.js-next'; import { Converter, WriteStream } from '@iota/util.js-next'; -import { SmrParams, SmrWallet } from '../services/wallet/SmrWalletService'; +import { Wallet, WalletParams } from '../services/wallet/wallet'; export const submitBlock = async ( - wallet: SmrWallet, + wallet: Wallet, payload: ITransactionPayload, ): Promise => { const block: IBlock = { @@ -34,8 +34,8 @@ export const packEssence = ( inputs: IUTXOInput[], inputsCommitment: string, outputs: OutputTypes[], - wallet: SmrWallet, - params: SmrParams, + wallet: Wallet, + params: WalletParams, ) => { type: TRANSACTION_ESSENCE_TYPE, diff --git a/packages/functions/src/utils/token-minting-utils/alias.utils.ts b/packages/functions/src/utils/token-minting-utils/alias.utils.ts index d215334504..7b4ff063f2 100644 --- a/packages/functions/src/utils/token-minting-utils/alias.utils.ts +++ b/packages/functions/src/utils/token-minting-utils/alias.utils.ts @@ -9,7 +9,7 @@ import { TransactionHelper, } from '@iota/iota.js-next'; import { Converter, HexHelper } from '@iota/util.js-next'; -import { AddressDetails } from '../../services/wallet/wallet'; +import { AddressDetails } from '../../services/wallet/wallet.service'; import { Bech32AddressHelper } from '../bech32-address.helper'; export const EMPTY_ALIAS_ID = '0x0000000000000000000000000000000000000000000000000000000000000000'; diff --git a/packages/functions/src/utils/wallet.utils.ts b/packages/functions/src/utils/wallet.utils.ts index 5d9ea7d83f..9726ed8460 100644 --- a/packages/functions/src/utils/wallet.utils.ts +++ b/packages/functions/src/utils/wallet.utils.ts @@ -1,22 +1,7 @@ -import { - COL, - DecodedToken, - Member, - Network, - WEN_FUNC, - WenError, - WenRequest, -} from '@build-5/interfaces'; -import { Ed25519 } from '@iota/crypto.js'; -import { Ed25519 as Ed25519Next } from '@iota/crypto.js-next'; -import { Bech32Helper, Ed25519Address } from '@iota/iota.js'; -import { - Bech32Helper as Bech32HelperNext, - ED25519_ADDRESS_TYPE, - Ed25519Address as Ed25519AddressNext, -} from '@iota/iota.js-next'; -import { Converter } from '@iota/util.js'; -import { Converter as ConverterNext, HexHelper } from '@iota/util.js-next'; +import { COL, DecodedToken, Member, WEN_FUNC, WenError, WenRequest } from '@build-5/interfaces'; +import { Ed25519 } from '@iota/crypto.js-next'; +import { Bech32Helper, ED25519_ADDRESS_TYPE, Ed25519Address } from '@iota/iota.js-next'; +import { Converter, HexHelper } from '@iota/util.js-next'; import { recoverPersonalSignature } from '@metamask/eth-sig-util'; import { randomBytes } from 'crypto'; import dayjs from 'dayjs'; @@ -24,6 +9,7 @@ import { Wallet } from 'ethers'; import jwt from 'jsonwebtoken'; import { get } from 'lodash'; import { build5Db } from '../firebase/firestore/build5Db'; +import { WalletService } from '../services/wallet/wallet.service'; import { getCustomTokenLifetime, getJwtSecretKey } from './config.utils'; import { unAuthenticated } from './error.utils'; @@ -78,8 +64,7 @@ const validateWithSignature = async (req: WenRequest) => { const validateWithPublicKey = async (req: WenRequest) => { const network = req.publicKey!.network; - const validateFunc = getValidateFuncForNetwork(network); - const { member, address } = await validateFunc(req); + const { member, address } = await validatePubKey(req); if (!address) { throw unAuthenticated(WenError.failed_to_decode_token); } @@ -95,47 +80,15 @@ const validateWithPublicKey = async (req: WenRequest) => { return address; }; -const getValidateFuncForNetwork = (network: Network) => { - const smrNnetworks = [Network.SMR, Network.RMS]; - if (smrNnetworks.includes(network)) { - return validateSmrPubKey; - } - const iotaNnetworks = [Network.IOTA, Network.ATOI]; - if (iotaNnetworks.includes(network)) { - return validateIotaPubKey; - } - throw unAuthenticated(WenError.invalid_network); -}; - -const validateSmrPubKey = async (req: WenRequest) => { - const signedData = ConverterNext.hexToBytes(HexHelper.stripPrefix(req.signature!)); - const publicKey = ConverterNext.hexToBytes(HexHelper.stripPrefix(req.publicKey?.hex!)); - - const bech32Address = Bech32HelperNext.toBech32( - ED25519_ADDRESS_TYPE, - new Ed25519AddressNext(publicKey).toAddress(), - req.publicKey!.network, - ); - - const member = await getMember(bech32Address); - const unsignedData = ConverterNext.utf8ToBytes(`0x${toHex(member.nonce!)}`); - - const verify = Ed25519Next.verify(publicKey, unsignedData, signedData); - if (!verify) { - throw unAuthenticated(WenError.invalid_signature); - } - - return { member, address: bech32Address }; -}; - -const validateIotaPubKey = async (req: WenRequest) => { +const validatePubKey = async (req: WenRequest) => { const signedData = Converter.hexToBytes(HexHelper.stripPrefix(req.signature!)); const publicKey = Converter.hexToBytes(HexHelper.stripPrefix(req.publicKey?.hex!)); + const wallet = await WalletService.newWallet(req.publicKey!.network); const bech32Address = Bech32Helper.toBech32( ED25519_ADDRESS_TYPE, new Ed25519Address(publicKey).toAddress(), - req.publicKey!.network, + wallet.info.protocol.bech32Hrp, ); const member = await getMember(bech32Address); diff --git a/packages/functions/test-tangle/address.spec.ts b/packages/functions/test-tangle/address.spec.ts index d9cd6fdbd6..5ef4120b7b 100644 --- a/packages/functions/test-tangle/address.spec.ts +++ b/packages/functions/test-tangle/address.spec.ts @@ -15,9 +15,7 @@ import { import dayjs from 'dayjs'; import { isEmpty, set } from 'lodash'; import { build5Db } from '../src/firebase/firestore/build5Db'; -import { IotaWallet } from '../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; -import { WalletService } from '../src/services/wallet/wallet'; +import { WalletService } from '../src/services/wallet/wallet.service'; import { getAddress } from '../src/utils/address.utils'; import { dateToTimestamp } from '../src/utils/dateTime.utils'; import * as wallet from '../src/utils/wallet.utils'; @@ -29,7 +27,7 @@ import { wait, } from '../test/controls/common'; import { getWallet } from '../test/set-up'; -import { getRmsSoonTangleResponse, getTangleOrder } from './common'; +import { getTangleOrder } from './common'; import { requestFundsFromFaucet } from './faucet'; let walletSpy: any; @@ -55,10 +53,6 @@ describe('Address validation', () => { let space: string; let tangleOrder: Transaction; - beforeAll(async () => { - tangleOrder = await getTangleOrder(); - }); - beforeEach(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); member = await createMember(walletSpy); @@ -168,124 +162,58 @@ describe('Address validation', () => { expect(balanace).toBe(order.payload.amount); }); - it.each([false, true])( - 'Should validate rms address with tangle request', - async (validateSpace) => { - const wallet = await WalletService.newWallet(Network.RMS); - const tmp = await wallet.getNewIotaAddressDetails(); + it.each([ + { network: Network.RMS, validateSpace: true }, + { network: Network.RMS, validateSpace: false }, + { network: Network.ATOI, validateSpace: true }, + { network: Network.ATOI, validateSpace: false }, + ])('Should validate address with tangle request', async ({ network, validateSpace }) => { + tangleOrder = await getTangleOrder(network); + const wallet = await WalletService.newWallet(Network.RMS); + const tmp = await wallet.getNewIotaAddressDetails(); + + await build5Db() + .doc(`${COL.MEMBER}/${member}`) + .set({ validatedAddress: { [Network.RMS]: tmp.bech32 } }, true); + + if (validateSpace) { + space = (await createSpace(walletSpy, member)).uid; + await build5Db().doc(`${COL.SPACE}/${space}`).update({ validatedAddress: {} }); + } + await requestFundsFromFaucet(Network.RMS, tmp.bech32, 5 * MIN_IOTA_AMOUNT); + + const request = { + requestType: TangleRequestType.ADDRESS_VALIDATION, + }; + validateSpace && set(request, 'space', space); + await wallet.send(tmp, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { + customMetadata: { request }, + }); - await build5Db() - .doc(`${COL.MEMBER}/${member}`) - .set({ validatedAddress: { [Network.RMS]: tmp.bech32 } }, true); - - if (validateSpace) { - space = (await createSpace(walletSpy, member)).uid; - await build5Db().doc(`${COL.SPACE}/${space}`).update({ validatedAddress: {} }); - } - await requestFundsFromFaucet(Network.RMS, tmp.bech32, 5 * MIN_IOTA_AMOUNT); - - const request = { - requestType: TangleRequestType.ADDRESS_VALIDATION, - }; - validateSpace && set(request, 'space', space); - await wallet.send(tmp, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { request }, - }); - - const query = build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.CREDIT) - .where('member', '==', member); - - await wait(async () => { - const snap = await query.get(); - return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; - }); - - if (validateSpace) { - const spaceData = await build5Db().doc(`${COL.SPACE}/${space}`).get(); - expect(spaceData.validatedAddress![Network.RMS]).toBe(tmp.bech32); - } else { - const memberData = await build5Db().doc(`${COL.MEMBER}/${member}`).get(); - expect(memberData.validatedAddress![Network.RMS]).toBe(tmp.bech32); - expect(memberData.prevValidatedAddresses).toEqual([tmp.bech32]); - } + const query = build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.CREDIT) + .where('member', '==', member); - const snap = await build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', member) - .where('payload.type', '==', TransactionPayloadType.TANGLE_TRANSFER) - .get(); - expect(snap.length).toBe(1); - }, - ); + await wait(async () => { + const snap = await query.get(); + return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; + }); - it.each([false, true])( - 'Should validate atoi address with tangle request', - async (validateSpace) => { - const rmsWallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; - const rmsTmp = await rmsWallet.getNewIotaAddressDetails(); - const atoiWallet = (await WalletService.newWallet(Network.ATOI)) as IotaWallet; - const atoiTmp = await atoiWallet.getNewIotaAddressDetails(); - if (validateSpace) { - space = (await createSpace(walletSpy, member)).uid; - await build5Db().doc(`${COL.SPACE}/${space}`).update({ validatedAddress: {} }); - await build5Db() - .doc(`${COL.MEMBER}/${member}`) - .set({ validatedAddress: { [Network.RMS]: rmsTmp.bech32 } }, true); - } - const memberId = validateSpace ? member : rmsTmp.bech32; - - await requestFundsFromFaucet(Network.RMS, rmsTmp.bech32, 5 * MIN_IOTA_AMOUNT); - await requestFundsFromFaucet(Network.ATOI, atoiTmp.bech32, 5 * MIN_IOTA_AMOUNT); - - const request = { - requestType: TangleRequestType.ADDRESS_VALIDATION, - network: Network.ATOI, - }; - validateSpace && set(request, 'space', space); - await rmsWallet.send(rmsTmp, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { request }, - }); - - let query = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', memberId) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); - await wait(async () => { - const snap = await query.get(); - return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; - }); - let snap = await query.get(); - expect(snap.length).toBe(1); - const response = await getRmsSoonTangleResponse(snap[0], rmsWallet); - await atoiWallet.send(atoiTmp, response.address, response.amount, {}); - - query = build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.CREDIT) - .where('member', '==', memberId); - await wait(async () => { - const snap = await query.get(); - return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; - }); - - if (validateSpace) { - const spaceData = await build5Db().doc(`${COL.SPACE}/${space}`).get(); - expect(spaceData.validatedAddress![Network.ATOI]).toBe(atoiTmp.bech32); - } else { - const member = await build5Db().doc(`${COL.MEMBER}/${memberId}`).get(); - expect(member.validatedAddress![Network.RMS]).toBe(rmsTmp.bech32); - expect(member.validatedAddress![Network.ATOI]).toBe(atoiTmp.bech32); - expect(member.prevValidatedAddresses).toBeUndefined(); - } - - snap = await build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', memberId) - .where('payload.type', '==', TransactionPayloadType.TANGLE_TRANSFER) - .get(); - expect(snap.length).toBe(0); - }, - ); + if (validateSpace) { + const spaceData = await build5Db().doc(`${COL.SPACE}/${space}`).get(); + expect(spaceData.validatedAddress![Network.RMS]).toBe(tmp.bech32); + } else { + const memberData = await build5Db().doc(`${COL.MEMBER}/${member}`).get(); + expect(memberData.validatedAddress![Network.RMS]).toBe(tmp.bech32); + expect(memberData.prevValidatedAddresses).toEqual([tmp.bech32]); + } + + const snap = await build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', member) + .where('payload.type', '==', TransactionPayloadType.TANGLE_TRANSFER) + .get(); + expect(snap.length).toBe(1); + }); }); diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_1.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_1.spec.ts index d6adbd5954..6e7658e536 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_1.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_1.spec.ts @@ -12,8 +12,8 @@ import { } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, wait } from '../../test/controls/common'; @@ -32,14 +32,14 @@ describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); + walletService = await WalletService.newWallet(network); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_2.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_2.spec.ts index 27c10b1e5e..2ed23fdd7b 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_2.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_2.spec.ts @@ -13,8 +13,8 @@ import { import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, wait } from '../../test/controls/common'; @@ -30,14 +30,13 @@ describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { @@ -52,47 +51,51 @@ describe('Award tangle request', () => { guardianAddress = await walletService.getAddressDetails(guardianBech32); }); - it('Should create and fund award with tangle request after create', async () => { - const newAward = awardRequest(space.uid, token.symbol); - await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); - await walletService.send( - guardianAddress, - tangleOrder.payload.targetAddress!, - 5 * MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.AWARD_CREATE, - ...newAward, + it.each([Network.RMS, Network.ATOI])( + 'Should create and fund award with tangle request after create', + async (network: Network) => { + tangleOrder = await getTangleOrder(network); + const newAward = awardRequest(space.uid, token.symbol); + await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); + await walletService.send( + guardianAddress, + tangleOrder.payload.targetAddress!, + 5 * MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.AWARD_CREATE, + ...newAward, + }, }, }, - }, - ); + ); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) - .where('member', '==', guardian); - await wait(async () => { + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) + .where('member', '==', guardian); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1; + }); const snap = await creditQuery.get(); - return snap.length === 1; - }); - const snap = await creditQuery.get(); - const credit = snap[0] as Transaction; - expect(credit.payload.amount).toBe(5 * MIN_IOTA_AMOUNT); + const credit = snap[0] as Transaction; + expect(credit.payload.amount).toBe(5 * MIN_IOTA_AMOUNT); - await requestFundsFromFaucet( - Network.RMS, - credit.payload.response!.address as string, - credit.payload.response!.amount as number, - ); + await requestFundsFromFaucet( + Network.RMS, + credit.payload.response!.address as string, + credit.payload.response!.amount as number, + ); - const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); - await wait(async () => { - const award = (await awardDocRef.get()) as Award; - return award.funded; - }); - }); + const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); + await wait(async () => { + const award = (await awardDocRef.get()) as Award; + return award.funded; + }); + }, + ); it('Should create and fund award with new tangle request', async () => { const newAward = awardRequest(space.uid, token.symbol); diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_3.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_3.spec.ts index a321b1ccd4..07ae647e57 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_3.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_3.spec.ts @@ -17,8 +17,8 @@ import bigInt from 'big-integer'; import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -27,88 +27,90 @@ import { MEDIA } from '../../test/set-up'; import { getTangleOrder } from '../common'; import { requestFundsFromFaucet, requestMintedTokenFromFaucet } from '../faucet'; -const network = Network.RMS; let walletSpy: any; describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; - beforeAll(async () => { - walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); - }); + const beforeEach = async (network: Network) => { + tangleOrder = await getTangleOrder(network); - beforeEach(async () => { + walletSpy = jest.spyOn(wallet, 'decodeAuth'); + walletService = await WalletService.newWallet(network); guardian = await createMember(walletSpy); space = await createSpace(walletSpy, guardian); - token = await saveToken(space.uid, guardian); + token = await saveToken(space.uid, guardian, network); const guardianDocRef = build5Db().doc(`${COL.MEMBER}/${guardian}`); const guardianData = await guardianDocRef.get(); const guardianBech32 = getAddress(guardianData, network); guardianAddress = await walletService.getAddressDetails(guardianBech32); - }); + }; - it('Should create and fund with tangle request', async () => { - const newAward = awardRequest(space.uid, token.symbol); - await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); - await walletService.send(guardianAddress, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.AWARD_CREATE, - ...newAward, + it.each([Network.RMS, Network.ATOI])( + 'Should create and fund with tangle request', + async (network: Network) => { + await beforeEach(network); + + const newAward = awardRequest(space.uid, token.symbol, network); + await requestFundsFromFaucet(network, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); + await walletService.send( + guardianAddress, + tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { request: { requestType: TangleRequestType.AWARD_CREATE, ...newAward } }, }, - }, - }); - await MnemonicService.store(guardianAddress.bech32, guardianAddress.mnemonic); + ); + await MnemonicService.store(guardianAddress.bech32, guardianAddress.mnemonic); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) - .where('member', '==', guardian); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1; - }); - let snap = await creditQuery.get(); - let credit = snap[0] as Transaction; - expect(credit.payload.amount).toBe(MIN_IOTA_AMOUNT); - const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) + .where('member', '==', guardian); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1; + }); + let snap = await creditQuery.get(); + let credit = snap[0] as Transaction; + expect(credit.payload.amount).toBe(MIN_IOTA_AMOUNT); + const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); - await requestMintedTokenFromFaucet( - walletService, - guardianAddress, - MINTED_TOKEN_ID, - VAULT_MNEMONIC, - (credit.payload.response!.nativeTokens! as any)[0].amount, - ); - await walletService.send( - guardianAddress, - credit.payload.response!.address as string, - credit.payload.response!.amount as number, - { - nativeTokens: (credit.payload.response!.nativeTokens as NativeToken[]).map((nt: any) => ({ - ...nt, - amount: HexHelper.fromBigInt256(bigInt(nt.amount)), - })), - }, - ); + await requestMintedTokenFromFaucet( + walletService, + guardianAddress, + MINTED_TOKEN_ID, + VAULT_MNEMONIC, + (credit.payload.response!.nativeTokens! as any)[0].amount, + ); + await walletService.send( + guardianAddress, + credit.payload.response!.address as string, + credit.payload.response!.amount as number, + { + nativeTokens: (credit.payload.response!.nativeTokens as NativeToken[]).map((nt: any) => ({ + ...nt, + amount: HexHelper.fromBigInt256(bigInt(nt.amount)), + })), + }, + ); - await wait(async () => { - const award = (await awardDocRef.get()) as Award; - return award.funded; - }); - }); + await wait(async () => { + const award = (await awardDocRef.get()) as Award; + return award.funded; + }); + }, + ); }); -const awardRequest = (space: string, tokenSymbol: string) => ({ +const awardRequest = (space: string, tokenSymbol: string, network: Network) => ({ name: 'award', description: 'award', space, @@ -125,7 +127,7 @@ const awardRequest = (space: string, tokenSymbol: string) => ({ network, }); -const saveToken = async (space: string, guardian: string) => { +const saveToken = async (space: string, guardian: string, network: Network) => { const token = { symbol: getRandomSymbol(), approved: true, @@ -139,7 +141,7 @@ const saveToken = async (space: string, guardian: string) => { access: 0, icon: MEDIA, mintingData: { - network: Network.RMS, + network, tokenId: MINTED_TOKEN_ID, }, }; diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_4.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_4.spec.ts index f7c4688169..67c536d172 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_4.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_4.spec.ts @@ -14,8 +14,8 @@ import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, wait } from '../../test/controls/common'; @@ -31,14 +31,13 @@ describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { @@ -53,62 +52,79 @@ describe('Award tangle request', () => { guardianAddress = await walletService.getAddressDetails(guardianBech32); }); - it('Should create with tangle request, fund and approve', async () => { - const newAward = awardRequest(space.uid, token.symbol); - await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); - await walletService.send(guardianAddress, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { request: { requestType: TangleRequestType.AWARD_CREATE, ...newAward } }, - }); - await MnemonicService.store(guardianAddress.bech32, guardianAddress.mnemonic); + it.each([Network.RMS, Network.ATOI])( + 'Should create with tangle request, fund and approve', + async (network: Network) => { + tangleOrder = await getTangleOrder(network); + const newAward = awardRequest(space.uid, token.symbol); + await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); + await walletService.send( + guardianAddress, + tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { request: { requestType: TangleRequestType.AWARD_CREATE, ...newAward } }, + }, + ); + await MnemonicService.store(guardianAddress.bech32, guardianAddress.mnemonic); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) - .where('member', '==', guardian); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1; - }); - let snap = await creditQuery.get(); - let credit = snap[0] as Transaction; - await requestFundsFromFaucet( - Network.RMS, - credit.payload.response!.address as string, - credit.payload.response!.amount as number, - ); + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) + .where('member', '==', guardian); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1; + }); + let snap = await creditQuery.get(); + let credit = snap[0] as Transaction; + await requestFundsFromFaucet( + Network.RMS, + credit.payload.response!.address as string, + credit.payload.response!.amount as number, + ); - const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); - await wait(async () => { - const award = (await awardDocRef.get()) as Award; - return award.approved; - }); + const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); + await wait(async () => { + const award = (await awardDocRef.get()) as Award; + return award.approved; + }); - await walletService.send(guardianAddress, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.AWARD_APPROVE_PARTICIPANT, - award: credit.payload.response!.award, - members: Array.from(Array(150)).map(() => guardian), + await walletService.send( + guardianAddress, + tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.AWARD_APPROVE_PARTICIPANT, + award: credit.payload.response!.award, + members: Array.from(Array(150)).map(() => guardian), + }, + }, }, - }, - }); - - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 2 && - snap.reduce((acc, act) => acc && (act?.payload?.walletReference?.confirmed || false), true) ); - }); - snap = await creditQuery.get(); - credit = snap.find((d) => !isEmpty(d?.payload?.response?.badges))!; - expect(Object.keys(credit.payload.response!.badges as any).length).toBe(150); - await wait(async () => { - const snap = await build5Db().collection(COL.AIRDROP).where('member', '==', guardian).get(); - return snap.length === 150; - }); - }); + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 2 && + snap.reduce( + (acc, act) => acc && (act?.payload?.walletReference?.confirmed || false), + true, + ) + ); + }); + snap = await creditQuery.get(); + credit = snap.find((d) => !isEmpty(d?.payload?.response?.badges))!; + expect(Object.keys(credit.payload.response!.badges as any).length).toBe(150); + + await wait(async () => { + const snap = await build5Db().collection(COL.AIRDROP).where('member', '==', guardian).get(); + return snap.length === 150; + }); + }, + ); }); const awardRequest = (space: string, tokenSymbol: string) => ({ diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_5.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_5.spec.ts index c66c72c343..e12fb12911 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_5.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_5.spec.ts @@ -14,8 +14,8 @@ import { import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, wait } from '../../test/controls/common'; @@ -31,14 +31,14 @@ describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); + walletService = await WalletService.newWallet(network); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { @@ -53,7 +53,7 @@ describe('Award tangle request', () => { guardianAddress = await walletService.getAddressDetails(guardianBech32); }); - it('Should create with tangle request, fund and approve, only send only to smr address', async () => { + it('Should create with tangle request, fund and approve, only send to smr address', async () => { const newAward = awardRequest(space.uid, token.symbol); await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); await walletService.send(guardianAddress, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_6.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_6.spec.ts index 26056201d6..506fb72707 100644 --- a/packages/functions/test-tangle/award-tangle/award-tangle_6.spec.ts +++ b/packages/functions/test-tangle/award-tangle/award-tangle_6.spec.ts @@ -14,8 +14,8 @@ import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, wait } from '../../test/controls/common'; @@ -31,14 +31,14 @@ describe('Award tangle request', () => { let guardian: string; let space: Space; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let tangleOrder: Transaction; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; - tangleOrder = await getTangleOrder(); + walletService = await WalletService.newWallet(network); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award-tangle/award-tangle_7.spec.ts b/packages/functions/test-tangle/award-tangle/award-tangle_7.spec.ts new file mode 100644 index 0000000000..6a32808a65 --- /dev/null +++ b/packages/functions/test-tangle/award-tangle/award-tangle_7.spec.ts @@ -0,0 +1,118 @@ +import { + Award, + COL, + Member, + MIN_IOTA_AMOUNT, + Network, + Space, + TangleRequestType, + Token, + Transaction, + TransactionType, +} from '@build-5/interfaces'; +import dayjs from 'dayjs'; +import { build5Db } from '../../src/firebase/firestore/build5Db'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; +import { getAddress } from '../../src/utils/address.utils'; +import * as wallet from '../../src/utils/wallet.utils'; +import { createMember, createSpace, wait } from '../../test/controls/common'; +import { MEDIA } from '../../test/set-up'; +import { getTangleOrder } from '../common'; +import { requestFundsFromFaucet } from '../faucet'; +import { saveBaseToken } from './common'; + +const network = Network.RMS; +let walletSpy: any; + +describe('Award tangle request', () => { + let guardian: string; + let space: Space; + let guardianAddress: AddressDetails; + let walletService: Wallet; + let token: Token; + let tangleOrder: Transaction; + + beforeAll(async () => { + walletSpy = jest.spyOn(wallet, 'decodeAuth'); + walletService = await WalletService.newWallet(network); + }); + + beforeEach(async () => { + guardian = await createMember(walletSpy); + space = await createSpace(walletSpy, guardian); + + token = await saveBaseToken(space.uid, guardian); + + const guardianDocRef = build5Db().doc(`${COL.MEMBER}/${guardian}`); + const guardianData = await guardianDocRef.get(); + const guardianBech32 = getAddress(guardianData, network); + guardianAddress = await walletService.getAddressDetails(guardianBech32); + }); + + it.each([Network.RMS, Network.ATOI])( + 'Should create with tangle request', + async (network: Network) => { + tangleOrder = await getTangleOrder(network); + const newAward = awardRequest(space.uid, token.symbol, MEDIA); + await requestFundsFromFaucet(Network.RMS, guardianAddress.bech32, 5 * MIN_IOTA_AMOUNT); + await walletService.send( + guardianAddress, + tangleOrder.payload.targetAddress!, + 5 * MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.AWARD_CREATE, + ...newAward, + }, + }, + }, + ); + + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST) + .where('member', '==', guardian); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1; + }); + const snap = await creditQuery.get(); + const credit = snap[0] as Transaction; + expect(credit.payload.amount).toBe(5 * MIN_IOTA_AMOUNT); + + const awardDocRef = build5Db().doc(`${COL.AWARD}/${credit.payload.response!.award}`); + const award = (await awardDocRef.get()) as Award; + expect(award.uid).toBe(credit.payload.response!.award); + expect(award.name).toBe(newAward.name); + expect(award.description).toBe(newAward.description); + expect(award.space).toBe(newAward.space); + expect(award.endDate).toBeDefined(); + expect(award.network).toBe(newAward.network); + expect(award.badge.name).toBe(newAward.badge.name); + expect(award.badge.description).toBe(newAward.badge.description); + expect(award.badge.total).toBe(newAward.badge.total); + expect(award.badge.tokenReward).toBe(newAward.badge.tokenReward); + expect(award.badge.lockTime).toBe(newAward.badge.lockTime); + expect(award.badge.tokenUid).toBe(token.uid); + }, + ); +}); + +const awardRequest = (space: string, tokenSymbol: string, image: string) => ({ + name: 'award', + description: 'award', + space, + endDate: dayjs().add(2, 'd').toDate(), + badge: { + name: 'badge', + description: 'badge', + total: 2, + image, + tokenReward: MIN_IOTA_AMOUNT, + lockTime: 31557600000, + tokenSymbol, + }, + network, +}); diff --git a/packages/functions/test-tangle/award/award_1.spec.ts b/packages/functions/test-tangle/award/award_1.spec.ts index 9d1b9b443a..bcb539c430 100644 --- a/packages/functions/test-tangle/award/award_1.spec.ts +++ b/packages/functions/test-tangle/award/award_1.spec.ts @@ -27,8 +27,8 @@ import { fundAward, } from '../../src/runtime/firebase/award'; import { claimMintedTokenOrder } from '../../src/runtime/firebase/token/minting'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, mockWalletReturnValue, wait } from '../../test/controls/common'; @@ -36,7 +36,6 @@ import { MEDIA, testEnv } from '../../test/set-up'; import { requestFundsFromFaucet } from '../faucet'; import { awaitAllTransactionsForAward, saveBaseToken } from './common'; -const network = Network.RMS; let walletSpy: any; describe('Create award, base', () => { @@ -45,135 +44,139 @@ describe('Create award, base', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let now: dayjs.Dayjs; let token: Token; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; }); - beforeEach(async () => { + const setup = async (network: Network) => { now = dayjs(); + walletService = await WalletService.newWallet(network); guardian = await createMember(walletSpy); member = await createMember(walletSpy); space = await createSpace(walletSpy, guardian); - token = await saveBaseToken(space.uid, guardian); + token = await saveBaseToken(space.uid, guardian, network); - mockWalletReturnValue(walletSpy, guardian, awardRequest(space.uid, token.symbol)); + mockWalletReturnValue(walletSpy, guardian, awardRequest(network, space.uid, token.symbol)); award = await testEnv.wrap(createAward)({}); const guardianDocRef = build5Db().doc(`${COL.MEMBER}/${guardian}`); const guardianData = await guardianDocRef.get(); const guardianBech32 = getAddress(guardianData, network); guardianAddress = await walletService.getAddressDetails(guardianBech32); - }); + }; + + it.each([Network.ATOI, Network.RMS])( + 'Should create, fund and participate in award', + async (network: Network) => { + await setup(network); + mockWalletReturnValue(walletSpy, guardian, { uid: award.uid }); + const order = await testEnv.wrap(fundAward)({}); + await requestFundsFromFaucet(network, order.payload.targetAddress, order.payload.amount); + + const awardDocRef = build5Db().doc(`${COL.AWARD}/${award.uid}`); + await wait(async () => { + const award = await awardDocRef.get(); + return award.approved && award.funded; + }); + const awardData = await awardDocRef.get(); + expect(awardData.aliasBlockId).toBeDefined(); + expect(awardData.aliasId).toBeDefined(); + expect(awardData.collectionBlockId).toBeDefined(); + expect(awardData.collectionId).toBeDefined(); + + mockWalletReturnValue(walletSpy, member, { uid: award.uid }); + await testEnv.wrap(awardParticipate)({}); + + mockWalletReturnValue(walletSpy, guardian, { award: award.uid, members: [member, member] }); + await testEnv.wrap(approveAwardParticipant)({}); + + const memberDocRef = build5Db().doc(`${COL.MEMBER}/${member}`); + const memberData = await memberDocRef.get(); + const memberBech32 = getAddress(memberData, network); + + const tokenDocRef = build5Db().doc(`${COL.TOKEN}/${token.uid}`); + const distributionDocRef = tokenDocRef.collection(SUB_COL.DISTRIBUTION).doc(member); + let distribution = await distributionDocRef.get(); + expect(distribution.totalUnclaimedAirdrop).toBe(2 * MIN_IOTA_AMOUNT); + + const nttQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', member) + .where('payload.type', '==', TransactionPayloadType.BADGE); + await wait(async () => { + const snap = await nttQuery.get(); + return snap.length === 2; + }); + + mockWalletReturnValue(walletSpy, member, { symbol: token.symbol }); + const claimOrder = await testEnv.wrap(claimMintedTokenOrder)({}); + await requestFundsFromFaucet( + network, + claimOrder.payload.targetAddress, + claimOrder.payload.amount, + ); + + const billPaymentQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', member) + .where('type', '==', TransactionType.BILL_PAYMENT); + await wait(async () => { + const snap = await billPaymentQuery.get(); + return snap.length === 2; + }); + + await awaitAllTransactionsForAward(award.uid); + + distribution = await distributionDocRef.get(); + expect(distribution.totalUnclaimedAirdrop).toBe(0); + + await wait(async () => { + let balance = await walletService.getBalance(memberBech32); + return balance === 2 * MIN_IOTA_AMOUNT + claimOrder.payload.amount; + }); + + const indexer = new IndexerPluginClient(walletService.client); + + await wait(async () => { + const response = await indexer.nfts({ addressBech32: memberBech32 }); + return response.items.length === 2; + }); - it('Should create, fund and participate in award', async () => { - mockWalletReturnValue(walletSpy, guardian, { uid: award.uid }); - const order = await testEnv.wrap(fundAward)({}); - await requestFundsFromFaucet(network, order.payload.targetAddress, order.payload.amount); - - const awardDocRef = build5Db().doc(`${COL.AWARD}/${award.uid}`); - await wait(async () => { - const award = await awardDocRef.get(); - return award.approved && award.funded; - }); - const awardData = await awardDocRef.get(); - expect(awardData.aliasBlockId).toBeDefined(); - expect(awardData.aliasId).toBeDefined(); - expect(awardData.collectionBlockId).toBeDefined(); - expect(awardData.collectionId).toBeDefined(); - - mockWalletReturnValue(walletSpy, member, { uid: award.uid }); - await testEnv.wrap(awardParticipate)({}); - - mockWalletReturnValue(walletSpy, guardian, { award: award.uid, members: [member, member] }); - await testEnv.wrap(approveAwardParticipant)({}); - - const memberDocRef = build5Db().doc(`${COL.MEMBER}/${member}`); - const memberData = await memberDocRef.get(); - const memberBech32 = getAddress(memberData, network); - - const tokenDocRef = build5Db().doc(`${COL.TOKEN}/${token.uid}`); - const distributionDocRef = tokenDocRef.collection(SUB_COL.DISTRIBUTION).doc(member); - let distribution = await distributionDocRef.get(); - expect(distribution.totalUnclaimedAirdrop).toBe(2 * MIN_IOTA_AMOUNT); - - const nttQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', member) - .where('payload.type', '==', TransactionPayloadType.BADGE); - await wait(async () => { - const snap = await nttQuery.get(); - return snap.length === 2; - }); - - mockWalletReturnValue(walletSpy, member, { symbol: token.symbol }); - const claimOrder = await testEnv.wrap(claimMintedTokenOrder)({}); - await requestFundsFromFaucet( - network, - claimOrder.payload.targetAddress, - claimOrder.payload.amount, - ); - - const billPaymentQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', member) - .where('type', '==', TransactionType.BILL_PAYMENT); - await wait(async () => { - const snap = await billPaymentQuery.get(); - return snap.length === 2; - }); - - await awaitAllTransactionsForAward(award.uid); - - distribution = await distributionDocRef.get(); - expect(distribution.totalUnclaimedAirdrop).toBe(0); - - await wait(async () => { - let balance = await walletService.getBalance(memberBech32); - return balance === 2 * MIN_IOTA_AMOUNT + claimOrder.payload.amount; - }); - - const indexer = new IndexerPluginClient(walletService.client); - - await wait(async () => { const response = await indexer.nfts({ addressBech32: memberBech32 }); - return response.items.length === 2; - }); - - const response = await indexer.nfts({ addressBech32: memberBech32 }); - const promises = response.items.map( - async (outputId) => (await walletService.client.output(outputId)).output as INftOutput, - ); - const outputs = await Promise.all(promises); - for (const nttOutput of outputs) { - const timelock = nttOutput.unlockConditions.find( - (uc) => uc.type === TIMELOCK_UNLOCK_CONDITION_TYPE, - ) as ITimelockUnlockCondition; - expect(dayjs.unix(timelock.unixTime).isAfter(now.add(31557600000))).toBe(true); - } - - const burnAliasQuery = build5Db() - .collection(COL.TRANSACTION) - .where('payload.type', '==', TransactionPayloadType.BURN_ALIAS) - .where('member', '==', guardian); - await wait(async () => { - const snap = await burnAliasQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - - await wait(async () => { - const balance = await walletService.getBalance(guardianAddress.bech32); - return balance === award.aliasStorageDeposit; - }); - }); + const promises = response.items.map( + async (outputId) => (await walletService.client.output(outputId)).output as INftOutput, + ); + const outputs = await Promise.all(promises); + for (const nttOutput of outputs) { + const timelock = nttOutput.unlockConditions.find( + (uc) => uc.type === TIMELOCK_UNLOCK_CONDITION_TYPE, + ) as ITimelockUnlockCondition; + expect(dayjs.unix(timelock.unixTime).isAfter(now.add(31557600000))).toBe(true); + } + + const burnAliasQuery = build5Db() + .collection(COL.TRANSACTION) + .where('payload.type', '==', TransactionPayloadType.BURN_ALIAS) + .where('member', '==', guardian); + await wait(async () => { + const snap = await burnAliasQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); + + await wait(async () => { + const balance = await walletService.getBalance(guardianAddress.bech32); + return balance === award.aliasStorageDeposit; + }); + }, + ); }); -const awardRequest = (space: string, tokenSymbol: string) => ({ +const awardRequest = (network: Network, space: string, tokenSymbol: string) => ({ name: 'award', description: 'award', space, diff --git a/packages/functions/test-tangle/award/award_10.spec.ts b/packages/functions/test-tangle/award/award_10.spec.ts index c691574257..6a3772ae9a 100644 --- a/packages/functions/test-tangle/award/award_10.spec.ts +++ b/packages/functions/test-tangle/award/award_10.spec.ts @@ -5,9 +5,9 @@ import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { approveAwardParticipant, createAward, fundAward } from '../../src/runtime/firebase/award'; import { joinSpace } from '../../src/runtime/firebase/space'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -30,12 +30,12 @@ describe('Create award, native', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award/award_2.spec.ts b/packages/functions/test-tangle/award/award_2.spec.ts index 45eda9792d..038216c2de 100644 --- a/packages/functions/test-tangle/award/award_2.spec.ts +++ b/packages/functions/test-tangle/award/award_2.spec.ts @@ -31,8 +31,8 @@ import { import { joinSpace } from '../../src/runtime/firebase/space'; import { claimMintedTokenOrder } from '../../src/runtime/firebase/token/minting'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { mergeOutputs } from '../../src/utils/basic-output.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; @@ -58,13 +58,13 @@ describe('Create award, native', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let now: dayjs.Dayjs; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award/award_3.spec.ts b/packages/functions/test-tangle/award/award_3.spec.ts index 300d8f0b76..24434a18d8 100644 --- a/packages/functions/test-tangle/award/award_3.spec.ts +++ b/packages/functions/test-tangle/award/award_3.spec.ts @@ -40,7 +40,7 @@ describe('Create award, base', () => { mockWalletReturnValue(walletSpy, member, { uid: space?.uid }); await testEnv.wrap(joinSpace)({}); - token = await saveBaseToken(space.uid, guardian); + token = await saveBaseToken(space.uid, guardian, network); mockWalletReturnValue(walletSpy, guardian, awardRequest(space.uid, token.symbol)); award = await testEnv.wrap(createAward)({}); diff --git a/packages/functions/test-tangle/award/award_4.spec.ts b/packages/functions/test-tangle/award/award_4.spec.ts index 1d188c253b..93da81438a 100644 --- a/packages/functions/test-tangle/award/award_4.spec.ts +++ b/packages/functions/test-tangle/award/award_4.spec.ts @@ -22,8 +22,8 @@ import { } from '../../src/runtime/firebase/award'; import { joinSpace } from '../../src/runtime/firebase/space'; import { claimMintedTokenOrder } from '../../src/runtime/firebase/token/minting'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -41,12 +41,12 @@ describe('Create award, base', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { @@ -57,7 +57,7 @@ describe('Create award, base', () => { mockWalletReturnValue(walletSpy, member, { uid: space?.uid }); await testEnv.wrap(joinSpace)({}); - token = await saveBaseToken(space.uid, guardian); + token = await saveBaseToken(space.uid, guardian, network); mockWalletReturnValue(walletSpy, guardian, awardRequest(space.uid, token.symbol)); award = await testEnv.wrap(createAward)({}); diff --git a/packages/functions/test-tangle/award/award_5.spec.ts b/packages/functions/test-tangle/award/award_5.spec.ts index bc568c1369..8d19b057ee 100644 --- a/packages/functions/test-tangle/award/award_5.spec.ts +++ b/packages/functions/test-tangle/award/award_5.spec.ts @@ -27,9 +27,9 @@ import { } from '../../src/runtime/firebase/award'; import { joinSpace } from '../../src/runtime/firebase/space'; import { claimMintedTokenOrder } from '../../src/runtime/firebase/token/minting'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { mergeOutputs } from '../../src/utils/basic-output.utils'; import { dateToTimestamp, serverTime } from '../../src/utils/dateTime.utils'; @@ -55,12 +55,12 @@ describe('Create award, native', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award/award_6.spec.ts b/packages/functions/test-tangle/award/award_6.spec.ts index 92b22e86f9..54926c6079 100644 --- a/packages/functions/test-tangle/award/award_6.spec.ts +++ b/packages/functions/test-tangle/award/award_6.spec.ts @@ -17,8 +17,8 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { validateAddress } from '../../src/runtime/firebase/address'; import { approveAwardParticipant, createAward, fundAward } from '../../src/runtime/firebase/award'; import { claimMintedTokenOrder } from '../../src/runtime/firebase/token/minting'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { WalletService } from '../../src/services/wallet/wallet.service'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, mockWalletReturnValue, wait } from '../../test/controls/common'; import { MEDIA, testEnv } from '../../test/set-up'; @@ -33,18 +33,18 @@ describe('Award', () => { let space: Space; let award: Award; let token: Token; - let walletService: SmrWallet; + let walletService: Wallet; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { guardian = await createMember(walletSpy); space = await createSpace(walletSpy, guardian); - token = await saveBaseToken(space.uid, guardian); + token = await saveBaseToken(space.uid, guardian, network); mockWalletReturnValue(walletSpy, guardian, awardRequest(space.uid, token.symbol)); award = await testEnv.wrap(createAward)({}); diff --git a/packages/functions/test-tangle/award/award_7.spec.ts b/packages/functions/test-tangle/award/award_7.spec.ts index eee3f670ed..315b48eeec 100644 --- a/packages/functions/test-tangle/award/award_7.spec.ts +++ b/packages/functions/test-tangle/award/award_7.spec.ts @@ -13,9 +13,9 @@ import { INftOutput, IndexerPluginClient } from '@iota/iota.js-next'; import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { approveAwardParticipant, createAward, fundAward } from '../../src/runtime/firebase/award'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -38,13 +38,13 @@ describe('Create award, base', () => { let member: string; let space: Space; let award: Award; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; let guardianAddress: AddressDetails; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award/award_9.spec.ts b/packages/functions/test-tangle/award/award_9.spec.ts index 871e4996f9..1b7fc6a0b8 100644 --- a/packages/functions/test-tangle/award/award_9.spec.ts +++ b/packages/functions/test-tangle/award/award_9.spec.ts @@ -15,8 +15,8 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { approveAwardParticipant, createAward, fundAward } from '../../src/runtime/firebase/award'; import { joinSpace } from '../../src/runtime/firebase/space'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -39,12 +39,12 @@ describe('Create award, native', () => { let space: Space; let award: Award; let guardianAddress: AddressDetails; - let walletService: SmrWallet; + let walletService: Wallet; let token: Token; beforeAll(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); - walletService = (await WalletService.newWallet(network)) as SmrWallet; + walletService = await WalletService.newWallet(network); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/award/common.ts b/packages/functions/test-tangle/award/common.ts index ed8ab11afc..84a01442b6 100644 --- a/packages/functions/test-tangle/award/common.ts +++ b/packages/functions/test-tangle/award/common.ts @@ -37,7 +37,7 @@ const allConfirmed = (query: IQuery) => return allConfirmed; }); -export const saveBaseToken = async (space: string, guardian: string) => { +export const saveBaseToken = async (space: string, guardian: string, network = Network.RMS) => { const token = { symbol: getRandomSymbol(), approved: true, @@ -51,7 +51,7 @@ export const saveBaseToken = async (space: string, guardian: string) => { access: 0, icon: MEDIA, mintingData: { - network: Network.RMS, + network, }, }; await build5Db().doc(`${COL.TOKEN}/${token.uid}`).set(token); diff --git a/packages/functions/test-tangle/base-token-trading/Helper.ts b/packages/functions/test-tangle/base-token-trading/Helper.ts index 5391623a9a..33841832d8 100644 --- a/packages/functions/test-tangle/base-token-trading/Helper.ts +++ b/packages/functions/test-tangle/base-token-trading/Helper.ts @@ -3,8 +3,6 @@ import { COL, Member, Network, Token, TokenStatus } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { createMember } from '../../src/runtime/firebase/member'; import { IotaWallet } from '../../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { @@ -17,6 +15,8 @@ import { } from '../../test/controls/common'; import { MEDIA, getWallet, testEnv } from '../../test/set-up'; import { addValidatedAddress } from '../common'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; +import { Wallet } from '../../src/services/wallet/wallet'; export class Helper { public sourceNetwork = Network.ATOI; @@ -27,7 +27,7 @@ export class Helper { public buyerValidateAddress = {} as { [key: string]: AddressDetails }; public token: Token | undefined; public walletSpy: any | undefined; - public rmsWallet: SmrWallet | undefined; + public rmsWallet: Wallet | undefined; public atoiWallet: IotaWallet | undefined; public soonTokenId = ''; @@ -54,7 +54,7 @@ export class Helper { this.token = await this.saveToken(space.uid, guardian); this.atoiWallet = (await getWallet(Network.ATOI)) as IotaWallet; - this.rmsWallet = (await getWallet(Network.RMS)) as SmrWallet; + this.rmsWallet = await getWallet(Network.RMS); }; public saveToken = async (space: string, guardian: string) => { diff --git a/packages/functions/test-tangle/base-token-trading/base-token-trading_12.spec.ts b/packages/functions/test-tangle/base-token-trading/base-token-trading_12.spec.ts index 7741b71770..569ba33e0e 100644 --- a/packages/functions/test-tangle/base-token-trading/base-token-trading_12.spec.ts +++ b/packages/functions/test-tangle/base-token-trading/base-token-trading_12.spec.ts @@ -20,7 +20,7 @@ describe('Base token trading', () => { beforeEach(async () => { await helper.beforeEach(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); it('Should create sell order with tangle', async () => { diff --git a/packages/functions/test-tangle/collection-minting/Helper.ts b/packages/functions/test-tangle/collection-minting/Helper.ts index f2aed974a6..f6b39a70c9 100644 --- a/packages/functions/test-tangle/collection-minting/Helper.ts +++ b/packages/functions/test-tangle/collection-minting/Helper.ts @@ -30,13 +30,12 @@ import { import { openBid } from '../../src/runtime/firebase/nft'; import { createNft, orderNft, setForSaleNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; +import { Wallet } from '../../src/services/wallet/wallet'; import * as wallet from '../../src/utils/wallet.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -52,12 +51,12 @@ export class CollectionMintHelper { public space: Space | undefined; public royaltySpace: Space | undefined; public member: string | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public nftWallet: NftWallet | undefined; public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.nftWallet = new NftWallet(this.walletService); }; @@ -116,11 +115,7 @@ export class CollectionMintHelper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); mockWalletReturnValue(this.walletSpy, this.guardian!, this.dummyAuctionData(nft.uid)); await testEnv.wrap(setForSaleNft)({}); @@ -131,11 +126,7 @@ export class CollectionMintHelper { if (shouldBid) { mockWalletReturnValue(this.walletSpy, this.member!, { nft: nft.uid }); const bidOrder = await testEnv.wrap(openBid)({}); - const bidMilestone = await submitMilestoneFunc( - bidOrder.payload.targetAddress, - 2 * MIN_IOTA_AMOUNT, - ); - await milestoneProcessed(bidMilestone.milestone, bidMilestone.tranId); + await submitMilestoneFunc(bidOrder, 2 * MIN_IOTA_AMOUNT); } } return await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); diff --git a/packages/functions/test-tangle/collection-minting/collection-minting_4.spec.ts b/packages/functions/test-tangle/collection-minting/collection-minting_4.spec.ts index a35e8cfc26..cb33a6e36b 100644 --- a/packages/functions/test-tangle/collection-minting/collection-minting_4.spec.ts +++ b/packages/functions/test-tangle/collection-minting/collection-minting_4.spec.ts @@ -29,7 +29,7 @@ describe('Collection minting', () => { await helper.beforeEach(); }); - it.only.each([false, true])( + it.each([false, true])( 'Should mint, cancel active sells, not mint placeholder', async (limited: boolean) => { await helper.createAndOrderNft(); diff --git a/packages/functions/test-tangle/common.ts b/packages/functions/test-tangle/common.ts index 8dd93bea56..825c0143d3 100644 --- a/packages/functions/test-tangle/common.ts +++ b/packages/functions/test-tangle/common.ts @@ -12,7 +12,7 @@ import { Converter } from '@iota/util.js-next'; import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; +import { Wallet } from '../src/services/wallet/wallet'; import { generateRandomAmount } from '../src/utils/common.utils'; import { dateToTimestamp, serverTime } from '../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../src/utils/wallet.utils'; @@ -58,17 +58,17 @@ export const awaitTransactionConfirmationsForToken = async (token: string) => { expect(allConfirmed).toBe(true); }; -let tangleOrder: Transaction; -export const getTangleOrder = async () => { - if (tangleOrder) { - return tangleOrder; +const tangleOrders: { [key: string]: Transaction } = {}; +export const getTangleOrder = async (network: Network) => { + if (tangleOrders[network]) { + return tangleOrders[network]; } - const walletService = await getWallet(Network.RMS); + const walletService = await getWallet(network); const targetAddress = await walletService.getNewIotaAddressDetails(); const order = { type: TransactionType.ORDER, uid: getRandomEthAddress(), - network: Network.RMS, + network: network, createdOn: serverTime(), payload: { type: TransactionPayloadType.TANGLE_REQUEST, @@ -83,11 +83,11 @@ export const getTangleOrder = async () => { linkedTransactions: [], }; await build5Db().doc(`${COL.TRANSACTION}/${order.uid}`).create(order); - tangleOrder = order; - return tangleOrder; + tangleOrders[network] = order; + return tangleOrders[network]; }; -export const getRmsSoonTangleResponse = async (doc: Transaction, wallet: SmrWallet) => { +export const getRmsSoonTangleResponse = async (doc: Transaction, wallet: Wallet) => { const blockId = doc?.payload?.walletReference?.chainReference!; const block = await wallet!.client.block(blockId); const hexData = (block.payload)?.essence?.payload?.data || ''; diff --git a/packages/functions/test-tangle/db-roll/credit.highest.spec.ts b/packages/functions/test-tangle/db-roll/credit.highest.spec.ts deleted file mode 100644 index e13fef2c31..0000000000 --- a/packages/functions/test-tangle/db-roll/credit.highest.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { - COL, - MIN_IOTA_AMOUNT, - Network, - Transaction, - TransactionPayloadType, - TransactionType, -} from '@build-5/interfaces'; -import { creditHighestPayment } from '../../../database/scripts/dbUpgrades/1.0.63/creditHighestPayment'; -import { build5App } from '../../src/firebase/app/build5App'; -import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { getRandomEthAddress } from '../../src/utils/wallet.utils'; -import { wait } from '../../test/controls/common'; -import { getWallet } from '../../test/set-up'; -import { requestFundsFromFaucet } from '../faucet'; - -describe('Credit highest transaction', () => { - it('Should not credit', async () => { - const result = await creditHighestPayment(build5App() as any, getRandomEthAddress()); - expect(result).toBe(false); - }); - - it('Should credit', async () => { - const network = Network.RMS; - const wallet = await getWallet(network); - const sourceAddress = await wallet.getNewIotaAddressDetails(); - const targetAddress = await wallet.getNewIotaAddressDetails(); - - const payment: Transaction = { - type: TransactionType.PAYMENT, - uid: getRandomEthAddress(), - member: getRandomEthAddress(), - space: getRandomEthAddress(), - network, - payload: { - amount: MIN_IOTA_AMOUNT, - sourceAddress: sourceAddress.bech32, - targetAddress: targetAddress.bech32, - reconciled: true, - void: false, - sourceTransaction: [], - chainReference: null, - nft: getRandomEthAddress(), - collection: getRandomEthAddress(), - invalidPayment: false, - }, - }; - const paymentDocRef = build5Db().doc(`${COL.TRANSACTION}/${payment.uid}`); - await paymentDocRef.create(payment); - - await requestFundsFromFaucet(network, targetAddress.bech32, MIN_IOTA_AMOUNT); - - const result = await creditHighestPayment(build5App() as any, payment.uid); - expect(result).toBe(true); - - const creditDocRef = build5Db().doc( - `${COL.TRANSACTION}/0x3c368f6d447e5b703fd5b2d3a9d276809d03affe`, - ); - const credit = await creditDocRef.get(); - expect(credit?.type).toBe(TransactionType.CREDIT); - expect(credit?.space).toBe(payment.space); - expect(credit?.member).toBe(payment.member); - expect(credit?.network).toBe(payment.network); - expect(credit?.payload.type).toBe(TransactionPayloadType.DATA_NO_LONGER_VALID); - expect(credit?.payload.amount).toBe(payment.payload.amount); - expect(credit?.payload.sourceAddress).toBe(payment.payload.targetAddress); - expect(credit?.payload.targetAddress).toBe(payment.payload.sourceAddress); - expect(credit?.payload.nft).toBe(payment.payload.nft); - expect(credit?.payload.collection).toBe(payment.payload.collection); - expect(credit?.payload.invalidPayment).toBe(true); - - await wait(async () => { - const credit = await creditDocRef.get(); - return credit?.payload?.walletReference?.confirmed === true; - }); - - const paymentData = await paymentDocRef.get(); - expect(paymentData?.payload.invalidPayment).toBe(true); - }); -}); diff --git a/packages/functions/test-tangle/faucet.ts b/packages/functions/test-tangle/faucet.ts index 73055e3cb6..8d81effbed 100644 --- a/packages/functions/test-tangle/faucet.ts +++ b/packages/functions/test-tangle/faucet.ts @@ -1,11 +1,10 @@ import { Network, Timestamp } from '@build-5/interfaces'; -import { SingleNodeClient } from '@iota/iota.js'; -import { SingleNodeClient as SingleNodeClientNext } from '@iota/iota.js-next'; +import { SingleNodeClient } from '@iota/iota.js-next'; import { HexHelper } from '@iota/util.js-next'; import bigInt from 'big-integer'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../src/services/wallet/mnemonic'; -import { AddressDetails } from '../src/services/wallet/wallet'; +import { Wallet } from '../src/services/wallet/wallet'; +import { AddressDetails } from '../src/services/wallet/wallet.service'; import { getRandomElement } from '../src/utils/common.utils'; import { wait } from '../test/controls/common'; import { getWallet } from '../test/set-up'; @@ -72,7 +71,7 @@ export const requestFundsForManyFromFaucet = async ( }; export const requestMintedTokenFromFaucet = async ( - wallet: SmrWallet, + wallet: Wallet, targetAddress: AddressDetails, tokenId: string, vaultMnemonic: string, @@ -105,18 +104,14 @@ export const requestMintedTokenFromFaucet = async ( export const awaitLedgerInclusionState = async (blockId: string, network: Network) => { let ledgerInclusionState: string | undefined = ''; await wait(async () => { - ledgerInclusionState = await getLedgerInclusionState(blockId, network); + ledgerInclusionState = await getLedgerInclusionState(blockId); return ledgerInclusionState !== undefined; }, 120); return ledgerInclusionState; }; -const getLedgerInclusionState = async (blockId: string, network: Network) => { - if (network === Network.RMS) { - return (await publicRmsClient.blockMetadata(blockId)).ledgerInclusionState; - } - return (await publicAtoiClient.messageMetadata(blockId)).ledgerInclusionState; -}; +const getLedgerInclusionState = async (blockId: string) => + (await publicRmsClient.blockMetadata(blockId)).ledgerInclusionState; export const getFaucetMnemonic = (network: Network) => getRandomElement(network === Network.ATOI ? ATOI_FAUCET_MNEMONIC : RMS_FAUCET_MNEMONIC); @@ -140,34 +135,33 @@ export const RMS_FAUCET_MNEMONIC = [ 'ranch castle visa syrup famous mercy primary buddy slim vintage sting wonder fury corn vacant absent once cart waste pluck either stand picture thank', 'orient math boat embrace despair glass desert toast under vendor letter antique city original essence eagle address paddle pioneer crew liberty strike tragic actress', ]; +export const ATOI_FAUCET_MNEMONIC = RMS_FAUCET_MNEMONIC; +// export const ATOI_FAUCET_MNEMONIC = [ +// 'silver depend civil pilot paper short learn island skill carpet fatal damp damp narrow captain industry pond lion utility reduce seed noble volcano table', +// 'faint label strike still rapid auto later mesh grunt accuse gaze armed reject float fork dynamic ahead bright jar trouble drink neck open rebuild', +// 'chief addict broccoli square swim cannon damp lyrics novel evidence web tree sadness frozen provide power echo chalk prosper seminar speak attack wedding magnet', +// 'rather school always baby print wish worth fiscal lake pudding dial one warm bachelor lawsuit deposit pistol joke lemon rail dog night reform problem', +// 'chronic future orchard remember ball exhibit salt ghost churn dream urban bicycle hurry home ugly harbor antenna blur sing flock crime turtle tackle volcano', +// 'crowd patient puppy eternal weekend day ordinary ring runway rack ritual situate indoor glide smart act fetch safe creek disease corn voice legend viable', +// 'daughter now organ owner stairs quarter used also soap quit online fitness label city palace unaware fall normal summer guard ship erase ride equip', +// 'chat invest powder language marble still expire panther envelope fish animal sell rail drum lecture screen modify truth surface fashion visit smile impact action', +// 'doctor virtual pipe casual sock escape matter demise tumble silent annual hazard basket section cheap proof horse spoil river surround vote found sustain ritual', +// 'orange giant water leave glimpse below steel kick reward unique wealth index observe sure artist faint travel moral report destroy goose type theory sail', +// 'zebra put acoustic okay goddess clip proud pumpkin join abandon manual uncover scatter outer fatal tilt perfect menu silent route pool disagree credit design', +// 'renew wisdom goose fat satisfy trade expose era bright giraffe inhale occur bundle topic cactus parrot because remain kit leave dinner medal flash polar', +// 'slot skirt bracket merit language excess deal rich surface kingdom reunion armor apple receive song man tag man need drama idea relax steel vague', +// 'boost else leaf alpha shop inhale winner believe race scrap object scheme survey soon carpet pupil cloud odor dove blind palace thank run tribe', +// 'exist protect clown gown search document weasel next reveal battle excite only surround lottery leopard found history bicycle cattle deputy text utility soccer bacon', +// 'brown improve asset above fall embrace baby tackle fiber physical keep decide club convince increase three day century today enrich naive melody ethics jungle', +// 'quantum detect embody assist property judge rent east brain better more false blame table usual excess absent tragic token post unaware topic wrap phone', +// 'sea panel float tongue mention scrap can typical student section cattle neck bid artwork echo online motion desk chalk fog tail beauty pitch fame', +// 'whisper budget cup recycle upper jealous still unusual purpose charge twist deposit photo utility online gravity ten reject print unfair price opinion chair impulse', +// 'dilemma dry emerge tray little dry muffin solid math boil health bulb teach marine grace method smile torch attract brave almost exotic cost direct', +// 'seminar own leaf fluid avoid like pelican issue remind cradle topple island control parade brass wealth orange place media rebel lumber camera miss item', +// 'task eager same nerve board icon design trigger enlist blanket humble about april curious venue bounce flip old damage delay help clinic primary science', +// 'embark warm hen face helmet gauge extend quantum mandate oven unfair announce audit blanket ball like drift pigeon caution dumb error doll apart remain', +// 'island crucial frequent attitude error hard sock first crazy symbol soldier theme south when impact shuffle pause aerobic truck marine bike arrow turtle unit', +// 'diagram blame cabin battle vacuum goddess weird develop turn symbol sight dance trap loop sample culture purse pupil hobby deal wheel neglect behind tongue', +// ]; -export const ATOI_FAUCET_MNEMONIC = [ - 'silver depend civil pilot paper short learn island skill carpet fatal damp damp narrow captain industry pond lion utility reduce seed noble volcano table', - 'faint label strike still rapid auto later mesh grunt accuse gaze armed reject float fork dynamic ahead bright jar trouble drink neck open rebuild', - 'chief addict broccoli square swim cannon damp lyrics novel evidence web tree sadness frozen provide power echo chalk prosper seminar speak attack wedding magnet', - 'rather school always baby print wish worth fiscal lake pudding dial one warm bachelor lawsuit deposit pistol joke lemon rail dog night reform problem', - 'chronic future orchard remember ball exhibit salt ghost churn dream urban bicycle hurry home ugly harbor antenna blur sing flock crime turtle tackle volcano', - 'crowd patient puppy eternal weekend day ordinary ring runway rack ritual situate indoor glide smart act fetch safe creek disease corn voice legend viable', - 'daughter now organ owner stairs quarter used also soap quit online fitness label city palace unaware fall normal summer guard ship erase ride equip', - 'chat invest powder language marble still expire panther envelope fish animal sell rail drum lecture screen modify truth surface fashion visit smile impact action', - 'doctor virtual pipe casual sock escape matter demise tumble silent annual hazard basket section cheap proof horse spoil river surround vote found sustain ritual', - 'orange giant water leave glimpse below steel kick reward unique wealth index observe sure artist faint travel moral report destroy goose type theory sail', - 'zebra put acoustic okay goddess clip proud pumpkin join abandon manual uncover scatter outer fatal tilt perfect menu silent route pool disagree credit design', - 'renew wisdom goose fat satisfy trade expose era bright giraffe inhale occur bundle topic cactus parrot because remain kit leave dinner medal flash polar', - 'slot skirt bracket merit language excess deal rich surface kingdom reunion armor apple receive song man tag man need drama idea relax steel vague', - 'boost else leaf alpha shop inhale winner believe race scrap object scheme survey soon carpet pupil cloud odor dove blind palace thank run tribe', - 'exist protect clown gown search document weasel next reveal battle excite only surround lottery leopard found history bicycle cattle deputy text utility soccer bacon', - 'brown improve asset above fall embrace baby tackle fiber physical keep decide club convince increase three day century today enrich naive melody ethics jungle', - 'quantum detect embody assist property judge rent east brain better more false blame table usual excess absent tragic token post unaware topic wrap phone', - 'sea panel float tongue mention scrap can typical student section cattle neck bid artwork echo online motion desk chalk fog tail beauty pitch fame', - 'whisper budget cup recycle upper jealous still unusual purpose charge twist deposit photo utility online gravity ten reject print unfair price opinion chair impulse', - 'dilemma dry emerge tray little dry muffin solid math boil health bulb teach marine grace method smile torch attract brave almost exotic cost direct', - 'seminar own leaf fluid avoid like pelican issue remind cradle topple island control parade brass wealth orange place media rebel lumber camera miss item', - 'task eager same nerve board icon design trigger enlist blanket humble about april curious venue bounce flip old damage delay help clinic primary science', - 'embark warm hen face helmet gauge extend quantum mandate oven unfair announce audit blanket ball like drift pigeon caution dumb error doll apart remain', - 'island crucial frequent attitude error hard sock first crazy symbol soldier theme south when impact shuffle pause aerobic truck marine bike arrow turtle unit', - 'diagram blame cabin battle vacuum goddess weird develop turn symbol sight dance trap loop sample culture purse pupil hobby deal wheel neglect behind tongue', -]; - -const publicRmsClient = new SingleNodeClientNext('https://api.testnet.shimmer.network'); -const publicAtoiClient = new SingleNodeClient('https://api.lb-0.h.chrysalis-devnet.iota.cafe/'); +const publicRmsClient = new SingleNodeClient('https://api.testnet.shimmer.network'); diff --git a/packages/functions/test-tangle/metadata-nft/Helper.ts b/packages/functions/test-tangle/metadata-nft/Helper.ts index 5a7145aebe..2b168ec2f1 100644 --- a/packages/functions/test-tangle/metadata-nft/Helper.ts +++ b/packages/functions/test-tangle/metadata-nft/Helper.ts @@ -1,31 +1,42 @@ -import { COL, MIN_IOTA_AMOUNT, Member, Network, Space, Token } from '@build-5/interfaces'; +import { + COL, + MIN_IOTA_AMOUNT, + Member, + Network, + Space, + Token, + Transaction, +} from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember } from '../../test/controls/common'; import { getWallet } from '../../test/set-up'; +import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; export class Helper { - public network = Network.RMS; + public network: Network = Network.RMS; public space: Space = {} as any; public token: Token = {} as any; public member: string = ''; public memberAddress: AddressDetails = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public walletSpy: any; - public berforeAll = async () => { - this.walletService = (await getWallet(this.network)) as SmrWallet; - this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - }; + public tangleOrder: Transaction = {} as any; - public beforeEach = async () => { + public beforeEach = async (network: Network) => { + this.network = network; + this.walletService = await getWallet(this.network); + this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); this.member = await createMember(this.walletSpy); + this.tangleOrder = await getTangleOrder(this.network); + const memberData = await build5Db().doc(`${COL.MEMBER}/${this.member}`).get(); const memberAddress = getAddress(memberData, this.network); this.memberAddress = await this.walletService.getAddressDetails(memberAddress); diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts index 431651d795..8cd2a459e6 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_1.spec.ts @@ -2,6 +2,7 @@ import { COL, Collection, MIN_IOTA_AMOUNT, + Network, Nft, Space, TangleRequestType, @@ -13,27 +14,17 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { getOutputMetadata } from '../../src/utils/basic-output.utils'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should mint metada nft', async () => { + it.each([Network.RMS, Network.ATOI])('Should mint metada nft', async (network: Network) => { + await helper.beforeEach(network); const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; const blockId = await helper.walletService.send( helper.memberAddress, - tangleOrder.payload.targetAddress!, + helper.tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { customMetadata: { diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts index 8c88e04dcc..49dfbc06b1 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_2.spec.ts @@ -2,6 +2,7 @@ import { COL, Collection, MIN_IOTA_AMOUNT, + Network, Space, TangleRequestType, Transaction, @@ -9,113 +10,106 @@ import { } from '@build-5/interfaces'; import { IBasicOutput, ITransactionPayload } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; +import { Wallet } from '../../src/services/wallet/wallet'; import { getOutputMetadata } from '../../src/utils/basic-output.utils'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should mint metada nft, mint new one for same collection', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, + it.each([Network.RMS, Network.ATOI])( + 'Should mint metada nft, mint new one for same collection', + async (network: Network) => { + await helper.beforeEach(network); + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - const credit = (await creditQuery.get())[0]; + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); + const credit = (await creditQuery.get())[0]; - const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); - const collectionQuery = build5Db().collection(COL.COLLECTION).where('space', '==', space.uid); - const collection = (await collectionQuery.get())[0]; + const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); + const collectionQuery = build5Db().collection(COL.COLLECTION).where('space', '==', space.uid); + const collection = (await collectionQuery.get())[0]; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, - collectionId: collection.mintingData?.nftId, + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + collectionId: collection.mintingData?.nftId, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 2 && - snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 2 && + snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + ); + }); + const credits = await creditQuery.get(); + const credit1Meta = await getMetadata( + helper.walletService, + credits[0].payload.walletReference!.chainReference!, + ); + const credit2Meta = await getMetadata( + helper.walletService, + credits[1].payload.walletReference!.chainReference!, ); - }); - const credits = await creditQuery.get(); - const credit1Meta = await getMetadata( - helper.walletService, - credits[0].payload.walletReference!.chainReference!, - ); - const credit2Meta = await getMetadata( - helper.walletService, - credits[1].payload.walletReference!.chainReference!, - ); - expect(credit1Meta.aliasId).toBe(credit2Meta.aliasId); - expect(credit1Meta.collectionId).toBe(credit2Meta.collectionId); - expect(credit1Meta.nftId).not.toBe(credit2Meta.nftId); - }); + expect(credit1Meta.aliasId).toBe(credit2Meta.aliasId); + expect(credit1Meta.collectionId).toBe(credit2Meta.collectionId); + expect(credit1Meta.nftId).not.toBe(credit2Meta.nftId); + }, + ); }); -const getMetadata = async (wallet: SmrWallet, blockId: string) => { +const getMetadata = async (wallet: Wallet, blockId: string) => { const block = await wallet.client.block(blockId); const payload = block.payload! as ITransactionPayload; const output = payload.essence.outputs[0] as IBasicOutput; diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts index 93795a5d66..8af06e5581 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_3.spec.ts @@ -1,6 +1,7 @@ import { COL, MIN_IOTA_AMOUNT, + Network, Nft, TangleRequestType, Transaction, @@ -11,130 +12,123 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { getOutputMetadata } from '../../src/utils/basic-output.utils'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should mint metada nft then update metadata', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, + it.each([Network.RMS, Network.ATOI])( + 'Should mint metada nft then update metadata', + async (network: Network) => { + await helper.beforeEach(network); + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); - const nftQuery = build5Db().collection(COL.NFT).where('owner', '==', helper.member); - const nft = (await nftQuery.get())[0]; + const nftQuery = build5Db().collection(COL.NFT).where('owner', '==', helper.member); + const nft = (await nftQuery.get())[0]; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata: { asd: 'hello' }, - nftId: nft.mintingData?.nftId, + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata: { asd: 'hello' }, + nftId: nft.mintingData?.nftId, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); - - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 2 && - snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) ); - }); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); + + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 2 && + snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + ); + }); - const indexer = new IndexerPluginClient(helper.walletService.client); + const indexer = new IndexerPluginClient(helper.walletService.client); - let nftOutputId = (await indexer.nft(nft.mintingData?.nftId!)).items[0]; - let nftOutput = (await helper.walletService.client.output(nftOutputId)).output as INftOutput; - let meta = getOutputMetadata(nftOutput); - expect(meta).toEqual({ asd: 'hello' }); + let nftOutputId = (await indexer.nft(nft.mintingData?.nftId!)).items[0]; + let nftOutput = (await helper.walletService.client.output(nftOutputId)).output as INftOutput; + let meta = getOutputMetadata(nftOutput); + expect(meta).toEqual({ asd: 'hello' }); - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata: { asd: 'helloasdasd2' }, - nftId: nft.mintingData?.nftId, + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata: { asd: 'helloasdasd2' }, + nftId: nft.mintingData?.nftId, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); - - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 3 && - snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) ); - }); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); + + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 3 && + snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + ); + }); - nftOutputId = (await indexer.nft(nft.mintingData?.nftId!)).items[0]; - nftOutput = (await helper.walletService.client.output(nftOutputId)).output as INftOutput; - meta = getOutputMetadata(nftOutput); - expect(meta).toEqual({ asd: 'helloasdasd2' }); - }); + nftOutputId = (await indexer.nft(nft.mintingData?.nftId!)).items[0]; + nftOutput = (await helper.walletService.client.output(nftOutputId)).output as INftOutput; + meta = getOutputMetadata(nftOutput); + expect(meta).toEqual({ asd: 'helloasdasd2' }); + }, + ); }); diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts index f2cdc832b1..a9ee6f7d3f 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_4.spec.ts @@ -2,6 +2,7 @@ import { COL, Collection, MIN_IOTA_AMOUNT, + Network, Nft, Space, TangleRequestType, @@ -11,103 +12,97 @@ import { import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); + it.each([Network.RMS, Network.ATOI])( + 'Should mint metada nft, mint new one for same alias but new collection', + async (network: Network) => { + await helper.beforeEach(network); - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should mint metada nft, mint new one for same alias but new collection', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - const credit = (await creditQuery.get())[0]; + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); + const credit = (await creditQuery.get())[0]; - const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); + const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, - aliasId: space.alias?.aliasId, + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + aliasId: space.alias?.aliasId, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); - - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 2 && - snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) ); - }); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); + + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 2 && + snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + ); + }); - const nfts = await build5Db() - .collection(COL.NFT) - .where('owner', '==', helper.member) - .get(); - expect(nfts[0].collection).not.toBe(nfts[1].collection); - expect(nfts[0].space).toBe(nfts[1].space); + const nfts = await build5Db() + .collection(COL.NFT) + .where('owner', '==', helper.member) + .get(); + expect(nfts[0].collection).not.toBe(nfts[1].collection); + expect(nfts[0].space).toBe(nfts[1].space); - const collections = await build5Db() - .collection(COL.COLLECTION) - .where('space', '==', space.uid) - .get(); - expect(collections.length).toBe(2); - }); + const collections = await build5Db() + .collection(COL.COLLECTION) + .where('space', '==', space.uid) + .get(); + expect(collections.length).toBe(2); + }, + ); }); diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts index 068fac85ac..aebd7a8b4a 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_5.spec.ts @@ -2,6 +2,7 @@ import { COL, Collection, MIN_IOTA_AMOUNT, + Network, Space, TangleRequestType, Transaction, @@ -10,109 +11,106 @@ import { import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); + it.each([Network.RMS, Network.ATOI])( + 'Should mint metada nft, mint two new one for same collection&alias, in parallel', + async (network: Network) => { + await helper.beforeEach(network); - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should mint metada nft, mint two new one for same collection&alias, in parallel', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, - }, - }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); - - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); - - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - const credit = (await creditQuery.get())[0]; - - const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); - const collection = ( - await build5Db().collection(COL.COLLECTION).where('space', '==', space.uid).get() - )[0]; - - await helper.walletService.sendToMany( - helper.memberAddress, - [ + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, { - toAddress: tangleOrder.payload.targetAddress!, - amount: MIN_IOTA_AMOUNT, customMetadata: { request: { requestType: TangleRequestType.MINT_METADATA_NFT, metadata, - aliasId: space.alias?.aliasId, - collectionId: collection.mintingData?.nftId, }, }, }, - { - toAddress: tangleOrder.payload.targetAddress!, - amount: MIN_IOTA_AMOUNT, - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, - aliasId: space.alias?.aliasId, - collectionId: collection.mintingData?.nftId, + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); + + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); + + const creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); + const credit = (await creditQuery.get())[0]; + + const space = await build5Db().doc(`${COL.SPACE}/${credit.space}`).get(); + const collection = ( + await build5Db() + .collection(COL.COLLECTION) + .where('space', '==', space.uid) + .get() + )[0]; + + await helper.walletService.sendToMany( + helper.memberAddress, + [ + { + toAddress: helper.tangleOrder.payload.targetAddress!, + amount: MIN_IOTA_AMOUNT, + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + aliasId: space.alias?.aliasId, + collectionId: collection.mintingData?.nftId, + }, }, }, - }, - ], - {}, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); - - await wait(async () => { - const snap = await creditQuery.get(); - return ( - snap.length === 3 && - snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + { + toAddress: helper.tangleOrder.payload.targetAddress!, + amount: MIN_IOTA_AMOUNT, + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + aliasId: space.alias?.aliasId, + collectionId: collection.mintingData?.nftId, + }, + }, + }, + ], + {}, + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, ); - }); - }); + + await wait(async () => { + const snap = await creditQuery.get(); + return ( + snap.length === 3 && + snap.reduce((acc, act) => acc && (act.payload?.walletReference?.confirmed || false), true) + ); + }); + }, + ); }); diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts index 67effd2ba7..bb28209280 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_6.spec.ts @@ -1,6 +1,7 @@ import { COL, MIN_IOTA_AMOUNT, + Network, TangleRequestType, Transaction, TransactionType, @@ -10,90 +11,83 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should throw invalid nft id on update', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, + it.each([Network.RMS, Network.ATOI])( + 'Should throw invalid nft id on update', + async (network: Network) => { + await helper.beforeEach(network); + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); - let creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); + let creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata: { asd: 'hello' }, - nftId: getRandomEthAddress(), + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata: { asd: 'hello' }, + nftId: getRandomEthAddress(), + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); - await wait(async () => { + creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - const snap = await creditQuery.get(); - expect((snap[0].payload.response as any).message).toBe(WenError.invalid_nft_id.key); - }); + expect((snap[0].payload.response as any).message).toBe(WenError.invalid_nft_id.key); + }, + ); }); diff --git a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts index ef7326170a..d3d7ed0f2d 100644 --- a/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts +++ b/packages/functions/test-tangle/metadata-nft/mint-metadata-nft_7.spec.ts @@ -1,6 +1,7 @@ import { COL, MIN_IOTA_AMOUNT, + Network, TangleRequestType, Transaction, TransactionType, @@ -10,84 +11,78 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { Helper } from './Helper'; describe('Metadata nft', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.berforeAll(); - tangleOrder = await getTangleOrder(); - }); + it.each([Network.RMS, Network.ATOI])( + 'Should throw invalid collection id', + async (network: Network) => { + await helper.beforeEach(network); - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should throw invalid collection id', async () => { - const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, + const metadata = { mytest: 'mytest', asd: 'asdasdasd' }; + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + }, }, }, - }, - ); - await MnemonicService.store( - helper.memberAddress.bech32, - helper.memberAddress.mnemonic, - helper.network, - ); + ); + await MnemonicService.store( + helper.memberAddress.bech32, + helper.memberAddress.mnemonic, + helper.network, + ); - const mintMetadataNftQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.METADATA_NFT); - await wait(async () => { - const snap = await mintMetadataNftQuery.get(); - return snap.length === 3; - }); + const mintMetadataNftQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.METADATA_NFT); + await wait(async () => { + const snap = await mintMetadataNftQuery.get(); + return snap.length === 3; + }); - let creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); + let creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); - await helper.walletService.send( - helper.memberAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.MINT_METADATA_NFT, - metadata, - collectionId: getRandomEthAddress(), + await helper.walletService.send( + helper.memberAddress, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.MINT_METADATA_NFT, + metadata, + collectionId: getRandomEthAddress(), + }, }, }, - }, - ); - creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', helper.member) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); - await wait(async () => { + ); + creditQuery = build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', helper.member) + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; + }); const snap = await creditQuery.get(); - return snap.length === 1 && snap[0]?.payload?.walletReference?.confirmed; - }); - const snap = await creditQuery.get(); - expect((snap[0].payload.response as any).message).toBe(WenError.invalid_collection_id.key); - }); + expect((snap[0].payload.response as any).message).toBe(WenError.invalid_collection_id.key); + }, + ); }); diff --git a/packages/functions/test-tangle/minted-nft-trading/Helper.ts b/packages/functions/test-tangle/minted-nft-trading/Helper.ts index 9876aba678..d07c55d42b 100644 --- a/packages/functions/test-tangle/minted-nft-trading/Helper.ts +++ b/packages/functions/test-tangle/minted-nft-trading/Helper.ts @@ -26,19 +26,19 @@ import { } from '../../src/runtime/firebase/collection/index'; import { createNft, orderNft, setForSaleNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, } from '../../test/controls/common'; import { getWallet, MEDIA, testEnv } from '../../test/set-up'; +import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; export class Helper { @@ -49,17 +49,19 @@ export class Helper { public space: Space | undefined; public royaltySpace: Space | undefined; public member: string | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public nftWallet: NftWallet | undefined; public nft: Nft | undefined; + public tangleOrder: Transaction = {} as any; - public beforeAll = async () => { + public beforeEach = async (network: Network, collectionType = CollectionType.CLASSIC) => { + this.network = network; this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.nftWallet = new NftWallet(this.walletService); - }; - public beforeEach = async (collectionType = CollectionType.CLASSIC) => { + this.tangleOrder = await getTangleOrder(network); + this.guardian = await createMemberTest(this.walletSpy); this.member = await createMemberTest(this.walletSpy); this.space = await createSpace(this.walletSpy, this.guardian); @@ -116,11 +118,7 @@ export class Helper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); } this.nft = await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts index 26bc9ec4e6..dd4dad0da4 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1.spec.ts @@ -27,17 +27,10 @@ import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - beforeAll(async () => { - await helper.beforeAll(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - it.each([false, true])( 'Should bid twice on minted nft and withdraw it', async (hasExpiration: boolean) => { + await helper.beforeEach(Network.RMS); await helper.createAndOrderNft(); await helper.mintCollection(); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts index 8e356c06aa..5b077cec78 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_10.spec.ts @@ -5,29 +5,18 @@ import { Nft, NftPurchaseTangleRequest, TangleRequestType, - Transaction, } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { awaitLedgerInclusionState, requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should buy 2 nft in parallel', async () => { + it.each([Network.RMS, Network.ATOI])('Should buy 2 nft in parallel', async (network: Network) => { + await helper.beforeEach(network); const address = await helper.walletService!.getNewIotaAddressDetails(); await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); @@ -41,7 +30,7 @@ describe('Minted nft trading', () => { const blockId = await helper.walletService!.send( address, - tangleOrder.payload.targetAddress!, + helper.tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { customMetadata: { @@ -56,18 +45,23 @@ describe('Minted nft trading', () => { ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - await awaitLedgerInclusionState(blockId, tangleOrder.network); + await awaitLedgerInclusionState(blockId, helper.tangleOrder.network); - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: nft2.uid, - disableWithdraw: true, - } as NftPurchaseTangleRequest, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: nft2.uid, + disableWithdraw: true, + } as NftPurchaseTangleRequest, + }, }, - }); + ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); const nftDocRef1 = build5Db().doc(`${COL.NFT}/${nft1.uid}`); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts index f885c31a73..9e0a367bd5 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_11.only.spec.ts @@ -12,24 +12,14 @@ import { import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { awaitLedgerInclusionState, requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); it('Should buy 2 nft in parallel, and deposit in parallel', async () => { + await helper.beforeEach(Network.RMS); const address = await helper.walletService!.getNewIotaAddressDetails(); requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); @@ -43,7 +33,7 @@ describe('Minted nft trading', () => { const blockId = await helper.walletService!.send( address, - tangleOrder.payload.targetAddress!, + helper.tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { customMetadata: { @@ -57,17 +47,22 @@ describe('Minted nft trading', () => { ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - await awaitLedgerInclusionState(blockId, tangleOrder.network); + await awaitLedgerInclusionState(blockId, helper.tangleOrder.network); - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: nft2.uid, - } as NftPurchaseTangleRequest, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: nft2.uid, + } as NftPurchaseTangleRequest, + }, }, - }); + ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); const nftDocRef1 = build5Db().doc(`${COL.NFT}/${nft1.uid}`); @@ -90,12 +85,12 @@ describe('Minted nft trading', () => { await helper.sendNftToAddress( address, - tangleOrder.payload.targetAddress!, + helper.tangleOrder.payload.targetAddress!, nft1.mintingData?.nftId!, ); await helper.sendNftToAddress( address, - tangleOrder.payload.targetAddress!, + helper.tangleOrder.payload.targetAddress!, nft2.mintingData?.nftId!, ); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts new file mode 100644 index 0000000000..44655c2827 --- /dev/null +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_1_b.spec.ts @@ -0,0 +1,124 @@ +import { + COL, + Member, + MIN_IOTA_AMOUNT, + Network, + Nft, + NftStatus, + Transaction, + TransactionType, + WenError, +} from '@build-5/interfaces'; +import { IndexerPluginClient, INftOutput, NFT_OUTPUT_TYPE } from '@iota/iota.js-next'; +import dayjs from 'dayjs'; +import { isEmpty } from 'lodash'; +import { finalizeAllNftAuctions } from '../../src/cron/nft.cron'; +import { build5Db } from '../../src/firebase/firestore/build5Db'; +import { openBid } from '../../src/runtime/firebase/nft'; +import { withdrawNft } from '../../src/runtime/firebase/nft/index'; +import { getAddress } from '../../src/utils/address.utils'; +import { Bech32AddressHelper } from '../../src/utils/bech32-address.helper'; +import { dateToTimestamp } from '../../src/utils/dateTime.utils'; +import { expectThrow, mockWalletReturnValue, wait } from '../../test/controls/common'; +import { testEnv } from '../../test/set-up'; +import { requestFundsFromFaucet } from '../faucet'; +import { Helper } from './Helper'; + +describe('Minted nft trading', () => { + const helper = new Helper(); + + it.each([false])( + 'Should bid twice on minted nft and withdraw it', + async (hasExpiration: boolean) => { + await helper.beforeEach(Network.ATOI); + await helper.createAndOrderNft(); + await helper.mintCollection(); + + await helper.setAvailableForAuction(); + + mockWalletReturnValue(helper.walletSpy, helper.member!, { nft: helper.nft!.uid }); + await expectThrow(testEnv.wrap(withdrawNft)({}), WenError.you_must_be_the_owner_of_nft.key); + + const expiresAt = hasExpiration ? dateToTimestamp(dayjs().add(2, 'h').toDate()) : undefined; + + mockWalletReturnValue(helper.walletSpy, helper.member!, { nft: helper.nft!.uid }); + const bidOrder = await testEnv.wrap(openBid)({}); + await requestFundsFromFaucet( + Network.RMS, + bidOrder.payload.targetAddress, + MIN_IOTA_AMOUNT, + expiresAt, + ); + + await wait(async () => { + const nft = await build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`).get(); + return !isEmpty(nft.auctionHighestTransaction); + }); + + const bidOrder2 = await testEnv.wrap(openBid)({}); + await requestFundsFromFaucet( + Network.RMS, + bidOrder2.payload.targetAddress, + 2 * MIN_IOTA_AMOUNT, + expiresAt, + ); + + await wait(async () => { + const nft = await build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`).get(); + + const payment = ( + await build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.PAYMENT) + .where('payload.sourceTransaction', 'array-contains', bidOrder2.uid) + .get() + )[0]; + return nft.auctionHighestTransaction === payment?.uid; + }); + + await build5Db() + .doc(`${COL.NFT}/${helper.nft!.uid}`) + .update({ auctionTo: dateToTimestamp(dayjs().subtract(1, 'm').toDate()) }); + + await finalizeAllNftAuctions(); + + await wait(async () => { + const nft = await build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`).get(); + return nft.owner === helper.member; + }); + + mockWalletReturnValue(helper.walletSpy, helper.member!, { nft: helper.nft!.uid }); + await testEnv.wrap(withdrawNft)({}); + + const nft = await build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`).get(); + expect(nft.status).toBe(NftStatus.WITHDRAWN); + + await wait(async () => { + const transaction = ( + await build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.WITHDRAW_NFT) + .where('payload.nft', '==', helper.nft!.uid) + .get() + )[0]; + return transaction?.payload?.walletReference?.confirmed; + }); + + const indexer = new IndexerPluginClient(helper.walletService?.client!); + const output = ( + await helper.walletService!.client.output( + ( + await indexer.nft(nft.mintingData?.nftId!) + ).items[0], + ) + ).output; + const ownerAddress = Bech32AddressHelper.addressFromAddressUnlockCondition( + (output as INftOutput).unlockConditions, + 'rms', + NFT_OUTPUT_TYPE, + ); + const member = await build5Db().doc(`${COL.MEMBER}/${helper.member}`).get(); + expect(ownerAddress).toBe(getAddress(member, Network.ATOI)); + }, + ); +}); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_2.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_2.spec.ts index ec0e7fc0c5..dcf72e11a1 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_2.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_2.spec.ts @@ -23,15 +23,8 @@ import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - beforeAll(async () => { - await helper.beforeAll(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - it.each([false, true])('Should order nft and withdraw it', async (hasExpiration: boolean) => { + await helper.beforeEach(Network.RMS); const expiresAt = hasExpiration ? dateToTimestamp(dayjs().add(2, 'h').toDate()) : undefined; await helper.createAndOrderNft(); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_3.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_3.spec.ts index cdfc0c56c3..fa1ed63a34 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_3.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_3.spec.ts @@ -2,6 +2,7 @@ import { COL, Collection, CollectionStatus, + Network, UnsoldMintingOptions, WenError, } from '@build-5/interfaces'; @@ -15,15 +16,8 @@ import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - beforeAll(async () => { - await helper.beforeAll(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - it('Should throw can not be set for sale during minting', async () => { + await helper.beforeEach(Network.RMS); await helper.createAndOrderNft(); mockWalletReturnValue(helper.walletSpy, helper.guardian!, { diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_4.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_4.spec.ts index 9198451912..76ae5d373f 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_4.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_4.spec.ts @@ -14,39 +14,34 @@ import { IndexerPluginClient } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); it('Should purchase nft with tangle request', async () => { + await helper.beforeEach(Network.RMS); const address = await helper.walletService!.getNewIotaAddressDetails(); await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); await helper.createAndOrderNft(); await helper.mintCollection(); - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: helper.nft!.uid, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: helper.nft!.uid, + }, }, }, - }); + ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); await wait(async () => { @@ -65,15 +60,20 @@ describe('Minted nft trading', () => { expect(collection.nftsOnSale).toBe(1); expect(collection.nftsOnAuction).toBe(0); - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: helper.nft!.mintingData?.nftId, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: helper.nft!.mintingData?.nftId, + }, }, }, - }); + ); const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft?.uid}`); await wait(async () => { diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_5.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_5.spec.ts index 68eeee03ef..4fa442b41b 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_5.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_5.spec.ts @@ -10,40 +10,35 @@ import { } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { WalletService } from '../../src/services/wallet/wallet'; +import { WalletService } from '../../src/services/wallet/wallet.service'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); it('Should purchase pre_minted nft with tangle request', async () => { + await helper.beforeEach(Network.RMS); const address = await helper.walletService!.getNewIotaAddressDetails(); await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); await helper.createAndOrderNft(false); - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: helper.nft!.uid, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: helper.nft!.uid, + }, }, }, - }); + ); await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); const creditQuery = build5Db() diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_6.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_6.spec.ts index 9c91370de3..1e3ab8c4ab 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_6.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_6.spec.ts @@ -11,50 +11,48 @@ import { IndexerPluginClient } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); + it.each([Network.RMS, Network.ATOI])( + 'Should purchase random nft with tangle request', + async (network: Network) => { + await helper.beforeEach(network, CollectionType.GENERATED); + const address = await helper.walletService!.getNewIotaAddressDetails(); + await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); - beforeEach(async () => { - await helper.beforeEach(CollectionType.GENERATED); - }); + await helper.createAndOrderNft(false); + await helper.mintCollection(); - it('Should purchase random nft with tangle request', async () => { - const address = await helper.walletService!.getNewIotaAddressDetails(); - await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); - - await helper.createAndOrderNft(false); - await helper.mintCollection(); - - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + }, + }, }, - }, - }); - await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); + ); + await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - await wait(async () => { - const snap = await build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', address.bech32) - .where('type', '==', TransactionType.WITHDRAW_NFT) - .get(); - return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; - }); - const indexer = new IndexerPluginClient(helper.walletService!.client); - const nftOutputIds = await indexer.nfts({ addressBech32: address.bech32 }); - expect(nftOutputIds.items.length).toBe(1); - }); + await wait(async () => { + const snap = await build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', address.bech32) + .where('type', '==', TransactionType.WITHDRAW_NFT) + .get(); + return snap.length > 0 && snap[0]?.payload?.walletReference?.confirmed; + }); + const indexer = new IndexerPluginClient(helper.walletService!.client); + const nftOutputIds = await indexer.nfts({ addressBech32: address.bech32 }); + expect(nftOutputIds.items.length).toBe(1); + }, + ); }); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_7.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_7.spec.ts index 34cd0e7925..df1026029f 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_7.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_7.spec.ts @@ -15,101 +15,94 @@ import { IndexerPluginClient } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); - - beforeEach(async () => { - await helper.beforeEach(); - }); - - it('Should purchase nft with tangle request, first send wrong amount', async () => { - const address = await helper.walletService!.getNewIotaAddressDetails(); - await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); - - await helper.createAndOrderNft(); - await helper.mintCollection(); - - await helper.setAvailableForSale(); - - await helper.walletService!.send( - address, - tangleOrder.payload.targetAddress!, - 0.5 * MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: helper.nft!.mintingData?.nftId, + it.each([Network.RMS, Network.ATOI])( + 'Should purchase nft with tangle request, first send wrong amount', + async (network: Network) => { + await helper.beforeEach(network); + const address = await helper.walletService!.getNewIotaAddressDetails(); + await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); + + await helper.createAndOrderNft(); + await helper.mintCollection(); + + await helper.setAvailableForSale(); + + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + 0.5 * MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: helper.nft!.mintingData?.nftId, + }, }, }, - }, - ); - await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', address.bech32) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length > 0 && snap[0].payload?.walletReference?.confirmed; - }); - - const snap = await creditQuery.get(); - const credit = snap[0]; - const response = credit.payload.response as BaseTangleResponse; - - await helper.walletService!.send(address, response.address!, response.amount!, {}); - await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); + ); + await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft?.uid}`); - await wait(async () => { - const nft = await nftDocRef.get(); - return nft.status === NftStatus.WITHDRAWN; - }); - - await wait(async () => { - const snap = await build5Db() + const creditQuery = build5Db() .collection(COL.TRANSACTION) .where('member', '==', address.bech32) - .where('type', '==', TransactionType.WITHDRAW_NFT) - .get(); - return snap.length > 0 && snap[0].payload?.walletReference?.confirmed; - }); - - const indexer = new IndexerPluginClient(helper.walletService!.client); - const nftOutputIds = await indexer.nfts({ addressBech32: address.bech32 }); - expect(nftOutputIds.items.length).toBe(1); + .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); + await wait(async () => { + const snap = await creditQuery.get(); + return snap.length > 0 && snap[0].payload?.walletReference?.confirmed; + }); - const collectionDocRef = build5Db().doc(`${COL.COLLECTION}/${helper.nft?.collection}`); - const collection = await collectionDocRef.get(); - expect(collection.nftsOnSale).toBe(0); - expect(collection.nftsOnAuction).toBe(0); - - const orders = await build5Db() - .collection(COL.TRANSACTION) - .where('payload.type', '==', TransactionPayloadType.NFT_PURCHASE) - .where('payload.nft', '==', helper.nft!.uid) - .get(); + const snap = await creditQuery.get(); + const credit = snap[0]; + const response = credit.payload.response as BaseTangleResponse; + + await helper.walletService!.send(address, response.address!, response.amount!, {}); + await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); + + const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft?.uid}`); + await wait(async () => { + const nft = await nftDocRef.get(); + return nft.status === NftStatus.WITHDRAWN; + }); + + await wait(async () => { + const snap = await build5Db() + .collection(COL.TRANSACTION) + .where('member', '==', address.bech32) + .where('type', '==', TransactionType.WITHDRAW_NFT) + .get(); + return snap.length > 0 && snap[0].payload?.walletReference?.confirmed; + }); + + const indexer = new IndexerPluginClient(helper.walletService!.client); + const nftOutputIds = await indexer.nfts({ addressBech32: address.bech32 }); + expect(nftOutputIds.items.length).toBe(1); + + const collectionDocRef = build5Db().doc(`${COL.COLLECTION}/${helper.nft?.collection}`); + const collection = await collectionDocRef.get(); + expect(collection.nftsOnSale).toBe(0); + expect(collection.nftsOnAuction).toBe(0); + + const orders = await build5Db() + .collection(COL.TRANSACTION) + .where('payload.type', '==', TransactionPayloadType.NFT_PURCHASE) + .where('payload.nft', '==', helper.nft!.uid) + .get(); - const billPayments = await build5Db() - .collection(COL.TRANSACTION) - .where('type', '==', TransactionType.BILL_PAYMENT) - .where('payload.nft', '==', helper.nft!.uid) - .get(); - for (const billPayment of billPayments) { - expect(billPayment.payload.restrictions).toEqual(orders[0].payload.restrictions); - } - }); + const billPayments = await build5Db() + .collection(COL.TRANSACTION) + .where('type', '==', TransactionType.BILL_PAYMENT) + .where('payload.nft', '==', helper.nft!.uid) + .get(); + for (const billPayment of billPayments) { + expect(billPayment.payload.restrictions).toEqual(orders[0].payload.restrictions); + } + }, + ); }); diff --git a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_8.spec.ts b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_8.spec.ts index 26c1c45360..e31eb3fc17 100644 --- a/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_8.spec.ts +++ b/packages/functions/test-tangle/minted-nft-trading/minted-nft-trading_8.spec.ts @@ -6,52 +6,49 @@ import { NftPurchaseTangleRequest, NftStatus, TangleRequestType, - Transaction, } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; import { wait } from '../../test/controls/common'; -import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; import { Helper } from './Helper'; describe('Minted nft trading', () => { const helper = new Helper(); - let tangleOrder: Transaction; - beforeAll(async () => { - await helper.beforeAll(); - tangleOrder = await getTangleOrder(); - }); + it.each([Network.RMS, Network.ATOI])( + 'Should purchase nft with tangle request, no withdraw', + async (network: Network) => { + await helper.beforeEach(network); + const address = await helper.walletService!.getNewIotaAddressDetails(); + await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); - beforeEach(async () => { - await helper.beforeEach(); - }); + await helper.createAndOrderNft(); + await helper.mintCollection(); + await helper.setAvailableForSale(); - it('Should purchase nft with tangle request, no withdraw', async () => { - const address = await helper.walletService!.getNewIotaAddressDetails(); - await requestFundsFromFaucet(Network.RMS, address.bech32, 5 * MIN_IOTA_AMOUNT); + await helper.walletService!.send( + address, + helper.tangleOrder.payload.targetAddress!, + MIN_IOTA_AMOUNT, + { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_PURCHASE, + collection: helper.collection, + nft: helper.nft!.uid, + disableWithdraw: true, + } as NftPurchaseTangleRequest, + }, + }, + ); + await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - await helper.createAndOrderNft(); - await helper.mintCollection(); - await helper.setAvailableForSale(); - - await helper.walletService!.send(address, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_PURCHASE, - collection: helper.collection, - nft: helper.nft!.uid, - disableWithdraw: true, - } as NftPurchaseTangleRequest, - }, - }); - await MnemonicService.store(address.bech32, address.mnemonic, Network.RMS); - - const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`); - await wait(async () => { - const nft = await nftDocRef.get(); - return nft?.owner === address.bech32 && nft.status === NftStatus.MINTED; - }); - }); + const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`); + await wait(async () => { + const nft = await nftDocRef.get(); + return nft?.owner === address.bech32 && nft.status === NftStatus.MINTED; + }); + }, + ); }); diff --git a/packages/functions/test-tangle/minted-token-airdrop/Helper.ts b/packages/functions/test-tangle/minted-token-airdrop/Helper.ts index e9227810b9..a38746310d 100644 --- a/packages/functions/test-tangle/minted-token-airdrop/Helper.ts +++ b/packages/functions/test-tangle/minted-token-airdrop/Helper.ts @@ -9,8 +9,8 @@ import { TokenStatus, } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; +import { Wallet } from '../../src/services/wallet/wallet'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace, getRandomSymbol } from '../../test/controls/common'; @@ -23,11 +23,11 @@ export class Helper { public guardian: string | undefined; public member: string | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public walletSpy: any; public berforeAll = async () => { - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); }; @@ -51,7 +51,7 @@ export class Helper { export const saveToken = async ( space: string, guardian: string, - walletService: SmrWallet, + walletService: Wallet, tokenId = MINTED_TOKEN_ID, ) => { const vaultAddress = await walletService.getIotaAddressDetails(VAULT_MNEMONIC); diff --git a/packages/functions/test-tangle/minted-token-airdrop/minted-token-airdrop_4.spec.ts b/packages/functions/test-tangle/minted-token-airdrop/minted-token-airdrop_4.spec.ts index 37166541a8..2dffd8ae2f 100644 --- a/packages/functions/test-tangle/minted-token-airdrop/minted-token-airdrop_4.spec.ts +++ b/packages/functions/test-tangle/minted-token-airdrop/minted-token-airdrop_4.spec.ts @@ -31,7 +31,7 @@ describe('Minted token airdrop tangle claim', () => { beforeAll(async () => { await helper.berforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/minted-token-trade/Helper.ts b/packages/functions/test-tangle/minted-token-trade/Helper.ts index db2ecfd535..09ff284a05 100644 --- a/packages/functions/test-tangle/minted-token-trade/Helper.ts +++ b/packages/functions/test-tangle/minted-token-trade/Helper.ts @@ -16,8 +16,8 @@ import bigInt from 'big-integer'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { tradeToken } from '../../src/runtime/firebase/token/trading'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -43,13 +43,13 @@ export class Helper { public buyerAddress: AddressDetails | undefined; public guardian: string | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public walletSpy: any; public soonTokenId = ''; public berforeAll = async () => { - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); await createRoyaltySpaces(); this.soonTokenId = await saveSoon(); this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); @@ -146,7 +146,7 @@ export class Helper { export const saveToken = async ( space: string, guardian: string, - walletService: SmrWallet, + walletService: Wallet, tokenId = MINTED_TOKEN_ID, ) => { const vaultAddress = await walletService.getIotaAddressDetails(VAULT_MNEMONIC); diff --git a/packages/functions/test-tangle/minted-token-trade/minted-token-trade_18.spec.ts b/packages/functions/test-tangle/minted-token-trade/minted-token-trade_18.spec.ts index 841e278780..1203d7a39d 100644 --- a/packages/functions/test-tangle/minted-token-trade/minted-token-trade_18.spec.ts +++ b/packages/functions/test-tangle/minted-token-trade/minted-token-trade_18.spec.ts @@ -24,7 +24,7 @@ describe('Minted toke trading tangle request', () => { beforeAll(async () => { await helper.berforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-bid/Helper.ts b/packages/functions/test-tangle/nft-bid/Helper.ts index 8abae628c5..deeba46f3e 100644 --- a/packages/functions/test-tangle/nft-bid/Helper.ts +++ b/packages/functions/test-tangle/nft-bid/Helper.ts @@ -26,14 +26,13 @@ import { } from '../../src/runtime/firebase/collection/index'; import { createNft, orderNft, setForSaleNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -49,13 +48,13 @@ export class Helper { public space: Space = {} as any; public royaltySpace: Space = {} as any; public member: string = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public nftWallet: NftWallet = {} as any; public nft: Nft = {} as any; public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.nftWallet = new NftWallet(this.walletService); }; @@ -116,11 +115,7 @@ export class Helper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); } this.nft = await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); diff --git a/packages/functions/test-tangle/nft-bid/nft-bid.otr_1.spec.ts b/packages/functions/test-tangle/nft-bid/nft-bid.otr_1.spec.ts index b503596c14..4cd4ad9d1e 100644 --- a/packages/functions/test-tangle/nft-bid/nft-bid.otr_1.spec.ts +++ b/packages/functions/test-tangle/nft-bid/nft-bid.otr_1.spec.ts @@ -26,7 +26,7 @@ describe('Nft otr bid', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-bid/nft-bid.otr_2.spec.ts b/packages/functions/test-tangle/nft-bid/nft-bid.otr_2.spec.ts index 64c5912927..aa58ddc74b 100644 --- a/packages/functions/test-tangle/nft-bid/nft-bid.otr_2.spec.ts +++ b/packages/functions/test-tangle/nft-bid/nft-bid.otr_2.spec.ts @@ -23,7 +23,7 @@ describe('Nft otr bid', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-bid/nft-bid.otr_3.spec.ts b/packages/functions/test-tangle/nft-bid/nft-bid.otr_3.spec.ts index aa496cf282..da0dfa4302 100644 --- a/packages/functions/test-tangle/nft-bid/nft-bid.otr_3.spec.ts +++ b/packages/functions/test-tangle/nft-bid/nft-bid.otr_3.spec.ts @@ -6,7 +6,6 @@ import { NftBidTangleRequest, TangleRequestType, Transaction, - TransactionType, } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; @@ -27,7 +26,7 @@ describe('Nft otr bid', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.ATOI); }); beforeEach(async () => { @@ -35,48 +34,22 @@ describe('Nft otr bid', () => { }); it('Should bid on minted nft with ATOI otr, no withdraw', async () => { - const rmsAddress = await helper.walletService!.getNewIotaAddressDetails(); - await requestFundsFromFaucet(Network.RMS, rmsAddress.bech32, 5 * MIN_IOTA_AMOUNT); - const atoiWallet = (await getWallet(Network.ATOI)) as IotaWallet; const atoiAddress = await atoiWallet.getNewIotaAddressDetails(); - requestFundsFromFaucet(Network.ATOI, atoiAddress.bech32, 5 * MIN_IOTA_AMOUNT); + await requestFundsFromFaucet(Network.ATOI, atoiAddress.bech32, 5 * MIN_IOTA_AMOUNT); await helper.createAndOrderNft(); await helper.setAvailableForAuction(); - await helper.walletService!.send( - rmsAddress, - tangleOrder.payload.targetAddress!, - MIN_IOTA_AMOUNT, - { - customMetadata: { - request: { - requestType: TangleRequestType.NFT_BID, - nft: helper.nft.uid, - } as NftBidTangleRequest, - }, + await atoiWallet.send(atoiAddress, tangleOrder.payload.targetAddress!, MIN_IOTA_AMOUNT, { + customMetadata: { + request: { + requestType: TangleRequestType.NFT_BID, + nft: helper.nft.uid, + } as NftBidTangleRequest, }, - ); - await MnemonicService.store(rmsAddress.bech32, rmsAddress.mnemonic, Network.RMS); - - const creditQuery = build5Db() - .collection(COL.TRANSACTION) - .where('member', '==', rmsAddress.bech32) - .where('type', '==', TransactionType.CREDIT_TANGLE_REQUEST); - await wait(async () => { - const snap = await creditQuery.get(); - return snap.length > 0 && snap[0].payload?.walletReference?.confirmed; }); - const credit = (await creditQuery.get())[0]; - - await atoiWallet.send( - atoiAddress, - credit.payload.response?.address as string, - credit.payload.response?.amount! as number, - {}, - ); - + await MnemonicService.store(atoiAddress.bech32, atoiAddress.mnemonic, Network.RMS); const nftDocRef = build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`); await wait(async () => { const nft = await nftDocRef.get(); @@ -91,7 +64,7 @@ describe('Nft otr bid', () => { await wait(async () => { const nft = await build5Db().doc(`${COL.NFT}/${helper.nft!.uid}`).get(); - return nft.owner === rmsAddress.bech32; + return nft.owner === atoiAddress.bech32; }); }); }); diff --git a/packages/functions/test-tangle/nft-bid/nft-bid.otr_4.spec.ts b/packages/functions/test-tangle/nft-bid/nft-bid.otr_4.spec.ts index ac773660c1..a3827f362a 100644 --- a/packages/functions/test-tangle/nft-bid/nft-bid.otr_4.spec.ts +++ b/packages/functions/test-tangle/nft-bid/nft-bid.otr_4.spec.ts @@ -23,7 +23,7 @@ describe('Nft otr bid', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-set-for-sale/Helper.ts b/packages/functions/test-tangle/nft-set-for-sale/Helper.ts index e509665649..f11a4b4ce4 100644 --- a/packages/functions/test-tangle/nft-set-for-sale/Helper.ts +++ b/packages/functions/test-tangle/nft-set-for-sale/Helper.ts @@ -16,14 +16,13 @@ import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { approveCollection, createCollection } from '../../src/runtime/firebase/collection/index'; import { createNft, orderNft } from '../../src/runtime/firebase/nft/index'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, } from '../../test/controls/common'; @@ -37,12 +36,12 @@ export class Helper { public guardianAddress: AddressDetails = {} as any; public space: Space = {} as any; public royaltySpace: Space = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public nft: Nft = {} as any; public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); }; public beforeEach = async (collectionType = CollectionType.CLASSIC) => { @@ -83,11 +82,7 @@ export class Helper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); } this.nft = await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); diff --git a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_1.spec.ts b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_1.spec.ts index a5fbc936d2..c0d1170f40 100644 --- a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_1.spec.ts +++ b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_1.spec.ts @@ -20,7 +20,7 @@ describe('Nft set for sale OTR', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_2.spec.ts b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_2.spec.ts index 1535e73210..3ce8e8b70f 100644 --- a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_2.spec.ts +++ b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_2.spec.ts @@ -20,7 +20,7 @@ describe('Nft set for sale OTR', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_3.spec.ts b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_3.spec.ts index ae06d01ca5..7511615e7f 100644 --- a/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_3.spec.ts +++ b/packages/functions/test-tangle/nft-set-for-sale/nft-set-for-sale_3.spec.ts @@ -24,7 +24,7 @@ describe('Nft set for acution OTR', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/nft-staking/Helper.ts b/packages/functions/test-tangle/nft-staking/Helper.ts index e026efcf33..f61f851256 100644 --- a/packages/functions/test-tangle/nft-staking/Helper.ts +++ b/packages/functions/test-tangle/nft-staking/Helper.ts @@ -44,9 +44,9 @@ import { withdrawNft, } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { mergeOutputs, packBasicOutput } from '../../src/utils/basic-output.utils'; import { packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; @@ -57,7 +57,6 @@ import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -70,7 +69,7 @@ export class Helper { public collection: string | undefined; public guardian: string | undefined; public space: Space | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public walletSpy: any; public nft: Nft | undefined; public guardianAddress: AddressDetails | undefined; @@ -78,7 +77,7 @@ export class Helper { public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); }; public beforeEach = async () => { @@ -117,8 +116,7 @@ export class Helper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); this.nft = await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); return this.nft; diff --git a/packages/functions/test-tangle/proposal-tangle/Helper.ts b/packages/functions/test-tangle/proposal-tangle/Helper.ts index 2ba5135f67..ab5b1c1e72 100644 --- a/packages/functions/test-tangle/proposal-tangle/Helper.ts +++ b/packages/functions/test-tangle/proposal-tangle/Helper.ts @@ -17,8 +17,8 @@ import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { IQuery } from '../../src/firebase/firestore/interfaces'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -33,7 +33,7 @@ export class Helper { public guardian: string = ''; public space: Space = {} as any; public guardianAddress: AddressDetails = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public tangleOrder: Transaction = {} as any; public network = Network.RMS; public guardianCreditQuery: IQuery = {} as any; @@ -41,8 +41,8 @@ export class Helper { public proposalUid = ''; public beforeAll = async () => { - this.walletService = (await WalletService.newWallet(this.network)) as SmrWallet; - this.tangleOrder = await getTangleOrder(); + this.walletService = await WalletService.newWallet(this.network); + this.tangleOrder = await getTangleOrder(Network.RMS); }; public beforeEach = async () => { diff --git a/packages/functions/test-tangle/space-tangle/Helper.ts b/packages/functions/test-tangle/space-tangle/Helper.ts index 5dffd34877..e4902e614e 100644 --- a/packages/functions/test-tangle/space-tangle/Helper.ts +++ b/packages/functions/test-tangle/space-tangle/Helper.ts @@ -1,8 +1,8 @@ import { COL, Member, Network, Space, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { IQuery } from '../../src/firebase/firestore/interfaces'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, createSpace } from '../../test/controls/common'; @@ -14,7 +14,7 @@ export class Helper { public member: string = ''; public space: Space = {} as any; public memberAddress: AddressDetails = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public network = Network.RMS; public tangleOrder: Transaction = {} as any; public memberCreditQuery: IQuery = {} as any; @@ -22,8 +22,8 @@ export class Helper { public guardianAddress: AddressDetails = {} as any; public beforeAll = async () => { - this.walletService = (await WalletService.newWallet(this.network)) as SmrWallet; - this.tangleOrder = await getTangleOrder(); + this.walletService = await WalletService.newWallet(this.network); + this.tangleOrder = await getTangleOrder(Network.RMS); }; public beforeEach = async () => { diff --git a/packages/functions/test-tangle/staking/Helper.ts b/packages/functions/test-tangle/staking/Helper.ts index 42e2122d54..5f8d2972d8 100644 --- a/packages/functions/test-tangle/staking/Helper.ts +++ b/packages/functions/test-tangle/staking/Helper.ts @@ -23,9 +23,9 @@ import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositStake } from '../../src/runtime/firebase/stake'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp, serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -48,7 +48,7 @@ export class Helper { public member: Member | undefined; public memberAddress: AddressDetails | undefined; public space: Space | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public walletSpy: any; public network = Network.RMS; public token: Token | undefined; @@ -56,7 +56,7 @@ export class Helper { public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); }; public beforeEach = async () => { diff --git a/packages/functions/test-tangle/staking/staking_5.spec.ts b/packages/functions/test-tangle/staking/staking_5.spec.ts index b18627e89e..1d728993f2 100644 --- a/packages/functions/test-tangle/staking/staking_5.spec.ts +++ b/packages/functions/test-tangle/staking/staking_5.spec.ts @@ -22,7 +22,7 @@ describe('Stake reward test test', () => { beforeAll(async () => { await helper.beforeAll(); - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { diff --git a/packages/functions/test-tangle/tangleRequest/simple.token.trade.spec.ts b/packages/functions/test-tangle/tangleRequest/simple.token.trade.spec.ts index 0070e5d7fc..a44965873a 100644 --- a/packages/functions/test-tangle/tangleRequest/simple.token.trade.spec.ts +++ b/packages/functions/test-tangle/tangleRequest/simple.token.trade.spec.ts @@ -13,7 +13,7 @@ import { WenError, } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; +import { Wallet } from '../../src/services/wallet/wallet'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { createMember, getRandomSymbol, wait } from '../../test/controls/common'; @@ -26,11 +26,11 @@ let walletSpy: any; describe('Simple token trading', () => { let member: string; let token: Token; - let rmsWallet: SmrWallet; + let rmsWallet: Wallet; let tangleOrder: Transaction; beforeAll(async () => { - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { @@ -52,7 +52,7 @@ describe('Simple token trading', () => { tokenOwned: 100, }); - rmsWallet = (await getWallet(Network.RMS)) as SmrWallet; + rmsWallet = await getWallet(Network.RMS); }); it('Should credit on simple token buy', async () => { diff --git a/packages/functions/test-tangle/tangleRequest/tangle-request.spec.ts b/packages/functions/test-tangle/tangleRequest/tangle-request.spec.ts index c7d68defbf..8068b768d9 100644 --- a/packages/functions/test-tangle/tangleRequest/tangle-request.spec.ts +++ b/packages/functions/test-tangle/tangleRequest/tangle-request.spec.ts @@ -11,8 +11,7 @@ import { WenError, } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -20,24 +19,25 @@ import { createMember, createSpace, getRandomSymbol, wait } from '../../test/con import { getWallet, MEDIA } from '../../test/set-up'; import { getTangleOrder } from '../common'; import { requestFundsFromFaucet } from '../faucet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; let walletSpy: any; describe('Tangle request spec', () => { let member: string; - let rmsWallet: SmrWallet; + let rmsWallet: Wallet; let tangleOrder: Transaction; let rmsAddress: AddressDetails; let token: Token; beforeAll(async () => { - tangleOrder = await getTangleOrder(); + tangleOrder = await getTangleOrder(Network.RMS); }); beforeEach(async () => { walletSpy = jest.spyOn(wallet, 'decodeAuth'); member = await createMember(walletSpy); - rmsWallet = (await getWallet(Network.RMS)) as SmrWallet; + rmsWallet = await getWallet(Network.RMS); const space = await createSpace(walletSpy, member); token = await saveToken(space.uid, member); diff --git a/packages/functions/test-tangle/token-import/Helper.ts b/packages/functions/test-tangle/token-import/Helper.ts index 3b9290bb58..410ae6f449 100644 --- a/packages/functions/test-tangle/token-import/Helper.ts +++ b/packages/functions/test-tangle/token-import/Helper.ts @@ -1,8 +1,8 @@ import { COL, Member, Network, Space, SUB_COL, Token, TokenStatus } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { mintTokenOrder } from '../../src/runtime/firebase/token/minting'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -23,7 +23,7 @@ export class Helper { public space: Space = {} as any; public importSpace: Space = {} as any; public token: Token = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public member: string = ''; public walletSpy: any = {} as any; public network = Network.RMS; @@ -38,7 +38,7 @@ export class Helper { this.space = await createSpace(this.walletSpy, this.guardian.uid); this.importSpace = await createSpace(this.walletSpy, this.guardian.uid); this.token = await this.saveToken(this.space.uid, this.guardian.uid, this.member); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.address = await this.walletService.getAddressDetails( getAddress(this.guardian, this.network), ); diff --git a/packages/functions/test-tangle/token.based.voting/Helper.ts b/packages/functions/test-tangle/token.based.voting/Helper.ts index a30bbcd7aa..0e2b8d7771 100644 --- a/packages/functions/test-tangle/token.based.voting/Helper.ts +++ b/packages/functions/test-tangle/token.based.voting/Helper.ts @@ -24,8 +24,8 @@ import { } from '../../src/runtime/firebase/proposal'; import { joinSpace } from '../../src/runtime/firebase/space'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import * as wallet from '../../src/utils/wallet.utils'; @@ -39,13 +39,13 @@ export class Helper { public member: string = ''; public space: Space | undefined; public proposal: Proposal | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public guardianAddress: AddressDetails | undefined; public network = Network.RMS; public tokenId = ''; public beforeAll = async () => { - this.walletService = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + this.walletService = await WalletService.newWallet(Network.RMS); }; public beforeEach = async () => { diff --git a/packages/functions/test-tangle/token.claim.minted.spec.ts b/packages/functions/test-tangle/token.claim.minted.spec.ts index 47e3dca633..4dc6f10179 100644 --- a/packages/functions/test-tangle/token.claim.minted.spec.ts +++ b/packages/functions/test-tangle/token.claim.minted.spec.ts @@ -22,7 +22,7 @@ import { retryWallet } from '../src/cron/wallet.cron'; import { build5Db } from '../src/firebase/firestore/build5Db'; import { claimMintedTokenOrder, mintTokenOrder } from '../src/runtime/firebase/token/minting'; import { MnemonicService } from '../src/services/wallet/mnemonic'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; +import { Wallet } from '../src/services/wallet/wallet'; import { dateToTimestamp, serverTime } from '../src/utils/dateTime.utils'; import * as wallet from '../src/utils/wallet.utils'; import { getRandomEthAddress } from '../src/utils/wallet.utils'; @@ -45,10 +45,10 @@ describe('Token minting', () => { let guardian: Member; let space: Space; let token: any; - let walletService: SmrWallet; + let walletService: Wallet; beforeEach(async () => { - walletService = (await getWallet(network)) as SmrWallet; + walletService = await getWallet(network); walletSpy = jest.spyOn(wallet, 'decodeAuth'); const guardianId = await createMember(walletSpy); @@ -322,7 +322,7 @@ describe('Token minting', () => { }); const saveToken = async ( - walletService: SmrWallet, + walletService: Wallet, space: string, guardian: string, notMinted = false, diff --git a/packages/functions/test-tangle/token.mint/Helper.ts b/packages/functions/test-tangle/token.mint/Helper.ts index ee0b4719ab..49fab4c362 100644 --- a/packages/functions/test-tangle/token.mint/Helper.ts +++ b/packages/functions/test-tangle/token.mint/Helper.ts @@ -18,8 +18,8 @@ import { Converter, HexHelper } from '@iota/util.js-next'; import bigInt from 'big-integer'; import { cloneDeep } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; @@ -35,7 +35,7 @@ export class Helper { public address: AddressDetails = {} as any; public space: Space = {} as any; public token: Token = {} as any; - public walletService: SmrWallet = {} as any; + public walletService: Wallet = {} as any; public member: string = ''; public walletSpy: any = {} as any; public network = Network.RMS; @@ -57,7 +57,7 @@ export class Helper { approved, isPublicToken, ); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); this.address = await this.walletService.getAddressDetails( getAddress(this.guardian, this.network), ); @@ -95,7 +95,7 @@ export class Helper { }; public meltMintedToken = async ( - wallet: SmrWallet, + wallet: Wallet, token: Token, amount: number, fromAddress: string, @@ -157,14 +157,14 @@ export class Helper { }; } -export const getAliasOutput = async (wallet: SmrWallet, aliasId: string) => { +export const getAliasOutput = async (wallet: Wallet, aliasId: string) => { const indexer = new IndexerPluginClient(wallet.client); const response = await indexer.alias(aliasId); const outputResponse = await wallet.client.output(response.items[0]); return outputResponse.output as IAliasOutput; }; -export const getStateAndGovernorAddress = async (wallet: SmrWallet, alias: IAliasOutput) => { +export const getStateAndGovernorAddress = async (wallet: Wallet, alias: IAliasOutput) => { const hrp = wallet.info.protocol.bech32Hrp; return (alias.unlockConditions as IGovernorAddressUnlockCondition[]) .map((uc) => (uc.address as IEd25519Address).pubKeyHash) diff --git a/packages/functions/test-tangle/token.mint/token.mint_3.spec.ts b/packages/functions/test-tangle/token.mint/token.mint_3.spec.ts index cc881b149c..003f1037e2 100644 --- a/packages/functions/test-tangle/token.mint/token.mint_3.spec.ts +++ b/packages/functions/test-tangle/token.mint/token.mint_3.spec.ts @@ -20,7 +20,6 @@ import { tradeToken } from '../../src/runtime/firebase/token/trading'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import { expectThrow, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -47,15 +46,10 @@ describe('Token minting', () => { mockWalletReturnValue(helper.walletSpy, helper.guardian.uid, request); const order = await testEnv.wrap(tradeToken)({}); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const order2 = await testEnv.wrap(tradeToken)({}); - const milestone2 = await submitMilestoneFunc( - order2.payload.targetAddress, - order2.payload.amount, - ); - await milestoneProcessed(milestone2.milestone, milestone2.tranId); + await submitMilestoneFunc(order2); await wait(async () => { const buySnap = await build5Db() diff --git a/packages/functions/test-tangle/trade-base-token-order.spec.ts b/packages/functions/test-tangle/trade-base-token-order.spec.ts index 44b51dc2b1..67b598c2ac 100644 --- a/packages/functions/test-tangle/trade-base-token-order.spec.ts +++ b/packages/functions/test-tangle/trade-base-token-order.spec.ts @@ -16,7 +16,7 @@ import { import { build5Db } from '../src/firebase/firestore/build5Db'; import { createMember } from '../src/runtime/firebase/member'; import { cancelTradeOrder, tradeToken } from '../src/runtime/firebase/token/trading'; -import { AddressDetails } from '../src/services/wallet/wallet'; +import { AddressDetails } from '../src/services/wallet/wallet.service'; import { getAddress } from '../src/utils/address.utils'; import { serverTime } from '../src/utils/dateTime.utils'; import * as wallet from '../src/utils/wallet.utils'; diff --git a/packages/functions/test-tangle/tran.match.spec.ts b/packages/functions/test-tangle/tran.match.spec.ts index f575346f5e..869ffb5a6a 100644 --- a/packages/functions/test-tangle/tran.match.spec.ts +++ b/packages/functions/test-tangle/tran.match.spec.ts @@ -8,8 +8,8 @@ import { TransactionValidationType, } from '@build-5/interfaces'; import { build5Db } from '../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../src/services/wallet/wallet'; +import { Wallet } from '../src/services/wallet/wallet'; +import { AddressDetails } from '../src/services/wallet/wallet.service'; import { generateRandomAmount } from '../src/utils/common.utils'; import { serverTime } from '../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../src/utils/wallet.utils'; @@ -19,11 +19,11 @@ import { requestFundsFromFaucet } from './faucet'; describe('Transaction match', () => { let order: Transaction; - let wallet: SmrWallet; + let wallet: Wallet; let address: AddressDetails; beforeAll(async () => { - wallet = (await getWallet(Network.RMS)) as SmrWallet; + wallet = await getWallet(Network.RMS); }); beforeEach(async () => { @@ -69,7 +69,7 @@ describe('Transaction match', () => { }); }); -const saveOrder = async (wallet: SmrWallet) => { +const saveOrder = async (wallet: Wallet) => { const targetAddress = await wallet.getNewIotaAddressDetails(); const data = { type: TransactionType.ORDER, diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_1.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_1.spec.ts index a98cbf20d0..71e9dd7ae1 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_1.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_1.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_10.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_10.spec.ts index 240f837c11..0d7db7b86d 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_10.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_10.spec.ts @@ -2,7 +2,7 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_11.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_11.spec.ts index fd3cff2808..6fef5cbe06 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_11.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_11.spec.ts @@ -2,10 +2,8 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { isEmpty, isEqual } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { IotaWallet } from '../../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; @@ -84,10 +82,6 @@ const dummyPayment = ( const getOutputs = async (network: Network, address: AddressDetails) => { const wallet = await getWallet(network); - if (network === Network.RMS) { - const outputs = await (wallet as SmrWallet).getOutputs(address.bech32, [], false); - return Object.keys(outputs); - } - const outputs = await (wallet as IotaWallet).getOutputs(address.hex); + const outputs = await wallet.getOutputs(address.bech32, [], false); return Object.keys(outputs); }; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_12.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_12.spec.ts index 3d2d8645e2..98715ec78a 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_12.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_12.spec.ts @@ -1,19 +1,12 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; -import { ITransactionPayload, TRANSACTION_ID_LENGTH } from '@iota/iota.js'; -import { - ITransactionPayload as NextITransactionPayload, - TransactionHelper, -} from '@iota/iota.js-next'; -import { Converter, WriteStream } from '@iota/util.js'; +import { ITransactionPayload, TransactionHelper } from '@iota/iota.js-next'; import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { retryWallet } from '../../src/cron/wallet.cron'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { IotaWallet } from '../../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { dateToTimestamp, serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; @@ -78,26 +71,15 @@ describe('Transaction trigger spec', () => { }); consumedOutputIds = []; - if (network === Network.ATOI) { - const block = await (wallet as IotaWallet).client.message( - billPayment.payload.walletReference!.chainReference!, - ); - const inputs = (block.payload as ITransactionPayload).essence.inputs; - consumedOutputIds = inputs.map((input) => - outputIdFromTransactionData(input.transactionId, input.transactionOutputIndex), - ); - } else { - const block = await (wallet as SmrWallet).client.block( - billPayment.payload.walletReference!.chainReference!, - ); - const inputs = (block.payload as NextITransactionPayload).essence.inputs; - consumedOutputIds = inputs.map((input) => - TransactionHelper.outputIdFromTransactionData( - input.transactionId, - input.transactionOutputIndex, - ), - ); - } + + const block = await wallet.client.block(billPayment.payload.walletReference!.chainReference!); + const inputs = (block.payload as ITransactionPayload).essence.inputs; + consumedOutputIds = inputs.map((input) => + TransactionHelper.outputIdFromTransactionData( + input.transactionId, + input.transactionOutputIndex, + ), + ); expect(outputIds.sort()).toEqual(consumedOutputIds.sort()); }, ); @@ -126,19 +108,6 @@ const dummyPayment = ( const getOutputs = async (network: Network, address: AddressDetails) => { const wallet = await getWallet(network); - if (network === Network.RMS) { - const outputs = await (wallet as SmrWallet).getOutputs(address.bech32, [], false); - return Object.keys(outputs); - } - const outputs = await (wallet as IotaWallet).getOutputs(address.hex); + const outputs = await wallet.getOutputs(address.bech32, [], false); return Object.keys(outputs); }; - -const outputIdFromTransactionData = (transactionId: string, outputIndex: number): string => { - const writeStream = new WriteStream(); - writeStream.writeFixedHex('transactionId', TRANSACTION_ID_LENGTH, transactionId); - writeStream.writeUInt16('outputIndex', outputIndex); - const outputIdBytes = writeStream.finalBytes(); - - return Converter.bytesToHex(outputIdBytes); -}; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_13.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_13.spec.ts index f8ee423a70..ac7044fb85 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_13.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_13.spec.ts @@ -12,9 +12,7 @@ import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { retryWallet } from '../../src/cron/wallet.cron'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { IotaWallet } from '../../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { dateToTimestamp, serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; @@ -127,10 +125,6 @@ const dummyPayment = ( const getOutputs = async (network: Network, address: AddressDetails) => { const wallet = await getWallet(network); - if (network === Network.RMS) { - const outputs = await (wallet as SmrWallet).getOutputs(address.bech32, [], false); - return Object.keys(outputs); - } - const outputs = await (wallet as IotaWallet).getOutputs(address.hex); + const outputs = await wallet.getOutputs(address.bech32, [], false); return Object.keys(outputs); }; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_2.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_2.spec.ts index 8310ee8a71..f6f42be29f 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_2.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_2.spec.ts @@ -2,8 +2,7 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { STORAGE_DEPOSIT_RETURN_UNLOCK_CONDITION_TYPE } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; @@ -29,7 +28,7 @@ describe('Transaction trigger spec', () => { it('Bill payment with storage return condition', async () => { const network = Network.RMS; await setup(network); - const wallet = (await getWallet(network)) as SmrWallet; + const wallet = await getWallet(network); const billPayment = { type: TransactionType.BILL_PAYMENT, uid: getRandomEthAddress(), diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_3.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_3.spec.ts index 38913a6c58..4a61b230e7 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_3.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_3.spec.ts @@ -2,9 +2,8 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { addressBalance } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; @@ -31,7 +30,7 @@ describe('Transaction trigger spec', () => { it('Should send native tokens', async () => { const network = Network.RMS; await setup(network); - const wallet = (await getWallet(network)) as SmrWallet; + const wallet = await getWallet(network); const vaultAddress = await wallet.getIotaAddressDetails(VAULT_MNEMONIC); await MnemonicService.store(vaultAddress.bech32, vaultAddress.mnemonic); diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_4.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_4.spec.ts index 60dc34e406..1887bd9764 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_4.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_4.spec.ts @@ -2,9 +2,8 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { addressBalance } from '@iota/iota.js-next'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; @@ -31,7 +30,7 @@ describe('Transaction trigger spec', () => { it('Should send native tokens and credit it', async () => { const network = Network.RMS; await setup(network); - const wallet = (await getWallet(network)) as SmrWallet; + const wallet = await getWallet(network); const vaultAddress = await wallet.getIotaAddressDetails(VAULT_MNEMONIC); await MnemonicService.store(vaultAddress.bech32, vaultAddress.mnemonic); diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_5.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_5.spec.ts index c9c766eab9..95650f98de 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_5.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_5.spec.ts @@ -4,7 +4,7 @@ import dayjs from 'dayjs'; import { isEmpty } from 'lodash'; import { retryWallet } from '../../src/cron/wallet.cron'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { dateToTimestamp, serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_6.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_6.spec.ts index 5e13958cee..65efc6e461 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_6.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_6.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_7.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_7.spec.ts index 4cb5cc857e..a281dfd28f 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_7.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_7.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_8.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_8.spec.ts index dcde12aced..a5850df146 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_8.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_8.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_9.spec.ts b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_9.spec.ts index 1a4a5ab5c3..f2294ba469 100644 --- a/packages/functions/test-tangle/transaction-trigger/transaction-trigger_9.spec.ts +++ b/packages/functions/test-tangle/transaction-trigger/transaction-trigger_9.spec.ts @@ -2,7 +2,7 @@ import { COL, MIN_IOTA_AMOUNT, Network, Transaction, TransactionType } from '@build-5/interfaces'; import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { serverTime } from '../../src/utils/dateTime.utils'; import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { wait } from '../../test/controls/common'; diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/Helper.ts b/packages/functions/test-tangle/withdraw-deposit-nft/Helper.ts index 5874dd0fb1..02a83f059b 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/Helper.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/Helper.ts @@ -44,9 +44,9 @@ import { } from '../../src/runtime/firebase/nft/index'; import { claimSpace } from '../../src/runtime/firebase/space'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { MnemonicService } from '../../src/services/wallet/mnemonic'; -import { AddressDetails } from '../../src/services/wallet/wallet'; +import { Wallet } from '../../src/services/wallet/wallet'; +import { AddressDetails } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import { packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; import { serverTime } from '../../src/utils/dateTime.utils'; @@ -56,7 +56,6 @@ import { getRandomEthAddress } from '../../src/utils/wallet.utils'; import { createMember as createMemberTest, createSpace, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -69,7 +68,7 @@ export class Helper { public collection: string | undefined; public guardian: string | undefined; public space: Space | undefined; - public walletService: SmrWallet | undefined; + public walletService: Wallet | undefined; public walletSpy: any; public nft: Nft | undefined; public guardianAddress: AddressDetails | undefined; @@ -77,7 +76,7 @@ export class Helper { public beforeAll = async () => { this.walletSpy = jest.spyOn(wallet, 'decodeAuth'); - this.walletService = (await getWallet(this.network)) as SmrWallet; + this.walletService = await getWallet(this.network); }; public beforeEach = async () => { @@ -116,8 +115,7 @@ export class Helper { nft: nft.uid, }); const order = await testEnv.wrap(orderNft)({}); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); this.nft = await build5Db().doc(`${COL.NFT}/${nft.uid}`).get(); return this.nft; diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_a.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_a.spec.ts index 208e945299..7e4b426b79 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_a.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_a.spec.ts @@ -20,8 +20,7 @@ import { cloneDeep } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft } from '../../src/runtime/firebase/nft'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { indexToString, packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; import { EMPTY_NFT_ID, createNftOutput } from '../../src/utils/collection-minting-utils/nft.utils'; @@ -98,7 +97,7 @@ describe('Collection minting', () => { }); const mintCustomCollection = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); const totalAmount = Object.values(consumedOutputs).reduce( (acc, act) => acc + Number(act.amount), @@ -133,7 +132,7 @@ const mintCustomCollection = async (address: AddressDetails, metadata: any) => { }; const mintNft = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const nftWallet = new NftWallet(wallet); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_b.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_b.spec.ts index 68d20579f1..80f38fd562 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_b.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_12_b.spec.ts @@ -13,8 +13,7 @@ import { cloneDeep } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft } from '../../src/runtime/firebase/nft'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { indexToString, packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; import { EMPTY_NFT_ID, createNftOutput } from '../../src/utils/collection-minting-utils/nft.utils'; @@ -95,7 +94,7 @@ describe('Collection minting', () => { }); const mintCustomCollection = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); const totalAmount = Object.values(consumedOutputs).reduce( (acc, act) => acc + Number(act.amount), @@ -130,7 +129,7 @@ const mintCustomCollection = async (address: AddressDetails, metadata: any) => { }; const mintNft = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const nftWallet = new NftWallet(wallet); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_13.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_13.spec.ts index cf86f15da1..4ce3e9bc17 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_13.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_13.spec.ts @@ -13,8 +13,7 @@ import { cloneDeep } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft } from '../../src/runtime/firebase/nft'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; -import { AddressDetails, WalletService } from '../../src/services/wallet/wallet'; +import { AddressDetails, WalletService } from '../../src/services/wallet/wallet.service'; import { packBasicOutput } from '../../src/utils/basic-output.utils'; import { indexToString, packEssence, packPayload, submitBlock } from '../../src/utils/block.utils'; import { EMPTY_NFT_ID, createNftOutput } from '../../src/utils/collection-minting-utils/nft.utils'; @@ -120,7 +119,7 @@ describe('Collection minting', () => { }); const mintCustomCollection = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); const totalAmount = Object.values(consumedOutputs).reduce( (acc, act) => acc + Number(act.amount), @@ -155,7 +154,7 @@ const mintCustomCollection = async (address: AddressDetails, metadata: any) => { }; const mintNft = async (address: AddressDetails, metadata: any) => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const nftWallet = new NftWallet(wallet); const consumedOutputs = await wallet.getOutputs(address.bech32, [], false); diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_14.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_14.spec.ts index bb1083c0de..5c05415961 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_14.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_14.spec.ts @@ -13,7 +13,6 @@ import { build5Db } from '../../src/firebase/firestore/build5Db'; import { creditUnrefundable } from '../../src/runtime/firebase/credit/index'; import { depositNft, withdrawNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import { mockWalletReturnValue, wait } from '../../test/controls/common'; @@ -52,7 +51,7 @@ describe('Collection minting', () => { let snap = await query.get(); expect(snap[0].payload.nftId).toBe(nft.mintingData?.nftId); - const wallet = (await getWallet(helper.network)) as SmrWallet; + const wallet = await getWallet(helper.network); const guardianDocRef = build5Db().doc(`${COL.MEMBER}/${helper.guardian}`); const guardianData = await guardianDocRef.get(); const guardianAddress = getAddress(guardianData, helper.network!); diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_a.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_a.spec.ts index d02441dcd6..0edf760c48 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_a.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_a.spec.ts @@ -4,7 +4,6 @@ import { isEqual } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft, withdrawNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { getAddress } from '../../src/utils/address.utils'; import { mockWalletReturnValue, wait } from '../../test/controls/common'; import { getWallet, testEnv } from '../../test/set-up'; @@ -46,7 +45,7 @@ describe('Collection minting', () => { expect(nft.owner).toBeNull(); expect(isEqual(nft.mintingData, mintingData)).toBe(true); - const wallet = (await getWallet(helper.network)) as SmrWallet; + const wallet = await getWallet(helper.network); const guardianData = await build5Db().doc(`${COL.MEMBER}/${helper.guardian}`).get(); const nftWallet = new NftWallet(wallet); let outputs = await nftWallet.getNftOutputs( diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_b.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_b.spec.ts index a737618e64..aac821841a 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_b.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_b.spec.ts @@ -13,7 +13,6 @@ import { isEqual } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft, withdrawNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import { mockWalletReturnValue, wait } from '../../test/controls/common'; @@ -58,7 +57,7 @@ describe('Collection minting', () => { expect(nft.owner).toBeNull(); expect(isEqual(nft.mintingData, mintingData)).toBe(true); - const wallet = (await getWallet(helper.network)) as SmrWallet; + const wallet = await getWallet(helper.network); const guardianData = await build5Db().doc(`${COL.MEMBER}/${helper.guardian}`).get(); const nftWallet = new NftWallet(wallet); let outputs = await nftWallet.getNftOutputs( diff --git a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_c.spec.ts b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_c.spec.ts index d8a26ddd21..8a11957f9f 100644 --- a/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_c.spec.ts +++ b/packages/functions/test-tangle/withdraw-deposit-nft/deposit-withraw-nft_1_c.spec.ts @@ -5,7 +5,6 @@ import { isEqual } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { depositNft, withdrawNft } from '../../src/runtime/firebase/nft/index'; import { NftWallet } from '../../src/services/wallet/NftWallet'; -import { SmrWallet } from '../../src/services/wallet/SmrWalletService'; import { getAddress } from '../../src/utils/address.utils'; import { dateToTimestamp } from '../../src/utils/dateTime.utils'; import { mockWalletReturnValue, wait } from '../../test/controls/common'; @@ -47,7 +46,7 @@ describe('Collection minting', () => { expect(nft.hidden).toBe(true); expect(isEqual(nft.mintingData, mintingData)).toBe(true); - const wallet = (await getWallet(helper.network)) as SmrWallet; + const wallet = await getWallet(helper.network); const guardianData = await build5Db().doc(`${COL.MEMBER}/${helper.guardian}`).get(); const nftWallet = new NftWallet(wallet); let outputs = await nftWallet.getNftOutputs( diff --git a/packages/functions/test/auth.spec.ts b/packages/functions/test/auth.spec.ts index 25877aa9b5..2bbda040f1 100644 --- a/packages/functions/test/auth.spec.ts +++ b/packages/functions/test/auth.spec.ts @@ -1,15 +1,12 @@ import { COL, Member, Network, WEN_FUNC, WenError } from '@build-5/interfaces'; -import { Ed25519 } from '@iota/crypto.js'; -import { Ed25519 as Ed25519Next } from '@iota/crypto.js-next'; -import { Converter } from '@iota/util.js'; -import { Converter as ConverterNext } from '@iota/util.js-next'; +import { Ed25519 } from '@iota/crypto.js-next'; +import { Converter } from '@iota/util.js-next'; import { recoverPersonalSignature } from '@metamask/eth-sig-util'; import jwt from 'jsonwebtoken'; import { get } from 'lodash'; import { build5Db } from '../src/firebase/firestore/build5Db'; import { generateCustomToken } from '../src/runtime/firebase/auth'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; -import { WalletService } from '../src/services/wallet/wallet'; +import { WalletService } from '../src/services/wallet/wallet.service'; import * as config from '../src/utils/config.utils'; import { getJwtSecretKey } from '../src/utils/config.utils'; import * as wallet from '../src/utils/wallet.utils'; @@ -70,22 +67,22 @@ describe('Auth control test', () => { describe('Pub key test', () => { it.each([Network.RMS, Network.SMR])('Should validate SMR pub key', async (network: Network) => { - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const address = await wallet.getNewIotaAddressDetails(); const nonce = getRandomNonce(); const userDocRef = build5Db().doc(`${COL.MEMBER}/${address.bech32}`); await userDocRef.create({ uid: address.bech32, nonce }); - const signature = Ed25519Next.sign( + const signature = Ed25519.sign( address.keyPair.privateKey, Converter.utf8ToBytes(`0x${toHex(nonce)}`), ); const request = { address: 'address', - signature: ConverterNext.bytesToHex(signature), + signature: Converter.bytesToHex(signature), publicKey: { - hex: ConverterNext.bytesToHex(address.keyPair.publicKey), + hex: Converter.bytesToHex(address.keyPair.publicKey), network, }, body: {}, @@ -102,7 +99,7 @@ describe('Pub key test', () => { it.each([Network.IOTA, Network.ATOI])( 'Should validate IOTA pub key', async (network: Network) => { - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const address = await wallet.getNewIotaAddressDetails(); const nonce = getRandomNonce(); @@ -115,7 +112,7 @@ describe('Pub key test', () => { ); const request = { - address: 'address', + address: address.bech32, signature: Converter.bytesToHex(signature), publicKey: { hex: Converter.bytesToHex(address.keyPair.publicKey), @@ -134,27 +131,27 @@ describe('Pub key test', () => { ); it.each([Network.RMS, Network.SMR])('Should throw wrong pub key', async (network: Network) => { - const wallet = (await WalletService.newWallet(network)) as SmrWallet; + const wallet = await WalletService.newWallet(network); const address = await wallet.getNewIotaAddressDetails(); const nonce = getRandomNonce(); const userDocRef = build5Db().doc(`${COL.MEMBER}/${address.bech32}`); await userDocRef.create({ uid: address.bech32, nonce }); - const signature = Ed25519Next.sign( + const signature = Ed25519.sign( address.keyPair.privateKey, Converter.utf8ToBytes(`0x${toHex(nonce)}`), ); - const wallet2 = (await WalletService.newWallet( + const wallet2 = await WalletService.newWallet( network === Network.SMR ? Network.RMS : Network.SMR, - )) as SmrWallet; + ); const secondAddress = await wallet2.getNewIotaAddressDetails(); const request = { address: 'address', - signature: ConverterNext.bytesToHex(signature), + signature: Converter.bytesToHex(signature), publicKey: { - hex: ConverterNext.bytesToHex(secondAddress.keyPair.publicKey), + hex: Converter.bytesToHex(secondAddress.keyPair.publicKey), network, }, body: {}, @@ -168,22 +165,22 @@ describe('Pub key test', () => { }); it('Should update nonce when public key sign in', async () => { - const wallet = (await WalletService.newWallet(Network.RMS)) as SmrWallet; + const wallet = await WalletService.newWallet(Network.RMS); const address = await wallet.getNewIotaAddressDetails(); const nonce = getRandomNonce(); const userDocRef = build5Db().doc(`${COL.MEMBER}/${address.bech32}`); await userDocRef.create({ uid: address.bech32, nonce }); - const signature = Ed25519Next.sign( + const signature = Ed25519.sign( address.keyPair.privateKey, Converter.utf8ToBytes(`0x${toHex(nonce)}`), ); const request = { address: 'address', - signature: ConverterNext.bytesToHex(signature), + signature: Converter.bytesToHex(signature), publicKey: { - hex: ConverterNext.bytesToHex(address.keyPair.publicKey), + hex: Converter.bytesToHex(address.keyPair.publicKey), network: Network.RMS, }, body: {}, diff --git a/packages/functions/test/controls/address.spec.ts b/packages/functions/test/controls/address.spec.ts index c17de9ad02..1976e8670d 100644 --- a/packages/functions/test/controls/address.spec.ts +++ b/packages/functions/test/controls/address.spec.ts @@ -2,7 +2,7 @@ import { COL, Member, Network, Proposal, Space, WenError } from '@build-5/interf import { isEmpty } from 'lodash'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { validateAddress } from '../../src/runtime/firebase/address'; -import { WalletService } from '../../src/services/wallet/wallet'; +import { WalletService } from '../../src/services/wallet/wallet.service'; import { getAddress } from '../../src/utils/address.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { testEnv } from '../set-up'; @@ -10,7 +10,6 @@ import { createMember, createSpace, expectThrow, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, validateMemberAddressFunc, @@ -40,11 +39,7 @@ describe('Address validation test', () => { it('Should validate member address', async () => { const order = await validateMemberAddressFunc(walletSpy, member); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress!, - order.payload.amount!, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); await waitForAddressValidation(member, COL.MEMBER); }); @@ -64,11 +59,7 @@ describe('Address validation test', () => { it('Should validate space address', async () => { let order = await validateSpaceAddressFunc(walletSpy, member, space); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress!, - order.payload.amount!, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + const milestone = await submitMilestoneFunc(order); const proposalQuery = build5Db().collection(COL.PROPOSAL).where('space', '==', space); await wait(async () => { @@ -90,11 +81,7 @@ describe('Address validation test', () => { await waitForAddressValidation(space, COL.SPACE); order = await validateSpaceAddressFunc(walletSpy, member, space); - const milestone2 = await submitMilestoneFunc( - order.payload.targetAddress!, - order.payload.amount!, - ); - await milestoneProcessed(milestone2.milestone, milestone2.tranId); + const milestone2 = await submitMilestoneFunc(order); await wait(async () => { const snap = await proposalQuery.get(); @@ -131,11 +118,7 @@ describe('Address validation test', () => { it('Should replace member address', async () => { const validate = async () => { const order = await validateMemberAddressFunc(walletSpy, member); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress!, - order.payload.amount!, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); }; await validate(); await waitForAddressValidation(member, COL.MEMBER); diff --git a/packages/functions/test/controls/common.ts b/packages/functions/test/controls/common.ts index 72f33e3bcd..14f7cf6f9d 100644 --- a/packages/functions/test/controls/common.ts +++ b/packages/functions/test/controls/common.ts @@ -10,15 +10,19 @@ import { Transaction, TransactionPayloadType, TransactionType, + getMilestoneCol, } from '@build-5/interfaces'; -import chance from 'chance'; +import { TransactionHelper } from '@iota/iota.js-next'; +import dayjs from 'dayjs'; import { build5Db } from '../../src/firebase/firestore/build5Db'; import { validateAddress } from '../../src/runtime/firebase/address'; import { createMember as createMemberFunc } from '../../src/runtime/firebase/member'; import { createSpace as createSpaceFunc } from '../../src/runtime/firebase/space/index'; +import { packBasicOutput } from '../../src/utils/basic-output.utils'; +import { packEssence, packPayload } from '../../src/utils/block.utils'; import * as config from '../../src/utils/config.utils'; -import { serverTime } from '../../src/utils/dateTime.utils'; import * as ipUtils from '../../src/utils/ip.utils'; +import { createUnlock } from '../../src/utils/smr.utils'; import * as wallet from '../../src/utils/wallet.utils'; import { MEDIA, getWallet, testEnv } from '../set-up'; @@ -40,17 +44,16 @@ export const expectThrow = async (call: C | Promise, error: E, message? export const milestoneProcessed = async ( nextMilestone: string, defTranId: string, - network?: Network, + network: Network, ) => { for (let attempt = 0; attempt < 400; ++attempt) { await new Promise((r) => setTimeout(r, 500)); - const doc = await build5Db() - .doc( - `${COL.MILESTONE + (network ? `_${network}` : '')}/${nextMilestone}/${ - SUB_COL.TRANSACTIONS - }/${defTranId}`, - ) - .get>(); + const milestoneTranDocRef = build5Db() + .collection(getMilestoneCol(network)) + .doc(nextMilestone) + .collection(SUB_COL.TRANSACTIONS) + .doc(defTranId); + const doc = await milestoneTranDocRef.get>(); if (doc?.processed) { return; } @@ -58,30 +61,42 @@ export const milestoneProcessed = async ( throw new Error('Milestone was not processed. Id: ' + nextMilestone); }; -export const submitMilestoneFunc = async (address: string, amount: number, network?: Network) => - submitMilestoneOutputsFunc([{ address, amount }], network); +export const submitMilestoneFunc = async (order: Transaction, customAmount?: number) => { + const amount = customAmount || order.payload.amount || 0; + const network = order.network || Network.IOTA; + const to = order.payload.targetAddress!; + const walletService = await getWallet(network); + + const from = await walletService.getNewIotaAddressDetails(); + + const consumedOutputId = '0xbdb062b39e38c3ea0b37c32d564ee839da4e1d66ceb035a56ed1e87caa3fc5950000'; + const consumedOutputs = packBasicOutput(from.bech32, amount, [], walletService.info); + const inputs = [TransactionHelper.inputFromOutputId(consumedOutputId)]; + const inputsCommitment = TransactionHelper.getInputsCommitment([consumedOutputs]); + const outputs = [packBasicOutput(to, amount, [], walletService.info)]; + const essence = packEssence(inputs, inputsCommitment, outputs, walletService, {}); + const unlocks = [createUnlock(essence, from.keyPair)]; + const payload = packPayload(essence, unlocks); -export const submitMilestoneOutputsFunc = async (outputs: T[], network?: Network) => { - const milestoneColl = build5Db().collection( - (COL.MILESTONE + (network ? `_${network}` : '')) as COL, - ); + const milestoneColl = getMilestoneCol(network); const nextMilestone = wallet.getRandomEthAddress(); - const defTranId = chance().string({ - pool: 'abcdefghijklmnopqrstuvwxyz', - casing: 'lower', - length: 40, + const defTranId = wallet.getRandomEthAddress(); + const tranDocRef = build5Db() + .doc(`${milestoneColl}/${nextMilestone}`) + .collection(SUB_COL.TRANSACTIONS) + .doc(defTranId); + await tranDocRef.set({ + uid: defTranId, + createdOn: dayjs().toDate(), + blockId: wallet.getRandomEthAddress(), + milestone: wallet.getRandomEthAddress(), + payload, }); - const defaultFromAddress = - 'iota' + chance().string({ pool: 'abcdefghijklmnopqrstuvwxyz', casing: 'lower', length: 40 }); - const doc = milestoneColl.doc(nextMilestone).collection(SUB_COL.TRANSACTIONS).doc(defTranId); - await doc.set({ - createdOn: serverTime(), - messageId: 'mes-' + defTranId, - inputs: [{ address: defaultFromAddress, amount: 123 }], - outputs: outputs, - }); - await doc.update({ complete: true }); - return { milestone: nextMilestone, tranId: defTranId, fromAdd: defaultFromAddress }; + await tranDocRef.update({ complete: true }); + + await milestoneProcessed(nextMilestone, defTranId, network); + + return { milestone: nextMilestone, tranId: defTranId, fromAdd: from.bech32 }; }; export const validateSpaceAddressFunc = async ( diff --git a/packages/functions/test/controls/nft-bidding.spec.ts b/packages/functions/test/controls/nft-bidding.spec.ts index 4414e69213..fd46097b91 100644 --- a/packages/functions/test/controls/nft-bidding.spec.ts +++ b/packages/functions/test/controls/nft-bidding.spec.ts @@ -31,7 +31,6 @@ import { createMember, createSpace, expectThrow, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -72,8 +71,7 @@ const dummySaleData = (uid: string) => ({ const bidNft = async (memberId: string, amount: number) => { mockWalletReturnValue(walletSpy, memberId, { nft: nft.uid }); const bidOrder = await testEnv.wrap(openBid)({}); - const nftMilestone = await submitMilestoneFunc(bidOrder.payload.targetAddress, amount); - await milestoneProcessed(nftMilestone.milestone, nftMilestone.tranId); + await submitMilestoneFunc(bidOrder, amount); return bidOrder; }; @@ -121,11 +119,7 @@ beforeEach(async () => { collection: collection.uid, nft: nft.uid, }); - const nftMilestone = await submitMilestoneFunc( - nftOrder.payload.targetAddress, - nftOrder.payload.amount, - ); - await milestoneProcessed(nftMilestone.milestone, nftMilestone.tranId); + await submitMilestoneFunc(nftOrder); await wait(async () => { collection = await collectionDocRef.get(); return collection.availableNfts === 0; diff --git a/packages/functions/test/controls/order.spec.ts b/packages/functions/test/controls/order.spec.ts index c10abcba58..82f0bad5c2 100644 --- a/packages/functions/test/controls/order.spec.ts +++ b/packages/functions/test/controls/order.spec.ts @@ -30,11 +30,9 @@ import { createMember, createSpace, expectThrow, - milestoneProcessed, mockIpCheck, mockWalletReturnValue, submitMilestoneFunc, - submitMilestoneOutputsFunc, wait, } from './common'; @@ -165,11 +163,7 @@ describe('Ordering flows', () => { saleAccess: nft.saleAccess || null, saleAccessMembers: nft.saleAccessMembers || [], }); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDocRef = db.collection(COL.NFT).doc(nft.uid); nft = await nftDocRef.get(); @@ -202,8 +196,7 @@ describe('Ordering flows', () => { let nft: Nft = await createNftFunc(member, dummyNft(collection, price)); let order = await submitOrderFunc(member, { collection: collection.uid, nft: nft.uid }); - let milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDocRef = db.collection(COL.NFT).doc(nft.uid); nft = await nftDocRef.get(); @@ -216,8 +209,7 @@ describe('Ordering flows', () => { const buyer = await createMember(walletSpy); order = await submitOrderFunc(buyer, { collection: collection.uid, nft: nft.uid }); - milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const secondSoldNft = await nftDocRef.get(); expect(secondSoldNft.soldOn).toEqual(nft.soldOn); @@ -232,8 +224,7 @@ describe('Ordering flows', () => { const nft = await createNftFunc(member, dummyNft(collection, price)); const order = await submitOrderFunc(member, { collection: collection.uid, nft: nft.uid }); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDbRec: any = await db.collection(COL.NFT).doc(nft.uid).get(); expect(member).toBe(nftDbRec.owner); @@ -255,8 +246,7 @@ describe('Ordering flows', () => { await createNftFunc(member, dummyNft(collection, price)); const order = await submitOrderFunc(member, { collection: collection.uid }); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDbRec: any = await db.collection(COL.NFT).doc(order.payload.nft).get(); expect(member).toBe(nftDbRec.owner); @@ -273,8 +263,7 @@ describe('Ordering flows', () => { await createNftFunc(member, dummyNft(collection, price)); const order = await submitOrderFunc(member, { collection: collection.uid }); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDbRec: any = await db.collection(COL.NFT).doc(order.payload.nft).get(); expect(member).toBe(nftDbRec.owner); @@ -345,10 +334,7 @@ describe('Ordering flows', () => { } for (const o of orders) { - const milestone = await submitMilestoneOutputsFunc([ - { amount: o.payload.amount, address: o.payload.targetAddress }, - ]); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(o); } // Validate each owner has the NFTs. @@ -386,8 +372,7 @@ describe('Ordering flows', () => { // Confirm payment. const wrongAmount = order.payload.amount * 1.5; - const milestone = await submitMilestoneFunc(order.payload.targetAddress, wrongAmount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + const milestone = await submitMilestoneFunc(order, wrongAmount); const nftDbRec = await db.collection(COL.NFT).doc(order.payload.nft).get(); expect(nftDbRec?.sold).toBe(false); @@ -429,9 +414,7 @@ describe('Ordering flows', () => { collection: collection.uid, }); - // Confirm payment. - const milestone = await submitMilestoneFunc(order.payload.targetAddress, order.payload.amount); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order); const nftDbRec: any = await db.collection(COL.NFT).doc(order.payload.nft).get(); expect(nftDbRec.sold).toBe(true); diff --git a/packages/functions/test/controls/token-distribution-auto-trigger.spec.ts b/packages/functions/test/controls/token-distribution-auto-trigger.spec.ts index 58fcc7d554..170affe1e0 100644 --- a/packages/functions/test/controls/token-distribution-auto-trigger.spec.ts +++ b/packages/functions/test/controls/token-distribution-auto-trigger.spec.ts @@ -24,7 +24,6 @@ import { createMember, createSpace, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, tokenProcessed, @@ -141,11 +140,10 @@ describe('Token trigger test', () => { const orderPromises = input.totalDeposit.map(async (_, i) => { const order = await submitTokenOrderFunc(walletSpy, members[i], { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, + await submitMilestoneFunc( + order, Number(bigDecimal.multiply(input.totalDeposit[i], MIN_IOTA_AMOUNT)), ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); return order; }); @@ -220,11 +218,10 @@ describe('Token trigger test', () => { .map(() => 7) .map(async (totalDeposit, i) => { const order = await submitTokenOrderFunc(walletSpy, members[i], { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, + await submitMilestoneFunc( + order, Number(bigDecimal.multiply(totalDeposit, MIN_IOTA_AMOUNT)), ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); return order; }); diff --git a/packages/functions/test/controls/token-distribution.spec.ts b/packages/functions/test/controls/token-distribution.spec.ts index d4d884eadd..f9d2adb546 100644 --- a/packages/functions/test/controls/token-distribution.spec.ts +++ b/packages/functions/test/controls/token-distribution.spec.ts @@ -27,7 +27,6 @@ import { createRoyaltySpaces, createSpace, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, tokenProcessed, @@ -364,11 +363,10 @@ describe('Token trigger test', () => { const orderPromises = Array.from(Array(input.totalDeposit.length)).map(async (_, i) => { const order = await submitTokenOrderFunc(walletSpy, members[i], { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, + await submitMilestoneFunc( + order, Number(bigDecimal.multiply(input.totalDeposit[i], MIN_IOTA_AMOUNT)), ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); return order; }); @@ -458,11 +456,7 @@ describe('Token trigger test', () => { const orderPromises = totalDeposits.map(async (totalDeposit, i) => { const order = await submitTokenOrderFunc(walletSpy, members[i], { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - Number(bigDecimal.multiply(totalDeposit, MIN_IOTA_AMOUNT)), - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, Number(bigDecimal.multiply(totalDeposit, MIN_IOTA_AMOUNT))); return order; }); @@ -512,8 +506,7 @@ describe('Token trigger test', () => { await build5Db().doc(`${COL.TOKEN}/${token.uid}`).create(token); const order = await submitTokenOrderFunc(walletSpy, members[0], { token: token.uid }); - const nextMilestone = await submitMilestoneFunc(order.payload.targetAddress, totalPaid); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, totalPaid); await build5Db().doc(`${COL.TOKEN}/${token.uid}`).update({ status: TokenStatus.PROCESSING }); await tokenProcessed(token.uid, 1, true); diff --git a/packages/functions/test/controls/token-trade.buy.spec.ts b/packages/functions/test/controls/token-trade.buy.spec.ts index 9fa58593bb..b52de1701c 100644 --- a/packages/functions/test/controls/token-trade.buy.spec.ts +++ b/packages/functions/test/controls/token-trade.buy.spec.ts @@ -19,7 +19,6 @@ import { createMember, expectThrow, getRandomSymbol, - milestoneProcessed, mockIpCheck, mockWalletReturnValue, submitMilestoneFunc, @@ -56,8 +55,7 @@ describe('Trade controller, buy token', () => { }; mockWalletReturnValue(walletSpy, memberAddress, request); const order = await testEnv.wrap(tradeToken)({}); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, MIN_IOTA_AMOUNT * 5); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(order, MIN_IOTA_AMOUNT * 5); const buySnap = await build5Db() .collection(COL.TOKEN_MARKET) @@ -96,11 +94,8 @@ describe('Trade controller, buy token', () => { mockWalletReturnValue(walletSpy, memberAddress, request); const order = await testEnv.wrap(tradeToken)({}); - const milestone = await submitMilestoneFunc(order.payload.targetAddress, MIN_IOTA_AMOUNT * 5); - await milestoneProcessed(milestone.milestone, milestone.tranId); - - const milestone2 = await submitMilestoneFunc(order.payload.targetAddress, MIN_IOTA_AMOUNT * 5); - await milestoneProcessed(milestone2.milestone, milestone2.tranId); + await submitMilestoneFunc(order, MIN_IOTA_AMOUNT * 5); + await submitMilestoneFunc(order, MIN_IOTA_AMOUNT * 5); const buysSnap = await build5Db() .collection(COL.TOKEN_MARKET) diff --git a/packages/functions/test/controls/token-trade.trigger.spec.ts b/packages/functions/test/controls/token-trade.trigger.spec.ts index 7956822f4f..1c1c317f0b 100644 --- a/packages/functions/test/controls/token-trade.trigger.spec.ts +++ b/packages/functions/test/controls/token-trade.trigger.spec.ts @@ -34,7 +34,6 @@ import { createMember, createRoyaltySpaces, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, saveSoon, submitMilestoneFunc, @@ -46,11 +45,10 @@ let walletSpy: any; const buyTokenFunc = async (memberAddress: string, request: any) => { mockWalletReturnValue(walletSpy, memberAddress, { ...request, type: TokenTradeOrderType.BUY }); const order = await testEnv.wrap(tradeToken)({}); - const milestone = await submitMilestoneFunc( - order.payload.targetAddress, + await submitMilestoneFunc( + order, Number(bigDecimal.floor(bigDecimal.multiply(request.price, request.count))), ); - await milestoneProcessed(milestone.milestone, milestone.tranId); return order; }; diff --git a/packages/functions/test/controls/token.order.spec.ts b/packages/functions/test/controls/token.order.spec.ts index a11efe9819..fb5e897193 100644 --- a/packages/functions/test/controls/token.order.spec.ts +++ b/packages/functions/test/controls/token.order.spec.ts @@ -22,7 +22,6 @@ import { createSpace, expectThrow, getRandomSymbol, - milestoneProcessed, mockIpCheck, mockWalletReturnValue, submitMilestoneFunc, @@ -94,11 +93,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should create token order', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const distribution = await build5Db() .doc(`${COL.TOKEN}/${token.uid}/${SUB_COL.DISTRIBUTION}/${memberAddress}`) @@ -109,18 +104,10 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should order more token', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const order2 = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone2 = await submitMilestoneFunc( - order2.payload.targetAddress, - order2.payload.amount, - ); - await milestoneProcessed(nextMilestone2.milestone, nextMilestone2.tranId); + await submitMilestoneFunc(order2); const distribution = await build5Db() .doc(`${COL.TOKEN}/${token.uid}/${SUB_COL.DISTRIBUTION}/${memberAddress}`) @@ -132,11 +119,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should create token order and should credit some amount', async () => { for (const _ of [0, 1]) { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); } const distribution = await build5Db() @@ -169,11 +152,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should create token order and should credit all amount', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const distribution = await build5Db() .doc(`${COL.TOKEN}/${token.uid}/${SUB_COL.DISTRIBUTION}/${memberAddress}`) @@ -204,11 +183,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should create token order and should fail credit, not in cool down period', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); await build5Db() .doc(`${COL.TOKEN}/${token.uid}`) @@ -223,11 +198,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should throw, amount too much to refund', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const distribution = await build5Db() .doc(`${COL.TOKEN}/${token.uid}/${SUB_COL.DISTRIBUTION}/${memberAddress}`) @@ -243,11 +214,7 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should throw, amount too much to refund after second credit', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); await build5Db() .doc(`${COL.TOKEN}/${token.uid}`) @@ -310,14 +277,9 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { mockWalletReturnValue(walletSpy, memberAddress, { token: token.uid }); await expectThrow(testEnv.wrap(orderToken)({}), WenError.you_dont_have_required_NFTs.key); }); - it('Should create token order and should credit, not leave less then MIN amount', async () => { const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - 1.5 * MIN_IOTA_AMOUNT, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, 1.5 * MIN_IOTA_AMOUNT); const distribution = await build5Db() .doc(`${COL.TOKEN}/${token.uid}/${SUB_COL.DISTRIBUTION}/${memberAddress}`) @@ -341,12 +303,10 @@ describe('Token controller: ' + WEN_FUNC.orderToken, () => { it('Should create order and deposit in parallel', async () => { const array = Array.from(Array(10)); const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const amounts = array.map((_, index) => index * MIN_IOTA_AMOUNT); - const total = array.reduce((sum, _, index) => sum + index * MIN_IOTA_AMOUNT, 0); - const deposit = async (amount: number) => { - const nextMilestone = await submitMilestoneFunc(order.payload.targetAddress, amount); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); - }; + const amounts = array.map((_, index) => (index + 1) * MIN_IOTA_AMOUNT); + const total = array.reduce((sum, _, index) => sum + (index + 1) * MIN_IOTA_AMOUNT, 0); + const deposit = async (amount: number) => submitMilestoneFunc(order, amount); + const promises = amounts.map(deposit); await Promise.all(promises); const distribution = ( diff --git a/packages/functions/test/controls/token/token.airdrop.claim.spec.ts b/packages/functions/test/controls/token/token.airdrop.claim.spec.ts index 6bc26d42eb..65cd81f485 100644 --- a/packages/functions/test/controls/token/token.airdrop.claim.spec.ts +++ b/packages/functions/test/controls/token/token.airdrop.claim.spec.ts @@ -27,7 +27,6 @@ import { createSpace, expectThrow, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -91,11 +90,7 @@ describe('Claim airdropped token test', () => { await airdrop(); mockWalletReturnValue(walletSpy, guardian, { token: token.uid }); const order = await testEnv.wrap(claimAirdroppedToken)({}); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const orderTran = await build5Db().doc(`${COL.TRANSACTION}/${order.uid}`).get(); expect(orderTran.member).toBe(guardian); @@ -128,11 +123,7 @@ describe('Claim airdropped token test', () => { mockWalletReturnValue(walletSpy, guardian, { token: token.uid }); const order = await testEnv.wrap(claimAirdroppedToken)({}); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const orderTran = await build5Db().doc(`${COL.TRANSACTION}/${order.uid}`).get(); expect(orderTran.member).toBe(guardian); @@ -175,11 +166,7 @@ describe('Claim airdropped token test', () => { mockWalletReturnValue(walletSpy, guardian, { token: token.uid }); const order = await testEnv.wrap(claimAirdroppedToken)({}); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const orderTran = await build5Db().doc(`${COL.TRANSACTION}/${order.uid}`).get(); expect(orderTran.member).toBe(guardian); @@ -207,11 +194,7 @@ describe('Claim airdropped token test', () => { const claimToken = async () => { const order = await testEnv.wrap(claimAirdroppedToken)({}); await new Promise((r) => setTimeout(r, 1000)); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); return order; }; const promises = [claimToken(), claimToken()]; @@ -268,11 +251,7 @@ describe('Claim airdropped token test', () => { mockWalletReturnValue(walletSpy, guardian, { token: token.uid }); const order = await testEnv.wrap(claimAirdroppedToken)({}); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - order.payload.amount, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order); const orderTran = await build5Db().doc(`${COL.TRANSACTION}/${order.uid}`).get(); expect(orderTran.member).toBe(guardian); diff --git a/packages/functions/test/controls/token/token.cancel.pub.sale.spec.ts b/packages/functions/test/controls/token/token.cancel.pub.sale.spec.ts index 6b2e5df1e8..e4db5eeb47 100644 --- a/packages/functions/test/controls/token/token.cancel.pub.sale.spec.ts +++ b/packages/functions/test/controls/token/token.cancel.pub.sale.spec.ts @@ -25,7 +25,6 @@ import { createMember, createSpace, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, wait, @@ -60,11 +59,7 @@ const setAvailableOrderAndCancelSale = async ( ), }); const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - miotas * MIN_IOTA_AMOUNT, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, miotas * MIN_IOTA_AMOUNT); const distribution = await distributionDocRef.get(); expect(distribution.totalDeposit).toBe(miotas * MIN_IOTA_AMOUNT); @@ -166,11 +161,7 @@ describe('Token controller: ' + WEN_FUNC.cancelPublicSale, () => { ), }); const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - 7 * MIN_IOTA_AMOUNT, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, 7 * MIN_IOTA_AMOUNT); await tokenDocRef.update({ status: TokenStatus.PROCESSING }); await wait(async () => (await tokenDocRef.get())?.status === TokenStatus.PRE_MINTED); diff --git a/packages/functions/test/controls/token/token.order.and.claim.air.spec.ts b/packages/functions/test/controls/token/token.order.and.claim.air.spec.ts index 5c54f72eb6..c9310a4f73 100644 --- a/packages/functions/test/controls/token/token.order.and.claim.air.spec.ts +++ b/packages/functions/test/controls/token/token.order.and.claim.air.spec.ts @@ -22,7 +22,6 @@ import { createMember, createSpace, getRandomSymbol, - milestoneProcessed, mockWalletReturnValue, submitMilestoneFunc, tokenProcessed, @@ -96,19 +95,11 @@ describe('Order and claim airdropped token test', () => { expect(distribution.totalUnclaimedAirdrop).toBe(5); const order = await submitTokenOrderFunc(walletSpy, memberAddress, { token: token.uid }); - const nextMilestone = await submitMilestoneFunc( - order.payload.targetAddress, - 5 * token.pricePerToken, - ); - await milestoneProcessed(nextMilestone.milestone, nextMilestone.tranId); + await submitMilestoneFunc(order, 5 * token.pricePerToken); mockWalletReturnValue(walletSpy, memberAddress, { token: token.uid }); const claimOrder = await testEnv.wrap(claimAirdroppedToken)({}); - const milestone = await submitMilestoneFunc( - claimOrder.payload.targetAddress, - claimOrder.payload.amount, - ); - await milestoneProcessed(milestone.milestone, milestone.tranId); + await submitMilestoneFunc(claimOrder); await wait(async () => { const snap = await build5Db() diff --git a/packages/functions/test/milestone.sync.ts b/packages/functions/test/milestone.sync.ts index 12586f0b1f..40023e256d 100644 --- a/packages/functions/test/milestone.sync.ts +++ b/packages/functions/test/milestone.sync.ts @@ -1,14 +1,11 @@ import { OutputTypes, TREASURY_OUTPUT_TYPE } from '@iota/iota.js-next'; -import { COL, MilestoneTransaction, Network, SUB_COL } from '@build-5/interfaces'; +import { COL, Network, SUB_COL } from '@build-5/interfaces'; import * as adminPackage from 'firebase-admin'; - import { last } from 'lodash'; import { build5Db } from '../src/firebase/firestore/build5Db'; - -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; - +import { Wallet } from '../src/services/wallet/wallet'; import { getWallet, projectId } from './set-up'; process.env.FIRESTORE_EMULATOR_HOST = ''; @@ -21,11 +18,11 @@ const app = adminPackage.initializeApp(config, 'second'); const onlineDb = app.firestore(); process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080'; -const syncMilestones = async (col: COL, network: Network) => { +const syncMilestones = async (col: COL) => { const lastDocQuery = onlineDb.collection(col).orderBy('createdOn', 'desc').limit(1); let lastDoc = (await lastDocQuery.get()).docs[0]; - const wallet = (await getWallet(Network.RMS)) as SmrWallet; + const wallet = await getWallet(Network.RMS); while (1) { const snap = await onlineDb @@ -37,21 +34,23 @@ const syncMilestones = async (col: COL, network: Network) => { lastDoc = last(snap.docs) || lastDoc; const batch = build5Db().batch(); - snap.docs.forEach((doc) => batch.create(build5Db().doc(doc.ref.path), doc.data())); + snap.docs.forEach((doc) => { + batch.create(build5Db().doc(doc.ref.path), doc.data()); + }); await batch.commit(); await new Promise((resolve) => setTimeout(resolve, 1000)); - const promises = snap.docs.map((doc) => syncTransactions(network, wallet, doc.ref.path)); + const promises = snap.docs.map((doc) => syncTransactions(wallet, doc.ref.path)); await Promise.all(promises); } }; -const syncTransactions = async (network: Network, wallet: SmrWallet, parentPath: string) => { +const syncTransactions = async (wallet: Wallet, parentPath: string) => { const snap = await onlineDb.collection(`${parentPath}/${SUB_COL.TRANSACTIONS}`).get(); const promises = snap.docs.map(async (doc) => { const data = doc.data(); - const addresses = await getAddesses(data, network, wallet); + const addresses = getAddesses(data, wallet); if (await addressInDb(addresses)) { await build5Db() .doc(doc!.ref.path) @@ -61,15 +60,10 @@ const syncTransactions = async (network: Network, wallet: SmrWallet, parentPath: await Promise.all(promises); }; -const getAddesses = async (doc: any, network: Network, wallet: SmrWallet) => { - if (network === Network.ATOI) { - return (doc as MilestoneTransaction).outputs.map((o) => o.address); - } - const promises = (doc.payload.essence.outputs as OutputTypes[]) +const getAddesses = (doc: any, wallet: Wallet) => + (doc.payload.essence.outputs as OutputTypes[]) .filter((o) => o.type !== TREASURY_OUTPUT_TYPE) .map((o) => wallet.bechAddressFromOutput(o as any)); - return await Promise.all(promises); -}; const addressInDb = async (addresses: string[]) => { for (const address of addresses) { @@ -81,5 +75,5 @@ const addressInDb = async (addresses: string[]) => { return false; }; -syncMilestones(COL.MILESTONE_RMS, Network.RMS); -syncMilestones(COL.MILESTONE_ATOI, Network.ATOI); +syncMilestones(COL.MILESTONE_RMS); +//TODO syncMilestones(COL.MILESTONE_ATOI, Network.ATOI); diff --git a/packages/functions/test/set-up.ts b/packages/functions/test/set-up.ts index 1bb50fb178..b1a0c97921 100644 --- a/packages/functions/test/set-up.ts +++ b/packages/functions/test/set-up.ts @@ -4,9 +4,8 @@ import express from 'express'; import test from 'firebase-functions-test'; import * as functions from 'firebase-functions/v2'; import { isEmpty } from 'lodash'; -import { IotaWallet } from '../src/services/wallet/IotaWalletService'; -import { SmrWallet } from '../src/services/wallet/SmrWalletService'; -import { WalletService } from '../src/services/wallet/wallet'; +import { Wallet } from '../src/services/wallet/wallet'; +import { WalletService } from '../src/services/wallet/wallet.service'; dotenv.config({ path: '.env.local' }); @@ -76,7 +75,7 @@ const setup = async () => { console.log('Setup env'); }; -const wallets: { [key: string]: IotaWallet | SmrWallet } = {}; +const wallets: { [key: string]: Wallet } = {}; export const getWallet = async (network: Network) => { const wallet = wallets[network]; diff --git a/packages/interfaces/src/api/post/AwardCreateRequest.ts b/packages/interfaces/src/api/post/AwardCreateRequest.ts index d4258adbde..5cdaa7f8a9 100644 --- a/packages/interfaces/src/api/post/AwardCreateRequest.ts +++ b/packages/interfaces/src/api/post/AwardCreateRequest.ts @@ -60,7 +60,7 @@ export interface AwardCreateRequest { /** * Network on wich the award will be minted and issued */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Build5 id of the space */ diff --git a/packages/interfaces/src/api/post/CollectionMintRequest.ts b/packages/interfaces/src/api/post/CollectionMintRequest.ts index 42782f3079..7576ccb35b 100644 --- a/packages/interfaces/src/api/post/CollectionMintRequest.ts +++ b/packages/interfaces/src/api/post/CollectionMintRequest.ts @@ -14,7 +14,7 @@ export interface CollectionMintRequest { /** * Network to use for minting the collection. */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Price in case unsold minting option is set to new price. Minimum 1000000, maximum 1000000000000 */ diff --git a/packages/interfaces/src/api/post/NftDepositRequest.ts b/packages/interfaces/src/api/post/NftDepositRequest.ts index d9e64cb74f..59965b4f51 100644 --- a/packages/interfaces/src/api/post/NftDepositRequest.ts +++ b/packages/interfaces/src/api/post/NftDepositRequest.ts @@ -10,5 +10,5 @@ export interface NftDepositRequest { /** * Network on wich the nft was minted. */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; } diff --git a/packages/interfaces/src/api/post/NftStakeRequest.ts b/packages/interfaces/src/api/post/NftStakeRequest.ts index 7cd4be25aa..f50020aeb0 100644 --- a/packages/interfaces/src/api/post/NftStakeRequest.ts +++ b/packages/interfaces/src/api/post/NftStakeRequest.ts @@ -10,7 +10,7 @@ export interface NftStakeRequest { /** * Network on which the nft was staked. */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Type of the stake. */ diff --git a/packages/interfaces/src/api/post/TokenImportRequest.ts b/packages/interfaces/src/api/post/TokenImportRequest.ts index 1682b638ec..d13044084b 100644 --- a/packages/interfaces/src/api/post/TokenImportRequest.ts +++ b/packages/interfaces/src/api/post/TokenImportRequest.ts @@ -10,7 +10,7 @@ export interface ImportMintedTokenRequest { /** * Network name on which the token was minted. */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Build5 space id to which the token should be associated with. */ diff --git a/packages/interfaces/src/api/post/TokenMintRequest.ts b/packages/interfaces/src/api/post/TokenMintRequest.ts index a72e6187f1..e33027a434 100644 --- a/packages/interfaces/src/api/post/TokenMintRequest.ts +++ b/packages/interfaces/src/api/post/TokenMintRequest.ts @@ -10,7 +10,7 @@ export interface TokenMintRequest { /** * Network to use to mint the token. */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Build5 id of the token to mint. */ diff --git a/packages/interfaces/src/api/tangle/AwardCreateTangleRequest.ts b/packages/interfaces/src/api/tangle/AwardCreateTangleRequest.ts index 0b51f2e59b..9ab0dce718 100644 --- a/packages/interfaces/src/api/tangle/AwardCreateTangleRequest.ts +++ b/packages/interfaces/src/api/tangle/AwardCreateTangleRequest.ts @@ -49,7 +49,7 @@ export interface AwardCreateTangleRequest { /** * Network on wich the award will be minted and issued */ - network: 'smr' | 'rms'; + network: 'iota' | 'smr' | 'atoi' | 'rms'; /** * Type of the tangle request. */ diff --git a/packages/interfaces/src/config.ts b/packages/interfaces/src/config.ts index f5cd2be99f..51da76f10e 100644 --- a/packages/interfaces/src/config.ts +++ b/packages/interfaces/src/config.ts @@ -139,8 +139,8 @@ export const MIN_TOKEN_START_DATE_DAY = 7; export const DEFAULT_NETWORK = Network.IOTA; export const PROD_NETWORKS = [Network.IOTA, Network.SMR]; export const TEST_NETWORKS = [Network.ATOI, Network.RMS]; -export const PROD_AVAILABLE_MINTABLE_NETWORKS = [Network.SMR]; -export const TEST_AVAILABLE_MINTABLE_NETWORKS = [Network.SMR, Network.RMS]; +export const PROD_AVAILABLE_MINTABLE_NETWORKS = PROD_NETWORKS; +export const TEST_AVAILABLE_MINTABLE_NETWORKS = [...PROD_NETWORKS, ...TEST_NETWORKS]; export const MAX_FIELD_NAME_LENGTH = 30; export const MAX_FIELD_VALUE_LENGTH = 100; diff --git a/packages/interfaces/src/models/milestone.ts b/packages/interfaces/src/models/milestone.ts index 74ee69df4b..5488c2bcd1 100644 --- a/packages/interfaces/src/models/milestone.ts +++ b/packages/interfaces/src/models/milestone.ts @@ -19,7 +19,8 @@ export interface MilestoneTransaction extends Base { createdOn: Timestamp; messageId: string; milestone: number; - inputs: MilestoneTransactionEntry[]; + fromAddresses: string[]; + consumedOutputIds: string[]; outputs: MilestoneTransactionEntry[]; processed: boolean; build5TransactionId?: string; diff --git a/packages/interfaces/src/utils.ts b/packages/interfaces/src/utils.ts index 96c9fc9735..bea3fa9acc 100644 --- a/packages/interfaces/src/utils.ts +++ b/packages/interfaces/src/utils.ts @@ -1,4 +1,5 @@ import { MAX_WEEKS_TO_STAKE } from './config'; +import { COL, Network } from './models'; const M = 1 / (MAX_WEEKS_TO_STAKE - 1); const B = 2 - M * MAX_WEEKS_TO_STAKE; @@ -13,3 +14,16 @@ export const generateRandomFileName = () => const v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); + +export const getMilestoneCol = (network: Network) => { + switch (network) { + case Network.IOTA: + return COL.MILESTONE_SMR; + case Network.ATOI: + return COL.MILESTONE_RMS; //TODO set ti back to ATOI + case Network.SMR: + return COL.MILESTONE_SMR; + case Network.RMS: + return COL.MILESTONE_RMS; + } +};