From 980924113caf4d3923b306f80828bb48a7cc9868 Mon Sep 17 00:00:00 2001 From: Gerald Date: Fri, 13 Oct 2023 13:58:37 +0200 Subject: [PATCH] Release @argent-x/extension@6.9.0 --- .changeset/README.md | 5 + .changeset/config.json | 15 + .github/dependabot.yml | 12 - .github/workflows/changeset.yml | 68 + .github/workflows/pull-request.yml | 429 +- .github/workflows/release.yml | 88 +- .gitignore | 8 +- .husky/pre-commit | 2 +- .npmrc | 6 + .nvmrc | 2 +- .vscode/settings.json | 1 + .yarnrc | 1 - .yarnrc.yml | 1 - Contributing.md | 6 +- Deployment.md | 74 +- License.md | 253 +- Readme.md | 16 +- docs/tools-for-local-testing.md | 2 +- lerna.json | 6 - nx.json | 12 - package.json | 66 +- packages/dapp/.gitignore | 4 +- packages/dapp/.vscode/settings.json | 4 + packages/dapp/README.md | 2 +- packages/dapp/package.json | 19 +- packages/dapp/src/components/TokenDapp.tsx | 182 +- packages/dapp/src/pages/index.tsx | 8 +- packages/dapp/src/services/token.service.ts | 11 +- packages/dapp/src/services/wallet.service.ts | 74 +- packages/dapp/tsconfig.json | 4 +- packages/e2e/.env.example | 4 + packages/e2e/.vscode/settings.json | 4 + packages/e2e/Dockerfile | 8 +- .../e2e/extension/network-setup/Dockerfile | 4 +- packages/e2e/extension/playwright.config.ts | 35 + packages/e2e/extension/src/config.ts | 37 +- packages/e2e/extension/src/fixtures.ts | 3 + .../e2e/extension/src/languages/ILanguage.ts | 16 + .../e2e/extension/src/languages/en/index.ts | 27 +- .../e2e/extension/src/page-objects/Account.ts | 146 +- .../extension/src/page-objects/Activity.ts | 2 +- .../extension/src/page-objects/AddressBook.ts | 18 +- .../e2e/extension/src/page-objects/Dapps.ts | 53 + .../src/page-objects/DeveloperSettings.ts | 4 +- .../src/page-objects/ExtensionPage.ts | 98 +- .../extension/src/page-objects/Navigation.ts | 12 +- .../e2e/extension/src/page-objects/Network.ts | 43 +- .../src/specs/accountSettings.spec.ts | 51 +- .../extension/src/specs/addressBook.spec.ts | 82 +- .../e2e/extension/src/specs/dapps.spec.ts | 91 + .../extension/src/specs/dappsBanner.spec.ts | 34 +- .../e2e/extension/src/specs/network.spec.ts | 15 +- .../extension/src/specs/receiveFunds.spec.ts | 59 - .../e2e/extension/src/specs/recovery.spec.ts | 80 +- .../e2e/extension/src/specs/sendFunds.spec.ts | 141 + .../extension/src/specs/sendFundsMax.spec.ts | 78 - .../src/specs/sendFundsPartial.spec.ts | 77 - .../e2e/extension/src/specs/welcome.spec.ts | 3 + packages/e2e/extension/src/test.ts | 31 +- packages/e2e/extension/src/utils/account.ts | 102 + packages/e2e/package.json | 16 +- packages/e2e/playwright.config.ts | 53 - packages/e2e/tsconfig.json | 5 +- packages/e2e/webwallet/playwright.config.ts | 44 + packages/e2e/webwallet/src/config.ts | 12 + packages/e2e/webwallet/src/fixtures.ts | 5 + .../e2e/webwallet/src/page-objects/Login.ts | 66 + .../webwallet/src/page-objects/Navigation.ts | 40 + .../src/page-objects/WebWalletPage.ts | 21 + .../e2e/webwallet/src/specs/login.spec.ts | 18 + packages/e2e/webwallet/src/test.ts | 135 + packages/eslint-plugin-local/.eslintrc.js | 31 + packages/eslint-plugin-local/package.json | 24 + .../src/code-import-patterns.ts | 91 + packages/eslint-plugin-local/src/index.ts | 5 + packages/eslint-plugin-local/tsconfig.json | 8 + packages/extension/.env.example | 14 +- packages/extension/.eslintrc.base.js | 55 + packages/extension/.eslintrc.js | 73 +- packages/extension/.vscode/settings.json | 4 + packages/extension/CHANGELOG.md | 152 + packages/extension/manifest/v2.json | 2 +- packages/extension/manifest/v3.json | 2 +- packages/extension/package.json | 107 +- packages/extension/scripts/export.ts | 110 + .../extension/src/assets/default-tokens.json | 66 +- .../__new/procedures/account/create.ts | 6 +- .../__new/procedures/account/deploy.ts | 19 +- .../__new/procedures/account/index.ts | 2 + .../__new/procedures/account/select.ts | 21 + .../__new/procedures/account/upgrade.ts | 4 +- .../accountMessaging/cancelEscape.ts | 55 + .../accountMessaging/changeGuardian.ts | 61 + .../escapeAndChangeGuardian.ts | 110 + .../getEncryptedPrivateKey.ts | 42 + .../getEncryptedSeedPhrase.ts | 41 + .../accountMessaging/getNextPublicKey.ts | 0 .../getNextPublicKeyForMultisig.ts | 31 + .../accountMessaging/getPublicKey.ts | 31 + .../getPublicKeysBufferForMultisig.ts | 33 + .../procedures/accountMessaging/index.ts | 22 + .../accountMessaging/triggerEscapeGuardian.ts | 48 + .../__new/procedures/action/approve.ts | 18 + .../__new/procedures/action/approveAndWait.ts | 18 + .../__new/procedures/action/index.ts | 12 + .../__new/procedures/action/reject.ts | 18 + .../__new/procedures/action/rejectAll.ts | 9 + .../__new/procedures/addressBook/add.ts | 17 + .../__new/procedures/addressBook/index.ts | 10 + .../__new/procedures/addressBook/remove.ts | 12 + .../__new/procedures/addressBook/update.ts | 12 + .../procedures/argentAccount/addAccount.ts | 17 + .../procedures/argentAccount/confirmEmail.ts | 22 + .../argentAccount/getPreferences.ts | 17 + .../__new/procedures/argentAccount/index.ts | 20 + .../argentAccount/isTokenExpired.ts | 17 + .../__new/procedures/argentAccount/logout.ts | 14 + .../procedures/argentAccount/requestEmail.ts | 22 + .../argentAccount/updatePreferences.model.ts | 14 + .../argentAccount/updatePreferences.ts | 19 + .../argentAccount/validateAccount.ts | 14 + .../__new/procedures/multisig/addAccount.ts | 17 + .../__new/procedures/multisig/addOwner.ts | 17 + .../procedures/multisig/addPendingAccount.ts | 22 + .../multisig/addTransactionSignature.ts | 22 + .../__new/procedures/multisig/deploy.ts | 17 + .../__new/procedures/multisig/index.ts | 20 + .../__new/procedures/multisig/removeOwner.ts | 17 + .../__new/procedures/multisig/replaceOwner.ts | 17 + .../procedures/multisig/updateThreshold.ts | 17 + .../__new/procedures/network/add.ts | 11 - .../__new/procedures/network/index.ts | 6 - .../procedures/recovery/recoverSeedphrase.ts | 7 +- .../__new/procedures/session/checkPassword.ts | 36 + .../__new/procedures/session/index.ts | 12 + .../__new/procedures/session/isPasswordSet.ts | 14 + .../__new/procedures/session/start.ts | 73 + .../__new/procedures/session/stop.ts | 13 + .../__new/procedures/tokens/addToken.ts | 10 + .../procedures/tokens/fetchAccountBalance.ts | 36 + .../__new/procedures/tokens/fetchDetails.ts | 13 + .../procedures/tokens/getAccountBalance.ts | 34 + .../procedures/tokens/getAllTokenBalances.ts | 30 + .../tokens/getCurrencyValueForTokens.ts | 15 + .../__new/procedures/tokens/index.ts | 18 + .../__new/procedures/tokens/removeToken.ts | 9 + .../__new/procedures/transfer/index.ts | 6 + .../__new/procedures/transfer/send.ts | 33 + .../procedures/udc/getConstructorParams.ts | 51 + .../background/__new/procedures/udc/index.ts | 7 + .../extension/src/background/__new/router.ts | 38 +- .../__new/services/action/background.ts | 155 + .../background/__new/services/action/index.ts | 10 + .../__new/services/action/interface.ts | 17 + .../__new/services/analytics/index.ts | 8 + .../__new/services/analytics/worker.ts | 17 + .../services/argentAccount/implementation.ts | 206 + .../__new/services/argentAccount/index.ts | 6 + .../__new/services/http/singleton.ts | 3 + .../__new/services/multisig/implementation.ts | 212 + .../__new/services/multisig/index.ts | 8 + .../__new/services/network/background.test.ts | 59 + .../__new/services/network/background.ts | 38 + .../__new/services/network/index.ts | 21 + .../__new/services/network/interface.ts | 9 + .../__new/services/network/status.ts | 75 + .../__new/services/network/worker.ts | 56 + .../onboarding/implementation.test.ts | 2 - .../services/onboarding/implementation.ts | 14 +- .../__new/services/ui/background.test.ts | 86 + .../__new/services/ui/background.ts | 100 + .../src/background/__new/services/ui/index.ts | 18 + .../background/__new/services/ui/interface.ts | 24 + .../extension/src/background/__new/trpc.ts | 49 +- .../extension/src/background/accountDeploy.ts | 26 +- .../src/background/accountDeployAction.ts | 6 +- .../src/background/accountMessaging.ts | 293 +- .../src/background/accountUpgrade.ts | 36 +- .../src/background/actionHandlers.ts | 170 +- .../src/background/actionMessaging.ts | 62 +- .../extension/src/background/actionQueue.ts | 65 - .../extension/src/background/activeTabs.ts | 36 +- .../extension/src/background/background.ts | 16 +- .../src/background/devnet/declareAccounts.ts | 31 +- packages/extension/src/background/download.ts | 5 - packages/extension/src/background/index.ts | 324 +- .../src/background/keys/keyDerivation.ts | 126 +- .../messageHandling/addMessageListeners.ts | 43 + .../src/background/messageHandling/handle.ts | 104 + .../background/messageHandling/messages.ts | 40 + .../extension/src/background/messagingDocs.md | 161 +- .../src/background/migrations/index.ts | 63 + .../migrations/network/removeTestnet2.ts | 5 + .../src/background/migrations/token/v5.9.ts | 37 + .../src/background/migrations/wallet/index.ts | 17 + .../migrations/wallet/testnet2Accounts.ts | 39 + .../migrations/wallet/v5.8.1.test.ts | 73 + .../background/migrations/wallet/v5.8.1.ts | 76 + .../{ => multisig}/multisigDeployAction.ts | 18 +- .../src/background/multisigMessaging.ts | 260 - .../src/background/network/network.service.ts | 31 - .../network/networkStatus.worker.ts | 143 - .../src/background/networkMessaging.ts | 56 +- packages/extension/src/background/nonce.ts | 26 +- .../extension/src/background/onboarding.ts | 8 - .../background/preAuthorizationMessaging.ts | 60 +- packages/extension/src/background/respond.ts | 14 + .../src/background/schema/backup.schema.ts | 109 +- .../src/background/sessionMessaging.ts | 68 - .../src/background/shieldMessaging.ts | 192 - .../extension/src/background/swr/helpers.ts | 43 - .../extension/src/background/swr/index.ts | 87 - .../extension/src/background/swr/types.ts | 14 - .../src/background/tokenMessaging.ts | 25 +- .../src/background/transactions/badgeText.ts | 13 +- .../transactions/checkTransactionHash.ts | 25 + .../transactions/determineUpdates.ts | 2 +- .../fees/multisigFeeEstimation.ts | 32 - .../src/background/transactions/fees/store.ts | 49 - .../transactions/onupdate/declareContract.ts | 2 +- .../transactions/onupdate/deployAccount.ts | 2 +- .../background/transactions/onupdate/nonce.ts | 2 +- .../transactions/onupdate/notifications.ts | 13 +- .../transactions/onupdate/upgrade.ts | 2 +- .../transactions/service/base.test.ts | 90 + .../background/transactions/service/base.ts | 58 + .../transactions/service/starknet.service.ts | 186 + .../background/transactions/service/worker.ts | 10 + .../transactions/sources/onchain.ts | 46 +- .../transactions/sources/voyager.model.ts | 11 + .../transactions/sources/voyager.ts | 13 +- .../src/background/transactions/store.ts | 36 +- .../src/background/transactions/tracking.ts | 34 - .../transactions/transactionAdapter.ts | 11 + .../transactions/transactionExecution.ts | 184 +- .../transactions/transactionMessaging.ts | 381 +- .../background/transactions/transformers.ts | 4 +- .../extension/src/background/udcAction.ts | 121 +- .../extension/src/background/udcMessaging.ts | 82 +- .../src/background/utils/argentMaxFee.ts | 6 +- .../src/background/utils/uniqueSet.test.ts | 67 + .../src/background/utils/uniqueSet.ts | 25 + packages/extension/src/background/wallet.ts | 1283 - .../wallet/account/shared.service.test.ts | 340 + .../wallet/account/shared.service.ts | 191 + .../wallet/account/starknet.service.test.ts | 138 + .../wallet/account/starknet.service.ts | 196 + .../wallet/backup/backup.service.ts | 74 + .../wallet/crypto/shared.service.ts | 60 + .../wallet/crypto/starknet.service.ts | 402 + .../background/wallet/deployment/interface.ts | 35 + .../wallet/deployment/starknet.service.ts | 551 + .../extension/src/background/wallet/index.ts | 246 + .../{accounts.ts => wallet/loadContracts.ts} | 4 +- .../background/wallet/recovery/interface.ts | 15 + .../wallet/recovery/shared.service.test.ts | 115 + .../wallet/recovery/shared.service.ts | 53 + .../wallet/recovery/starknet.service.ts | 411 + .../background/wallet/session/interface.ts | 5 + .../wallet/session/session.service.ts | 164 + .../wallet/session/walletSession.model.ts | 4 + .../background/wallet/starknet.constants.ts | 22 + .../src/background/wallet/test.utils.ts | 221 + .../src/background/walletSingleton.ts | 145 +- packages/extension/src/background/workers.ts | 22 + packages/extension/src/content.ts | 2 +- .../extension/src/inpage/ArgentXAccount.ts | 35 +- ...{ArgentXAccount3.ts => ArgentXAccount4.ts} | 43 +- .../extension/src/inpage/ArgentXProvider.ts | 24 + .../extension/src/inpage/ArgentXProvider4.ts | 28 + .../src/inpage/requestMessageHandlers.ts | 86 +- .../src/inpage/starknetWindowObject.ts | 27 +- packages/extension/src/inpage/trpcClient.ts | 2 +- .../src/shared/__new/services/ui/constants.ts | 1 + .../__new/services/ui/implementation.test.ts | 2 + .../__new/services/ui/implementation.ts | 29 +- .../src/shared/__new/services/ui/interface.ts | 31 +- .../shared/account/details/escape.model.ts | 18 + .../getAccountCairoVersionFromChain.ts | 39 + .../getAccountClassHashFromChain.test.ts | 249 + .../details/getAccountClassHashFromChain.ts | 133 + .../getAccountDeployStatusFromChain.ts | 24 + .../details/getAccountGuardiansFromChain.ts | 1 - .../details/getAccountTypesFromChain.ts | 101 - .../details/getAndMergeAccountDetails.test.ts | 6 +- .../details/getAndMergeAccountDetails.ts | 10 +- .../src/shared/account/details/getEscape.ts | 55 +- .../src/shared/account/details/getGuardian.ts | 36 +- .../account/details/getImplementation.ts | 58 +- .../src/shared/account/details/index.ts | 7 + .../details/tryGetClassHashFromMulticall.ts | 21 + .../details/tryGetClassHashFromProvider.ts | 13 + .../src/shared/account/details/util.ts | 4 +- .../extension/src/shared/account/selectors.ts | 2 +- .../account/service/implementation.test.ts | 46 +- .../shared/account/service/implementation.ts | 49 +- .../src/shared/account/service/index.ts | 4 + .../src/shared/account/service/interface.ts | 5 +- .../src/shared/account/store/index.ts | 7 +- .../shared/account/store/serialize.test.ts | 54 +- .../src/shared/account/store/serialize.ts | 51 +- .../src/shared/account/storeMigration.ts | 6 +- .../extension/src/shared/account/update.ts | 92 +- .../account/worker/implementation.test.ts | 165 + .../shared/account/worker/implementation.ts | 149 + .../src/shared/account/worker/index.ts | 8 + .../extension/src/shared/actionQueue/index.ts | 5 + .../src/shared/actionQueue/queue/interface.ts | 17 + .../shared/actionQueue/queue/queue.test.ts | 88 + .../src/shared/actionQueue/queue/queue.ts | 123 + .../src/shared/actionQueue/schema.ts | 21 + .../shared/actionQueue/service/interface.ts | 17 + .../extension/src/shared/actionQueue/store.ts | 11 - .../src/shared/actionQueue/store/index.ts | 27 + .../extension/src/shared/actionQueue/types.ts | 14 +- .../extension/src/shared/addressBook/index.ts | 61 - .../src/shared/addressBook/schema.ts | 40 +- .../src/shared/addressBook/selectors.ts | 8 - .../service/implementation.test.ts | 187 + .../addressBook/service/implementation.ts | 88 + .../src/shared/addressBook/service/index.ts | 4 + .../shared/addressBook/service/interface.ts | 9 + .../src/shared/addressBook/storage.ts | 10 - .../src/shared/addressBook/store/index.ts | 23 + .../extension/src/shared/addressBook/type.ts | 23 +- packages/extension/src/shared/analytics.ts | 54 +- .../extension/src/shared/api/constants.ts | 70 +- .../shared/argentAccount/service/interface.ts | 23 + packages/extension/src/shared/avatarImage.ts | 43 - .../src/shared/call/changeGuardianCall.ts | 7 +- .../shared/call/changeMultisigSignersCall.ts | 38 +- .../extension/src/shared/call/erc20Call.ts | 14 +- .../src/shared/call/nftTransferCall.ts | 15 +- .../shared/call/setMultisigThresholdCalls.ts | 8 +- .../src/shared/chain/service/__test__/mock.ts | 27 + .../shared/chain/service/implementation.ts | 70 + .../src/shared/chain/service/index.ts | 4 + .../src/shared/chain/service/interface.ts | 16 + packages/extension/src/shared/config.ts | 17 + .../src/shared/devnet/mintFeeToken.ts | 16 +- .../extension/src/shared/errors/Readme.md | 46 + .../extension/src/shared/errors/account.ts | 26 + .../src/shared/errors/accountMessaging.ts | 21 + .../extension/src/shared/errors/action.ts | 13 + .../src/shared/errors/addressBook.ts | 16 + .../src/shared/errors/argentAccount.ts | 61 + .../extension/src/shared/errors/baseError.ts | 40 + .../extension/src/shared/errors/errorData.ts | 33 + .../extension/src/shared/errors/multisig.ts | 15 + .../extension/src/shared/errors/network.ts | 16 + .../extension/src/shared/errors/pubKey.ts | 15 + .../extension/src/shared/errors/recovery.ts | 19 + .../extension/src/shared/errors/session.ts | 18 + packages/extension/src/shared/errors/token.ts | 22 + .../src/shared/errors/transaction.ts | 17 + packages/extension/src/shared/errors/udc.ts | 20 + .../extension/src/shared/errors/wallet.ts | 16 + .../extension/src/shared/explorer/type.ts | 9 +- .../src/shared/knownDapps/implementation.ts | 45 + .../extension/src/shared/knownDapps/index.ts | 13 + .../src/shared/knownDapps/interface.ts | 11 + .../knownDapps/worker/implementation.ts | 32 + .../src/shared/knownDapps/worker/index.ts | 8 + .../src/shared/messages/AccountMessage.ts | 99 +- .../src/shared/messages/ActionMessage.ts | 13 +- .../src/shared/messages/MultisigMessage.ts | 74 - .../src/shared/messages/NetworkMessage.ts | 2 +- .../messages/PreAuthorisationMessage.ts | 2 +- .../src/shared/messages/SessionMessage.ts | 15 - .../src/shared/messages/ShieldMessage.ts | 27 - .../src/shared/messages/TokenMessage.ts | 2 +- .../src/shared/messages/TransactionMessage.ts | 54 +- .../src/shared/messages/UdcMessage.ts | 18 - .../extension/src/shared/messages/index.ts | 4 - .../src/shared/multicall/getMulticall.ts | 34 +- .../extension/src/shared/multisig/account.ts | 258 +- .../src/shared/multisig/multisig.model.ts | 85 +- .../src/shared/multisig/multisig.service.ts | 176 - .../multisig/pendingTransactionsStore.ts | 21 +- .../src/shared/multisig/repository.ts | 38 + .../service/backend/implementation.ts | 268 + .../shared/multisig/service/backend/index.ts | 6 + .../multisig/service/backend/interface.ts | 34 + .../shared/multisig/service/backend/types.ts | 22 + .../multisig/service/messaging/interface.ts | 25 + .../extension/src/shared/multisig/signer.ts | 15 +- .../extension/src/shared/multisig/store.ts | 20 - .../extension/src/shared/multisig/types.ts | 39 +- .../src/shared/multisig/utils/baseMultisig.ts | 55 +- .../utils/getMultisigTransactionType.ts | 23 + .../shared/multisig/utils/pendingMultisig.ts | 31 +- .../src/shared/multisig/utils/selectors.ts | 6 +- .../src/shared/multisig/view/index.ts | 6 + .../{tracking.ts => worker/implementation.ts} | 175 +- .../src/shared/multisig/worker/index.ts | 10 + .../extension/src/shared/network/constants.ts | 24 + .../extension/src/shared/network/defaults.ts | 112 +- .../extension/src/shared/network/index.ts | 65 +- .../extension/src/shared/network/provider.ts | 89 +- .../extension/src/shared/network/schema.ts | 162 +- .../extension/src/shared/network/selectors.ts | 10 +- .../shared/network/service/implementation.ts | 42 +- .../src/shared/network/service/index.ts | 4 + .../src/shared/network/service/interface.ts | 8 +- .../src/shared/network/statusStore.ts | 19 + .../extension/src/shared/network/storage.ts | 18 - .../extension/src/shared/network/store.ts | 35 + packages/extension/src/shared/network/type.ts | 17 +- .../extension/src/shared/network/utils.ts | 81 +- .../src/shared/network/view/index.ts | 4 - .../src/shared/nft/worker/implementation.ts | 137 + .../extension/src/shared/nft/worker/index.ts | 20 + .../{background => shared}/notification.ts | 19 +- .../extension/src/shared/preAuthorizations.ts | 2 +- .../src/shared/schedule/chromeService.test.ts | 120 + .../src/shared/schedule/chromeService.ts | 91 + .../extension/src/shared/schedule/index.ts | 4 + .../src/shared/schedule/interface.ts | 19 + .../extension/src/shared/schemas/address.ts | 26 - .../shared/settings/defaultBlockExplorers.ts | 2 - .../extension/src/shared/settings/index.ts | 16 +- .../extension/src/shared/settings/store.ts | 3 +- .../extension/src/shared/settings/types.ts | 3 +- .../src/shared/shield/GuardianSelfSigner.ts | 15 +- .../shared/shield/GuardianSignerArgentX.ts | 7 +- .../src/shared/shield/backend/account.ts | 43 +- .../extension/src/shared/shield/constants.ts | 5 +- .../extension/src/shared/shield/register.ts | 59 - .../extension/src/shared/shield/validation.ts | 131 - .../validation/addBackendAccount.test.ts | 66 + .../shield/validation/addBackendAccount.ts | 22 + .../validateAccount.test.ts} | 84 +- .../shield/validation/validateAccount.ts | 83 + .../shared/shield/validation/verification.ts | 24 + .../__new/__test__/inmemoryImplementations.ts | 1 + .../storage/__new/__test__/object.test.ts | 53 + .../src/shared/storage/__new/base.ts | 44 + .../src/shared/storage/__new/chrome.ts | 148 + .../src/shared/storage/__new/object.ts | 1 + .../src/shared/storage/__new/prune.ts | 70 + .../storage/__new/repositories/knownDapp.ts | 16 + .../storage/__new/repositories/network.ts | 4 - .../shared/storage/__new/repositories/nft.ts | 49 + .../storage/__test__/chrome-storage.mock.ts | 4 +- .../extension/src/shared/storage/hooks.ts | 25 +- .../extension/src/shared/storage/keyvalue.ts | 30 +- .../extension/src/shared/storage/object.ts | 4 +- .../token/{ => __deprecated}/storage.ts | 6 +- .../shared/token/{ => __deprecated}/type.ts | 13 +- .../shared/token/{ => __deprecated}/utils.ts | 11 +- .../shared/token/__new/repository/token.ts | 17 + .../token/__new/repository/tokenBalance.ts | 16 + .../token/__new/repository/tokenPrice.ts | 15 + .../token/__new/service/implementation.ts | 497 + .../src/shared/token/__new/service/index.ts | 12 + .../shared/token/__new/service/interface.ts | 69 + .../shared/token/__new/types/token.model.ts | 54 + .../token/__new/types/tokenBalance.model.ts | 25 + .../token/__new/types/tokenPrice.model.ts | 39 + .../src/shared/token/__new/utils/index.ts | 67 + .../token/__new/worker/implementation.ts | 292 + .../src/shared/token/__new/worker/index.ts | 27 + .../shared/token/__new/worker/interface.ts | 27 + packages/extension/src/shared/token/amount.ts | 42 - .../src/shared/token/getTokenBalance.ts | 40 - packages/extension/src/shared/token/price.ts | 102 +- .../src/shared/transactionReview.service.ts | 8 +- .../fees/estimatedFeesRepository.ts | 67 + .../transactionSimulation/fees/fees.model.ts | 31 + .../transactionSimulation.service.ts | 94 +- .../src/shared/transactionSimulation/types.ts | 67 +- .../src/shared/transactionSimulation/utils.ts | 47 + packages/extension/src/shared/transactions.ts | 89 +- .../src/shared/transactions/interface.ts | 19 + .../src/shared/transactions/utils.test.ts | 28 + .../src/shared/transactions/utils.ts | 14 + .../src/shared/udc/service/interface.ts | 8 + packages/extension/src/shared/udc/type.ts | 10 +- .../src/shared/utils/accountsEqual.ts | 29 + .../src/shared/utils/accountsMultisigSort.ts | 42 +- .../extension/src/shared/utils/accountv4.ts | 12 + .../src/shared/utils/argentAccountVersion.ts | 48 + packages/extension/src/shared/utils/encode.ts | 14 + packages/extension/src/shared/utils/error.ts | 7 +- packages/extension/src/shared/utils/number.ts | 87 +- .../src/shared/utils/starknetNetwork.ts | 38 +- .../src/shared/utils/transactionSucceeded.ts | 24 + .../src/shared/utils/transactions.test.ts | 49 + .../src/shared/utils/transactions.ts | 12 + packages/extension/src/shared/wallet.model.ts | 9 +- .../extension/src/shared/wallet.service.ts | 46 +- .../src/shared/wallet/storeMigration.ts | 6 +- .../src/shared/wallet/walletStore.ts | 1 + packages/extension/src/ui/App.tsx | 32 +- packages/extension/src/ui/AppRoutes.tsx | 235 +- packages/extension/src/ui/app.state.ts | 4 +- .../ui/components/AddContactBottomSheet.tsx | 31 - .../src/ui/components/AddressCopyButton.tsx | 16 +- .../src/ui/components/ControlledInput.tsx | 18 +- .../src/ui/components/ControlledTextArea.tsx | 35 + .../src/ui/components/CopyTooltip.tsx | 2 + .../src/ui/components/ErrorScreen.tsx | 17 + .../src/ui/components/Icons/AtTheRateIcon.tsx | 19 - .../extension/src/ui/components/InputText.tsx | 2 + .../src/ui/components/LoadingPulse.tsx | 27 - .../src/ui/components/ModalSheet.tsx | 37 + .../extension/src/ui/components/Options.tsx | 138 +- .../src/ui/components/ScreenSkeleton.tsx | 26 + .../src/ui/components/StatusIndicator.tsx | 8 +- .../src/ui/components/SuspenseScreen.tsx | 9 + .../accountActivity/AccountActivity.tsx | 3 +- .../AccountActivityContainer.tsx | 31 +- .../PendingMultisigTransactions.tsx | 11 +- .../accountActivity/PendingTransactions.tsx | 2 +- .../accountActivity/TransactionDetail.tsx | 53 +- .../TransactionDetailScreen.tsx | 4 +- .../accountActivity/TransactionListItem.tsx | 8 +- .../transform/__test__/tokensByNetwork.ts | 4 +- .../goerli-alpha/account-created-alt.json | 2 + ...-dapp-influence-crewmate-purchase-nft.json | 2 + .../goerli-alpha/novel-dapp-no-game.json | 2 + .../transformExplorerTransaction.test.ts | 38 +- .../fingerprintExplorerTransaction.ts | 7 +- .../transformExplorerTransaction.ts | 2 +- .../defaultDisplayNameTransformer.ts | 13 +- .../explorerTransaction/transformers/type.ts | 2 +- .../transform/getTokenForContractAddress.ts | 4 +- .../features/accountActivity/transform/is.ts | 7 +- .../transaction-calls/goerli-alpha/index.ts | 7 +- .../goerli-alpha/multisig-add-owner.json | 9 + .../goerli-alpha/multisig-remove-owner.json | 9 + .../goerli-alpha/multisig-replace-owner.json | 8 + .../__test__/transformTransaction.test.ts | 59 +- .../transaction/transformTransaction.ts | 2 +- .../changeMultisigThresholdTransformer.ts | 2 +- .../transformers/changeMultisigTransformer.ts | 47 +- .../transformers/guardianTransformer.ts | 8 +- .../pendingMultisigTransactionAdapter.ts | 3 +- .../transaction/transformers/type.ts | 2 +- .../accountActivity/transform/type.ts | 5 +- .../features/accountActivity/ui/NFTImage.tsx | 13 +- .../features/accountActivity/ui/NFTTitle.tsx | 14 +- .../ui/SwapTransactionIcon.tsx | 4 +- .../accountActivity/ui/TransactionIcon.tsx | 19 +- .../accountActivity/ui/TransferTitle.tsx | 2 +- .../features/accountActivity/useActivity.ts | 18 +- .../accountActivity/useArgentExplorer.ts | 25 +- .../useTransactionFees.test.ts | 4 +- .../accountActivity/useTransactionFees.ts | 13 +- .../accountActivity/useTransactionNonce.ts | 22 + .../accountEdit/AccountEditButtons.tsx | 92 +- .../AccountEditButtonsMultisig.tsx | 6 + .../accountEdit/AccountEditScreen.tsx | 11 +- .../AccountImplementationScreen.tsx | 37 +- .../ChangeAccountImplementationScreen.tsx | 145 + .../accountNfts/AccountCollection.tsx | 53 + .../accountNfts/AccountCollections.tsx | 121 +- .../AccountCollectionsContainer.tsx | 57 + .../features/accountNfts/CollectionNfts.tsx | 187 +- .../accountNfts/CollectionNftsContainer.tsx | 23 + .../CollectionNftsGenericError.tsx | 26 + .../features/accountNfts/EmptyCollections.tsx | 52 +- .../src/ui/features/accountNfts/NftImage.tsx | 22 + .../features/accountNfts/NftModelViewer.tsx | 5 +- .../src/ui/features/accountNfts/NftScreen.tsx | 93 +- .../accountNfts/NftScreenContainer.tsx | 44 + .../ui/features/accountNfts/SendNftScreen.tsx | 393 - .../ui/features/accountNfts/ViewOnMenu.tsx | 26 +- .../ui/features/accountNfts/aspect.mock.ts | 298 - .../ui/features/accountNfts/aspect.model.ts | 104 - .../accountNfts/aspect.service.test.ts | 52 - .../ui/features/accountNfts/aspect.service.ts | 233 - .../accountNfts/mint-square.service.ts | 18 - .../src/ui/features/accountNfts/nfts.state.ts | 49 + .../ui/features/accountNfts/useCollections.ts | 91 - .../src/ui/features/accountNfts/useNfts.ts | 42 - .../ui/features/accountNfts/useRemoteNft.ts | 64 + .../accountPlugins.tsx/AddPluginScreen.tsx | 4 +- .../accountPlugins.tsx/PluginAccount.ts | 19 +- .../accountPlugins.tsx/useIsPlugin.tsx | 3 +- .../accountTokens/AccountDeprecatedBanner.tsx | 31 + .../ui/features/accountTokens/AccountName.tsx | 69 - .../accountTokens/AccountTokens.test.tsx | 74 + .../features/accountTokens/AccountTokens.tsx | 302 +- .../AccountTokensButtons.test.tsx | 55 + .../accountTokens/AccountTokensButtons.tsx | 138 +- .../AccountTokensButtonsContainer.tsx | 109 + .../accountTokens/AccountTokensContainer.tsx | 161 + .../accountTokens/AccountTokensHeader.tsx | 32 +- .../accountTokens/ExportPrivateKeyScreen.tsx | 6 +- .../accountTokens/HideTokenScreen.tsx | 103 +- .../HideTokenScreenContainer.tsx | 46 + .../SaveRecoverySeedphraseBanner.tsx | 50 + .../accountTokens/SendTokenScreen.tsx | 613 - .../ui/features/accountTokens/TokenIcon.tsx | 2 +- .../ui/features/accountTokens/TokenList.tsx | 40 +- .../features/accountTokens/TokenListItem.tsx | 75 +- .../accountTokens/TokenListItemContainer.tsx | 28 +- .../ui/features/accountTokens/TokenMenu.tsx | 7 +- .../accountTokens/TokenMenuDeprecated.tsx | 111 - .../ui/features/accountTokens/TokenScreen.tsx | 179 - .../features/accountTokens/UpgradeBanner.tsx | 24 +- .../WarningRecoverySeedphraseBanner.tsx | 42 + .../features/accountTokens/tokenPriceHooks.ts | 78 +- .../features/accountTokens/tokens.service.ts | 203 +- .../ui/features/accountTokens/tokens.state.ts | 186 +- .../accountTokens/useAddFundsDialog.tsx | 114 + .../useDisplayTokenAmountAndCurrencyValue.tsx | 3 +- .../accountTokens/useFeeTokenBalance.ts | 16 + .../useLiveTokenBalanceForAccount.ts | 198 + .../accountTokens/useMaxFeeForTransfer.ts | 49 +- .../accountTokens/usePrettyAccountBalance.ts | 17 + .../features/accountTokens/usePrivateKey.ts | 21 +- .../useTokenBalanceForAccount.ts | 220 +- .../accountTokens/useTransactionStatus.ts | 8 +- .../src/ui/features/accounts/Account.ts | 31 +- .../accounts/AccountAddressListItem.tsx | 119 + .../AccountAddressListItemSaveAccessory.tsx | 30 + .../ui/features/accounts/AccountContainer.tsx | 24 +- .../accounts/AccountDeprecatedModal.tsx | 81 + .../accounts/AccountListHiddenScreen.test.tsx | 42 +- .../accounts/AccountListHiddenScreen.tsx | 38 +- .../AccountListHiddenScreenContainer.tsx | 52 +- .../ui/features/accounts/AccountListItem.tsx | 232 +- .../AccountListItemDeprecatedBadge.tsx | 23 + .../AccountListItemShieldBadgeContainer.tsx | 2 +- .../accounts/AccountListItemSkeleton.tsx | 30 + .../accounts/AccountListItemWithBalance.tsx | 17 + .../features/accounts/AccountListScreen.tsx | 106 +- .../accounts/AccountListScreenContainer.tsx | 51 +- .../accounts/AccountListScreenItem.test.tsx | 43 +- .../accounts/AccountListScreenItem.tsx | 116 +- .../AccountListScreenItemContainer.tsx | 62 +- .../accounts/AccountNavigationBar.tsx | 31 +- .../AccountNavigationBarContainer.tsx | 11 +- .../ui/features/accounts/AccountScreen.tsx | 43 +- .../accounts/AccountScreenEmpty.test.tsx | 5 +- .../features/accounts/AccountScreenEmpty.tsx | 2 - .../ui/features/accounts/AccountSelect.tsx | 17 +- .../accounts/AddNewAccountScreen.test.tsx | 2 +- .../features/accounts/AddNewAccountScreen.tsx | 29 +- .../accounts/AddNewAccountScreenContainer.tsx | 60 +- .../accounts/AddressBookMenu.test.tsx | 13 +- .../ui/features/accounts/AddressBookMenu.tsx | 6 +- .../accounts/ClickableShieldBanner.tsx | 37 + .../features/accounts/DeployAccountScreen.tsx | 2 +- .../accounts/DeployAccountScreenContainer.tsx | 7 +- .../features/accounts/GroupedAccountList.tsx | 39 +- .../HideOrDeleteAccountConfirmScreen.tsx | 10 +- ...eOrDeleteAccountConfirmScreenContainer.tsx | 16 +- .../MigrationDisclaimerScreen.test.tsx | 16 - .../accounts/MigrationDisclaimerScreen.tsx | 41 - .../MigrationDisclaimerScreenContainer.tsx | 32 - .../accounts/PrettyAccountAddress.tsx | 107 - .../accounts/PrettyAccountAddressArgentX.tsx | 74 + .../features/accounts/UpgradeScreen.test.tsx | 22 - .../ui/features/accounts/UpgradeScreen.tsx | 37 - .../accounts/UpgradeScreenContainer.tsx | 32 - .../accounts/UpgradeScreenV4.test.tsx | 68 - .../ui/features/accounts/UpgradeScreenV4.tsx | 90 - .../accounts/UpgradeScreenV4Container.tsx | 104 - .../accounts/accountListItem.model.ts | 29 + .../features/accounts/accountMetadata.test.ts | 3 + .../accounts/accountNavigationBar.model.ts | 18 + .../accounts/accountTransactions.state.ts | 42 +- .../accounts/accountUpgradeCheck.test.ts | 156 + .../features/accounts/accountUpgradeCheck.ts | 123 + .../ui/features/accounts/accounts.service.ts | 17 +- .../ui/features/accounts/accounts.state.ts | 51 +- .../accounts/deployAccountScreen.model.ts | 6 + .../hideOrDeleteAccountConfirmScreen.model.ts | 11 + .../accounts/networkTransactions.state.ts | 40 + .../ui/features/accounts/upgrade.service.ts | 238 - .../features/accounts/useAccountOrContact.ts | 43 + .../src/ui/features/accounts/usePublicKey.ts | 21 +- .../src/ui/features/actions/ActionScreen.tsx | 8 +- .../AddNetworkScreen.test.tsx | 7 +- .../AddNetworkScreen/AddNetworkScreen.tsx | 156 +- .../AddNetworkScreenContainer.tsx | 14 +- .../actions/AddTokenActionScreenContainer.tsx | 14 +- .../features/actions/AddTokenScreen.test.tsx | 110 + .../ui/features/actions/AddTokenScreen.tsx | 286 +- .../actions/AddTokenScreenContainer.tsx | 220 +- .../features/actions/ApproveDeployAccount.tsx | 42 +- .../actions/ApproveSignatureScreen.test.tsx | 36 + .../actions/ApproveSignatureScreen.tsx | 15 +- .../ApproveSignatureScreenContainer.tsx | 67 +- .../DeclareContractActionScreenContainer.tsx | 62 +- .../DeployAccountActionScreenContainer.tsx | 67 +- .../DeployContractActionScreenContainer.tsx | 73 +- .../DeployMultisigActionScreenContainer.tsx | 63 +- .../actions/ExecuteFromOutsideScreen.tsx | 22 + .../actions/SignActionScreenContainer.tsx | 39 +- .../SignatureRequestRejectedScreen.tsx | 57 + .../TransactionActionScreenContainer.tsx | 62 +- .../features/actions/__fixtures__/accounts.ts | 28 +- .../features/actions/__fixtures__/aspect.ts | 210 + .../actions/__fixtures__/dataToSign.ts | 36 + .../ui/features/actions/__fixtures__/index.ts | 5 + .../features/actions/__fixtures__/jediswap.ts | 154 +- .../features/actions/__fixtures__/transfer.ts | 127 + .../ui/features/actions/__fixtures__/types.ts | 12 + .../src/ui/features/actions/actions.state.ts | 4 - .../connectDapp/ConnectDappAccountSelect.tsx | 4 +- .../connectDapp/ConnectDappScreen.test.tsx | 57 + .../actions/connectDapp/ConnectDappScreen.tsx | 173 +- .../ConnectDappScreenContainer.tsx | 76 +- .../features/actions/connectDapp/DappIcon.tsx | 23 +- .../actions/connectDapp/DappIconContainer.tsx | 7 + .../actions/connectDapp/KnownDappModal.tsx | 83 + .../connectDapp/useDappDisplayAttributes.ts | 45 +- .../CombinedFeeEstimation.test.tsx | 117 + .../feeEstimation/CombinedFeeEstimation.tsx | 26 +- .../CombinedFeeEstimationContainer.tsx | 84 +- .../DeployAccountFeeEstimation.tsx | 56 +- .../feeEstimation/FeeEstimation.test.tsx | 65 + .../actions/feeEstimation/FeeEstimation.tsx | 27 +- .../feeEstimation/FeeEstimationContainer.tsx | 82 +- .../__fixtures__/combinedFeeEstimation.ts | 96 + .../__fixtures__/feeEstimation.ts | 82 + .../feeEstimation/__fixtures__/feeToken.ts | 4 + .../feeEstimation/__fixtures__/index.ts | 2 + .../actions/feeEstimation/feeError.test.ts | 69 + .../actions/feeEstimation/feeError.ts | 135 + .../feeEstimation/feeEstimation.model.ts | 16 + .../features/actions/feeEstimation/types.ts | 51 +- .../feeEstimation/ui/CopyErrorIcon.tsx | 4 +- .../feeEstimation/ui/FeeEstimationBox.tsx | 10 +- .../feeEstimation/ui/FeeEstimationText.tsx | 1 + .../ui/InsufficientFundsAccordion.tsx | 5 +- .../ui/TransactionFailureAccordion.tsx | 20 +- .../feeEstimation/ui/WaitingForFunds.tsx | 19 + .../actions/feeEstimation/useEstimatedFees.ts | 8 + .../features/actions/feeEstimation/utils.tsx | 66 +- .../features/actions/hooks/useActionScreen.ts | 75 +- .../transaction/ApproveDeployMultisig.tsx | 36 +- ...Info.tsx => AccountNetworkInfoArgentX.tsx} | 20 +- .../ApproveTransactionScreen.test.tsx | 165 + .../ApproveTransactionScreen.tsx | 267 +- .../ApproveTransactionScreenContainer.tsx | 291 +- .../BalanceChangeOverview/NftDetails.tsx | 190 - ...x.tsx => BalanceChangeOverviewArgentX.tsx} | 87 +- .../ConfirmScreen.tsx | 148 +- .../{index.tsx => DappHeaderArgentX.tsx} | 16 +- .../TransactionIcon/NftTransactionIcon.tsx | 8 +- .../TransactionIcon/ReplaceOwnerIcon.tsx | 13 + .../TransactionIcon/SendTransactionIcon.tsx | 2 +- .../TransactionIcon/SwapTransactionIcon.tsx | 8 +- .../DappHeader/TransactionIcon/index.test.tsx | 12 +- .../DappHeader/TransactionIcon/index.tsx | 11 +- ...nTitle.tsx => TransactionTitleArgentX.tsx} | 36 +- .../MultisigBanner.tsx | 20 +- .../NftDetailsArgentXContainer.tsx | 54 + .../TransactionActions.tsx | 63 +- ...Modal.tsx => VerifiedDappModalArgentX.tsx} | 7 +- .../VerifiedDappBanner/index.tsx | 10 +- .../WithActionScreenErrorFooter.tsx | 45 + .../approveTransactionScreen.model.ts | 59 + .../fields/AccountAddressField.tsx | 23 +- .../transaction/fields/DappContractField.tsx | 6 +- .../transaction/fields/ParameterField.tsx | 11 +- .../actions/transaction/fields/TokenField.tsx | 6 +- .../transaction/getKnownWalletAddress.ts | 2 +- .../ui/features/actions/transaction/types.ts | 3 +- .../transaction/useTransactionReview.ts | 28 +- .../useTransactionSimulatedData.ts | 183 +- .../transaction/useTransactionSimulation.ts | 71 +- .../src/ui/features/actions/utils.ts | 44 +- .../ArgentAccountBaseEmailScreen.tsx | 134 + .../ArgentAccountEmailNotificationsScreen.tsx | 92 + ...countEmailNotificationsScreenContainer.tsx | 44 + .../ArgentAccountEmailScreen.tsx | 44 + .../ArgentAccountFeaturesList.tsx | 82 + .../ArgentAccountLoggedInScreen.tsx | 75 + .../ArgentAccountLoggedInScreenContainer.tsx | 55 + .../argentAccountBaseEmailScreen.model.ts | 18 + .../hooks/useArgentAccountTokenExpired.tsx | 5 + .../hooks/useEmailPreferences.tsx | 11 + .../features/funding/FundingBridgeScreen.tsx | 49 +- .../funding/FundingFaucetFallbackScreen.tsx | 58 + .../features/funding/FundingOnRampOption.tsx | 65 + .../funding/FundingProviderScreen.tsx | 36 +- .../features/funding/FundingQrCodeScreen.tsx | 4 - .../src/ui/features/funding/FundingScreen.tsx | 101 +- .../src/ui/features/funding/banxa.svg | 16 - .../src/ui/features/funding/card.svg | 12 - .../src/ui/features/funding/coinbase.svg | 6 - .../src/ui/features/funding/ethereum.svg | 9 - .../src/ui/features/funding/orbiter.svg | 22 - .../src/ui/features/funding/ramp.svg | 7 - .../src/ui/features/funding/starknet.svg | 7 - .../src/ui/features/funding/utils.ts | 7 + .../src/ui/features/lock/LockScreen.tsx | 49 +- .../src/ui/features/lock/ResetScreen.tsx | 2 +- .../src/ui/features/multisig/AddOwnerForm.tsx | 94 +- .../CreateMultisigStartScreen.tsx | 2 + .../MultisigFirstStep.test.tsx | 2 +- .../MultisigFirstStep.tsx | 7 +- .../MultisigSecondStep.tsx | 39 +- .../features/multisig/JoinMultisigScreen.tsx | 10 +- .../multisig/JoinMultisigSettingsScreen.tsx | 2 +- .../src/ui/features/multisig/Multisig.ts | 23 +- .../multisig/MultisigAddOwnersScreen.tsx | 21 +- .../ui/features/multisig/MultisigBanner.tsx | 12 +- .../multisig/MultisigConfirmationsScreen.tsx | 22 +- .../features/multisig/MultisigDeleteModal.tsx | 2 +- .../multisig/MultisigListAccounts.tsx | 4 +- .../MultisigListScreenItemContainer.tsx | 43 + .../ui/features/multisig/MultisigOwner.tsx | 183 + .../multisig/MultisigOwnerNameModal.tsx | 62 + .../multisig/MultisigOwnersScreen.tsx | 104 +- ...ultisigPendingTransactionDetailsScreen.tsx | 216 +- .../multisig/MultisigRemoveOwnerModal.tsx | 57 + .../multisig/MultisigRemoveOwnerScreen.tsx | 17 +- .../multisig/MultisigReplaceOwnerScreen.tsx | 102 + .../MultisigSignatureScreenWarning.tsx | 21 + ...MultisigTransactionConfirmationsScreen.tsx | 152 +- .../features/multisig/NewMultisigScreen.tsx | 26 +- .../multisig/RemovedMultisigWarningScreen.tsx | 15 +- .../ui/features/multisig/ReplaceOwnerForm.tsx | 49 + .../multisig/hooks/pubkeySchema.test.ts | 39 + .../multisig/hooks/useCreateMultisigForm.ts | 43 +- .../hooks/useCreatePendingMultisig.ts | 10 +- .../multisig/hooks/useIsSignerInMultisig.ts | 5 +- .../hooks/useMultisigDataforAccount.ts | 58 - .../multisig/hooks/useReplaceOwnerForm.ts | 16 + .../multisig/hooks/useUpdateThreshold.ts | 2 +- .../src/ui/features/multisig/multisig.mock.ts | 8 +- .../ui/features/multisig/multisig.state.ts | 17 +- .../multisig/multisigTransactions.state.ts | 6 +- .../NetworkSwitcher/NetworkSwitcher.test.tsx | 22 +- .../NetworkSwitcher/NetworkSwitcherButton.tsx | 6 +- .../NetworkSwitcherContainer.tsx | 31 +- .../NetworkSwitcher/NetworkSwitcherList.tsx | 32 +- .../NetworkWarningScreen.test.tsx | 4 +- .../networks/hooks/useCurrentNetwork.ts | 17 + .../networks/hooks/useIsDefaultNetwork.ts | 7 + .../ui/features/networks/hooks/useNetwork.ts | 17 +- .../ui/features/networks/hooks/useNetworks.ts | 11 +- .../useShouldShowNetworkUpgradeMessage.ts | 49 - .../OnboardingDisclaimerScreen.test.tsx | 4 + .../onboarding/OnboardingDisclaimerScreen.tsx | 5 +- .../OnboardingDisclaimerScreenContainer.tsx | 6 +- .../OnboardingFinishScreen.test.tsx | 4 +- .../onboarding/OnboardingPasswordScreen.tsx | 12 +- .../OnboardingPasswordScreenContainer.tsx | 9 +- .../OnboardingPrivacyStatementScreen.test.tsx | 4 +- ...OnboardingRestoreBackupScreenContainer.tsx | 3 - ...boardingRestorePasswordScreenContainer.tsx | 45 +- .../OnboardingRestoreSeedScreen.test.tsx | 8 +- .../OnboardingRestoreSeedScreen.tsx | 2 +- .../OnboardingRestoreSeedScreenContainer.tsx | 7 +- .../OnboardingStartScreenContainer.tsx | 6 +- .../onboarding/hooks/useOnboardingScreen.ts | 10 +- .../ui/features/recovery/CopySeedPhrase.tsx | 4 +- .../ui/features/recovery/RecoveryBanner.tsx | 24 - .../features/recovery/RecoverySetupScreen.tsx | 7 +- .../recovery/SeedRecoveryConfirmScreen.tsx | 32 - .../recovery/SeedRecoverySetupScreen.tsx | 61 +- .../features/recovery/backupDownload.state.ts | 15 - .../hasSavedRecoverySeedphraseAtom.tsx | 10 + .../features/recovery/hooks/useSeedPhrase.ts | 19 +- .../ui/features/recovery/recovery.service.ts | 39 +- .../features/recovery/ui/SeedPhraseGrid.tsx | 55 +- .../ui/features/recovery/ui/SeedWordBadge.tsx | 5 +- .../recovery/ui/SeedWordBadgeNumber.tsx | 4 +- .../ui/features/recovery/ui/WarningText.tsx | 16 +- .../src/ui/features/send/NftInput.tsx | 58 + .../SendAmountAndAssetNftScreenContainer.tsx | 80 + .../send/SendAmountAndAssetScreen.tsx | 98 + .../SendAmountAndAssetScreenContainer.tsx | 68 + ...SendAmountAndAssetTokenScreenContainer.tsx | 300 + .../src/ui/features/send/SendAssetScreen.tsx | 149 + .../SendCollectionNftsScreenContainer.tsx | 51 + .../send/SendModalAddContactScreen.tsx | 42 + .../ui/features/send/SendRecipientScreen.tsx | 246 + .../send/SendRecipientScreenContainer.tsx | 219 + .../src/ui/features/send/SendScreen.tsx | 214 - .../src/ui/features/send/TokenAmountInput.tsx | 169 + .../src/ui/features/send/amountInput.test.ts | 34 + .../src/ui/features/send/amountInput.ts | 9 + .../src/ui/features/send/schema.test.ts | 43 + .../extension/src/ui/features/send/schema.ts | 37 + .../send/sendRecipientScreen.model.ts | 8 + .../ui/features/send/useFilteredAccounts.ts | 33 + .../features/send/useFilteredCollections.ts | 25 + .../ui/features/send/useFilteredContacts.ts | 33 + .../src/ui/features/send/useFilteredTokens.ts | 29 + .../send/useGetAddressFromStarknetId.ts | 73 + .../settings/AddressBookAddOrEditScreen.tsx | 290 + .../AddressBookAddOrEditScreenContainer.tsx | 130 + .../settings/AddressBookSettingsScreen.tsx | 142 + .../AddressBookSettingsScreenContainer.tsx | 33 + .../settings/AddressbookAddOrEditScreen.tsx | 287 - .../settings/AddressbookSettingsScreen.tsx | 119 - .../settings/BeforeYouContinueScreen.tsx | 52 + .../features/settings/BetaFeatureSettings.tsx | 57 + .../features/settings/DeveloperSettings.tsx | 12 +- .../DeclareOrDeployContractSuccess.tsx | 104 - .../DeclareOrDeployContractSuccessScreen.tsx | 95 + ...OrDeployContractSuccessScreenContainer.tsx | 20 + .../DeclareSmartContractForm.tsx | 314 +- .../DeclareSmartContractScreen.tsx | 11 +- .../DeploySmartContractForm.tsx | 115 +- .../DeploySmartContractParameters.tsx | 3 +- .../DeploySmartContractScreen.tsx | 14 +- .../deploySmartContractForm.model.ts | 20 + .../ui/ContractWithClassHash.tsx | 49 + .../DeveloperSettings/ui/FileInputButton.tsx | 67 + .../DeveloperSettings/useFormSelects.tsx | 4 +- .../settings/ExperimentalSettings.tsx | 33 - .../settings/NetworkSettingsEditScreen.tsx | 14 +- .../settings/NetworkSettingsFormScreen.tsx | 174 +- .../NetworkSettingsFormScreenContainer.tsx | 152 + .../settings/NetworkSettingsScreen.tsx | 44 +- .../settings/PrivacySettingsScreen.tsx | 25 - .../features/settings/SeedSettingsScreen.tsx | 48 +- .../ui/features/settings/SettingsScreen.tsx | 148 +- .../ui/features/settings/SupportFooter.tsx | 15 +- .../settings/WithArgentServicesEnabled.tsx | 39 - .../settings/selectedNetwork.state.ts | 22 - .../settings/validateRemoveNetwork.ts | 13 - .../shield/ShieldAccountActionScreen.tsx | 15 +- .../shield/ShieldAccountEmailScreen.tsx | 15 +- .../shield/ShieldAccountOTPScreen.tsx | 47 +- .../shield/ShieldAccountStartScreen.tsx | 27 +- .../features/shield/ShieldBaseEmailScreen.tsx | 113 - .../shield/ShieldBaseFinishScreen.tsx | 48 +- .../features/shield/ShieldBaseOTPScreen.tsx | 72 +- .../shield/ShieldValidationErrorScreen.tsx | 8 +- .../shield/WithArgentShieldVerified.tsx | 95 +- .../features/shield/escape/EscapeBanner.tsx | 2 +- .../shield/escape/EscapeGuardianReady.tsx | 2 +- .../features/shield/escape/EscapeSigner.tsx | 2 +- .../shield/escape/EscapeWarningScreen.tsx | 14 +- .../shield/escape/WithEscapeWarning.tsx | 13 - .../shield/escape/accountHasEscape.ts | 4 + .../shield/escape/useAccountEscape.ts | 7 +- .../src/ui/features/shield/shield.state.ts | 7 +- .../ui/features/shield/useAccountGuardian.ts | 6 +- .../features/shield/useArgentShieldEnabled.ts | 36 - .../shield/usePendingChangingGuardian.ts | 10 +- .../stateRestoration/useRestorationState.ts | 8 +- .../statusMessage/useStatusMessage.ts | 22 +- .../extension/src/ui/features/swap/Swap.tsx | 2 - .../src/ui/features/swap/ui/CurrencyValue.tsx | 6 +- .../src/ui/features/swap/ui/OwnedToken.tsx | 14 +- .../src/ui/features/swap/ui/TokenPrice.tsx | 4 +- packages/extension/src/ui/hooks/useAction.ts | 1 + .../extension/src/ui/hooks/useAddressBook.ts | 33 + .../src/ui/hooks/useAutoFocusInputRef.ts | 39 + .../hooks/useOnAppRoutesAnimationComplete.ts | 17 + packages/extension/src/ui/hooks/useQuery.ts | 9 + .../extension/src/ui/hooks/useResetAll.ts | 19 + packages/extension/src/ui/index.tsx | 4 +- packages/extension/src/ui/routes.ts | 121 +- .../accountMessaging/implementation.ts | 94 + .../src/ui/services/accountMessaging/index.ts | 3 + .../ui/services/accountMessaging/interface.ts | 19 + .../src/ui/services/action/client.ts | 24 + .../extension/src/ui/services/action/index.ts | 4 + .../extension/src/ui/services/addressBook.ts | 34 - .../src/ui/services/addressBook/client.ts | 22 + .../src/ui/services/addressBook/index.ts | 4 + .../extension/src/ui/services/addresses.ts | 86 +- .../extension/src/ui/services/analytics.ts | 11 - .../services/argentAccount/implementation.ts | 59 + .../src/ui/services/argentAccount/index.ts | 4 + .../src/ui/services/argentAccount/utils.ts | 37 + .../extension/src/ui/services/background.ts | 18 - .../src/ui/services/backgroundAccounts.ts | 161 +- .../src/ui/services/backgroundActions.ts | 19 - .../src/ui/services/backgroundMultisigs.ts | 108 - .../src/ui/services/backgroundSessions.ts | 59 - .../src/ui/services/backgroundTransactions.ts | 24 +- .../src/ui/services/blockExplorer.service.ts | 14 +- .../src/ui/services/extension/clientLegacy.ts | 41 - .../src/ui/services/extension/index.ts | 14 - .../src/ui/services/extension/interface.ts | 3 - .../src/ui/services/knownDapps/index.ts | 40 + .../src/ui/services/messaging/trpc.ts | 2 +- .../ui/services/multisig/implementation.ts | 88 + .../src/ui/services/multisig/index.ts | 4 + .../src/ui/services/multisig/interface.ts | 9 + .../src/ui/services/nfts/implementation.ts | 236 + .../extension/src/ui/services/nfts/index.ts | 26 + .../src/ui/services/nfts/interface.ts | 40 + .../src/ui/services/nfts/test/index.test.ts | 185 + .../src/ui/services/nfts/test/nft.mock.ts | 99 + .../ui/services/recovery/implementation.ts | 5 +- .../src/ui/services/recovery/interface.ts | 2 +- .../src/ui/services/resetAndReload.tsx | 7 +- packages/extension/src/ui/services/sentry.ts | 14 +- .../src/ui/services/session/implementation.ts | 23 + .../src/ui/services/session/index.ts | 4 + .../src/ui/services/session/interface.ts | 8 + .../ui/services/{swr.ts => swr.service.ts} | 9 +- .../src/ui/services/tokens/implementation.ts | 170 + .../extension/src/ui/services/tokens/index.ts | 4 + .../src/ui/services/tokens/interface.ts | 50 + .../src/ui/services/tokens/test/index.test.ts | 293 + .../extension/src/ui/services/tokens/types.ts | 3 + .../extension/src/ui/services/tokens/utils.ts | 33 + .../extension/src/ui/services/transactions.ts | 17 +- .../extension/src/ui/services/udc.service.ts | 58 +- .../src/ui/services/udc/implementation.ts | 13 + .../extension/src/ui/services/udc/index.ts | 5 + .../extension/src/ui/services/ui/client.ts | 14 + .../extension/src/ui/services/ui/index.ts | 6 + .../extension/src/ui/services/ui/interface.ts | 4 + .../src/ui/services/useStarknetId.ts | 43 +- .../src/ui/services/useStopSession.ts | 17 + packages/extension/src/ui/test/utils.tsx | 8 +- packages/extension/src/ui/useEntryRoute.tsx | 21 +- packages/extension/src/ui/views/account.ts | 18 +- packages/extension/src/ui/views/actions.ts | 37 + .../extension/src/ui/views/addressBook.ts | 31 + .../extension/src/ui/views/estimatedFees.ts | 21 + .../__tests__/atomFromRepo.test.tsx | 55 + .../__tests__/atomFromStore.test.tsx | 53 + .../__tests__/atomWithSubscription.test.tsx | 152 + .../ui/views/implementation/atomFromRepo.ts | 43 +- .../ui/views/implementation/atomFromStore.ts | 37 +- .../implementation/atomWithSubscription.ts | 99 + packages/extension/src/ui/views/knownDapps.ts | 4 + packages/extension/src/ui/views/multisig.ts | 33 + packages/extension/src/ui/views/network.ts | 38 + packages/extension/src/ui/views/nft.ts | 187 + packages/extension/src/ui/views/session.ts | 20 + packages/extension/src/ui/views/token.ts | 102 + .../extension/src/ui/views/tokenBalances.ts | 64 + .../extension/src/ui/views/tokenPrices.ts | 14 + .../__fixtures__/argent-api-prices.mock.json | 38 +- .../__fixtures__/argent-api-tokens.mock.json | 144 +- .../tokens-with-balance.mock.json | 8 +- packages/extension/test/account.mock.ts | 6 +- packages/extension/test/addresses.test.ts | 46 +- packages/extension/test/backup.mock.json | 2 +- packages/extension/test/fetcher.test.ts | 4 + packages/extension/test/keyDerivation.test.ts | 25 +- packages/extension/test/network.mock.ts | 26 + packages/extension/test/schema.test.ts | 11 +- packages/extension/test/setup.ts | 12 +- packages/extension/test/setupTestAccount.ts | 4 +- packages/extension/test/swr.test.tsx | 5 +- packages/extension/test/tokenPrice.test.ts | 22 +- .../extension/test/tokenPriceHooks.test.tsx | 7 +- packages/extension/test/tokens.test.ts | 57 +- packages/extension/test/utils/number.test.ts | 11 +- packages/extension/test/wallet.test.ts | 293 +- packages/extension/test/walletAccount.mock.ts | 8 +- packages/extension/tsconfig.json | 13 +- packages/extension/vite.config.ts | 48 +- packages/extension/vitest.config.ts | 50 + packages/extension/webpack.config.js | 49 +- packages/get-starknet/.gitignore | 4 +- packages/get-starknet/CHANGELOG.md | 26 + packages/get-starknet/package.json | 33 +- packages/get-starknet/src/main.ts | 29 +- packages/get-starknet/src/modal/Modal.svelte | 550 +- .../src/modal/argentMobile/adapter.ts | 157 + .../src/modal/argentMobile/argentModal.ts | 158 + .../src/modal/argentMobile/getDevice.ts | 15 + .../src/modal/argentMobile/index.ts | 11 + .../src/modal/argentMobile/login.ts | 114 + .../argentMobile/starknet/starknet.model.ts | 24 + .../argentMobile/starknet/starknetAccount.ts | 52 + .../argentMobile/starknet/starknetAdapter.ts | 212 + .../argentMobile/starknet/starknetSigner.ts | 51 + packages/get-starknet/src/modal/index.ts | 12 +- packages/get-starknet/tsconfig.json | 5 +- packages/guardian/.vscode/settings.json | 4 + packages/guardian/package.json | 13 +- .../guardian/src/services/GuardianSigner.ts | 57 +- packages/guardian/tsconfig.json | 2 +- packages/multicall/.vscode/settings.json | 4 + packages/multicall/CHANGELOG.md | 7 + .../__snapshots__/integration.test.ts.snap | 77 + .../multicall/__tests__/integration.test.ts | 10 +- packages/multicall/package.json | 19 +- packages/multicall/src/aggregate.ts | 27 +- packages/multicall/src/dataloader.ts | 10 +- packages/multicall/tsconfig.json | 2 +- packages/sessions/.vscode/settings.json | 4 + packages/sessions/README.md | 4 +- packages/sessions/package.json | 16 +- packages/sessions/src/account.ts | 33 +- packages/sessions/src/utils.ts | 15 +- packages/sessions/tsconfig.json | 2 +- packages/shared/.vscode/settings.json | 4 + packages/shared/CHANGELOG.md | 7 + packages/shared/package.json | 22 +- packages/shared/src/account/accountv4.ts | 12 + packages/shared/src/account/index.ts | 1 + packages/shared/src/argent/errors.ts | 20 + packages/shared/src/argent/interface.ts | 5 + packages/shared/src/assets/tokens.json | 8 - .../shared/src/bigdecimal/formatUnits.test.ts | 31 + packages/shared/src/bigdecimal/formatUnits.ts | 21 + packages/shared/src/bigdecimal/index.ts | 3 + .../shared/src/bigdecimal/parseUnits.test.ts | 43 + packages/shared/src/bigdecimal/parseUnits.ts | 33 + packages/shared/src/bigdecimal/utils.test.ts | 46 + packages/shared/src/bigdecimal/utils.ts | 75 + packages/shared/src/chains/index.ts | 3 + .../src/chains/starknet/address.test.ts | 57 + .../shared/src/chains/starknet/address.ts | 110 + .../src/chains/starknet/addressInput.test.ts | 119 + .../src/chains/starknet/addressInput.ts | 25 + .../src/chains/starknet/starknetId.test.ts | 112 + .../shared/src/chains/starknet/starknetId.ts | 51 + packages/shared/src/hooks/index.ts | 1 + packages/shared/src/hooks/useDebounce.ts | 30 + packages/shared/src/http/swr.ts | 9 + packages/shared/src/index.ts | 6 + packages/shared/src/knownDapps/argent.ts | 27 + packages/shared/src/knownDapps/index.ts | 3 + packages/shared/src/knownDapps/interface.ts | 5 + packages/shared/src/knownDapps/model.ts | 35 + packages/shared/src/nfts/argent.ts | 267 + packages/shared/src/nfts/aspect.model.ts | 53 - packages/shared/src/nfts/aspect.ts | 183 - packages/shared/src/nfts/index.ts | 4 +- packages/shared/src/nfts/interface.ts | 99 + packages/shared/src/nfts/useNfts.ts | 94 +- packages/shared/src/nfts/utils.ts | 116 +- packages/shared/src/signer/index.ts | 1 + .../src/signer}/seedphrase.ts | 0 packages/shared/src/tokens/balances.ts | 19 +- packages/shared/src/tokens/price.ts | 65 +- packages/shared/src/tokens/token.ts | 8 +- packages/shared/src/tokens/tokenPriceHooks.ts | 2 +- .../transactions/aggregatedSimDataTypes.ts | 11 +- packages/shared/src/transactions/amount.ts | 40 + .../src/transactions/buildTransactions.ts | 22 +- .../transactions/findTransfersAndApprovals.ts | 5 +- packages/shared/src/transactions/index.ts | 4 +- .../transactions/transactionReviewTypes.ts | 6 +- .../transactionSimulationTypes.ts | 55 +- .../src/transactions/useAggregatedSimData.ts | 114 +- .../src/transactions/useBalanceChange.ts | 15 +- .../src/transactions/useErc20Transactions.ts | 36 + .../src/transactions/useErc721Transactions.ts | 27 + .../transactions/useMaxAmountTransaction.ts | 7 +- .../src/transactions/useTransactionReview.ts | 4 +- .../transactions/useTransactionSimulation.ts | 198 +- packages/shared/src/utils/address.ts | 3 + packages/shared/src/utils/addresses.ts | 82 - .../src/utils}/avatarImage.test.ts | 2 +- packages/shared/src/utils/avatarImage.ts | 6 +- packages/shared/src/utils/base58.ts | 22 + packages/shared/src/utils/bigNumber.ts | 8 + packages/shared/src/utils/env.test.ts | 27 + packages/shared/src/utils/env.ts | 3 + .../schemas => shared/src/utils}/hex.ts | 0 packages/shared/src/utils/index.ts | 13 +- .../shared/src/utils/isContractDeployed.ts | 4 +- packages/shared/src/utils/number.ts | 87 +- packages/shared/src/utils/parseAmount.ts | 21 +- packages/shared/src/utils/readFileAsString.ts | 14 + packages/shared/src/utils/schemas.ts | 7 + packages/shared/src/utils/starknet.ts | 56 + packages/shared/src/utils/useEventEmitter.tsx | 157 + packages/shared/test/setup.ts | 23 + packages/shared/tsconfig.json | 5 +- packages/shared/vitest.config.ts | 36 + packages/stack-router/.eslintrc.js | 13 +- packages/stack-router/.vscode/settings.json | 4 + packages/stack-router/README.md | 2 +- .../stack-router/example/public/index.html | 4 +- packages/stack-router/example/tsconfig.json | 2 +- packages/stack-router/package.json | 22 +- packages/stack-router/src/StackRoutes.tsx | 7 +- .../stack-router/src/StackRoutesConfig.tsx | 3 + packages/stack-router/src/StackScreen.tsx | 9 +- .../stack-router/src/StackScreenContainer.tsx | 2 +- .../src/presentation/presentationVariants.ts | 52 +- .../src/presentation/transitions.ts | 2 +- packages/stack-router/tsconfig.json | 2 +- packages/stack-router/vite.config.ts | 2 +- .../.gitignore | 4 +- .../CHANGELOG.md | 19 + .../package.json | 21 +- .../src/main.ts | 125 +- .../tsconfig.json | 4 +- .../vite.config.ts | 12 + packages/storybook/.env.example | 1 + packages/storybook/.eslintrc.js | 1 + packages/storybook/.storybook/main.ts | 28 +- packages/storybook/.storybook/polyfill.ts | 5 + packages/storybook/.vscode/settings.json | 4 + packages/storybook/package.json | 36 +- .../src/decorators/globalDecorators.tsx | 4 +- .../accountTokens/TokenListItem.stories.tsx | 47 +- .../accounts/AccountActivity.stories.tsx | 2 +- .../AccountAddressListItem.stories.tsx | 42 + .../accounts/AccountListItem.stories.tsx | 109 +- .../AccountListItemSkeleton.stories.tsx | 19 + .../accounts/AccountListScreen.stories.tsx | 79 +- .../accounts/AddressBookMenu.stories.tsx | 57 +- .../MigrationDisclaimerScreen.stories.tsx | 12 - .../PrettyAccountAddressArgentX.stories.tsx | 51 + .../TransactionDetailExplorer.stories.tsx | 2 +- .../accounts/TransactionDetailRaw.stories.tsx | 19 +- .../accounts/TransactionListItem.stories.tsx | 2 +- .../accounts/UpgradeScreenV4.stories.tsx | 55 - .../accounts/__fixtures__/addressBook.ts | 86 + .../AccountNetworkInfoArgentX.stories.tsx | 18 + .../actions/AddNetworkScreen.stories.tsx | 29 + .../ApproveSignatureScreen.stories.tsx | 36 +- .../ApproveTransactionScreen.stories.tsx | 37 +- .../BalanceChangeOverviewArgentX.stories.tsx | 13 + .../actions/ConnectDappScreen.stories.tsx | 2 +- ...MultisigSignatureScreenWarning.stories.tsx | 20 + .../features/actions/__fixtures__/aspect.ts | 182 - .../features/actions/__fixtures__/transfer.ts | 98 - .../CombinedFeeEstimation.stories.tsx | 5 +- .../transaction/FeeEstimation.stories.tsx | 5 +- .../transaction/TokenField.stories.tsx | 2 +- .../fees/combinedFeeEstimationFixtures.ts | 82 - .../fees/feeEstimationFixtures.ts | 68 - .../src/features/send/NftInput.stories.tsx | 43 + .../send/TokenAmountInput.stories.tsx | 75 + .../AddressBookAddOrEditScreen.stories.tsx | 53 + .../AddressBookSettingsScreen.stories.tsx | 24 + ...eOrDeployContractSuccessScreen.stories.tsx | 26 + .../DeclareSmartContractForm.stories.tsx | 15 + .../DeploySmartContractForm.stories.tsx} | 4 +- .../shield/EscapeGuardian.stories.tsx | 2 +- .../features/shield/EscapeSigner.stories.tsx | 2 +- .../shield/ShieldBaseEmailScreen.stories.tsx | 16 +- .../ShieldValidationErrorScreen.stories.tsx | 2 +- packages/storybook/src/tokens.ts | 32 + packages/storybook/src/tokensByNetwork.ts | 11 - .../src/ui/components/Accordion.stories.tsx | 15 + .../components/AccountNetworkInfo.stories.tsx | 36 + .../BalanceChangeOverview.stories.tsx | 13 + .../src/ui/components/DappIcon.stories.tsx | 7 - .../ui/components/DetailAccordion.stories.tsx | 19 +- .../ui/components/ErrorBoundary.stories.tsx | 9 +- .../src/ui/components/Input.stories.tsx | 39 +- .../src/ui/components/Menu.stories.tsx | 26 +- .../src/ui/components/ModalDialog.stories.tsx | 30 + .../ui/components/ModalDialogData.stories.tsx | 33 + .../NavigationContainerSkeleton.stories.tsx | 12 + .../src/ui/components/NftDetails.stories.tsx | 33 + .../src/ui/components/Option.stories.tsx | 16 +- .../PasswordStrengthIndicator.stories.tsx | 32 + .../PrettyAccountAddress.stories.tsx | 39 +- .../src/ui/components/Select.stories.tsx | 72 + .../src/ui/components/Tabs.stories.tsx | 35 + .../components/TextAreaDeprecated.stories.tsx | 17 - .../components/TextareaAutosize.stories.tsx | 34 + packages/storybook/tsconfig.json | 4 +- packages/swap/.eslintrc.js | 13 +- packages/swap/.gitignore | 4 +- packages/swap/package.json | 19 +- packages/swap/src/assets/tokens.json | 8 - packages/swap/src/lib/hooks/Pairs.ts | 3 +- packages/swap/src/lib/hooks/Wallet.ts | 18 +- packages/swap/src/lib/hooks/useApproveCall.ts | 6 +- .../src/lib/hooks/useCurrentBlockTimestamp.ts | 2 - packages/swap/src/lib/hooks/useMulticall.ts | 5 +- .../swap/src/lib/hooks/useSwapCallback.ts | 15 +- packages/swap/src/lib/services/network.ts | 4 +- packages/swap/src/sdk/constants.ts | 12 +- packages/swap/src/sdk/entities/pair.ts | 6 +- packages/swap/src/sdk/entities/token.ts | 8 +- packages/swap/src/sdk/hash.ts | 40 - packages/swap/src/tokenlist/index.ts | 1 - packages/swap/tsconfig.json | 2 +- packages/swap/vite.config.ts | 2 +- packages/ui/.env.example | 2 +- packages/ui/.eslintrc.js | 13 +- packages/ui/.vscode/settings.json | 4 + packages/ui/README.md | 4 +- packages/ui/package.json | 32 +- packages/ui/scripts/generate-icons.ts | 2 +- packages/ui/src/components/Absolute.tsx | 3 +- packages/ui/src/components/Accordion.tsx | 94 +- packages/ui/src/components/Alert.tsx | 21 + packages/ui/src/components/AlertDialog.tsx | 2 +- packages/ui/src/components/Button.tsx | 8 +- packages/ui/src/components/ButtonRect.tsx | 8 + packages/ui/src/components/CellStack.tsx | 3 + packages/ui/src/components/CopyTooltip.tsx | 15 +- packages/ui/src/components/DapplandBanner.tsx | 2 +- .../ui/src/components/DetailAccordion.tsx | 37 +- packages/ui/src/components/FlowHeader.tsx | 20 +- packages/ui/src/components/Input.tsx | 39 +- packages/ui/src/components/LoadingPulse.tsx | 4 +- packages/ui/src/components/Menu.tsx | 3 + packages/ui/src/components/ModalDialog.tsx | 66 + .../ui/src/components/ModalDialogData.tsx | 46 + packages/ui/src/components/NavigationBar.tsx | 44 +- .../ui/src/components/NavigationContainer.tsx | 21 +- .../components/PasswordStrengthIndicator.tsx | 117 +- .../PasswordStrengthIndicatorBar.tsx | 37 + packages/ui/src/components/PinInput.tsx | 2 +- packages/ui/src/components/SeedInput.tsx | 1 + packages/ui/src/components/Select.tsx | 72 +- packages/ui/src/components/SelectOption.tsx | 15 - packages/ui/src/components/Tabs.tsx | 58 + .../src/components/TextWithAmount/index.tsx | 7 +- packages/ui/src/components/Textarea.tsx | 9 + .../ui/src/components/TextareaAutosize.tsx | 35 + packages/ui/src/components/TokenButton.tsx | 65 +- .../components/fees/CombinedFeeEstimation.tsx | 14 +- .../ui/src/components/fees/FeeEstimation.tsx | 12 +- packages/ui/src/components/fees/utils.tsx | 17 +- .../ui/src/components/icons/ActivityIcon.tsx | 8 +- .../ui/src/components/icons/AddCircleIcon.tsx | 8 +- packages/ui/src/components/icons/AddIcon.tsx | 8 +- .../src/components/icons/AddressBookIcon.tsx | 14 +- .../ui/src/components/icons/AddressIcon.tsx | 10 +- .../ui/src/components/icons/AlertFillIcon.tsx | 8 +- .../ui/src/components/icons/AlertIcon.tsx | 12 +- .../src/components/icons/AnnouncementIcon.tsx | 10 +- .../ui/src/components/icons/ApproveIcon.tsx | 8 +- .../icons/ArgentShieldDeactivateIcon.tsx | 12 +- .../src/components/icons/ArgentShieldIcon.tsx | 10 +- .../ui/src/components/icons/ArrowDownIcon.tsx | 8 +- .../ui/src/components/icons/ArrowLeftIcon.tsx | 10 +- .../src/components/icons/ArrowRightIcon.tsx | 10 +- .../ui/src/components/icons/ArrowUpIcon.tsx | 12 +- packages/ui/src/components/icons/BellIcon.tsx | 10 +- packages/ui/src/components/icons/BinIcon.tsx | 12 +- packages/ui/src/components/icons/CardIcon.tsx | 12 +- .../components/icons/CheckboxActiveIcon.tsx | 8 +- .../components/icons/CheckboxDefaultIcon.tsx | 10 +- .../src/components/icons/ChevronDownIcon.tsx | 10 +- .../src/components/icons/ChevronLeftIcon.tsx | 10 +- .../src/components/icons/ChevronRightIcon.tsx | 10 +- .../ui/src/components/icons/ChevronUpIcon.tsx | 10 +- .../components/icons/ChromeExtensionIcon.tsx | 8 +- .../ui/src/components/icons/CloseIcon.tsx | 8 +- packages/ui/src/components/icons/CodeIcon.tsx | 8 +- packages/ui/src/components/icons/CopyIcon.tsx | 12 +- .../ui/src/components/icons/DeployIcon.tsx | 12 +- .../ui/src/components/icons/DocumentIcon.tsx | 12 +- .../src/components/icons/DropdownDownIcon.tsx | 10 +- .../components/icons/DropdownRightIcon.tsx | 10 +- .../src/components/icons/DropdownUpIcon.tsx | 10 +- packages/ui/src/components/icons/EditIcon.tsx | 10 +- .../ui/src/components/icons/EmailIcon.tsx | 10 +- .../ui/src/components/icons/ExpandIcon.tsx | 8 +- .../ui/src/components/icons/ExtendedIcon.tsx | 12 +- packages/ui/src/components/icons/FailIcon.tsx | 10 +- packages/ui/src/components/icons/HelpIcon.tsx | 12 +- packages/ui/src/components/icons/HideIcon.tsx | 12 +- .../ui/src/components/icons/HistoryIcon.tsx | 10 +- .../ui/src/components/icons/ImageIcon.tsx | 12 +- .../ui/src/components/icons/InfoFillIcon.tsx | 8 +- packages/ui/src/components/icons/InfoIcon.tsx | 12 +- packages/ui/src/components/icons/KeyIcon.tsx | 12 +- packages/ui/src/components/icons/LinkIcon.tsx | 12 +- .../ui/src/components/icons/LoaderIcon.tsx | 8 +- packages/ui/src/components/icons/LockIcon.tsx | 12 +- .../ui/src/components/icons/LogoutIcon.tsx | 18 + .../ui/src/components/icons/MinusIcon.tsx | 10 +- packages/ui/src/components/icons/MoreIcon.tsx | 8 +- .../ui/src/components/icons/MulticallIcon.tsx | 14 +- .../ui/src/components/icons/MultisigIcon.tsx | 14 +- .../components/icons/MultisigImageIcon.tsx | 38 + .../src/components/icons/MultisigJoinIcon.tsx | 12 +- .../components/icons/MultisigRemoveIcon.tsx | 12 +- .../components/icons/MultisigReplaceIcon.tsx | 18 + .../ui/src/components/icons/NetworkIcon.tsx | 10 +- packages/ui/src/components/icons/NftIcon.tsx | 10 +- .../ui/src/components/icons/PasswordIcon.tsx | 8 +- packages/ui/src/components/icons/PinIcon.tsx | 8 +- .../ui/src/components/icons/PluginIcon.tsx | 10 +- .../ui/src/components/icons/PointerIcon.tsx | 20 +- .../ui/src/components/icons/ProfileIcon.tsx | 10 +- packages/ui/src/components/icons/QrIcon.tsx | 16 +- .../src/components/icons/QuestionMarkIcon.tsx | 8 +- .../ui/src/components/icons/ReceiveIcon.tsx | 8 +- .../ui/src/components/icons/ResendIcon.tsx | 8 +- .../ui/src/components/icons/RestoreIcon.tsx | 8 +- .../ui/src/components/icons/SearchIcon.tsx | 10 +- packages/ui/src/components/icons/SendIcon.tsx | 10 +- .../ui/src/components/icons/SessionIcon.tsx | 18 + .../ui/src/components/icons/SettingsIcon.tsx | 14 +- .../ui/src/components/icons/ShareIcon.tsx | 10 +- .../ui/src/components/icons/ShieldIcon.tsx | 10 +- packages/ui/src/components/icons/SignIcon.tsx | 18 + .../ui/src/components/icons/SpinnerIcon.tsx | 10 +- .../ui/src/components/icons/SupportIcon.tsx | 12 +- packages/ui/src/components/icons/SwapIcon.tsx | 20 +- .../components/icons/SwitchDirectionIcon.tsx | 8 +- .../src/components/icons/TickCircleIcon.tsx | 12 +- packages/ui/src/components/icons/TickIcon.tsx | 10 +- .../ui/src/components/icons/UpgradeIcon.tsx | 12 +- .../components/icons/UploadDocumentIcon.tsx | 12 +- .../ui/src/components/icons/VerifiedIcon.tsx | 8 +- packages/ui/src/components/icons/ViewIcon.tsx | 14 +- .../ui/src/components/icons/WalletIcon.tsx | 12 +- packages/ui/src/components/icons/index.ts | 9 +- packages/ui/src/components/index.ts | 5 +- .../ui/src/components/logos/ArgentLogo.tsx | 26 - .../ui/src/components/logos/ArgentXLogo.tsx | 8 +- .../src/components/logos/ArgentXLogoFull.tsx | 8 +- packages/ui/src/components/logos/Aspect.tsx | 10 +- packages/ui/src/components/logos/Banxa.tsx | 18 + packages/ui/src/components/logos/Briq.tsx | 8 +- packages/ui/src/components/logos/Coinbase.tsx | 10 +- packages/ui/src/components/logos/Discord.tsx | 8 +- packages/ui/src/components/logos/EmptyNft.tsx | 25 + packages/ui/src/components/logos/Ethereum.tsx | 10 +- packages/ui/src/components/logos/Flex.tsx | 224 + .../ui/src/components/logos/Frenslands.tsx | 12 +- packages/ui/src/components/logos/Github.tsx | 8 +- packages/ui/src/components/logos/Image.tsx | 24 + .../ui/src/components/logos/Influence.tsx | 12 +- packages/ui/src/components/logos/Jediswap.tsx | 8 +- .../ui/src/components/logos/Layerswap.tsx | 29 + packages/ui/src/components/logos/Ledger.tsx | 8 +- .../ui/src/components/logos/Mintsquare.tsx | 14 +- .../src/components/logos/MultisigDiagram.tsx | 47 - packages/ui/src/components/logos/Orbiter.tsx | 26 + packages/ui/src/components/logos/Ramp.tsx | 22 + packages/ui/src/components/logos/Starknet.tsx | 12 +- packages/ui/src/components/logos/Twitter.tsx | 8 +- packages/ui/src/components/logos/Unframed.tsx | 22 + packages/ui/src/components/logos/Zklend.tsx | 80 + packages/ui/src/components/logos/index.ts | 13 +- .../transactions/AccountNetworkInfo.tsx | 10 +- .../transactions/BalanceChangeOverview.tsx | 377 - .../components/transactions/DappHeader.tsx | 77 - .../components/transactions/NftDetails.tsx | 192 +- .../transactions/PrettyAccountAddress.tsx | 2 +- .../transactions/TransactionActions.tsx | 72 +- .../transactions/TransactionError.tsx | 36 + .../TransactionIcon/NftTransactionIcon.tsx | 16 +- .../transactions/TransactionIcon/index.tsx | 20 +- .../transactions/TransactionTitle.tsx | 132 - .../ui/src/components/transactions/index.ts | 8 +- packages/ui/src/hooks/useScrollRestoration.ts | 3 +- packages/ui/src/theme/colors.ts | 4 + packages/ui/src/theme/index.tsx | 8 +- packages/ui/src/theme/skeleton.ts | 25 + packages/ui/test/setup.ts | 2 +- packages/ui/tsconfig.json | 3 +- packages/ui/vite.config.ts | 32 +- packages/ui/vitest.config.ts | 36 + packages/web-sdk/.gitignore | 4 +- packages/web-sdk/CHANGELOG.md | 7 + packages/web-sdk/package.json | 20 +- packages/web-sdk/src/account.ts | 75 + .../web-sdk/src/argentStarknetWindowObject.ts | 155 + packages/web-sdk/src/main.ts | 82 +- packages/web-sdk/src/trpc.ts | 134 + packages/web-sdk/src/wormhole.ts | 321 - packages/web-sdk/tsconfig.json | 3 +- packages/web-sdk/vite.config.ts | 41 +- packages/window/.eslintrc.js | 1 + packages/window/.gitignore | 4 +- packages/window/package.json | 20 +- packages/window/src/index.ts | 5 +- .../src/messages/__tests__/windowMock.mock.ts | 5 +- packages/window/src/starknet.ts | 8 +- packages/window/src/types.ts | 38 +- packages/window/src/utils/mittx.ts | 122 + packages/window/tsconfig.json | 2 +- packages/window/vite.config.ts | 9 +- packages/window/vitest.config.ts | 13 + patches/@noble+hashes+1.3.0.patch | 39 - patches/starknet+4.22.0.patch | 83 - pnpm-lock.yaml | 28176 ++++++++++++++++ pnpm-workspace.yaml | 2 + renovate.json | 15 + .../calculate-contract-hash/requirements.txt | 2 +- scripts/license-report.sh | 2 +- scripts/update-starknet-js.sh | 6 +- scripts/version.sh | 3 + yarn.lock | 21547 ------------ 1476 files changed, 71287 insertions(+), 44193 deletions(-) create mode 100644 .changeset/README.md create mode 100644 .changeset/config.json delete mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/changeset.yml create mode 100644 .npmrc delete mode 100644 .yarnrc delete mode 100644 .yarnrc.yml delete mode 100644 lerna.json delete mode 100644 nx.json create mode 100644 packages/dapp/.vscode/settings.json create mode 100644 packages/e2e/.env.example create mode 100644 packages/e2e/.vscode/settings.json create mode 100644 packages/e2e/extension/playwright.config.ts create mode 100644 packages/e2e/extension/src/page-objects/Dapps.ts create mode 100644 packages/e2e/extension/src/specs/dapps.spec.ts delete mode 100644 packages/e2e/extension/src/specs/receiveFunds.spec.ts create mode 100644 packages/e2e/extension/src/specs/sendFunds.spec.ts delete mode 100644 packages/e2e/extension/src/specs/sendFundsMax.spec.ts delete mode 100644 packages/e2e/extension/src/specs/sendFundsPartial.spec.ts create mode 100644 packages/e2e/extension/src/utils/account.ts delete mode 100644 packages/e2e/playwright.config.ts create mode 100644 packages/e2e/webwallet/playwright.config.ts create mode 100644 packages/e2e/webwallet/src/config.ts create mode 100644 packages/e2e/webwallet/src/fixtures.ts create mode 100644 packages/e2e/webwallet/src/page-objects/Login.ts create mode 100644 packages/e2e/webwallet/src/page-objects/Navigation.ts create mode 100644 packages/e2e/webwallet/src/page-objects/WebWalletPage.ts create mode 100644 packages/e2e/webwallet/src/specs/login.spec.ts create mode 100644 packages/e2e/webwallet/src/test.ts create mode 100644 packages/eslint-plugin-local/.eslintrc.js create mode 100644 packages/eslint-plugin-local/package.json create mode 100644 packages/eslint-plugin-local/src/code-import-patterns.ts create mode 100644 packages/eslint-plugin-local/src/index.ts create mode 100644 packages/eslint-plugin-local/tsconfig.json create mode 100644 packages/extension/.eslintrc.base.js create mode 100644 packages/extension/.vscode/settings.json create mode 100644 packages/extension/CHANGELOG.md create mode 100644 packages/extension/scripts/export.ts create mode 100644 packages/extension/src/background/__new/procedures/account/select.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/cancelEscape.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/changeGuardian.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/escapeAndChangeGuardian.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedPrivateKey.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedSeedPhrase.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKey.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKeyForMultisig.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getPublicKey.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/getPublicKeysBufferForMultisig.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/index.ts create mode 100644 packages/extension/src/background/__new/procedures/accountMessaging/triggerEscapeGuardian.ts create mode 100644 packages/extension/src/background/__new/procedures/action/approve.ts create mode 100644 packages/extension/src/background/__new/procedures/action/approveAndWait.ts create mode 100644 packages/extension/src/background/__new/procedures/action/index.ts create mode 100644 packages/extension/src/background/__new/procedures/action/reject.ts create mode 100644 packages/extension/src/background/__new/procedures/action/rejectAll.ts create mode 100644 packages/extension/src/background/__new/procedures/addressBook/add.ts create mode 100644 packages/extension/src/background/__new/procedures/addressBook/index.ts create mode 100644 packages/extension/src/background/__new/procedures/addressBook/remove.ts create mode 100644 packages/extension/src/background/__new/procedures/addressBook/update.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/addAccount.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/confirmEmail.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/getPreferences.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/index.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/isTokenExpired.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/logout.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/requestEmail.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.model.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.ts create mode 100644 packages/extension/src/background/__new/procedures/argentAccount/validateAccount.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/addAccount.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/addOwner.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/addPendingAccount.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/addTransactionSignature.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/deploy.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/index.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/removeOwner.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/replaceOwner.ts create mode 100644 packages/extension/src/background/__new/procedures/multisig/updateThreshold.ts delete mode 100644 packages/extension/src/background/__new/procedures/network/add.ts delete mode 100644 packages/extension/src/background/__new/procedures/network/index.ts create mode 100644 packages/extension/src/background/__new/procedures/session/checkPassword.ts create mode 100644 packages/extension/src/background/__new/procedures/session/index.ts create mode 100644 packages/extension/src/background/__new/procedures/session/isPasswordSet.ts create mode 100644 packages/extension/src/background/__new/procedures/session/start.ts create mode 100644 packages/extension/src/background/__new/procedures/session/stop.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/addToken.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/fetchAccountBalance.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/fetchDetails.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/getAccountBalance.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/getAllTokenBalances.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/getCurrencyValueForTokens.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/index.ts create mode 100644 packages/extension/src/background/__new/procedures/tokens/removeToken.ts create mode 100644 packages/extension/src/background/__new/procedures/transfer/index.ts create mode 100644 packages/extension/src/background/__new/procedures/transfer/send.ts create mode 100644 packages/extension/src/background/__new/procedures/udc/getConstructorParams.ts create mode 100644 packages/extension/src/background/__new/procedures/udc/index.ts create mode 100644 packages/extension/src/background/__new/services/action/background.ts create mode 100644 packages/extension/src/background/__new/services/action/index.ts create mode 100644 packages/extension/src/background/__new/services/action/interface.ts create mode 100644 packages/extension/src/background/__new/services/analytics/index.ts create mode 100644 packages/extension/src/background/__new/services/analytics/worker.ts create mode 100644 packages/extension/src/background/__new/services/argentAccount/implementation.ts create mode 100644 packages/extension/src/background/__new/services/argentAccount/index.ts create mode 100644 packages/extension/src/background/__new/services/http/singleton.ts create mode 100644 packages/extension/src/background/__new/services/multisig/implementation.ts create mode 100644 packages/extension/src/background/__new/services/multisig/index.ts create mode 100644 packages/extension/src/background/__new/services/network/background.test.ts create mode 100644 packages/extension/src/background/__new/services/network/background.ts create mode 100644 packages/extension/src/background/__new/services/network/index.ts create mode 100644 packages/extension/src/background/__new/services/network/interface.ts create mode 100644 packages/extension/src/background/__new/services/network/status.ts create mode 100644 packages/extension/src/background/__new/services/network/worker.ts create mode 100644 packages/extension/src/background/__new/services/ui/background.test.ts create mode 100644 packages/extension/src/background/__new/services/ui/background.ts create mode 100644 packages/extension/src/background/__new/services/ui/index.ts create mode 100644 packages/extension/src/background/__new/services/ui/interface.ts delete mode 100644 packages/extension/src/background/actionQueue.ts delete mode 100644 packages/extension/src/background/download.ts create mode 100644 packages/extension/src/background/messageHandling/addMessageListeners.ts create mode 100644 packages/extension/src/background/messageHandling/handle.ts create mode 100644 packages/extension/src/background/messageHandling/messages.ts create mode 100644 packages/extension/src/background/migrations/index.ts create mode 100644 packages/extension/src/background/migrations/network/removeTestnet2.ts create mode 100644 packages/extension/src/background/migrations/token/v5.9.ts create mode 100644 packages/extension/src/background/migrations/wallet/index.ts create mode 100644 packages/extension/src/background/migrations/wallet/testnet2Accounts.ts create mode 100644 packages/extension/src/background/migrations/wallet/v5.8.1.test.ts create mode 100644 packages/extension/src/background/migrations/wallet/v5.8.1.ts rename packages/extension/src/background/{ => multisig}/multisigDeployAction.ts (71%) delete mode 100644 packages/extension/src/background/multisigMessaging.ts delete mode 100644 packages/extension/src/background/network/network.service.ts delete mode 100644 packages/extension/src/background/network/networkStatus.worker.ts delete mode 100644 packages/extension/src/background/onboarding.ts create mode 100644 packages/extension/src/background/respond.ts delete mode 100644 packages/extension/src/background/sessionMessaging.ts delete mode 100644 packages/extension/src/background/shieldMessaging.ts delete mode 100644 packages/extension/src/background/swr/helpers.ts delete mode 100644 packages/extension/src/background/swr/index.ts delete mode 100644 packages/extension/src/background/swr/types.ts create mode 100644 packages/extension/src/background/transactions/checkTransactionHash.ts delete mode 100644 packages/extension/src/background/transactions/fees/multisigFeeEstimation.ts delete mode 100644 packages/extension/src/background/transactions/fees/store.ts create mode 100644 packages/extension/src/background/transactions/service/base.test.ts create mode 100644 packages/extension/src/background/transactions/service/base.ts create mode 100644 packages/extension/src/background/transactions/service/starknet.service.ts create mode 100644 packages/extension/src/background/transactions/service/worker.ts create mode 100644 packages/extension/src/background/transactions/sources/voyager.model.ts delete mode 100644 packages/extension/src/background/transactions/tracking.ts create mode 100644 packages/extension/src/background/transactions/transactionAdapter.ts create mode 100644 packages/extension/src/background/utils/uniqueSet.test.ts create mode 100644 packages/extension/src/background/utils/uniqueSet.ts delete mode 100644 packages/extension/src/background/wallet.ts create mode 100644 packages/extension/src/background/wallet/account/shared.service.test.ts create mode 100644 packages/extension/src/background/wallet/account/shared.service.ts create mode 100644 packages/extension/src/background/wallet/account/starknet.service.test.ts create mode 100644 packages/extension/src/background/wallet/account/starknet.service.ts create mode 100644 packages/extension/src/background/wallet/backup/backup.service.ts create mode 100644 packages/extension/src/background/wallet/crypto/shared.service.ts create mode 100644 packages/extension/src/background/wallet/crypto/starknet.service.ts create mode 100644 packages/extension/src/background/wallet/deployment/interface.ts create mode 100644 packages/extension/src/background/wallet/deployment/starknet.service.ts create mode 100644 packages/extension/src/background/wallet/index.ts rename packages/extension/src/background/{accounts.ts => wallet/loadContracts.ts} (72%) create mode 100644 packages/extension/src/background/wallet/recovery/interface.ts create mode 100644 packages/extension/src/background/wallet/recovery/shared.service.test.ts create mode 100644 packages/extension/src/background/wallet/recovery/shared.service.ts create mode 100644 packages/extension/src/background/wallet/recovery/starknet.service.ts create mode 100644 packages/extension/src/background/wallet/session/interface.ts create mode 100644 packages/extension/src/background/wallet/session/session.service.ts create mode 100644 packages/extension/src/background/wallet/session/walletSession.model.ts create mode 100644 packages/extension/src/background/wallet/starknet.constants.ts create mode 100644 packages/extension/src/background/wallet/test.utils.ts create mode 100644 packages/extension/src/background/workers.ts rename packages/extension/src/inpage/{ArgentXAccount3.ts => ArgentXAccount4.ts} (69%) create mode 100644 packages/extension/src/inpage/ArgentXProvider.ts create mode 100644 packages/extension/src/inpage/ArgentXProvider4.ts create mode 100644 packages/extension/src/shared/__new/services/ui/constants.ts create mode 100644 packages/extension/src/shared/account/details/escape.model.ts create mode 100644 packages/extension/src/shared/account/details/getAccountCairoVersionFromChain.ts create mode 100644 packages/extension/src/shared/account/details/getAccountClassHashFromChain.test.ts create mode 100644 packages/extension/src/shared/account/details/getAccountClassHashFromChain.ts create mode 100644 packages/extension/src/shared/account/details/getAccountDeployStatusFromChain.ts delete mode 100644 packages/extension/src/shared/account/details/getAccountTypesFromChain.ts create mode 100644 packages/extension/src/shared/account/details/index.ts create mode 100644 packages/extension/src/shared/account/details/tryGetClassHashFromMulticall.ts create mode 100644 packages/extension/src/shared/account/details/tryGetClassHashFromProvider.ts create mode 100644 packages/extension/src/shared/account/worker/implementation.test.ts create mode 100644 packages/extension/src/shared/account/worker/implementation.ts create mode 100644 packages/extension/src/shared/account/worker/index.ts create mode 100644 packages/extension/src/shared/actionQueue/index.ts create mode 100644 packages/extension/src/shared/actionQueue/queue/interface.ts create mode 100644 packages/extension/src/shared/actionQueue/queue/queue.test.ts create mode 100644 packages/extension/src/shared/actionQueue/queue/queue.ts create mode 100644 packages/extension/src/shared/actionQueue/schema.ts create mode 100644 packages/extension/src/shared/actionQueue/service/interface.ts delete mode 100644 packages/extension/src/shared/actionQueue/store.ts create mode 100644 packages/extension/src/shared/actionQueue/store/index.ts delete mode 100644 packages/extension/src/shared/addressBook/index.ts delete mode 100644 packages/extension/src/shared/addressBook/selectors.ts create mode 100644 packages/extension/src/shared/addressBook/service/implementation.test.ts create mode 100644 packages/extension/src/shared/addressBook/service/implementation.ts create mode 100644 packages/extension/src/shared/addressBook/service/index.ts create mode 100644 packages/extension/src/shared/addressBook/service/interface.ts delete mode 100644 packages/extension/src/shared/addressBook/storage.ts create mode 100644 packages/extension/src/shared/addressBook/store/index.ts create mode 100644 packages/extension/src/shared/argentAccount/service/interface.ts delete mode 100644 packages/extension/src/shared/avatarImage.ts create mode 100644 packages/extension/src/shared/chain/service/__test__/mock.ts create mode 100644 packages/extension/src/shared/chain/service/implementation.ts create mode 100644 packages/extension/src/shared/chain/service/index.ts create mode 100644 packages/extension/src/shared/chain/service/interface.ts create mode 100644 packages/extension/src/shared/config.ts create mode 100644 packages/extension/src/shared/errors/Readme.md create mode 100644 packages/extension/src/shared/errors/account.ts create mode 100644 packages/extension/src/shared/errors/accountMessaging.ts create mode 100644 packages/extension/src/shared/errors/action.ts create mode 100644 packages/extension/src/shared/errors/addressBook.ts create mode 100644 packages/extension/src/shared/errors/argentAccount.ts create mode 100644 packages/extension/src/shared/errors/baseError.ts create mode 100644 packages/extension/src/shared/errors/errorData.ts create mode 100644 packages/extension/src/shared/errors/multisig.ts create mode 100644 packages/extension/src/shared/errors/network.ts create mode 100644 packages/extension/src/shared/errors/pubKey.ts create mode 100644 packages/extension/src/shared/errors/recovery.ts create mode 100644 packages/extension/src/shared/errors/session.ts create mode 100644 packages/extension/src/shared/errors/token.ts create mode 100644 packages/extension/src/shared/errors/transaction.ts create mode 100644 packages/extension/src/shared/errors/udc.ts create mode 100644 packages/extension/src/shared/errors/wallet.ts create mode 100644 packages/extension/src/shared/knownDapps/implementation.ts create mode 100644 packages/extension/src/shared/knownDapps/index.ts create mode 100644 packages/extension/src/shared/knownDapps/interface.ts create mode 100644 packages/extension/src/shared/knownDapps/worker/implementation.ts create mode 100644 packages/extension/src/shared/knownDapps/worker/index.ts delete mode 100644 packages/extension/src/shared/messages/MultisigMessage.ts delete mode 100644 packages/extension/src/shared/messages/ShieldMessage.ts delete mode 100644 packages/extension/src/shared/multisig/multisig.service.ts create mode 100644 packages/extension/src/shared/multisig/repository.ts create mode 100644 packages/extension/src/shared/multisig/service/backend/implementation.ts create mode 100644 packages/extension/src/shared/multisig/service/backend/index.ts create mode 100644 packages/extension/src/shared/multisig/service/backend/interface.ts create mode 100644 packages/extension/src/shared/multisig/service/backend/types.ts create mode 100644 packages/extension/src/shared/multisig/service/messaging/interface.ts delete mode 100644 packages/extension/src/shared/multisig/store.ts create mode 100644 packages/extension/src/shared/multisig/utils/getMultisigTransactionType.ts create mode 100644 packages/extension/src/shared/multisig/view/index.ts rename packages/extension/src/shared/multisig/{tracking.ts => worker/implementation.ts} (55%) create mode 100644 packages/extension/src/shared/multisig/worker/index.ts create mode 100644 packages/extension/src/shared/network/constants.ts create mode 100644 packages/extension/src/shared/network/service/index.ts create mode 100644 packages/extension/src/shared/network/statusStore.ts delete mode 100644 packages/extension/src/shared/network/storage.ts create mode 100644 packages/extension/src/shared/network/store.ts delete mode 100644 packages/extension/src/shared/network/view/index.ts create mode 100644 packages/extension/src/shared/nft/worker/implementation.ts create mode 100644 packages/extension/src/shared/nft/worker/index.ts rename packages/extension/src/{background => shared}/notification.ts (75%) create mode 100644 packages/extension/src/shared/schedule/chromeService.test.ts create mode 100644 packages/extension/src/shared/schedule/chromeService.ts create mode 100644 packages/extension/src/shared/schedule/index.ts create mode 100644 packages/extension/src/shared/schedule/interface.ts delete mode 100644 packages/extension/src/shared/schemas/address.ts delete mode 100644 packages/extension/src/shared/shield/register.ts delete mode 100644 packages/extension/src/shared/shield/validation.ts create mode 100644 packages/extension/src/shared/shield/validation/addBackendAccount.test.ts create mode 100644 packages/extension/src/shared/shield/validation/addBackendAccount.ts rename packages/extension/src/shared/shield/{validation.test.ts => validation/validateAccount.test.ts} (81%) create mode 100644 packages/extension/src/shared/shield/validation/validateAccount.ts create mode 100644 packages/extension/src/shared/shield/validation/verification.ts create mode 100644 packages/extension/src/shared/storage/__new/__test__/object.test.ts create mode 100644 packages/extension/src/shared/storage/__new/base.ts create mode 100644 packages/extension/src/shared/storage/__new/chrome.ts create mode 100644 packages/extension/src/shared/storage/__new/prune.ts create mode 100644 packages/extension/src/shared/storage/__new/repositories/knownDapp.ts delete mode 100644 packages/extension/src/shared/storage/__new/repositories/network.ts create mode 100644 packages/extension/src/shared/storage/__new/repositories/nft.ts rename packages/extension/src/shared/token/{ => __deprecated}/storage.ts (86%) rename packages/extension/src/shared/token/{ => __deprecated}/type.ts (73%) rename packages/extension/src/shared/token/{ => __deprecated}/utils.ts (64%) create mode 100644 packages/extension/src/shared/token/__new/repository/token.ts create mode 100644 packages/extension/src/shared/token/__new/repository/tokenBalance.ts create mode 100644 packages/extension/src/shared/token/__new/repository/tokenPrice.ts create mode 100644 packages/extension/src/shared/token/__new/service/implementation.ts create mode 100644 packages/extension/src/shared/token/__new/service/index.ts create mode 100644 packages/extension/src/shared/token/__new/service/interface.ts create mode 100644 packages/extension/src/shared/token/__new/types/token.model.ts create mode 100644 packages/extension/src/shared/token/__new/types/tokenBalance.model.ts create mode 100644 packages/extension/src/shared/token/__new/types/tokenPrice.model.ts create mode 100644 packages/extension/src/shared/token/__new/utils/index.ts create mode 100644 packages/extension/src/shared/token/__new/worker/implementation.ts create mode 100644 packages/extension/src/shared/token/__new/worker/index.ts create mode 100644 packages/extension/src/shared/token/__new/worker/interface.ts delete mode 100644 packages/extension/src/shared/token/amount.ts delete mode 100644 packages/extension/src/shared/token/getTokenBalance.ts create mode 100644 packages/extension/src/shared/transactionSimulation/fees/estimatedFeesRepository.ts create mode 100644 packages/extension/src/shared/transactionSimulation/fees/fees.model.ts create mode 100644 packages/extension/src/shared/transactionSimulation/utils.ts create mode 100644 packages/extension/src/shared/transactions/interface.ts create mode 100644 packages/extension/src/shared/transactions/utils.test.ts create mode 100644 packages/extension/src/shared/transactions/utils.ts create mode 100644 packages/extension/src/shared/udc/service/interface.ts create mode 100644 packages/extension/src/shared/utils/accountsEqual.ts create mode 100644 packages/extension/src/shared/utils/accountv4.ts create mode 100644 packages/extension/src/shared/utils/argentAccountVersion.ts create mode 100644 packages/extension/src/shared/utils/transactionSucceeded.ts create mode 100644 packages/extension/src/shared/utils/transactions.test.ts create mode 100644 packages/extension/src/shared/utils/transactions.ts delete mode 100644 packages/extension/src/ui/components/AddContactBottomSheet.tsx create mode 100644 packages/extension/src/ui/components/ControlledTextArea.tsx create mode 100644 packages/extension/src/ui/components/ErrorScreen.tsx delete mode 100644 packages/extension/src/ui/components/Icons/AtTheRateIcon.tsx delete mode 100644 packages/extension/src/ui/components/LoadingPulse.tsx create mode 100644 packages/extension/src/ui/components/ModalSheet.tsx create mode 100644 packages/extension/src/ui/components/ScreenSkeleton.tsx create mode 100644 packages/extension/src/ui/components/SuspenseScreen.tsx create mode 100644 packages/extension/src/ui/features/accountActivity/transform/transaction/__test__/__fixtures__/transaction-calls/goerli-alpha/multisig-add-owner.json create mode 100644 packages/extension/src/ui/features/accountActivity/transform/transaction/__test__/__fixtures__/transaction-calls/goerli-alpha/multisig-remove-owner.json create mode 100644 packages/extension/src/ui/features/accountActivity/transform/transaction/__test__/__fixtures__/transaction-calls/goerli-alpha/multisig-replace-owner.json create mode 100644 packages/extension/src/ui/features/accountActivity/useTransactionNonce.ts create mode 100644 packages/extension/src/ui/features/accountEdit/ChangeAccountImplementationScreen.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/AccountCollection.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/AccountCollectionsContainer.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/CollectionNftsContainer.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/CollectionNftsGenericError.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/NftImage.tsx create mode 100644 packages/extension/src/ui/features/accountNfts/NftScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/accountNfts/SendNftScreen.tsx delete mode 100644 packages/extension/src/ui/features/accountNfts/aspect.mock.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/aspect.model.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/aspect.service.test.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/aspect.service.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/mint-square.service.ts create mode 100644 packages/extension/src/ui/features/accountNfts/nfts.state.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/useCollections.ts delete mode 100644 packages/extension/src/ui/features/accountNfts/useNfts.ts create mode 100644 packages/extension/src/ui/features/accountNfts/useRemoteNft.ts create mode 100644 packages/extension/src/ui/features/accountTokens/AccountDeprecatedBanner.tsx delete mode 100644 packages/extension/src/ui/features/accountTokens/AccountName.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/AccountTokens.test.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/AccountTokensButtons.test.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/AccountTokensButtonsContainer.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/AccountTokensContainer.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/HideTokenScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/SaveRecoverySeedphraseBanner.tsx delete mode 100644 packages/extension/src/ui/features/accountTokens/SendTokenScreen.tsx delete mode 100644 packages/extension/src/ui/features/accountTokens/TokenMenuDeprecated.tsx delete mode 100644 packages/extension/src/ui/features/accountTokens/TokenScreen.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/WarningRecoverySeedphraseBanner.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/useAddFundsDialog.tsx create mode 100644 packages/extension/src/ui/features/accountTokens/useFeeTokenBalance.ts create mode 100644 packages/extension/src/ui/features/accountTokens/useLiveTokenBalanceForAccount.ts create mode 100644 packages/extension/src/ui/features/accountTokens/usePrettyAccountBalance.ts create mode 100644 packages/extension/src/ui/features/accounts/AccountAddressListItem.tsx create mode 100644 packages/extension/src/ui/features/accounts/AccountAddressListItemSaveAccessory.tsx create mode 100644 packages/extension/src/ui/features/accounts/AccountDeprecatedModal.tsx create mode 100644 packages/extension/src/ui/features/accounts/AccountListItemDeprecatedBadge.tsx create mode 100644 packages/extension/src/ui/features/accounts/AccountListItemSkeleton.tsx create mode 100644 packages/extension/src/ui/features/accounts/AccountListItemWithBalance.tsx create mode 100644 packages/extension/src/ui/features/accounts/ClickableShieldBanner.tsx delete mode 100644 packages/extension/src/ui/features/accounts/MigrationDisclaimerScreen.test.tsx delete mode 100644 packages/extension/src/ui/features/accounts/MigrationDisclaimerScreen.tsx delete mode 100644 packages/extension/src/ui/features/accounts/MigrationDisclaimerScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/accounts/PrettyAccountAddress.tsx create mode 100644 packages/extension/src/ui/features/accounts/PrettyAccountAddressArgentX.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreen.test.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreen.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreenV4.test.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreenV4.tsx delete mode 100644 packages/extension/src/ui/features/accounts/UpgradeScreenV4Container.tsx create mode 100644 packages/extension/src/ui/features/accounts/accountListItem.model.ts create mode 100644 packages/extension/src/ui/features/accounts/accountNavigationBar.model.ts create mode 100644 packages/extension/src/ui/features/accounts/accountUpgradeCheck.test.ts create mode 100644 packages/extension/src/ui/features/accounts/accountUpgradeCheck.ts create mode 100644 packages/extension/src/ui/features/accounts/deployAccountScreen.model.ts create mode 100644 packages/extension/src/ui/features/accounts/hideOrDeleteAccountConfirmScreen.model.ts create mode 100644 packages/extension/src/ui/features/accounts/networkTransactions.state.ts create mode 100644 packages/extension/src/ui/features/accounts/useAccountOrContact.ts create mode 100644 packages/extension/src/ui/features/actions/AddTokenScreen.test.tsx create mode 100644 packages/extension/src/ui/features/actions/ApproveSignatureScreen.test.tsx create mode 100644 packages/extension/src/ui/features/actions/ExecuteFromOutsideScreen.tsx create mode 100644 packages/extension/src/ui/features/actions/SignatureRequestRejectedScreen.tsx rename packages/{storybook/src => extension/src/ui}/features/actions/__fixtures__/accounts.ts (71%) create mode 100644 packages/extension/src/ui/features/actions/__fixtures__/aspect.ts create mode 100644 packages/extension/src/ui/features/actions/__fixtures__/dataToSign.ts create mode 100644 packages/extension/src/ui/features/actions/__fixtures__/index.ts rename packages/{storybook/src => extension/src/ui}/features/actions/__fixtures__/jediswap.ts (66%) create mode 100644 packages/extension/src/ui/features/actions/__fixtures__/transfer.ts create mode 100644 packages/extension/src/ui/features/actions/__fixtures__/types.ts delete mode 100644 packages/extension/src/ui/features/actions/actions.state.ts create mode 100644 packages/extension/src/ui/features/actions/connectDapp/ConnectDappScreen.test.tsx create mode 100644 packages/extension/src/ui/features/actions/connectDapp/DappIconContainer.tsx create mode 100644 packages/extension/src/ui/features/actions/connectDapp/KnownDappModal.tsx create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/CombinedFeeEstimation.test.tsx create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/FeeEstimation.test.tsx create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/__fixtures__/combinedFeeEstimation.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/__fixtures__/feeEstimation.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/__fixtures__/feeToken.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/__fixtures__/index.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/feeError.test.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/feeError.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/feeEstimation.model.ts create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/ui/WaitingForFunds.tsx create mode 100644 packages/extension/src/ui/features/actions/feeEstimation/useEstimatedFees.ts rename packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/{AccountNetworkInfo.tsx => AccountNetworkInfoArgentX.tsx} (70%) create mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/ApproveTransactionScreen.test.tsx delete mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/BalanceChangeOverview/NftDetails.tsx rename packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/{BalanceChangeOverview/index.tsx => BalanceChangeOverviewArgentX.tsx} (82%) rename packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/DappHeader/{index.tsx => DappHeaderArgentX.tsx} (83%) create mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/DappHeader/TransactionIcon/ReplaceOwnerIcon.tsx rename packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/DappHeader/{TransactionTitle.tsx => TransactionTitleArgentX.tsx} (82%) create mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/NftDetailsArgentXContainer.tsx rename packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/VerifiedDappBanner/{VerifiedDappModal.tsx => VerifiedDappModalArgentX.tsx} (90%) create mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/WithActionScreenErrorFooter.tsx create mode 100644 packages/extension/src/ui/features/actions/transaction/ApproveTransactionScreen/approveTransactionScreen.model.ts create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountBaseEmailScreen.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountEmailNotificationsScreen.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountEmailNotificationsScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountEmailScreen.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountFeaturesList.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountLoggedInScreen.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/ArgentAccountLoggedInScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/argentAccountBaseEmailScreen.model.ts create mode 100644 packages/extension/src/ui/features/argentAccount/hooks/useArgentAccountTokenExpired.tsx create mode 100644 packages/extension/src/ui/features/argentAccount/hooks/useEmailPreferences.tsx create mode 100644 packages/extension/src/ui/features/funding/FundingFaucetFallbackScreen.tsx create mode 100644 packages/extension/src/ui/features/funding/FundingOnRampOption.tsx delete mode 100644 packages/extension/src/ui/features/funding/banxa.svg delete mode 100644 packages/extension/src/ui/features/funding/card.svg delete mode 100644 packages/extension/src/ui/features/funding/coinbase.svg delete mode 100644 packages/extension/src/ui/features/funding/ethereum.svg delete mode 100644 packages/extension/src/ui/features/funding/orbiter.svg delete mode 100644 packages/extension/src/ui/features/funding/ramp.svg delete mode 100644 packages/extension/src/ui/features/funding/starknet.svg create mode 100644 packages/extension/src/ui/features/funding/utils.ts create mode 100644 packages/extension/src/ui/features/multisig/MultisigListScreenItemContainer.tsx create mode 100644 packages/extension/src/ui/features/multisig/MultisigOwner.tsx create mode 100644 packages/extension/src/ui/features/multisig/MultisigOwnerNameModal.tsx create mode 100644 packages/extension/src/ui/features/multisig/MultisigRemoveOwnerModal.tsx create mode 100644 packages/extension/src/ui/features/multisig/MultisigReplaceOwnerScreen.tsx create mode 100644 packages/extension/src/ui/features/multisig/MultisigSignatureScreenWarning.tsx create mode 100644 packages/extension/src/ui/features/multisig/ReplaceOwnerForm.tsx create mode 100644 packages/extension/src/ui/features/multisig/hooks/pubkeySchema.test.ts delete mode 100644 packages/extension/src/ui/features/multisig/hooks/useMultisigDataforAccount.ts create mode 100644 packages/extension/src/ui/features/multisig/hooks/useReplaceOwnerForm.ts create mode 100644 packages/extension/src/ui/features/networks/hooks/useIsDefaultNetwork.ts delete mode 100644 packages/extension/src/ui/features/networks/hooks/useShouldShowNetworkUpgradeMessage.ts delete mode 100644 packages/extension/src/ui/features/recovery/RecoveryBanner.tsx delete mode 100644 packages/extension/src/ui/features/recovery/SeedRecoveryConfirmScreen.tsx delete mode 100644 packages/extension/src/ui/features/recovery/backupDownload.state.ts create mode 100644 packages/extension/src/ui/features/recovery/hasSavedRecoverySeedphraseAtom.tsx create mode 100644 packages/extension/src/ui/features/send/NftInput.tsx create mode 100644 packages/extension/src/ui/features/send/SendAmountAndAssetNftScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/send/SendAmountAndAssetScreen.tsx create mode 100644 packages/extension/src/ui/features/send/SendAmountAndAssetScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/send/SendAmountAndAssetTokenScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/send/SendAssetScreen.tsx create mode 100644 packages/extension/src/ui/features/send/SendCollectionNftsScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/send/SendModalAddContactScreen.tsx create mode 100644 packages/extension/src/ui/features/send/SendRecipientScreen.tsx create mode 100644 packages/extension/src/ui/features/send/SendRecipientScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/send/SendScreen.tsx create mode 100644 packages/extension/src/ui/features/send/TokenAmountInput.tsx create mode 100644 packages/extension/src/ui/features/send/amountInput.test.ts create mode 100644 packages/extension/src/ui/features/send/amountInput.ts create mode 100644 packages/extension/src/ui/features/send/schema.test.ts create mode 100644 packages/extension/src/ui/features/send/schema.ts create mode 100644 packages/extension/src/ui/features/send/sendRecipientScreen.model.ts create mode 100644 packages/extension/src/ui/features/send/useFilteredAccounts.ts create mode 100644 packages/extension/src/ui/features/send/useFilteredCollections.ts create mode 100644 packages/extension/src/ui/features/send/useFilteredContacts.ts create mode 100644 packages/extension/src/ui/features/send/useFilteredTokens.ts create mode 100644 packages/extension/src/ui/features/send/useGetAddressFromStarknetId.ts create mode 100644 packages/extension/src/ui/features/settings/AddressBookAddOrEditScreen.tsx create mode 100644 packages/extension/src/ui/features/settings/AddressBookAddOrEditScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/settings/AddressBookSettingsScreen.tsx create mode 100644 packages/extension/src/ui/features/settings/AddressBookSettingsScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/settings/AddressbookAddOrEditScreen.tsx delete mode 100644 packages/extension/src/ui/features/settings/AddressbookSettingsScreen.tsx create mode 100644 packages/extension/src/ui/features/settings/BeforeYouContinueScreen.tsx create mode 100644 packages/extension/src/ui/features/settings/BetaFeatureSettings.tsx delete mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/DeclareOrDeployContractSuccess.tsx create mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/DeclareOrDeployContractSuccessScreen.tsx create mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/DeclareOrDeployContractSuccessScreenContainer.tsx create mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/deploySmartContractForm.model.ts create mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/ui/ContractWithClassHash.tsx create mode 100644 packages/extension/src/ui/features/settings/DeveloperSettings/ui/FileInputButton.tsx create mode 100644 packages/extension/src/ui/features/settings/NetworkSettingsFormScreenContainer.tsx delete mode 100644 packages/extension/src/ui/features/settings/selectedNetwork.state.ts delete mode 100644 packages/extension/src/ui/features/shield/ShieldBaseEmailScreen.tsx create mode 100644 packages/extension/src/ui/features/shield/escape/accountHasEscape.ts delete mode 100644 packages/extension/src/ui/features/shield/useArgentShieldEnabled.ts create mode 100644 packages/extension/src/ui/hooks/useAddressBook.ts create mode 100644 packages/extension/src/ui/hooks/useAutoFocusInputRef.ts create mode 100644 packages/extension/src/ui/hooks/useOnAppRoutesAnimationComplete.ts create mode 100644 packages/extension/src/ui/hooks/useQuery.ts create mode 100644 packages/extension/src/ui/hooks/useResetAll.ts create mode 100644 packages/extension/src/ui/services/accountMessaging/implementation.ts create mode 100644 packages/extension/src/ui/services/accountMessaging/index.ts create mode 100644 packages/extension/src/ui/services/accountMessaging/interface.ts create mode 100644 packages/extension/src/ui/services/action/client.ts create mode 100644 packages/extension/src/ui/services/action/index.ts delete mode 100644 packages/extension/src/ui/services/addressBook.ts create mode 100644 packages/extension/src/ui/services/addressBook/client.ts create mode 100644 packages/extension/src/ui/services/addressBook/index.ts create mode 100644 packages/extension/src/ui/services/argentAccount/implementation.ts create mode 100644 packages/extension/src/ui/services/argentAccount/index.ts create mode 100644 packages/extension/src/ui/services/argentAccount/utils.ts delete mode 100644 packages/extension/src/ui/services/backgroundActions.ts delete mode 100644 packages/extension/src/ui/services/backgroundMultisigs.ts delete mode 100644 packages/extension/src/ui/services/backgroundSessions.ts delete mode 100644 packages/extension/src/ui/services/extension/clientLegacy.ts delete mode 100644 packages/extension/src/ui/services/extension/index.ts delete mode 100644 packages/extension/src/ui/services/extension/interface.ts create mode 100644 packages/extension/src/ui/services/knownDapps/index.ts create mode 100644 packages/extension/src/ui/services/multisig/implementation.ts create mode 100644 packages/extension/src/ui/services/multisig/index.ts create mode 100644 packages/extension/src/ui/services/multisig/interface.ts create mode 100644 packages/extension/src/ui/services/nfts/implementation.ts create mode 100644 packages/extension/src/ui/services/nfts/index.ts create mode 100644 packages/extension/src/ui/services/nfts/interface.ts create mode 100644 packages/extension/src/ui/services/nfts/test/index.test.ts create mode 100644 packages/extension/src/ui/services/nfts/test/nft.mock.ts create mode 100644 packages/extension/src/ui/services/session/implementation.ts create mode 100644 packages/extension/src/ui/services/session/index.ts create mode 100644 packages/extension/src/ui/services/session/interface.ts rename packages/extension/src/ui/services/{swr.ts => swr.service.ts} (90%) create mode 100644 packages/extension/src/ui/services/tokens/implementation.ts create mode 100644 packages/extension/src/ui/services/tokens/index.ts create mode 100644 packages/extension/src/ui/services/tokens/interface.ts create mode 100644 packages/extension/src/ui/services/tokens/test/index.test.ts create mode 100644 packages/extension/src/ui/services/tokens/types.ts create mode 100644 packages/extension/src/ui/services/tokens/utils.ts create mode 100644 packages/extension/src/ui/services/udc/implementation.ts create mode 100644 packages/extension/src/ui/services/udc/index.ts create mode 100644 packages/extension/src/ui/services/ui/client.ts create mode 100644 packages/extension/src/ui/services/ui/index.ts create mode 100644 packages/extension/src/ui/services/ui/interface.ts create mode 100644 packages/extension/src/ui/services/useStopSession.ts create mode 100644 packages/extension/src/ui/views/actions.ts create mode 100644 packages/extension/src/ui/views/addressBook.ts create mode 100644 packages/extension/src/ui/views/estimatedFees.ts create mode 100644 packages/extension/src/ui/views/implementation/__tests__/atomFromRepo.test.tsx create mode 100644 packages/extension/src/ui/views/implementation/__tests__/atomFromStore.test.tsx create mode 100644 packages/extension/src/ui/views/implementation/__tests__/atomWithSubscription.test.tsx create mode 100644 packages/extension/src/ui/views/implementation/atomWithSubscription.ts create mode 100644 packages/extension/src/ui/views/knownDapps.ts create mode 100644 packages/extension/src/ui/views/multisig.ts create mode 100644 packages/extension/src/ui/views/network.ts create mode 100644 packages/extension/src/ui/views/nft.ts create mode 100644 packages/extension/src/ui/views/session.ts create mode 100644 packages/extension/src/ui/views/token.ts create mode 100644 packages/extension/src/ui/views/tokenBalances.ts create mode 100644 packages/extension/src/ui/views/tokenPrices.ts create mode 100644 packages/extension/test/network.mock.ts create mode 100644 packages/extension/vitest.config.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/adapter.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/argentModal.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/getDevice.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/index.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/login.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/starknet/starknet.model.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/starknet/starknetAccount.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/starknet/starknetAdapter.ts create mode 100644 packages/get-starknet/src/modal/argentMobile/starknet/starknetSigner.ts create mode 100644 packages/guardian/.vscode/settings.json create mode 100644 packages/multicall/.vscode/settings.json create mode 100644 packages/multicall/CHANGELOG.md create mode 100644 packages/multicall/__tests__/__snapshots__/integration.test.ts.snap create mode 100644 packages/sessions/.vscode/settings.json create mode 100644 packages/shared/.vscode/settings.json create mode 100644 packages/shared/CHANGELOG.md create mode 100644 packages/shared/src/account/accountv4.ts create mode 100644 packages/shared/src/account/index.ts create mode 100644 packages/shared/src/argent/errors.ts create mode 100644 packages/shared/src/argent/interface.ts create mode 100644 packages/shared/src/bigdecimal/formatUnits.test.ts create mode 100644 packages/shared/src/bigdecimal/formatUnits.ts create mode 100644 packages/shared/src/bigdecimal/index.ts create mode 100644 packages/shared/src/bigdecimal/parseUnits.test.ts create mode 100644 packages/shared/src/bigdecimal/parseUnits.ts create mode 100644 packages/shared/src/bigdecimal/utils.test.ts create mode 100644 packages/shared/src/bigdecimal/utils.ts create mode 100644 packages/shared/src/chains/index.ts create mode 100644 packages/shared/src/chains/starknet/address.test.ts create mode 100644 packages/shared/src/chains/starknet/address.ts create mode 100644 packages/shared/src/chains/starknet/addressInput.test.ts create mode 100644 packages/shared/src/chains/starknet/addressInput.ts create mode 100644 packages/shared/src/chains/starknet/starknetId.test.ts create mode 100644 packages/shared/src/chains/starknet/starknetId.ts create mode 100644 packages/shared/src/hooks/index.ts create mode 100644 packages/shared/src/hooks/useDebounce.ts create mode 100644 packages/shared/src/knownDapps/argent.ts create mode 100644 packages/shared/src/knownDapps/index.ts create mode 100644 packages/shared/src/knownDapps/interface.ts create mode 100644 packages/shared/src/knownDapps/model.ts create mode 100644 packages/shared/src/nfts/argent.ts delete mode 100644 packages/shared/src/nfts/aspect.model.ts delete mode 100644 packages/shared/src/nfts/aspect.ts create mode 100644 packages/shared/src/nfts/interface.ts create mode 100644 packages/shared/src/signer/index.ts rename packages/{extension/src/shared/schemas => shared/src/signer}/seedphrase.ts (100%) create mode 100644 packages/shared/src/transactions/amount.ts create mode 100644 packages/shared/src/transactions/useErc20Transactions.ts create mode 100644 packages/shared/src/transactions/useErc721Transactions.ts create mode 100644 packages/shared/src/utils/address.ts delete mode 100644 packages/shared/src/utils/addresses.ts rename packages/{extension/test => shared/src/utils}/avatarImage.test.ts (96%) create mode 100644 packages/shared/src/utils/base58.ts create mode 100644 packages/shared/src/utils/bigNumber.ts create mode 100644 packages/shared/src/utils/env.test.ts create mode 100644 packages/shared/src/utils/env.ts rename packages/{extension/src/shared/schemas => shared/src/utils}/hex.ts (100%) create mode 100644 packages/shared/src/utils/readFileAsString.ts create mode 100644 packages/shared/src/utils/schemas.ts create mode 100644 packages/shared/src/utils/starknet.ts create mode 100644 packages/shared/src/utils/useEventEmitter.tsx create mode 100644 packages/shared/test/setup.ts create mode 100644 packages/shared/vitest.config.ts create mode 100644 packages/stack-router/.vscode/settings.json create mode 100644 packages/starknet-react-webwallet-connector/CHANGELOG.md create mode 100644 packages/storybook/.env.example create mode 100644 packages/storybook/.vscode/settings.json create mode 100644 packages/storybook/src/features/accounts/AccountAddressListItem.stories.tsx create mode 100644 packages/storybook/src/features/accounts/AccountListItemSkeleton.stories.tsx delete mode 100644 packages/storybook/src/features/accounts/MigrationDisclaimerScreen.stories.tsx create mode 100644 packages/storybook/src/features/accounts/PrettyAccountAddressArgentX.stories.tsx delete mode 100644 packages/storybook/src/features/accounts/UpgradeScreenV4.stories.tsx create mode 100644 packages/storybook/src/features/accounts/__fixtures__/addressBook.ts create mode 100644 packages/storybook/src/features/actions/AccountNetworkInfoArgentX.stories.tsx create mode 100644 packages/storybook/src/features/actions/AddNetworkScreen.stories.tsx create mode 100644 packages/storybook/src/features/actions/BalanceChangeOverviewArgentX.stories.tsx create mode 100644 packages/storybook/src/features/actions/MultisigSignatureScreenWarning.stories.tsx delete mode 100644 packages/storybook/src/features/actions/__fixtures__/aspect.ts delete mode 100644 packages/storybook/src/features/actions/__fixtures__/transfer.ts delete mode 100644 packages/storybook/src/features/actions/transaction/__fixtures__/fees/combinedFeeEstimationFixtures.ts delete mode 100644 packages/storybook/src/features/actions/transaction/__fixtures__/fees/feeEstimationFixtures.ts create mode 100644 packages/storybook/src/features/send/NftInput.stories.tsx create mode 100644 packages/storybook/src/features/send/TokenAmountInput.stories.tsx create mode 100644 packages/storybook/src/features/settings/AddressBookAddOrEditScreen.stories.tsx create mode 100644 packages/storybook/src/features/settings/AddressBookSettingsScreen.stories.tsx create mode 100644 packages/storybook/src/features/settings/DeclareOrDeployContractSuccessScreen.stories.tsx create mode 100644 packages/storybook/src/features/settings/DeclareSmartContractForm.stories.tsx rename packages/storybook/src/features/{accounts/UpgradeScreen.stories.tsx => settings/DeploySmartContractForm.stories.tsx} (52%) create mode 100644 packages/storybook/src/tokens.ts delete mode 100644 packages/storybook/src/tokensByNetwork.ts create mode 100644 packages/storybook/src/ui/components/AccountNetworkInfo.stories.tsx create mode 100644 packages/storybook/src/ui/components/BalanceChangeOverview.stories.tsx create mode 100644 packages/storybook/src/ui/components/ModalDialog.stories.tsx create mode 100644 packages/storybook/src/ui/components/ModalDialogData.stories.tsx create mode 100644 packages/storybook/src/ui/components/NavigationContainerSkeleton.stories.tsx create mode 100644 packages/storybook/src/ui/components/NftDetails.stories.tsx create mode 100644 packages/storybook/src/ui/components/PasswordStrengthIndicator.stories.tsx create mode 100644 packages/storybook/src/ui/components/Select.stories.tsx create mode 100644 packages/storybook/src/ui/components/Tabs.stories.tsx delete mode 100644 packages/storybook/src/ui/components/TextAreaDeprecated.stories.tsx create mode 100644 packages/storybook/src/ui/components/TextareaAutosize.stories.tsx delete mode 100644 packages/swap/src/sdk/hash.ts create mode 100644 packages/ui/.vscode/settings.json create mode 100644 packages/ui/src/components/ButtonRect.tsx create mode 100644 packages/ui/src/components/ModalDialog.tsx create mode 100644 packages/ui/src/components/ModalDialogData.tsx create mode 100644 packages/ui/src/components/PasswordStrengthIndicatorBar.tsx delete mode 100644 packages/ui/src/components/SelectOption.tsx create mode 100644 packages/ui/src/components/Tabs.tsx create mode 100644 packages/ui/src/components/TextareaAutosize.tsx create mode 100644 packages/ui/src/components/icons/LogoutIcon.tsx create mode 100644 packages/ui/src/components/icons/MultisigImageIcon.tsx create mode 100644 packages/ui/src/components/icons/MultisigReplaceIcon.tsx create mode 100644 packages/ui/src/components/icons/SessionIcon.tsx create mode 100644 packages/ui/src/components/icons/SignIcon.tsx delete mode 100644 packages/ui/src/components/logos/ArgentLogo.tsx create mode 100644 packages/ui/src/components/logos/Banxa.tsx create mode 100644 packages/ui/src/components/logos/EmptyNft.tsx create mode 100644 packages/ui/src/components/logos/Flex.tsx create mode 100644 packages/ui/src/components/logos/Image.tsx create mode 100644 packages/ui/src/components/logos/Layerswap.tsx delete mode 100644 packages/ui/src/components/logos/MultisigDiagram.tsx create mode 100644 packages/ui/src/components/logos/Orbiter.tsx create mode 100644 packages/ui/src/components/logos/Ramp.tsx create mode 100644 packages/ui/src/components/logos/Unframed.tsx create mode 100644 packages/ui/src/components/logos/Zklend.tsx delete mode 100644 packages/ui/src/components/transactions/BalanceChangeOverview.tsx delete mode 100644 packages/ui/src/components/transactions/DappHeader.tsx create mode 100644 packages/ui/src/components/transactions/TransactionError.tsx delete mode 100644 packages/ui/src/components/transactions/TransactionTitle.tsx create mode 100644 packages/ui/src/theme/skeleton.ts create mode 100644 packages/ui/vitest.config.ts create mode 100644 packages/web-sdk/CHANGELOG.md create mode 100644 packages/web-sdk/src/account.ts create mode 100644 packages/web-sdk/src/argentStarknetWindowObject.ts create mode 100644 packages/web-sdk/src/trpc.ts delete mode 100644 packages/web-sdk/src/wormhole.ts create mode 100644 packages/window/src/utils/mittx.ts create mode 100644 packages/window/vitest.config.ts delete mode 100644 patches/@noble+hashes+1.3.0.patch delete mode 100644 patches/starknet+4.22.0.patch create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 renovate.json create mode 100755 scripts/version.sh delete mode 100644 yarn.lock diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 000000000..5654e898b --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,5 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 000000000..8a4617a04 --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", + "changelog": "@changesets/cli/changelog", + "commit": false, + "fixed": [], + "linked": [], + "access": "restricted", + "baseBranch": "release/next", + "updateInternalDependencies": "patch", + "ignore": [], + "privatePackages": { + "tag": true, + "version": true + } +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 237c7bc00..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,12 +0,0 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: -# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates - -version: 2 -updates: - - package-ecosystem: "npm" # See documentation for possible values - directory: "/" # Location of package manifests - schedule: - interval: "weekly" - day: "thursday" diff --git a/.github/workflows/changeset.yml b/.github/workflows/changeset.yml new file mode 100644 index 000000000..48e2fa5de --- /dev/null +++ b/.github/workflows/changeset.yml @@ -0,0 +1,68 @@ +name: Bootstrap Release + +on: + push: + branches: + - release/next + +concurrency: ${{ github.workflow }}-${{ github.ref }} + +jobs: + create-release: + name: Release + runs-on: ubuntu-latest + steps: + - name: Checkout Repo + uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + token: ${{ secrets.ARGENTBOT_GITHUB_PAT }} + + - name: Install Node.js + uses: actions/setup-node@v3 + with: + node-version: "18.x" + + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + + - name: Get pnpm store directory + id: pnpm-cache + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT + + - uses: actions/cache@v3 + name: Setup pnpm cache + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - name: Install dependencies + run: pnpm install + + - name: Create Release Pull Request + id: changesets + uses: changesets/action@v1 + with: + version: bash ./scripts/version.sh + env: + GITHUB_TOKEN: ${{ secrets.ARGENTBOT_GITHUB_PAT }} + + - name: Tag + if: steps.changesets.outputs.hasChangesets == 'false' + # replace GITHUB_TOKEN with PAT to allow CI to run on tags + env: + GITHUB_TOKEN: ${{ secrets.ARGENTBOT_GITHUB_PAT }} + # You can do something when a publish should happen. + run: | + # check if tags already exists + pnpm changeset tag + git push --follow-tags origin ${{ github.ref }} diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index d1a9dc15b..de3fb696e 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -5,69 +5,118 @@ on: - develop pull_request: -env: - FEATURE_PRIVACY_SETTINGS: "true" - FEATURE_EXPERIMENTAL_SETTINGS: "true" - FEATURE_BANXA: "true" - FEATURE_LAYERSWAP: "true" - FEATURE_ORBITER: "true" - FEATURE_VERIFIED_DAPPS: "true" - FEATURE_ARGENT_SHIELD: "true" - ARGENT_SHIELD_NETWORK_ID: "mainnet-alpha" - FEATURE_MULTISIG: "false" - - SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY }} - SENTRY_DSN: ${{ secrets.SENTRY_DSN }} - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - RAMP_API_KEY: ${{ secrets.RAMP_API_KEY }} - SAFE_ENV_VARS: true - ARGENT_API_BASE_URL: ${{ vars.ARGENT_API_BASE_URL }} - ARGENT_TRANSACTION_REVIEW_API_BASE_URL: ${{ vars.ARGENT_TRANSACTION_REVIEW_API_BASE_URL }} - ARGENT_X_STATUS_URL: ${{ vars.ARGENT_X_STATUS_URL }} - ARGENT_EXPLORER_BASE_URL: ${{ vars.ARGENT_EXPLORER_BASE_URL }} - jobs: - setup: + build-all-artifacts: runs-on: ubuntu-latest + strategy: + matrix: + env: [prod, hydrogen] + extension_type: [chrome, firefox] + + environment: ${{ matrix.env }} + + env: + # FEATURE flags + FEATURE_PRIVACY_SETTINGS: "true" + FEATURE_EXPERIMENTAL_SETTINGS: "false" + FEATURE_BETA_FEATURES: "true" + FEATURE_BANXA: "true" + FEATURE_LAYERSWAP: "true" + FEATURE_ORBITER: "true" + FEATURE_VERIFIED_DAPPS: "true" + FEATURE_MULTISIG: "true" + + # API URLs + ARGENT_API_BASE_URL: ${{ vars.ARGENT_API_BASE_URL }} + ARGENT_X_STATUS_URL: ${{ vars.ARGENT_X_STATUS_URL }} + + # API ENVIRONMENT + ARGENT_X_ENVIRONMENT: ${{ matrix.env }} + + # Sentry + SENTRY_DSN: ${{ secrets.SENTRY_DSN }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ENVIRONMENT: "staging" + + # Misc + SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY }} + RAMP_API_KEY: ${{ secrets.RAMP_API_KEY }} + SAFE_ENV_VARS: false + MULTICALL_MAX_BATCH_SIZE: 20 + + # Refresh intervals + FAST: 20 # 20s + MEDIUM: 60 # 60s + SLOW: 60 * 5 # 5m + VERY_SLOW: 24 * 60 * 60 # 1d steps: - - uses: actions/checkout@v3 + # Setup Project + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + - uses: actions/setup-node@v3 with: - node-version: "16" - cache: "yarn" + node-version: "18.x" + cache: "pnpm" + + - name: Get pnpm store directory + id: pnpm-cache + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT + + - uses: actions/cache@v3 + name: Setup pnpm cache + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- - name: Setup project - run: yarn setup + run: pnpm run setup - - name: Build extension - run: yarn lerna run --scope @argent-x/extension build + - name: Build extension for ${{ matrix.extension_type }} + run: pnpm run build:extension - - name: Check bundlesize for Chrome - run: yarn run bundlewatch + - name: Check bundlesize for ${{ matrix.extension_type }} + run: pnpm bundlewatch - - name: Cache build + - name: Use Cache uses: actions/cache@v3 with: path: ./* - key: ${{ github.sha }} + key: ${{ github.sha }}-${{ matrix.extension_type }}-${{ matrix.env }} - name: Set filename prefix - run: echo "FILENAME_PREFIX=$(echo argent-extension-${{ github.ref_name }} | tr / -)" >> $GITHUB_ENV + run: echo "FILENAME_PREFIX=$(echo argent-x-${{ matrix.env }}-${{ github.ref_name }} | tr / -)" >> $GITHUB_ENV - - name: Create chrome zip - run: (cd ./packages/extension/dist && zip -r "../../../${{ env.FILENAME_PREFIX }}-chrome.zip" .) + - name: Create ${{ matrix.extension_type }} zip + run: (cd ./packages/extension/dist && zip -r "../../../${{ env.FILENAME_PREFIX }}-${{ matrix.extension_type }}" .) - - name: Upload Chrome extension + - name: Upload ${{ matrix.extension_type }} extension uses: actions/upload-artifact@v3 with: - name: ${{ env.FILENAME_PREFIX }}-chrome.zip - path: "*-chrome.zip" - retention-days: 5 + name: ${{ env.FILENAME_PREFIX }}-${{ matrix.extension_type }} + path: "*-${{ matrix.extension_type }}.zip" + retention-days: 3 test-unit: runs-on: ubuntu-latest - needs: [setup] + needs: [build-all-artifacts] + environment: "hydrogen" # test-unit is always run against hydrogen + + env: + ARGENT_API_BASE_URL: ${{ vars.ARGENT_API_BASE_URL }} + ARGENT_X_STATUS_URL: ${{ vars.ARGENT_X_STATUS_URL }} + ARGENT_X_ENVIRONMENT: "hydrogen" services: devnet: @@ -76,27 +125,44 @@ jobs: - 5050:5050 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 with: - node-version: "16" - cache: "yarn" fetch-depth: 0 + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + + - uses: actions/setup-node@v3 + with: + node-version: "18.x" + cache: "pnpm" + + - name: Restore pnpm cache + uses: actions/cache@v3 + with: + path: ~/.pnpm-store + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + - name: Restore cached build uses: actions/cache@v3 with: path: ./* - key: ${{ github.sha }} + key: ${{ github.sha }}-chrome-hydrogen # test-unit is always run against chrome-hydrogen build - name: Lint - run: yarn lint + run: pnpm run lint - name: Run tests - run: yarn test:ci + run: pnpm run test:ci - name: SonarCloud Scan # TODO replace with master as soon as sonarcloud fixes the issue with action https://community.sonarsource.com/t/sonarsource-sonarcloud-github-action-failing-with-node-js-12-error/89664/2 - uses: SonarSource/sonarcloud-github-action@v1.8 + uses: SonarSource/sonarcloud-github-action@v1.9 with: projectBaseDir: ./packages/extension env: @@ -105,111 +171,187 @@ jobs: test-e2e: runs-on: ubuntu-latest - needs: [setup] + needs: [build-all-artifacts] strategy: matrix: - project: [chromium] + project: [ArgentX] shardIndex: [1, 2, 3, 4, 5, 6, 7, 8] shardTotal: [8] - services: - devnet: - image: argentlabs-argent-x.jfrog.io/e2e-starknet-devnet:latest - ports: - - 5050:5050 - credentials: - username: ${{ secrets.JFROG_USERNAME }} - password: ${{ secrets.JFROG_PASSWORD }} + env: + ARGENT_X_ENVIRONMENT: "hydrogen" + E2E_TESTNET_SEED1: ${{ secrets.E2E_TESTNET_SEED1 }} + E2E_TESTNET_SEED2: ${{ secrets.E2E_TESTNET_SEED2 }} + E2E_TESTNET_SEED3: ${{ secrets.E2E_TESTNET_SEED3 }} + E2E_ACCOUNT_1_SEED2: ${{ secrets.E2E_ACCOUNT_1_SEED2 }} + E2E_ACCOUNT_1_SEED3: ${{ secrets.E2E_ACCOUNT_1_SEED3 }} + ## BANK ACCOUNT, USED FOR FUND OTHER ACCOUNTS + E2E_SENDER_ADDRESS: ${{ secrets.E2E_SENDER_ADDRESS }} + E2E_SENDER_PRIVATEKEY: ${{ secrets.E2E_SENDER_PRIVATEKEY }} + E2E_SENDER_SEED: ${{ secrets.E2E_SENDER_SEED }} + STARKNET_TESTNET_URL: ${{ secrets.STARKNET_TESTNET_URL }} + STARKSCAN_TESTNET_URL: ${{ secrets.STARKSCAN_TESTNET_URL }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + - uses: actions/setup-node@v3 with: - node-version: "16" - cache: "yarn" + node-version: "18.x" + cache: "pnpm" + + - name: Restore pnpm cache + uses: actions/cache@v3 + with: + path: ~/.pnpm-store + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- - name: Restore cached build uses: actions/cache@v3 with: path: ./* - key: ${{ github.sha }} + key: ${{ github.sha }}-chrome-${{ env.ARGENT_X_ENVIRONMENT }} # test-e2e is always run against chrome-hydrogen build - name: Install Playwright Browsers run: npx playwright install chromium - name: Run e2e tests - run: xvfb-run --auto-servernum yarn test:e2e --project=${{ matrix.project }} --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} + run: xvfb-run --auto-servernum pnpm test:e2e:extension --project=${{ matrix.project }} --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} - name: Upload artifacts uses: actions/upload-artifact@v3 if: always() with: - name: test-results + name: test-artifacts path: | - packages/test-results/ packages/e2e/artifacts/playwright/ - packages/e2e/artifacts/reports/ retention-days: 5 - build_firefox_extension: - runs-on: ubuntu-latest - if: ${{ github.event_name == 'pull_request' }} # Run only for pull requests - needs: [setup] + - name: Upload blob report to GitHub Actions Artifacts + if: always() + uses: actions/upload-artifact@v3 + with: + name: all-blob-reports + path: packages/e2e/blob-report/ + retention-days: 5 + + merge-reports: + needs: [test-e2e, test-webwallet] + if: always() + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + - uses: actions/setup-node@v3 with: node-version: "16" - cache: "yarn" + cache: "pnpm" - - name: Restore cached build + - name: Restore pnpm cache uses: actions/cache@v3 with: - path: ./* - key: ${{ github.sha }} + path: ~/.pnpm-store + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- - - name: Build Firefox version - run: MANIFEST_VERSION=v2 yarn --cwd packages/extension build + - name: Download blob reports from GitHub Actions Artifacts + uses: actions/download-artifact@v3 + with: + name: all-blob-reports + path: all-blob-reports - - name: Set filename prefix - run: echo "FILENAME_PREFIX=$(echo argent-extension-${{ github.ref_name }} | tr / -)" >> $GITHUB_ENV + - name: Merge into HTML Report + run: npx playwright merge-reports --reporter html ./all-blob-reports - - name: Create firefox zip - run: (cd ./packages/extension/dist && zip -r "../../../${{ env.FILENAME_PREFIX }}-firefox.zip" .) + - name: Upload HTML report + uses: actions/upload-artifact@v3 + with: + name: html-report--attempt-${{ github.run_attempt }} + path: playwright-report + retention-days: 14 - - name: Check bundlesize for firefox - run: yarn run bundlewatch + add_pr_comments: + runs-on: ubuntu-latest + if: ${{ github.event_name == 'pull_request' && github.actor != 'dependabot[bot]'}} # Run only for pull requests and if not triggered by dependabot + needs: [build-all-artifacts, test-unit, test-e2e] - - name: Upload artifacts for firefox - uses: actions/upload-artifact@v3 + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install with: - name: ${{ env.FILENAME_PREFIX }}-firefox.zip - path: "*-firefox.zip" - retention-days: 5 + version: 8 + run_install: false + + - uses: actions/setup-node@v3 + with: + node-version: "18.x" + cache: "pnpm" + + - name: Restore pnpm cache + uses: actions/cache@v3 + with: + path: ~/.pnpm-store + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - name: Set GHA_BRANCH + run: echo "GHA_BRANCH=$(echo $GITHUB_REF | awk -F / '{print $3}')" >> $GITHUB_ENV + + - name: Comment PR + continue-on-error: true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh pr comment ${{ env.GHA_BRANCH }} --body "[Builds for local testing](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})" create_sentry_release: runs-on: ubuntu-latest if: ${{ github.event_name == 'pull_request' && github.actor != 'dependabot[bot]'}} # Run only for pull requests and if not triggered by dependabot - needs: [setup] + needs: [build-all-artifacts, test-unit, test-e2e] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + - uses: actions/setup-node@v3 with: - node-version: "16" - cache: "yarn" + node-version: "18.x" + cache: "pnpm" - name: Restore cached build uses: actions/cache@v3 with: path: ./* - key: ${{ github.sha }} - - - name: Build extension - run: yarn lerna run --scope @argent-x/extension build + key: ${{ github.sha }}-chrome-hydrogen - name: Get Extension version id: package-version @@ -233,25 +375,96 @@ jobs: SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} SENTRY_LOG_LEVEL: debug with: - environment: staging - sourcemaps: "./packages/extension/sourcemaps" + environment: ${{ env.SENTRY_ENVIRONMENT }} + sourcemaps: "./packages/extension/dist ./packages/extension/sourcemaps" + url_prefix: "~/" version: ${{ steps.package-version.outputs.current-version }}-rc__${{ github.sha }} ignore_missing: true - add_pr_comments: + test-webwallet: runs-on: ubuntu-latest - if: ${{ github.event_name == 'pull_request' && github.actor != 'dependabot[bot]'}} # Run only for pull requests and if not triggered by dependabot - needs: [build_firefox_extension, test-unit, test-e2e] + needs: [build-all-artifacts] + continue-on-error: true + + environment: hydrogen + env: + NEXT_PUBLIC_NETWORK: "testnet" + NEXT_PUBLIC_RAMP_API_KEY: ${{ secrets.RAMP_API_KEY }} + NEXT_PUBLIC_FEATURE_COSIGNER: "true" + NEXT_PUBLIC_ARGENT_API_BASE_URL: ${{ vars.ARGENT_API_BASE_URL }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - name: Set GHA_BRANCH - run: echo "GHA_BRANCH=$(echo $GITHUB_REF | awk -F / '{print $3}')" >> $GITHUB_ENV + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false - - name: Comment PR - continue-on-error: true + - uses: actions/setup-node@v3 + with: + node-version: "18.x" + cache: "pnpm" + + - name: Restore cached build + uses: actions/cache@v3 + with: + path: ./* + key: ${{ github.sha }} + + - name: Build webwallet + run: pnpm run build:web + + - name: Install Playwright Browsers + run: pnpm playwright install --with-deps + + - name: Run tests + run: | + pnpm run --filter @argent/web start:ci & + pnpm run test:e2e:webwallet + + - name: Upload artifacts + uses: actions/upload-artifact@v3 + if: always() + with: + name: test-artifacts + path: | + packages/e2e/artifacts/playwright/ + retention-days: 5 + + - name: Upload blob report to GitHub Actions Artifacts + if: always() + uses: actions/upload-artifact@v3 + with: + name: all-blob-reports + path: packages/e2e/blob-report/ + retention-days: 5 + + slack_notif: + runs-on: ubuntu-latest + if: always() + needs: [test-unit, test-e2e, test-webwallet] + + steps: + - name: Send notification to Slack + uses: 8398a7/action-slack@v3.15.1 + with: + status: custom + custom_payload: | + { + text: "*ArgentX* - ${{ env.BUILD_TYPE }} - ${{ env.BUILD_STATUS == 'good' && 'SUCCESS' || 'FAILED' }}", + attachments: [{ + fallback: 'fallback', + color: '${{ env.BUILD_STATUS }}', + title: 'Artifacts for testing ${{ env.BUILD_TYPE }} <${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.number }}|${{ github.event.number }} ${{ github.event.pull_request.title }}>', + text: '<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}#artifacts|Artifacts link>', + fields: [{},], + actions: [{}]}] + } env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh pr comment ${{ env.GHA_BRANCH }} --body "[Builds for local testing](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})" + BUILD_TYPE: ${{ github.event_name == 'pull_request' && 'pull request' || 'develop' }} + BUILD_STATUS: ${{ needs.test-unit.result == 'success' && needs.test-e2e.result == 'success' && needs.test-webwallet.result == 'success' && 'good' || 'danger' }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9d596d790..a45da55be 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,19 +2,23 @@ name: Release on: push: + branches: + - release/* tags: - - "extension/*" + # - "@argent-x/extension@*" + - "**" env: FEATURE_PRIVACY_SETTINGS: "true" - FEATURE_EXPERIMENTAL_SETTINGS: "true" + FEATURE_EXPERIMENTAL_SETTINGS: "false" + FEATURE_BETA_FEATURES: "true" FEATURE_BANXA: "true" FEATURE_LAYERSWAP: "true" FEATURE_ORBITER: "true" FEATURE_VERIFIED_DAPPS: "true" - FEATURE_ARGENT_SHIELD: "true" ARGENT_SHIELD_NETWORK_ID: "mainnet-alpha" - FEATURE_MULTISIG: "false" + FEATURE_MULTISIG: "true" + SENTRY_ENVIRONMENT: "production" NPM_ACCESS_TOKEN: ${{ secrets.NPM_ACCESS_TOKEN }} SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY }} SENTRY_DSN: ${{ secrets.SENTRY_DSN }} @@ -26,47 +30,55 @@ env: ARGENT_TRANSACTION_REVIEW_API_BASE_URL: ${{ vars.ARGENT_TRANSACTION_REVIEW_API_BASE_URL }} ARGENT_X_STATUS_URL: ${{ vars.ARGENT_X_STATUS_URL }} ARGENT_EXPLORER_BASE_URL: ${{ vars.ARGENT_EXPLORER_BASE_URL }} + ARGENT_X_ENVIRONMENT: "prod" + MULTICALL_MAX_BATCH_SIZE: 20 + FAST: 20 # 20s + MEDIUM: 60 # 60s + SLOW: 60 * 5 # 5m + VERY_SLOW: 24 * 60 * 60 # 1d jobs: build: + if: ${{ !startsWith(github.ref, 'refs/tags/') || startsWith(github.ref, 'refs/tags/') && contains(github.ref, 'extension') }} runs-on: ubuntu-latest permissions: contents: write steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 with: - node-version: "16" - cache: "yarn" - - run: yarn setup - - run: yarn build --ignore @argent/web + fetch-depth: 0 - - name: Release npm packages - # if flow is triggered by a tag, publish to npm - if: startsWith(github.ref, 'refs/tags/') - run: | - npm config set "//registry.npmjs.org/:_authToken" "$NPM_ACCESS_TOKEN" - cp Readme.md ./packages/get-starknet/README.md - yarn --cwd packages/get-starknet publish --access public || exit 0 - yarn --cwd packages/sessions publish --access public || exit 0 + - uses: pnpm/action-setup@v2 + name: Install pnpm + id: pnpm-install + with: + version: 8 + run_install: false + + - uses: actions/setup-node@v3 + with: + node-version: "18.x" + cache: "pnpm" + - run: pnpm run setup + - run: pnpm --filter=\!@argent/web build - - run: yarn --cwd packages/dapp export + - run: pnpm --filter @argent-x/dapp export - name: Check bundlesize for chrome - run: yarn run bundlewatch + run: pnpm bundlewatch - name: Create chrome zip run: (cd ./packages/extension/dist && zip -r "../../../${{ env.FILENAME }}-chrome.zip" .) - name: Build Firefox version - run: MANIFEST_VERSION=v2 yarn --cwd packages/extension build + run: MANIFEST_VERSION=v2 pnpm --filter @argent-x/extension build - name: Create firefox zip run: (cd ./packages/extension/dist && zip -r "../../../${{ env.FILENAME }}-firefox.zip" .) - name: Check bundlesize for firefox - run: yarn run bundlewatch + run: pnpm bundlewatch - name: Upload artifacts for chrome uses: actions/upload-artifact@v3 @@ -84,10 +96,6 @@ jobs: retention-days: 14 if-no-files-found: error - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: Get Extension version id: package-version run: | @@ -99,10 +107,11 @@ jobs: ls -l ./packages/extension if [ ! -d "./packages/extension/sourcemaps" ]; then echo "No sourcemaps found" - exit 0 + exit 1 fi - name: Create Sentry release + if: startsWith(github.ref, 'refs/tags/') uses: getsentry/action-release@v1 env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} @@ -110,17 +119,36 @@ jobs: SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} SENTRY_LOG_LEVEL: debug with: - environment: production - sourcemaps: "./packages/extension/sourcemaps" - url_prefix: "~/sourcemaps" + environment: ${{ env.SENTRY_ENVIRONMENT }} + sourcemaps: "./packages/extension/dist ./packages/extension/sourcemaps" + url_prefix: "~/" version: ${{ steps.package-version.outputs.current-version }} ignore_missing: true + # TODO: include all packages + - name: Release npm packages + # if flow is triggered by a tag, publish to npm + if: startsWith(github.ref, 'refs/tags/') + run: | + npm config set "//registry.npmjs.org/:_authToken" "$NPM_ACCESS_TOKEN" + cp Readme.md ./packages/get-starknet/README.md + pnpm --filter @argent/get-starknet publish --no-git-checks --access public || exit 0 + pnpm --filter @argent/web-sdk publish --no-git-checks --access public || exit 0 + pnpm --filter @argent/starknet-react-webwallet-connector publish --no-git-checks --access public || exit 0 + pnpm --filter @argent-x/sessions publish --no-git-checks --access public || exit 0 + + - name: Get product version + id: product-version + run: | + PRODUCT_VERSION=$(cat ./packages/extension/dist/manifest.json | jq -r '.version') + echo "current-version=${PRODUCT_VERSION}" >> $GITHUB_OUTPUT + - name: Release if: startsWith(github.ref, 'refs/tags/') uses: softprops/action-gh-release@v1 with: generate_release_notes: true + title: extension@${{ steps.product-version.outputs.current-version }} files: | ${{ env.FILENAME }}-chrome.zip ${{ env.FILENAME }}-firefox.zip diff --git a/.gitignore b/.gitignore index a64bb2498..50a60fe98 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ Thumbs.db *.sublime-workspace *.log package-lock.json -pnpm-lock.yaml +yarn.lock .eslintcache **/node_modules/ @@ -16,4 +16,8 @@ coverage *.tsbuildinfo license-report.md -**/.next \ No newline at end of file +**/.next + +**/.parcel-cache + +vite.config.ts.timestamp-* \ No newline at end of file diff --git a/.husky/pre-commit b/.husky/pre-commit index 5a182ef10..a5a29d9f7 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,4 @@ #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" -yarn lint-staged +pnpm lint-staged diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..7aa020b91 --- /dev/null +++ b/.npmrc @@ -0,0 +1,6 @@ +ignore-scripts=true +shamefully-hoist=true +shell-emulator=true +prefer-workspace-packages=true +resolution-mode=highest +auto-install-peers=true diff --git a/.nvmrc b/.nvmrc index c818c7b00..67a228a44 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -16.15.0 \ No newline at end of file +18.18.0 \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 88d913bef..96f6a5305 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,5 @@ { + "json.schemaDownload.enable": true, "typescript.tsdk": "node_modules/typescript/lib", "vitest.exclude": [ "**/e2e/**", diff --git a/.yarnrc b/.yarnrc deleted file mode 100644 index 5455c6c5d..000000000 --- a/.yarnrc +++ /dev/null @@ -1 +0,0 @@ -ignore-scripts true diff --git a/.yarnrc.yml b/.yarnrc.yml deleted file mode 100644 index 1e5671cea..000000000 --- a/.yarnrc.yml +++ /dev/null @@ -1 +0,0 @@ -enableScripts: false diff --git a/Contributing.md b/Contributing.md index cd073c7f3..3e12baa76 100644 --- a/Contributing.md +++ b/Contributing.md @@ -10,7 +10,7 @@ _[Use GitHub interface](https://blog.sapegin.me/all/open-source-for-everyone/) f - If it’s your first pull request, watch [this amazing course](http://makeapullrequest.com/) by [Kent C. Dodds](https://twitter.com/kentcdodds). - Fork the repository and clone your fork. -- Setup project: `yarn setup`. +- Setup project: `pnpm run setup`. ## Development workflow @@ -19,10 +19,10 @@ Always start from `develop` branch and merge back to `develop` branch. To build your changes run: ```bash -yarn build +pnpm build ``` -**Please update yarn lock file (`yarn.lock`) if you add or update dependencies.** +**Please update pnpm lock file (`pnpm-lock.yaml`) if you add or update dependencies.** ## Other notes diff --git a/Deployment.md b/Deployment.md index d403f11a5..6770e81a3 100644 --- a/Deployment.md +++ b/Deployment.md @@ -2,18 +2,62 @@ We automated some parts of the release process to make things easier. This file lists the necessary steps to release the latest version of the application: -- Check and ensure the previous release branch `release/vX.Y.Z` was merged into `main` -- Check and ensure `main` was back-merged into `develop` -- Check and ensure you are working in the latest `develop` branch -- Run `yarn run version` - this will: - - update the `version` in each `package.json` and `manifest.json` - - create branch `release/vX.Y.Z` - - create tag `vX.Y.Z` - - push the branch and tag automatically -- Pushing a tag triggers a release build action in GitHub -- Wait for pipeline to create release containing the extension zip -- If the automatic npm publish failed, do it manually (ask Gerald) -- Create GitHub pull request to merge the new branch `release/vX.Y.Z` into `main` -- Create GitHub pull request to back-merge `main` into `develop` -- Edit release to contain a bit more than just the auto generated notes and maybe a proper title -- Submit to Chrome Web Store (ask Ismael) +## Preparation + +- Check and ensure that + - previous release branch `release/next` was merged into `develop` + - the branch `release/next` was deleted + +## Create the next release branch + +- Check and ensure you are working in the latest `develop` branch and that it's up to date with origin +- From `develop` create a new branch `release/next` + - Every release goes from this branch, it's a limitation of [changesets](https://github.com/changesets/changesets) +- This will cause an action to run in GitHub, but you must now also add a changeset + +## Update the extension version + +- If you need to change the version displayed in the extension, create a PR merging into `release/next` to update the `"version": "x.x.x",` inside: + - `packages/extension/manifest/v2.json` + - `packages/extension/manifest/v3.json` + +## Create the release PR + +- Need to have an 'intent to release' +- In your local `release/next` branch run `pnpm changeset` +- Use SPACE to select and ENTER to confirm in the wizard; + - Select the extension package and packages that may show as "changed" + - This can be the case, if an npm package was marked for release before + - Choose a minor version bump + - When prompted Please enter a summary for this change, enter `Release` + - When finished the wizard will create a file in the `.changeset` folder + - Commit and push the changes + - This will cause another action to run in GitHub + - Check the bootstrap release action + - On completion this opens a PR called 'Version Packages' + +## Add more fixes and features to the next release + +- All PR's for the next release should merge into `release/next` until the release is done + +## Release Candidate and QA + +- All QA testing should happen on Release Candidate `release/next` branch +- Merge after QA is happy and RC is ready to be published + +## Make the release + +- Merge 'Version Packages' PR + - This will cause the package version(s) in `release/next` branch to be updated according to the changeset + - This will create a tag + - That will cause the release to be built +- Back-merge `release/next` into develop +- Delete `release/next` branch + +## Make a Hotfix to the last release + +- Create a new `release/next` branch from the last release tag, then follow steps above + +## Submit to store + +- Submit to Chrome Web Store (ask Ismael or Thomas) diff --git a/License.md b/License.md index 3183a706d..40d5de608 100644 --- a/License.md +++ b/License.md @@ -1,245 +1,8 @@ -# GNU General Public License - -_Version 3, 29 June 2007_ -_Copyright © 2007 Free Software Foundation, Inc. <>_ - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and other kinds of works. - -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -## TERMS AND CONDITIONS - -### 0. Definitions - -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on the Program. - -To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that **(1)** displays an appropriate copyright notice, and **(2)** tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - -### 1. Source Code - -The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. - -A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - -The “System Libraries” of an executable work include anything, other than the work as a whole, that **(a)** is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and **(b)** serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions - -All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law - -No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - -### 4. Conveying Verbatim Copies - -You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions - -You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - -- **a)** The work must carry prominent notices stating that you modified it, and giving a relevant date. -- **b)** The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. -- **c)** You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. -- **d)** If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - -### 6. Conveying Non-Source Forms - -You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - -- **a)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. -- **b)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either **(1)** a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or **(2)** access to copy the Corresponding Source from a network server at no charge. -- **c)** Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. -- **d)** Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. -- **e)** Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - -A “User Product” is either **(1)** a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or **(2)** anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - -### 7. Additional Terms - -“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - -- **a)** Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or -- **b)** Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or -- **c)** Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or -- **d)** Limiting the use for publicity purposes of names of licensors or authors of the material; or -- **e)** Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or -- **f)** Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. - -All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - -### 8. Termination - -You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated **(a)** provisionally, unless and until the copyright holder explicitly and finally terminates your license, and **(b)** permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies - -You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - -### 10. Automatic Licensing of Downstream Recipients - -Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - -An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - -### 11. Patents - -A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - -In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either **(1)** cause the Corresponding Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the patent license for this particular work, or **(3)** arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - -A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license **(a)** in connection with copies of the covered work conveyed by you (or copies made from those copies), or **(b)** primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - -### 12. No Surrender of Others' Freedom - -If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - -### 13. Use with the GNU Affero General Public License - -Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. - -### 14. Revised Versions of this License - -The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - -### 15. Disclaimer of Warranty - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -### 16. Limitation of Liability - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16 - -If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - -_END OF TERMS AND CONDITIONS_ - -## How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. - -You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <>. - -The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <>. +All intellectual property rights, interests and titles in the code, application, software and documents (“Works”) are owned by Argent Labs Ltd (“Argent”). You are granted a non-exclusive, non-transferable licence to copy, modify, publish, adapt, and create derivative outputs of the Works (“Generated Works”) solely for non-commercial purposes. Non-commercial purposes means, at the sole discretion of Argent: +* Personal use without any commercial exploitation +* Public educational, public research or charitable use +* Use by any organisation provided that the monthly active users are less than 1000. + +A notice must be present in any Generated Works stating that the Works are owned by Argent and subject to these licence terms. You may not use, process or otherwise interact with the Works in any way not expressly permitted here. + +If you have any questions, please contact us at legal@argent.xyz. diff --git a/Readme.md b/Readme.md index 9f1524b9c..f25ac225a 100644 --- a/Readme.md +++ b/Readme.md @@ -48,7 +48,7 @@ If you want to use this StarkNet Wallet extension with your dapp, the easiest wa ```bash # starknet.js is a peer dependency -yarn add @argent/get-starknet starknet +pnpm add @argent/get-starknet starknet ``` The package is a light wrapper around [starknet.js](https://github.com/0xs34n/starknet.js) to interact with the wallet extension. You can then use it like the following: @@ -86,8 +86,8 @@ Checkout [starknet.js](https://github.com/0xs34n/starknet.js) to learn more abou First clone this repository on your machine then run: ```bash -yarn setup # setup dependencies -yarn build # run build process for all packages +pnpm run setup # setup dependencies +pnpm build # run build process for all packages ``` Now you need to load the locally built chrome extension into your browser, by loading an unpacked extension from path `packages/extension/dist`: @@ -116,8 +116,8 @@ To contribute to this repository please read the [contributing guidelines](Contr To setup the repo on your machine just run: ```bash -yarn setup # setup dependencies -yarn dev # run build process for all packages in watch mode +pnpm run setup # setup dependencies +pnpm dev # run build process for all packages in watch mode ``` This project contains 3 packages: @@ -155,8 +155,8 @@ For convenience this service can be started with [Docker desktop](https://www.do ### Run tests ```bash -yarn test # run unit tests for all packages -yarn test:e2e # run end-to-end tests for all packages +pnpm test # run unit tests for all packages +pnpm test:e2e # run end-to-end tests for all packages ``` ### Tools to help with testing @@ -177,4 +177,4 @@ One more thank you to the StarkWare Team. [Argent](https://github.com/argentlabs) and [contributors](https://github.com/argentlabs/argent-x/graphs/contributors). -GNU General Public License V3, see the included [License.md](License.md) file. +See the included [License.md](License.md) file. diff --git a/docs/tools-for-local-testing.md b/docs/tools-for-local-testing.md index a311caba8..94ed3e456 100644 --- a/docs/tools-for-local-testing.md +++ b/docs/tools-for-local-testing.md @@ -13,7 +13,7 @@ To help test contract upgrades there is a simple script which will declare an up nvm use 18 # start the tool - yarn devnet:upgrade-helper + pnpm devnet:upgrade-helper ``` - Set the contract class hash in Settings → Manage Networks → Localhost → Advanced diff --git a/lerna.json b/lerna.json deleted file mode 100644 index a97799c58..000000000 --- a/lerna.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "packages": ["packages/*"], - "version": "6.3.0", - "npmClient": "yarn", - "useWorkspaces": true -} diff --git a/nx.json b/nx.json deleted file mode 100644 index 95a95c753..000000000 --- a/nx.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "nx/presets/npm.json", - "tasksRunnerOptions": { - "default": { - "runner": "nx/tasks-runners/default", - "options": { - "cacheableOperations": ["build", "lint", "test"], - "parallel": 5 - } - } - } -} diff --git a/package.json b/package.json index 2acfe5c07..17d90ff86 100644 --- a/package.json +++ b/package.json @@ -5,51 +5,46 @@ "repository": "github:argentlabs/argent-x", "homepage": "https://github.com/argentlabs/argent-x/#readme", "devDependencies": { - "@lavamoat/allow-scripts": "^2.3.0", + "@changesets/cli": "^2.26.1", + "@lavamoat/allow-scripts": "^2.3.1", "@lavamoat/preinstall-always-fail": "^1.0.0", "bundlewatch": "^0.3.3", - "husky": "^8.0.0", + "husky": "^8.0.3", "import-sort-style-module": "^6.0.0", - "lerna": "^6.4.1", - "lint-staged": ">=10", - "nx": "^15.6.3", - "patch-package": "^6.4.7", - "prettier": ">=2", + "lint-staged": "^14.0.0", + "nx": "^16.2.2", + "patch-package": "^8.0.0", + "prettier": ">=2.8.8", "prettier-plugin-import-sort": "^0.0.7", - "ts-node": "^10.8.1" - }, - "workspaces": { - "nohoist": [ - "packages/web", - "packages/dapp" - ], - "packages": [ - "packages/*" - ] + "ts-node": "^10.9.1" }, "resolutions": { - "@babel/preset-react": "7.17.12", - "@babel/plugin-transform-react-jsx": "7.17.12" + "@babel/preset-react": "7.22.15", + "@babel/plugin-transform-react-jsx": "7.22.15" }, "scripts": { "format": "prettier --loglevel warn --write \"**/*.{js,jsx,ts,tsx,css,md,yml,json}\"", - "dev": "NODE_ENV=development lerna run dev --parallel", - "dev:ui": "NODE_ENV=development lerna run dev:ui --parallel", - "build-storybook": "lerna run build-storybook --", + "dev": "NODE_ENV=development pnpm run -r --stream --parallel dev", + "dev:ui": "NODE_ENV=development pnpm --parallel run dev:ui ", + "dev:extension": "NODE_ENV=development pnpm run --filter @argent-x/extension -r --stream --parallel dev", + "build-storybook": "pnpm run --filter @argent-x/storybook build-storybook", "clean": "rm -rf packages/extension/dist packages/get-starket/dist", - "build": "lerna run build --stream", - "build:sourcemaps": "GEN_SOURCE_MAPS=true lerna run build", - "lint": "lerna run lint --stream", - "test": "lerna run test --stream", - "test:watch": "lerna run test:watch --stream", - "test:e2e": "yarn workspace @argent-x/e2e run test:e2e", - "setup": "yarn install --frozen-lockfile && yarn allow-scripts && husky install && patch-package && lerna run setup --stream", - "test:ci": "lerna run test:ci --stream --parallel", - "storybook": "cd packages/storybook && yarn storybook", + "build": "pnpm run -r --parallel --stream build", + "build:extension": "pnpm run --filter @argent-x/extension build", + "build:web": "pnpm run --filter @argent/web build", + "build:sourcemaps": "GEN_SOURCE_MAPS=true pnpm run build", + "lint": "pnpm run -r --parallel lint ", + "test": "pnpm run -r --parallel --stream test", + "test:watch": "pnpm run -r --paralle; --stream test:watch ", + "test:e2e:extension": "pnpm run --filter @argent-x/e2e test:extension", + "test:e2e:webwallet": "pnpm run --filter @argent-x/e2e test:webwallet", + "setup": "pnpm install --frozen-lockfile && pnpm allow-scripts && husky install && patch-package && pnpm run -r --stream setup", + "test:ci": "pnpm run --stream --parallel test:ci ", + "storybook": "cd packages/storybook && pnpm run storybook", "devnet:upgrade-helper": "NODE_NO_WARNINGS=1 ts-node ./scripts/devnet-upgrade-helper.ts", "devnet:setup-contracts": "NODE_NO_WARNINGS=1 ts-node ./scripts/devnet-setup-contracts.ts", - "version": "lerna version --no-push --no-git-tag-version && yarn --cwd packages/extension run version", - "export": "lerna run export --scope=@argent/web" + "export": "pnpm run --filter=@argent/web export", + "export:extension": "pnpm run --filter @argent-x/extension export" }, "importSort": { ".js, .jsx, .ts, .tsx": { @@ -77,7 +72,10 @@ "@lavamoat/preinstall-always-fail": false, "nx": false, "nx>@parcel/watcher": false, - "nx>@swc/core": false + "nx>@swc/core": false, + "lerna>@nrwl/devkit>nx": false, + "lerna>nx": false, + "lerna>nx>@nrwl/cli>nx": false } } } diff --git a/packages/dapp/.gitignore b/packages/dapp/.gitignore index 88b6f0d98..1947ee109 100644 --- a/packages/dapp/.gitignore +++ b/packages/dapp/.gitignore @@ -21,8 +21,8 @@ # debug npm-debug.log* -yarn-debug.log* -yarn-error.log* +pnpm-debug.log* +pnpm-error.log* # local env files .env.local diff --git a/packages/dapp/.vscode/settings.json b/packages/dapp/.vscode/settings.json new file mode 100644 index 000000000..cc43ff1bb --- /dev/null +++ b/packages/dapp/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "json.schemaDownload.enable": true, + "typescript.tsdk": "../../node_modules/typescript/lib" +} diff --git a/packages/dapp/README.md b/packages/dapp/README.md index c87e0421d..59408a4a2 100644 --- a/packages/dapp/README.md +++ b/packages/dapp/README.md @@ -7,7 +7,7 @@ First, run the development server: ```bash npm run dev # or -yarn dev +pnpm dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. diff --git a/packages/dapp/package.json b/packages/dapp/package.json index 942cbabba..8dddfe69c 100644 --- a/packages/dapp/package.json +++ b/packages/dapp/package.json @@ -1,6 +1,6 @@ { "name": "@argent-x/dapp", - "version": "6.3.0", + "version": "6.3.2", "private": true, "scripts": { "dev": "next dev", @@ -10,21 +10,22 @@ "lint": "next lint" }, "dependencies": { - "@argent/get-starknet": "^6.3.0", - "@argent/x-sessions": "^6.3.0", + "@argent/shared": "^6.3.1", + "@argent/get-starknet": "^6.3.1", + "@argent/x-sessions": "^6.3.1", "ethers": "^5.5.1", - "next": "^13.0.0", + "next": "^13.4.6", "react": "^18.0.0", "react-dom": "^18.0.0", - "starknet": "^4.21.0", - "starknet5": "npm:starknet@5.0.0-beta.3" + "starknet": "5.18.0", + "micro-starknet": "^0.2.3" }, "devDependencies": { - "@types/node": "18.15.12", + "@types/node": "20.6.5", "@types/react": "^18.0.0", "@types/react-dom": "^18.0.0", "eslint": "8", - "eslint-config-next": "13.2.3", - "typescript": "^4.9.4" + "eslint-config-next": "13.5.3", + "typescript": "^5.0.4" } } diff --git a/packages/dapp/src/components/TokenDapp.tsx b/packages/dapp/src/components/TokenDapp.tsx index 4b44daed0..501f52d54 100644 --- a/packages/dapp/src/components/TokenDapp.tsx +++ b/packages/dapp/src/components/TokenDapp.tsx @@ -1,7 +1,17 @@ import { SessionAccount, createSession } from "@argent/x-sessions" -import { FC, useEffect, useState } from "react" -import { Abi, AccountInterface, Contract, ec } from "starknet" -import { hash } from "starknet5" +import { FC, useEffect, useMemo, useState } from "react" +import { + Abi, + AccountInterface, + Contract, + stark, + hash, + GatewayError, + isSierra, + CompiledSierraCasm, + DeclareContractPayload, + UniversalDeployerContractPayload, +} from "starknet" import Erc20Abi from "../../abi/ERC20.json" import { truncateAddress, truncateHex } from "../services/address.service" @@ -16,30 +26,17 @@ import { addNetwork, addToken, declare, + deploy, signMessage, waitForTransaction, + declareAndDeploy, } from "../services/wallet.service" import styles from "../styles/Home.module.css" - -const { genKeyPair, getStarkKey } = ec +import { getStarkKey, utils } from "micro-starknet" +import { readFileAsString } from "@argent/shared" type Status = "idle" | "approve" | "pending" | "success" | "failure" -const readFileAsString = (file: File): Promise => { - return new Promise((resolve, reject) => { - const reader = new FileReader() - reader.onload = () => { - if (reader.result) { - return resolve(reader.result?.toString()) - } - return reject(new Error("Could not read file")) - } - reader.onerror = reject - reader.onabort = reject.bind(null, new Error("User aborted")) - reader.readAsText(file) - }) -} - export const TokenDapp: FC<{ showSession: null | boolean account: AccountInterface @@ -54,10 +51,13 @@ export const TokenDapp: FC<{ const [transactionError, setTransactionError] = useState("") const [addTokenError, setAddTokenError] = useState("") const [classHash, setClassHash] = useState("") - const [contract, setContract] = useState() + const [contract, setContract] = useState(null) + const [casm, setCasm] = useState(null) + const [shouldDeploy, setShouldDeploy] = useState(false) + const [deployClassHash, setDeployClassHash] = useState("") const [addNetworkError, setAddNetworkError] = useState("") - const [sessionSigner] = useState(genKeyPair()) + const [sessionSigner] = useState(utils.randomPrivateKey()) const [sessionAccount, setSessionAccount] = useState< SessionAccount | undefined >() @@ -71,11 +71,11 @@ export const TokenDapp: FC<{ try { await waitForTransaction(lastTransactionHash) setTransactionStatus("success") - } catch (error: any) { + } catch (error) { setTransactionStatus("failure") let message = error ? `${error}` : "No further details" - if (error?.response) { - message = JSON.stringify(error.response, null, 2) + if (error instanceof GatewayError) { + message = JSON.stringify(error.message, null, 2) } setTransactionError(message) } @@ -139,7 +139,7 @@ export const TokenDapp: FC<{ const result = await signMessage(shortText) console.log(result) - setLastSig(result) + setLastSig(stark.formatSignature(result)) setTransactionStatus("success") } catch (e) { console.error(e) @@ -208,9 +208,45 @@ export const TokenDapp: FC<{ if (!classHash) { throw new Error("No class hash") } - const result = await declare(contract, classHash) - console.log(result) + const payload: DeclareContractPayload = { + contract, + classHash, + } + if (casm) { + payload.casm = casm + delete payload.classHash + } + if (shouldDeploy) { + const result = await declareAndDeploy(payload) + console.log(result) + setLastTransactionHash(result.deploy.transaction_hash) + } else { + const result = await declare(payload) + console.log(result) + setLastTransactionHash(result.transaction_hash) + } + setTransactionStatus("pending") + } catch (e) { + console.error(e) + setTransactionStatus("idle") + } + } + const contractIsSierra = useMemo(() => { + return contract && isSierra(contract) + }, [contract]) + + const handleDeploy = async (e: React.FormEvent) => { + try { + e.preventDefault() + if (!deployClassHash) { + throw new Error("No class hash") + } + const payload: UniversalDeployerContractPayload = { + classHash: deployClassHash, + } + const result = await deploy(payload) + console.log(result) setLastTransactionHash(result.transaction_hash) setTransactionStatus("pending") } catch (e) { @@ -367,7 +403,7 @@ export const TokenDapp: FC<{
-

Declare

+

Declare (and deploy)

{ - if (e.target.files) { - const file = e.target.files[0] - const fileAsString = await readFileAsString(file) - setContract(fileAsString) - - const classHash = hash.computeContractClassHash(fileAsString) - setClassHash(classHash) + if (!e.target.files) { + return } + setCasm(null) + + const file = e.target.files[0] + const fileAsString = await readFileAsString(file) + setContract(fileAsString) + + const classHash = hash.computeContractClassHash(fileAsString) + setClassHash(classHash) }} /> - + + + {contractIsSierra && ( + <> + + { + if (!e.target.files) { + return + } + const file = e.target.files[0] + const fileAsString = await readFileAsString(file) + const fileAsJson = JSON.parse(fileAsString) + setCasm(fileAsJson) + }} + /> + + )} + + setShouldDeploy(!shouldDeploy)} + /> + + + +
+
+

Deploy

+ + + { - setClassHash(e.target.value) + setDeployClassHash(e.target.value) }} - value={classHash} + value={deployClassHash} /> - +
@@ -422,8 +512,8 @@ export const TokenDapp: FC<{ try { await addToken(ETHTokenAddress) setAddTokenError("") - } catch (error: any) { - setAddTokenError(error.message) + } catch (error) { + setAddTokenError((error as any).message) } }} > @@ -437,8 +527,8 @@ export const TokenDapp: FC<{ try { await addToken(DAITokenAddress) setAddTokenError("") - } catch (error: any) { - setAddTokenError(error.message) + } catch (error) { + setAddTokenError((error as any).message) } }} > @@ -454,8 +544,8 @@ export const TokenDapp: FC<{ try { await handleAddNetwork() setAddNetworkError("") - } catch (error: any) { - setAddNetworkError(error.message) + } catch (error) { + setAddNetworkError((error as any).message) } }} > diff --git a/packages/dapp/src/pages/index.tsx b/packages/dapp/src/pages/index.tsx index 5e600d412..0fb272ae1 100644 --- a/packages/dapp/src/pages/index.tsx +++ b/packages/dapp/src/pages/index.tsx @@ -9,7 +9,7 @@ import { TokenDapp } from "../components/TokenDapp" import { truncateAddress } from "../services/address.service" import { addWalletChangeListener, - chainId, + getChainId, connectWallet, removeWalletChangeListener, silentConnectWallet, @@ -27,7 +27,8 @@ const Home: NextPage = () => { const handler = async () => { const wallet = await silentConnectWallet() setAddress(wallet?.selectedAddress) - setChain(chainId(wallet?.provider as any)) + const chainId = await getChainId(wallet?.provider as any) + setChain(chainId) setConnected(!!wallet?.isConnected) if (wallet?.account) { setAccount(wallet.account as any) @@ -66,7 +67,8 @@ const Home: NextPage = () => { async () => { const wallet = await connectWallet(enableWebWallet) setAddress(wallet?.selectedAddress) - setChain(chainId(wallet?.provider as any)) + const chainId = await getChainId(wallet?.provider as any) + setChain(chainId) setConnected(!!wallet?.isConnected) if (wallet?.account) { setAccount(wallet.account as any) diff --git a/packages/dapp/src/services/token.service.ts b/packages/dapp/src/services/token.service.ts index 80e25b6b0..a46ffcffb 100644 --- a/packages/dapp/src/services/token.service.ts +++ b/packages/dapp/src/services/token.service.ts @@ -1,6 +1,5 @@ -import { connect } from "@argent/get-starknet" -import { utils } from "ethers" -import { Abi, Contract, number, uint256 } from "starknet" +import { bigDecimal } from "@argent/shared" +import { Abi, Contract, num, uint256 } from "starknet" import Erc20Abi from "../../abi/ERC20.json" import { windowStarknet } from "./wallet.service" @@ -11,15 +10,15 @@ export const ETHTokenAddress = export const DAITokenAddress = "0x00da114221cb83fa859dbdb4c44beeaa0bb37c7537ad5ae66fe5e0efd20e6eb3" -function getUint256CalldataFromBN(bn: number.BigNumberish) { - return { type: "struct" as const, ...uint256.bnToUint256(bn) } +function getUint256CalldataFromBN(bn: num.BigNumberish) { + return uint256.bnToUint256(bn) } export function parseInputAmountToUint256( input: string, decimals: number = 18, ) { - return getUint256CalldataFromBN(utils.parseUnits(input, decimals).toString()) + return getUint256CalldataFromBN(bigDecimal.parseUnits(input, decimals)) } export const mintToken = async (mintAmount: string): Promise => { diff --git a/packages/dapp/src/services/wallet.service.ts b/packages/dapp/src/services/wallet.service.ts index 2b2322bda..245a5ef93 100644 --- a/packages/dapp/src/services/wallet.service.ts +++ b/packages/dapp/src/services/wallet.service.ts @@ -1,21 +1,44 @@ import { StarknetWindowObject, connect } from "@argent/get-starknet" import type { AddStarknetChainParameters } from "get-starknet-core" -import { ProviderInterface, shortString } from "starknet" +import { + AccountInterface, + DeclareContractPayload, + InvocationsDetails, + ProviderInterface, + UniversalDeployerContractPayload, + shortString, +} from "starknet" -export let windowStarknet: StarknetWindowObject | null = null +export type StarknetWindowObjectV5 = StarknetWindowObject & { + account: AccountInterface +} + +export let windowStarknet: StarknetWindowObjectV5 | null = null + +export const starknetVersion = "v5" export const silentConnectWallet = async () => { - const _windowStarknet = await connect({ modalMode: "neverAsk" }) - windowStarknet = _windowStarknet + const _windowStarknet = await connect({ + modalMode: "neverAsk", + }) + // comment this when using webwallet -- enable is already done by @argent/get-starknet and webwallet is currently using only v4 + // to remove when @argent/get-starknet will support both v4 and v5 + //await _windowStarknet?.enable({ starknetVersion }) + windowStarknet = _windowStarknet as StarknetWindowObjectV5 | null return windowStarknet ?? undefined } export const connectWallet = async (enableWebWallet: boolean) => { const _windowStarknet = await connect({ exclude: enableWebWallet ? [] : ["argentWebWallet"], - modalWalletAppearance: "email_first", + modalWalletAppearance: "all", + enableArgentMobile: true, }) - windowStarknet = _windowStarknet + + // comment this when using webwallet -- enable is already done by @argent/get-starknet and webwallet is currently using only v4 + // to remove when @argent/get-starknet will support both v4 and v5 + //await _windowStarknet?.enable({ starknetVersion }) + windowStarknet = _windowStarknet as StarknetWindowObjectV5 | null return windowStarknet ?? undefined } @@ -41,12 +64,15 @@ export const addToken = async (address: string): Promise => { }) } -export const chainId = (provider?: ProviderInterface): string | undefined => { +export const getChainId = async ( + provider?: ProviderInterface, +): Promise => { try { if (!provider) { throw Error("no provider") } - return shortString.decodeShortString(provider.chainId) + const chainId = await provider.getChainId() + return shortString.decodeShortString(chainId) } catch {} } @@ -102,15 +128,37 @@ export const removeWalletChangeListener = async ( windowStarknet.off("accountsChanged", handleEvent) } -export const declare = async (contract: string, classHash: string) => { +export const declare = async ( + payload: DeclareContractPayload, + transactionsDetail?: InvocationsDetails, +) => { if (!windowStarknet?.isConnected) { throw Error("starknet wallet not connected") } - return windowStarknet.account.declare({ - contract, - classHash, - }) + return windowStarknet.account.declare(payload, transactionsDetail) +} + +export const deploy = async ( + payload: UniversalDeployerContractPayload, + details?: InvocationsDetails, +) => { + if (!windowStarknet?.isConnected) { + throw Error("starknet wallet not connected") + } + + return windowStarknet.account.deploy(payload, details) +} + +export const declareAndDeploy = async ( + payload: DeclareContractPayload, + transactionsDetail?: InvocationsDetails, +) => { + if (!windowStarknet?.isConnected) { + throw Error("starknet wallet not connected") + } + + return windowStarknet.account.declareAndDeploy(payload, transactionsDetail) } export const addNetwork = async (params: AddStarknetChainParameters) => { diff --git a/packages/dapp/tsconfig.json b/packages/dapp/tsconfig.json index d3b45b03d..93514bc17 100644 --- a/packages/dapp/tsconfig.json +++ b/packages/dapp/tsconfig.json @@ -8,8 +8,8 @@ "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "node", + "module": "ESNext", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", diff --git a/packages/e2e/.env.example b/packages/e2e/.env.example new file mode 100644 index 000000000..33e7af73b --- /dev/null +++ b/packages/e2e/.env.example @@ -0,0 +1,4 @@ +ARGENT_X_ENVIRONMENT= +TESTNET_SEED1= +TESTNET_SEED2= +TESTNET_SEED3= \ No newline at end of file diff --git a/packages/e2e/.vscode/settings.json b/packages/e2e/.vscode/settings.json new file mode 100644 index 000000000..cc43ff1bb --- /dev/null +++ b/packages/e2e/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "json.schemaDownload.enable": true, + "typescript.tsdk": "../../node_modules/typescript/lib" +} diff --git a/packages/e2e/Dockerfile b/packages/e2e/Dockerfile index a98e4c6e4..5498d0ab8 100644 --- a/packages/e2e/Dockerfile +++ b/packages/e2e/Dockerfile @@ -1,8 +1,6 @@ - -FROM shardlabs/starknet-devnet:0.4.6 +FROM shardlabs/starknet-devnet:0.6.3 RUN addgroup -S localuser \ && adduser -S localuser -G localuser - USER localuser -COPY ./packages/extension/e2e/network-setup /network-setup -ENTRYPOINT [ "starknet-devnet", "--host", "0.0.0.0", "--port", "5050", "--seed", "0", "--lite-mode", "--load-path", "/network-setup/dump.pkl" ] \ No newline at end of file +COPY ./packages/e2e/extension/network-setup /network-setup +ENTRYPOINT [ "starknet-devnet", "--host", "0.0.0.0", "--port", "5050", "--seed", "0", "--lite-mode" ] \ No newline at end of file diff --git a/packages/e2e/extension/network-setup/Dockerfile b/packages/e2e/extension/network-setup/Dockerfile index db57732eb..728e9bee5 100644 --- a/packages/e2e/extension/network-setup/Dockerfile +++ b/packages/e2e/extension/network-setup/Dockerfile @@ -1,9 +1,9 @@ -FROM shardlabs/starknet-devnet:0.4.6 +FROM shardlabs/starknet-devnet:0.6.3 RUN addgroup -S localuser \ && adduser -S localuser -G localuser USER localuser COPY ./dump.pkl ./dump.pkl -ENTRYPOINT [ "starknet-devnet", "--host", "0.0.0.0", "--port", "5050", "--seed", "0", "--lite-mode", "--load-path", "./dump.pkl" ] \ No newline at end of file +ENTRYPOINT [ "starknet-devnet", "--host", "0.0.0.0", "--port", "5050", "--seed", "0", "--lite-mode" ] \ No newline at end of file diff --git a/packages/e2e/extension/playwright.config.ts b/packages/e2e/extension/playwright.config.ts new file mode 100644 index 000000000..360c9bb54 --- /dev/null +++ b/packages/e2e/extension/playwright.config.ts @@ -0,0 +1,35 @@ +import type { PlaywrightTestConfig } from "@playwright/test" +import config from "./src/config" + +const isCI = Boolean(process.env.CI) + +const playwrightConfig: PlaywrightTestConfig = { + projects: [ + { + name: "ArgentX", + use: { + trace: "on-first-retry", + viewport: { width: 360, height: 600 }, + actionTimeout: 60 * 1000, // 1 minute + permissions: ["clipboard-read", "clipboard-write"], + }, + timeout: 5 * 60e3, // 5 minutes + expect: { timeout: 30 * 1000 }, // 30 seconds + testDir: "./src/specs", + testMatch: /\.spec.ts$/, + retries: isCI ? 1 : 0, + outputDir: config.artifactsDir, + }, + ], + workers: 1, + reportSlowTests: { + threshold: 1 * 60e3, // 1 minute + max: 5, + }, + reporter: isCI ? [["github"], ["blob"]] : "list", + forbidOnly: isCI, + outputDir: config.artifactsDir, + preserveOutput: isCI ? "failures-only" : "never", +} + +export default playwrightConfig diff --git a/packages/e2e/extension/src/config.ts b/packages/e2e/extension/src/config.ts index 313bb9730..45e6b3cf1 100644 --- a/packages/e2e/extension/src/config.ts +++ b/packages/e2e/extension/src/config.ts @@ -5,30 +5,15 @@ export default { artifactsDir: path.resolve(__dirname, "../../artifacts/playwright"), reportsDir: path.resolve(__dirname, "../../artifacts/reports"), distDir: path.join(__dirname, "../../../extension/dist/"), - - wallets: [ - { - // NOTE: Seed phrase is here intentionally and is used only for local testing. DO NOT use for any other purpose - seed: "dove luxury shield hill chronic radio used barely rifle brick author bounce", - accounts: [ - // 0.9992 ETH, deployed - "0x0027A5C4b2Fe3D2F2623A9B9d91b73b53fBefba45087e572C22A27005a602B74", - // 2 ETH, not deployed - "0x03eC198B36781Bbb352ffa55c3E3b48F74C469da3495b6Bc211D87d61B9fDF7b", - ], - }, - { - // NOTE: Seed phrase is here intentionally and is used only for local testing. DO NOT use for any other purpose - seed: "muffin abandon fancy enhance neglect fit team biology loyal traffic ocean wash", - accounts: [ - // 1 ETH, not deployed - "0x035508Aaf6C124D348686F31ca9981568F0c0d29b563a2Ecb045aA8C81334057", - ], - }, - { - // NOTE: Seed phrase is here intentionally and is used only for local testing. DO NOT use for any other purpose - seed: "slam water student cotton chalk okay auto police frown smart vague salon", - // 32 accounts - }, - ], + testNetSeed1: process.env.E2E_TESTNET_SEED1, //wallet with 32 deployed accounts + testNetSeed2: process.env.E2E_TESTNET_SEED2, //wallet with 1 deployed account + testNetSeed3: process.env.E2E_TESTNET_SEED3, //wallet with 1 deployed account + destinationAddress: process.env.E2E_SENDER_ADDRESS, //used as transfers destination + senderAddr: process.env.E2E_SENDER_ADDRESS, + senderSeed: process.env.E2E_SENDER_SEED, + senderKey: process.env.E2E_SENDER_PRIVATEKEY, + account1Seed2: process.env.E2E_ACCOUNT_1_SEED2, + account1Seed3: process.env.E2E_ACCOUNT_1_SEED3, + starknetTestNetUrl: process.env.STARKNET_TESTNET_URL, + starkscanTestNetUrl: process.env.STARKSCAN_TESTNET_URL, } diff --git a/packages/e2e/extension/src/fixtures.ts b/packages/e2e/extension/src/fixtures.ts index 3b8f07e6b..721a9cea3 100644 --- a/packages/e2e/extension/src/fixtures.ts +++ b/packages/e2e/extension/src/fixtures.ts @@ -1,6 +1,9 @@ +import { ChromiumBrowserContext } from "@playwright/test" + import type ExtensionPage from "./page-objects/ExtensionPage" export interface TestExtensions { extension: ExtensionPage secondExtension: ExtensionPage + browserContext: ChromiumBrowserContext } diff --git a/packages/e2e/extension/src/languages/ILanguage.ts b/packages/e2e/extension/src/languages/ILanguage.ts index 780d66051..21f21beb4 100644 --- a/packages/e2e/extension/src/languages/ILanguage.ts +++ b/packages/e2e/extension/src/languages/ILanguage.ts @@ -17,6 +17,7 @@ export interface ILanguage { create: string cancel: string privacyStatement: string + reviewSend: string } account: { noAccounts: string @@ -31,6 +32,9 @@ export interface ILanguage { pendingTransactions: string recipientAddress: string saveAddress: string + confirmTheSeedPhrase: string + showAccountRecovery: string + wrongPassword: string } wallet: { //first screen @@ -70,6 +74,12 @@ export interface ILanguage { hiddenAccounts: string delete: string copy: string + copied: string + confirmRecovery: string + revealSeedPhrase: string + beforeYouContinue: string + seedWarning: string + deployAccount: string } developerSettings: { manageNetworks: string @@ -83,5 +93,11 @@ export interface ILanguage { addressRequired: string removeAddress: string delete: string + addressBook: string + } + dapps: { + connect: string + reject: string + resetAll: string } } diff --git a/packages/e2e/extension/src/languages/en/index.ts b/packages/e2e/extension/src/languages/en/index.ts index 8afb708eb..8bae6b2ef 100644 --- a/packages/e2e/extension/src/languages/en/index.ts +++ b/packages/e2e/extension/src/languages/en/index.ts @@ -18,20 +18,25 @@ const texts = { cancel: "Cancel", privacyStatement: "GDPR statement for browser extension wallet: Argent takes the privacy and security of individuals very seriously and takes every reasonable measure and precaution to protect and secure the personal data that we process. The browser extension wallet does not collect any personal information nor does it correlate any of your personal information with anonymous data processed as part of its services. On top of this Argent has robust information security policies and procedures in place to make sure any processing complies with applicable laws. If you would like to know more or have any questions then please visit our website at https://www.argent.xyz/", + reviewSend: "Review send", }, account: { noAccounts: "You have no accounts on ", createAccount: "Create account", addFunds: "Add funds", - fundsFromStarkNet: "From another StarkNet account", + fundsFromStarkNet: "From another Starknet wallet", fullAccountAddress: "Full account address", send: "Send", export: "Export", - accountRecovery: "Set up account recovery", + accountRecovery: "Save your recovery phrase", + showAccountRecovery: "Show recovery phrase", saveTheRecoveryPhrase: "Save the recovery phrase", + confirmTheSeedPhrase: + "I have saved my recovery phrase and understand I should never share it with anyone else", pendingTransactions: "Pending transactions", recipientAddress: "Recipient's address", saveAddress: "Save address", + wrongPassword: "Incorrect password", }, wallet: { //first screen @@ -44,7 +49,7 @@ const texts = { desc2: "StarkNet is in Alpha and may experience technical issues or introduce breaking changes from time to time. Please accept this before continuing.", lossOfFunds: - "I understand that StarkNet may introduce changes that make my existing account unusable and force to create new ones.", + "I understand that StarkNet will introduce changes (e.g. Cairo 1.0) that will affect my existing account(s) (e.g. rendering unusable) if I do not complete account upgrades.", alphaVersion: "I understand that StarkNet may experience performance issues and my transactions may fail for various reasons.", //third screen @@ -63,7 +68,7 @@ const texts = { settings: { addresBook: "Address book", connectedDapps: "Connected dapps", - showRecoveryPhase: "Show recovery phrase", + showRecoveryPhase: "Recovery phrase", developerSettings: "Developer settings", privacy: "Privacy", hideAccount: "Hide account", @@ -74,6 +79,14 @@ const texts = { hiddenAccounts: "Hidden accounts", delete: "Delete", copy: "Copy", + copied: "Copied", + confirmRecovery: + "I have saved my recovery phrase and understand I should never share it with anyone else", + revealSeedPhrase: "Click to reveal recovery phrase", + beforeYouContinue: "Before you continue...", + seedWarning: + "Please save your recovery phrase. This is the only way you will be able to recover your Argent X accounts", + deployAccount: "Deploy account", }, developerSettings: { manageNetworks: "Manage networks", @@ -87,6 +100,12 @@ const texts = { addressRequired: "Address is required", removeAddress: "Remove from address book", delete: "Delete", + addressBook: "Address book", + }, + dapps: { + connect: "Connect", + reject: "Reject", + resetAll: "Reset all dapp connections", }, } diff --git a/packages/e2e/extension/src/page-objects/Account.ts b/packages/e2e/extension/src/page-objects/Account.ts index 54d7062d1..711ddd7a1 100644 --- a/packages/e2e/extension/src/page-objects/Account.ts +++ b/packages/e2e/extension/src/page-objects/Account.ts @@ -14,6 +14,9 @@ export default class Account extends Navigation { constructor(page: Page) { super(page) } + accountName1 = "Account 1" + accountName2 = "Account 2" + get noAccountBanner() { return this.page.locator(`div h5:text-is("${lang.account.noAccounts}")`) } @@ -36,10 +39,20 @@ export default class Account extends Navigation { ) } + get accountAddressFromAssetsView() { + return this.page.locator('[data-testid="account-tokens"] button').first() + } + get send() { return this.page.locator(`button:text-is("${lang.account.send}")`) } + get deployAccount() { + return this.page.locator( + `button :text-is("${lang.settings.deployAccount}")`, + ) + } + token(tkn: TokenName) { return this.page.locator(`button :text-is('${tkn}')`) } @@ -65,11 +78,11 @@ export default class Account extends Navigation { } get sendMax() { - return this.page.locator('button:text-is("MAX")') + return this.page.locator('button:text-is("Max")') } - get recepientAddress() { - return this.page.locator('[name="recipient"]') + get recipientAddressQuery() { + return this.page.locator('[name="query"]') } account(accountName: string) { @@ -80,14 +93,33 @@ export default class Account extends Navigation { return this.page.locator('[data-testid="tokenBalance"]') } - currentBalance(tkn: "ETH") { - return this.page.locator(` //button//h6[contains(text(), '${tkn}')]`) + currentBalance(tkn: "Ethereum") { + return this.page.locator( + ` //button//h6[contains(text(), '${tkn}')]/following::p`, + ) + } + + currentBalanceDevNet(tkn: "ETH") { + return this.page.locator(`//button//h6[contains(text(), '${tkn}')]`) } get accountName() { return this.page.locator('[data-testid="account-tokens"] h2') } + async addAccountMainnet({ firstAccount = true }: { firstAccount?: boolean }) { + if (firstAccount) { + await this.createAccount.click() + } else { + await this.accountListSelector.click() + await this.addANewccountFromAccountList.click() + } + await this.addStandardAccountFromNewAccountScreen.click() + + await this.account("").last().click() + await expect(this.accountListSelector).toBeVisible() + } + async addAccount({ firstAccount = true }: { firstAccount?: boolean }) { if (firstAccount) { await this.createAccount.click() @@ -119,7 +151,7 @@ export default class Account extends Navigation { if (currentAccount != accountName) { await this.selectAccount(accountName) } - await expect(this.accountName).toHaveText(accountName) + await expect(this.accountListSelector).toHaveText(accountName) } async assets(accountName: string) { @@ -136,12 +168,14 @@ export default class Account extends Navigation { } return assetsList } - - async ensureAsset(accountName: string, name: "ETH", value: string) { + ////*[text() = 'Ethereum']/following-sibling::div + async ensureAsset(accountName: string, name: "Ethereum", value: string) { await this.ensureSelectedAccount(accountName) await expect( - this.page.locator(`button :text("${value} ${name}")`), - ).toBeVisible() + this.page.locator( + `//*[text() = '${name}']/following-sibling::div/p[text() = '${value}']`, + ), + ).toBeVisible({ timeout: 90000 }) } async getTotalFeeValue() { @@ -157,27 +191,40 @@ export default class Account extends Navigation { } async transfer({ originAccountName, - recepientAddress, + recipientAddress, tokenName, amount, + fillRecipientAddress = "paste", + submit = true, }: { originAccountName: string - recepientAddress: string + recipientAddress: string tokenName: TokenName amount: number | "MAX" + fillRecipientAddress?: "typing" | "paste" + submit?: boolean }) { await this.ensureSelectedAccount(originAccountName) await this.token(tokenName).click() - await this.send.last().click() + fillRecipientAddress === "paste" + ? await this.recipientAddressQuery.fill(recipientAddress) + : await this.recipientAddressQuery.type(recipientAddress) + if (recipientAddress.endsWith("stark")) { + await this.page.click(`button:has-text("${recipientAddress}")`) + } else { + await this.recipientAddressQuery.focus() + await this.page.keyboard.press("Enter") + } if (amount === "MAX") { + await expect(this.balance).toBeVisible() + await expect(this.sendMax).toBeVisible() await this.sendMax.click() } else { await this.amount.fill(amount.toString()) } - await this.recepientAddress.fill(recepientAddress) - await this.next.click() - await this.approve.click() + await this.reviewSend.click() + submit ?? (await this.approve.click()) } async ensureTokenBalance({ @@ -207,7 +254,19 @@ export default class Account extends Navigation { get setUpAccountRecovery() { return this.page.locator( - `button :text-is("${lang.account.accountRecovery}")`, + `button:text-is("${lang.account.accountRecovery}")`, + ) + } + + get showAccountRecovery() { + return this.page.locator( + `button:text-is("${lang.account.showAccountRecovery}")`, + ) + } + + get confirmTheSeedPhrase() { + return this.page.locator( + `p:text-is("${lang.account.confirmTheSeedPhrase}")`, ) } @@ -228,8 +287,12 @@ export default class Account extends Navigation { return this.page.locator(`button:text-is("${lang.account.saveAddress}")`) } - get contact() { - return this.page.locator("div h5") + get copyAddress() { + return this.page.locator('[data-testid="account-tokens"] button').first() + } + + contact(label: string) { + return this.page.locator(`div h6:text-is("${label}")`) } get dappsBanner() { @@ -239,4 +302,49 @@ export default class Account extends Navigation { get dappsBannerClose() { return this.page.locator('[title="Dappland"] svg') } + + async saveRecoveryPhrase() { + const nextModal = await this.next.isVisible({ timeout: 60 }) + if (nextModal) { + await Promise.all([ + expect( + this.page.locator( + `h3:has-text("${lang.settings.beforeYouContinue}")`, + ), + ).toBeVisible(), + expect( + this.page.locator(`p:has-text("${lang.settings.seedWarning}")`), + ).toBeVisible(), + ]) + await this.next.click() + } + await this.page + .locator(`span:has-text("${lang.settings.revealSeedPhrase}")`) + .click() + const pos = Array.from({ length: 12 }, (_, i) => i + 1) + const seed = await Promise.all( + pos.map(async (index) => { + return this.page + .locator(`//*[normalize-space() = '${index}']/parent::*`) + .textContent() + .then((text) => text?.replace(/[0-9]/g, "")) + }), + ).then((result) => result.join(" ")) + + await Promise.all([ + this.page.locator(`button:has-text("${lang.settings.copy}")`).click(), + expect( + this.page.locator(`button:has-text("${lang.settings.copied}")`), + ).toBeVisible(), + ]) + await this.page + .locator(`p:has-text("${lang.settings.confirmRecovery}")`) + .click() + await this.done.click() + const seedPhraseCopied = await this.page.evaluate( + `navigator.clipboard.readText();`, + ) + expect(seed).toBe(seedPhraseCopied) + return seedPhraseCopied + } } diff --git a/packages/e2e/extension/src/page-objects/Activity.ts b/packages/e2e/extension/src/page-objects/Activity.ts index 9160360f5..978590eaa 100644 --- a/packages/e2e/extension/src/page-objects/Activity.ts +++ b/packages/e2e/extension/src/page-objects/Activity.ts @@ -24,7 +24,7 @@ export default class Activity extends Navigation { checkActivity(nbr: number) { return Promise.all([ - this.menuPendingTransationsIndicator.click(), + this.menuPendingTransactionsIndicator.click(), this.ensurePendingTransactions(nbr), ]) } diff --git a/packages/e2e/extension/src/page-objects/AddressBook.ts b/packages/e2e/extension/src/page-objects/AddressBook.ts index 96074f5a3..999968ad8 100644 --- a/packages/e2e/extension/src/page-objects/AddressBook.ts +++ b/packages/e2e/extension/src/page-objects/AddressBook.ts @@ -32,33 +32,39 @@ export default class AddressBook extends Navigation { return this.page.locator(`button:text-is("${lang.common.cancel}")`) } - networkOption(name: "Localhost 5050" | "Testnet" | "Testnet 2" | "Mainnet") { - return this.page.locator(`div[aria-disabled="false"]:text-is("${name}")`) + networkOption(name: "Localhost 5050" | "Testnet" | "Mainnet") { + return this.page.locator(`button[role="menuitem"]:text-is("${name}")`) } get nameRequired() { return this.page.locator( - `//input[@name="name"]/following::p[contains(text(), '${lang.address.nameRequired}')]`, + `//input[@name="name"]/following::label[contains(text(), '${lang.address.nameRequired}')]`, ) } get addressRequired() { return this.page.locator( - `//textarea[@name="address"]/following::p[contains(text(), '${lang.address.addressRequired}')]`, + `//textarea[@name="address"]/following::label[contains(text(), '${lang.address.addressRequired}')]`, ) } - addressByname(name: string) { + addressByName(name: string) { return this.page.locator( `//button/following::*[contains(text(),'${name}')]`, ) } get deleteAddress() { - return this.page.locator(`button:text-is("${lang.address.removeAddress}")`) + return this.page.locator( + `button[aria-label="${lang.address.removeAddress}"]`, + ) } get delete() { return this.page.locator(`button:text-is("${lang.address.delete}")`) } + + get addressBook() { + return this.page.locator(`button:text-is("${lang.address.addressBook}")`) + } } diff --git a/packages/e2e/extension/src/page-objects/Dapps.ts b/packages/e2e/extension/src/page-objects/Dapps.ts new file mode 100644 index 000000000..74465d681 --- /dev/null +++ b/packages/e2e/extension/src/page-objects/Dapps.ts @@ -0,0 +1,53 @@ +import { ChromiumBrowserContext, Page, expect } from "@playwright/test" + +import { lang } from "../languages" +import Navigation from "./Navigation" + +export default class Dapps extends Navigation { + constructor(page: Page) { + super(page) + } + + connected(url: string) { + return this.page.locator( + `//button/*[contains(text(),'${url.slice(0, 30)}')]`, + ) + } + + disconnect(url: string) { + return this.page.locator( + `//button/*[contains(text(),'${url.slice(0, 30)}')]/following::button[1]`, + ) + } + + resetAll() { + return this.page.locator(`button:text-is("${lang.dapps.resetAll}")`) + } + + get accept() { + return this.page.locator(`button:text-is("${lang.dapps.connect}")`) + } + + get reject() { + return this.page.locator(`button:text-is("${lang.dapps.reject}")`) + } + + async requestConnectionFromDapp( + browserContext: ChromiumBrowserContext, + url: string, + ) { + //open dapp page + const dapp = await browserContext.newPage() + await dapp.setViewportSize({ width: 1080, height: 720 }) + await dapp.goto("chrome://inspect/#extensions") + await dapp.waitForTimeout(5000) + await dapp.goto(url) + + await dapp + .locator('div :text-matches("Connect Wallet", "i")') + .first() + .click() + await expect(dapp.locator("text=Argent X")).toBeVisible() + await dapp.locator("text=Argent X").click() + } +} diff --git a/packages/e2e/extension/src/page-objects/DeveloperSettings.ts b/packages/e2e/extension/src/page-objects/DeveloperSettings.ts index 4acc8de98..23978b04f 100644 --- a/packages/e2e/extension/src/page-objects/DeveloperSettings.ts +++ b/packages/e2e/extension/src/page-objects/DeveloperSettings.ts @@ -42,8 +42,8 @@ export default class DeveloperSettings { return this.page.locator('[name="chainId"]') } - get baseUrl() { - return this.page.locator('[name="baseUrl"]') + get sequencerUrl() { + return this.page.locator('[name="sequencerUrl"]') } get create() { diff --git a/packages/e2e/extension/src/page-objects/ExtensionPage.ts b/packages/e2e/extension/src/page-objects/ExtensionPage.ts index 6230edd1a..e0cf8a868 100644 --- a/packages/e2e/extension/src/page-objects/ExtensionPage.ts +++ b/packages/e2e/extension/src/page-objects/ExtensionPage.ts @@ -1,14 +1,17 @@ -import type { Page } from "@playwright/test" +import { expect, type Page } from "@playwright/test" import Messages from "../utils/Messages" import Account from "./Account" import Activity from "./Activity" import AddressBook from "./AddressBook" +import Dapps from "./Dapps" import DeveloperSettings from "./DeveloperSettings" import Navigation from "./Navigation" import Network from "./Network" import Settings from "./Settings" import Wallet from "./Wallet" +import config from "../config" +import { balanceEther, transferEth, AccountsToSetup } from "../utils/account" export default class ExtensionPage { page: Page @@ -21,6 +24,7 @@ export default class ExtensionPage { navigation: Navigation developerSettings: DeveloperSettings addressBook: AddressBook + dapps: Dapps constructor(page: Page, private extensionUrl: string) { this.page = page this.wallet = new Wallet(page) @@ -33,6 +37,7 @@ export default class ExtensionPage { this.navigation = new Navigation(page) this.developerSettings = new DeveloperSettings(page) this.addressBook = new AddressBook(page) + this.dapps = new Dapps(page) } async open() { @@ -51,7 +56,98 @@ export default class ExtensionPage { await this.page.keyboard.press(`${key}+KeyV`) } + async pasteSeed() { + await this.page.locator('[data-testid="seed-input-0"]').focus() + await this.paste() + } + async setClipBoardContent(text: string) { await this.page.evaluate(`navigator.clipboard.writeText('${text}')`) } + + async recoverWallet(seed: string, password?: string) { + await this.wallet.restoreExistingWallet.click() + await this.setClipBoardContent(seed) + await this.pasteSeed() + await this.navigation.continue.click() + + await this.wallet.password.fill(password ?? config.password) + await this.wallet.repeatPassword.fill(password ?? config.password) + + await this.navigation.continue.click() + await expect(this.wallet.finish.first()).toBeVisible({ + timeout: 180000, + }) + + await this.open() + await expect(this.network.networkSelector).toBeVisible() + } + + getClipboard() { + return this.page.evaluate(`navigator.clipboard.readText()`) + } + + async deployAccountByName(accountName: string) { + await this.navigation.showSettings.click() + await this.page.locator(`text=${accountName}`).click() + await this.account.deployAccount.click() + await this.navigation.confirm.click() + await this.navigation.back.click() + await this.navigation.close.click() + } + + async setupWallet({ + accountsToSetup, + }: { + accountsToSetup: AccountsToSetup[] + }) { + await this.wallet.newWalletOnboarding() + await this.open() + await this.account.accountAddressFromAssetsView.click() + const seed = await this.account + .saveRecoveryPhrase() + .then((adr) => String(adr)) + const accountAddresses: string[] = [] + + for (const [accIndex, acc] of accountsToSetup.entries()) { + console.log(accIndex, acc) + if (accIndex !== 0) { + await this.account.addAccount({ firstAccount: false }) + } + await this.account.copyAddress.click() + const accountAddress = await this.getClipboard().then((adr) => + String(adr), + ) + expect(accountAddress).toMatch(/^0x0/) + accountAddresses.push(accountAddress) + + if (acc.initialBalance > 0) { + await transferEth( + `${acc.initialBalance * Math.pow(10, 18)}`, // amount Ethereum has 18 decimals + accountAddress, // reciever wallet address + ) + await this.account.ensureAsset( + `Account ${accIndex + 1}`, + "Ethereum", + `${acc.initialBalance} ETH`, + ) + if (acc.deploy) { + await this.deployAccountByName(`Account ${accIndex + 1}`) + } + } + } + console.log(accountAddresses.length, accountAddresses, seed) + return { accountAddresses, seed } + } + + async validateTx(address: string) { + const initialBalance = await balanceEther(address) + await this.navigation.approve.click() + await this.activity.checkActivity(1) + await expect( + this.navigation.menuPendingTransactionsIndicator, + ).not.toBeVisible({ timeout: 60000 }) + const finalBalance = await balanceEther(address) + expect(parseFloat(finalBalance)).toBeGreaterThan(parseFloat(initialBalance)) + } } diff --git a/packages/e2e/extension/src/page-objects/Navigation.ts b/packages/e2e/extension/src/page-objects/Navigation.ts index 29570bffc..bbe871dd8 100644 --- a/packages/e2e/extension/src/page-objects/Navigation.ts +++ b/packages/e2e/extension/src/page-objects/Navigation.ts @@ -20,10 +20,18 @@ export default class Navigation { return this.page.locator(`button:text-is("${lang.common.confirm}")`) } + get confirm() { + return this.page.locator(`button:text-is("${lang.common.confirm}")`) + } + get next() { return this.page.locator(`button:text-is("${lang.common.next}")`) } + get reviewSend() { + return this.page.locator(`button:text-is("${lang.common.reviewSend}")`) + } + get done() { return this.page.locator(`button:text-is("${lang.common.done}")`) } @@ -51,7 +59,7 @@ export default class Navigation { } get lockWallet() { - return this.page.locator(`button:text-is("${lang.common.lockWallet}")`) + return this.page.locator(`[aria-label="${lang.common.lockWallet}"]`) } get reset() { @@ -62,7 +70,7 @@ export default class Navigation { return this.page.locator(`button:text-is("${lang.common.confirmReset}")`) } - get menuPendingTransationsIndicator() { + get menuPendingTransactionsIndicator() { return this.page.locator('[aria-label="Pending transactions"]') } diff --git a/packages/e2e/extension/src/page-objects/Network.ts b/packages/e2e/extension/src/page-objects/Network.ts index a6db6e9a2..0a761f319 100644 --- a/packages/e2e/extension/src/page-objects/Network.ts +++ b/packages/e2e/extension/src/page-objects/Network.ts @@ -1,10 +1,29 @@ import { Page, expect } from "@playwright/test" -type NetworkName = - | "Localhost 5050" - | "Testnet" - | "Testnet 2" - | "Mainnet" - | "My Network" +type NetworkName = "Localhost 5050" | "Testnet" | "Mainnet" | "My Network" +export function getDefaultNetwork() { + const argentXEnv = process.env.ARGENT_X_ENVIRONMENT + + if (!argentXEnv) { + throw new Error("ARGENT_X_ENVIRONMENT not set") + } + let defaultNetworkId: string + switch (argentXEnv.toLowerCase()) { + case "prod": + case "staging": + defaultNetworkId = "mainnet-alpha" + break + + case "hydrogen": + case "test": + defaultNetworkId = "goerli-alpha" + break + + default: + throw new Error(`Unknown ARGENTX_ENVIRONMENT: ${argentXEnv}`) + } + + return defaultNetworkId +} export default class Network { constructor(private page: Page) {} get networkSelector() { @@ -27,4 +46,16 @@ export default class Network { .allInnerTexts() return networks.map((net) => expect(availableNetworks).toContain(net)) } + + getDefaultNetworkName() { + const defaultNetworkId = getDefaultNetwork() + switch (defaultNetworkId.toLowerCase()) { + case "mainnet-alpha": + return "Mainnet" + case "goerli-alpha": + return "Testnet" + default: + throw new Error(`Unknown ARGENTX_Network: ${defaultNetworkId}`) + } + } } diff --git a/packages/e2e/extension/src/specs/accountSettings.spec.ts b/packages/e2e/extension/src/specs/accountSettings.spec.ts index 25e776a17..cd2301817 100644 --- a/packages/e2e/extension/src/specs/accountSettings.spec.ts +++ b/packages/e2e/extension/src/specs/accountSettings.spec.ts @@ -2,14 +2,17 @@ import { expect } from "@playwright/test" import config from "../config" import test from "../test" +import { lang } from "../languages" test.describe("Account settings", () => { test("User should be able to edit account name", async ({ extension }) => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1] = await extension.account.addAccount({}) + await extension.network.selectNetwork("Testnet") + const [accountName1] = await extension.account.addAccount({ + firstAccount: false, + }) await extension.navigation.showSettings.click() await extension.settings.account(accountName1!).click() @@ -27,8 +30,10 @@ test.describe("Account settings", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1] = await extension.account.addAccount({}) + await extension.network.selectNetwork("Testnet") + const [accountName1] = await extension.account.addAccount({ + firstAccount: false, + }) await extension.navigation.showSettings.click() await extension.settings.account(accountName1!).click() @@ -52,41 +57,40 @@ test.describe("Account settings", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Testnet 2") - const [accountName1] = await extension.account.addAccount({}) + await extension.network.selectNetwork("Testnet") + const [accountName2] = await extension.account.addAccount({ + firstAccount: false, + }) await extension.navigation.showSettings.click() - await extension.settings.account(accountName1!).click() + await extension.settings.account(accountName2!).click() await extension.settings.hideAccount.click() await extension.settings.confirmHide.click() - await expect(extension.account.account(accountName1!)).toBeHidden() + await expect(extension.account.account(accountName2!)).toBeHidden() await extension.settings.hiddenAccounts.click() - await extension.settings.unhideAccount(accountName1!).click() + await extension.settings.unhideAccount(accountName2!).click() + await extension.navigation.back.click() await expect(extension.settings.hiddenAccounts).toBeHidden() - await expect(extension.account.account(accountName1!)).toBeVisible() + await expect(extension.account.account(accountName2!)).toBeVisible() }) - test("User should be able to delete an account on local network", async ({ + test("User should be able unlock wallet using password", async ({ extension, }) => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1] = await extension.account.addAccount({}) - await extension.navigation.showSettings.click() - await extension.settings.account(accountName1!).click() - await extension.settings.deleteAccount.click() - await extension.settings.confirmDelete.click() + await extension.navigation.lockWallet.click() - await expect(extension.account.account(accountName1!)).toBeHidden() - await expect(extension.settings.hiddenAccounts).toBeHidden() + await extension.account.password.fill(config.password) + await extension.navigation.unlock.click() + await expect(extension.network.networkSelector).toBeVisible() }) - test("User should be able unlock wallet using password", async ({ + test("User should not be able unlock wallet using wrong password", async ({ extension, }) => { await extension.wallet.newWalletOnboarding() @@ -95,8 +99,11 @@ test.describe("Account settings", () => { await extension.navigation.showSettings.click() await extension.navigation.lockWallet.click() - await extension.account.password.fill(config.password) + await extension.account.password.fill("wrongpassword123!") await extension.navigation.unlock.click() - await expect(extension.network.networkSelector).toBeVisible() + await expect( + extension.page.locator(`label:text-is("${lang.account.wrongPassword}")`), + ).toBeVisible() + await expect(extension.account.password).toBeVisible() }) }) diff --git a/packages/e2e/extension/src/specs/addressBook.spec.ts b/packages/e2e/extension/src/specs/addressBook.spec.ts index c2935a67f..dca2eecad 100644 --- a/packages/e2e/extension/src/specs/addressBook.spec.ts +++ b/packages/e2e/extension/src/specs/addressBook.spec.ts @@ -5,11 +5,10 @@ import test from "../test" test.describe("Address Book", () => { test("Add, update, use and delete address", async ({ extension }) => { - await extension.wallet.newWalletOnboarding() - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - await extension.account.addAccount({}) + await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.002 }], + }) + await extension.navigation.showSettings.click() await extension.settings.addressBook.click() //create @@ -21,66 +20,89 @@ test.describe("Address Book", () => { await extension.addressBook.save.click() await expect(extension.addressBook.nameRequired).not.toBeVisible() await expect(extension.addressBook.addressRequired).toBeVisible() - await extension.addressBook.address.fill(config.wallets[0].accounts![0]) + await extension.addressBook.address.fill(config.account1Seed2!) await expect(extension.addressBook.nameRequired).not.toBeVisible() await expect(extension.addressBook.addressRequired).not.toBeVisible() await extension.addressBook.network.click() - await extension.addressBook.networkOption("Localhost 5050").click() + await extension.addressBook.networkOption("Testnet").click() await extension.addressBook.save.click() // update - await extension.addressBook.addressByname("My first address").click() + await extension.addressBook.addressByName("My first address").click() await extension.addressBook.name.fill("New name") await extension.addressBook.save.click() - await expect(extension.addressBook.addressByname("New name")).toBeVisible() + await expect(extension.addressBook.addressByName("New name")).toBeVisible() await extension.navigation.back.click() await extension.navigation.close.click() //transfer to address await extension.account.token("Ethereum").click() - await extension.account.send.click() - await extension.account.recipientAddress.click() - await extension.addressBook.addressByname("New name").click() + await extension.addressBook.addressBook.click() + await extension.addressBook.addressByName("New name").click() await extension.account.sendMax.click() - await extension.navigation.next.click() - await extension.navigation.approve.click() - await extension.activity.checkActivity(1) + await extension.navigation.reviewSend.click() + + await extension.validateTx(config.account1Seed2!) //delete address await extension.navigation.menuTokens.click() await extension.navigation.showSettings.click() await extension.settings.addressBook.click() - await extension.addressBook.addressByname("New name").click() + await extension.addressBook.addressByName("New name").click() await extension.addressBook.deleteAddress.click() await extension.addressBook.delete.click() await expect( - extension.addressBook.addressByname("New name"), + extension.addressBook.addressByName("New name"), ).not.toBeVisible() }) - test("Add address from send window", async ({ extension }) => { - await extension.wallet.newWalletOnboarding() - await extension.open() + test("Add address after typing", async ({ extension }) => { + await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.002 }], + }) + await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - await extension.account.addAccount({}) + await extension.network.selectNetwork("Testnet") await extension.account.token("Ethereum").click() - await extension.account.send.click() - await extension.account.recepientAddress.fill( - config.wallets[0].accounts![0], + await extension.account.recipientAddressQuery.type(config.account1Seed2!) + await extension.addressBook.add.click() + await expect(extension.addressBook.address).toHaveText( + config.account1Seed2!, ) + await extension.addressBook.name.fill("My address") + await extension.addressBook.save.click() + await extension.account.contact("My address").click() + + await extension.account.sendMax.click() + await extension.navigation.reviewSend.click() + + await extension.validateTx(config.account1Seed2!) + }) + + test("Add address from send window", async ({ extension }) => { + await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.002 }], + }) + + await expect(extension.network.networkSelector).toBeVisible() + await extension.network.selectNetwork("Testnet") + + await extension.account.token("Ethereum").click() + await extension.setClipBoardContent(config.account1Seed2!) + await extension.account.recipientAddressQuery.focus() + await extension.paste() + await extension.account.saveAddress.click() await expect(extension.addressBook.address).toHaveText( - config.wallets[0].accounts![0], + config.account1Seed2!, ) await extension.addressBook.name.fill("My address") await extension.addressBook.save.click() - await expect(extension.account.contact).toHaveText("My address") await extension.account.sendMax.click() - await extension.navigation.next.click() - await extension.navigation.approve.click() - await extension.activity.checkActivity(1) + await extension.navigation.reviewSend.click() + + await extension.validateTx(config.account1Seed2!) }) }) diff --git a/packages/e2e/extension/src/specs/dapps.spec.ts b/packages/e2e/extension/src/specs/dapps.spec.ts new file mode 100644 index 000000000..d2701d920 --- /dev/null +++ b/packages/e2e/extension/src/specs/dapps.spec.ts @@ -0,0 +1,91 @@ +import { expect } from "@playwright/test" + +import test from "../test" + +const aspectUrl = "https://testnet.aspect.co" +const testDappUrl = "https://dapp-argentlabs.vercel.app/" + +test.describe("Dapps", () => { + test("connect from aspect", async ({ extension, browserContext }) => { + //setup wallet + await extension.wallet.newWalletOnboarding() + await extension.open() + await extension.dapps.requestConnectionFromDapp(browserContext, aspectUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + //check connect dapps + await extension.navigation.showSettings.click() + await extension.settings.connectedDapps.click() + await expect(extension.dapps.connected(aspectUrl)).toBeVisible() + //disconnect dapp from ArgentX + await extension.dapps.disconnect(aspectUrl).click() + await expect(extension.dapps.connected(aspectUrl)).toBeHidden() + }) + + test("connect from testDapp", async ({ extension, browserContext }) => { + //setup wallet + await extension.wallet.newWalletOnboarding() + await extension.open() + await extension.dapps.requestConnectionFromDapp(browserContext, testDappUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + //check connect dapps + await extension.navigation.showSettings.click() + await extension.settings.connectedDapps.click() + await expect(extension.dapps.connected(testDappUrl)).toBeVisible() + //disconnect dapp from ArgentX + await extension.dapps.disconnect(testDappUrl).click() + await expect(extension.dapps.connected(testDappUrl)).toBeHidden() + }) + + test("reset all connections", async ({ extension, browserContext }) => { + //setup wallet + await extension.wallet.newWalletOnboarding() + await extension.open() + await extension.dapps.requestConnectionFromDapp(browserContext, aspectUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + await extension.dapps.requestConnectionFromDapp(browserContext, testDappUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + await extension.navigation.showSettings.click() + await extension.settings.connectedDapps.click() + await Promise.all([ + expect(extension.dapps.connected(testDappUrl)).toBeVisible(), + expect(extension.dapps.connected(aspectUrl)).toBeVisible(), + ]) + + await extension.dapps.resetAll().click() + await Promise.all([ + expect(extension.dapps.connected(testDappUrl)).toBeHidden(), + expect(extension.dapps.connected(aspectUrl)).toBeHidden(), + ]) + }) + + test("disconnect only one connected dapp", async ({ + extension, + browserContext, + }) => { + //setup wallet + await extension.wallet.newWalletOnboarding() + await extension.open() + await extension.dapps.requestConnectionFromDapp(browserContext, aspectUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + await extension.dapps.requestConnectionFromDapp(browserContext, testDappUrl) + //accept connection from ArgentX + await extension.dapps.accept.click() + await extension.navigation.showSettings.click() + await extension.settings.connectedDapps.click() + await Promise.all([ + expect(extension.dapps.connected(testDappUrl)).toBeVisible(), + expect(extension.dapps.connected(aspectUrl)).toBeVisible(), + ]) + + await extension.dapps.disconnect(testDappUrl).click() + await Promise.all([ + expect(extension.dapps.connected(testDappUrl)).toBeHidden(), + expect(extension.dapps.connected(aspectUrl)).toBeVisible(), + ]) + }) +}) diff --git a/packages/e2e/extension/src/specs/dappsBanner.spec.ts b/packages/e2e/extension/src/specs/dappsBanner.spec.ts index 905bbcde1..b4af268ce 100644 --- a/packages/e2e/extension/src/specs/dappsBanner.spec.ts +++ b/packages/e2e/extension/src/specs/dappsBanner.spec.ts @@ -1,6 +1,5 @@ import { expect } from "@playwright/test" -import config from "../config" import test from "../test" test.describe("Banner", () => { @@ -8,11 +7,6 @@ test.describe("Banner", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.account.setUpAccountRecovery.click() - await extension.account.saveTheRecoveryPhrase.click() - await extension.navigation.continue.click() - await extension.navigation.yes.click() - await expect(extension.account.setUpAccountRecovery).toBeHidden() await expect(extension.account.dappsBanner).toBeVisible() let href = await extension.account.dappsBanner.getAttribute("href") expect(href).toContain("https://www.dappland.com") @@ -28,11 +22,6 @@ test.describe("Banner", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.account.setUpAccountRecovery.click() - await extension.account.saveTheRecoveryPhrase.click() - await extension.navigation.continue.click() - await extension.navigation.yes.click() - await expect(extension.account.setUpAccountRecovery).toBeHidden() await expect(extension.account.dappsBanner).toBeVisible() await extension.account.dappsBannerClose.click() await expect(extension.account.dappsBanner).toBeHidden() @@ -41,23 +30,16 @@ test.describe("Banner", () => { test("dapps banner shoud be visible after account recovery", async ({ extension, }) => { - await extension.open() - await extension.wallet.restoreExistingWallet.click() - await extension.setClipBoardContent(config.wallets[1].seed) - await extension.paste() - await extension.navigation.continue.click() - - await extension.wallet.password.fill(config.password) - await extension.wallet.repeatPassword.fill(config.password) - - await extension.navigation.continue.click() - - await expect(extension.wallet.finish.first()).toBeVisible({ - timeout: 180000, + const { seed } = await extension.setupWallet({ + accountsToSetup: [ + { + initialBalance: 0, + }, + ], }) - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() + await extension.resetExtension() + await extension.recoverWallet(seed) await expect(extension.account.dappsBanner).toBeVisible() }) }) diff --git a/packages/e2e/extension/src/specs/network.spec.ts b/packages/e2e/extension/src/specs/network.spec.ts index 73ce362cd..461625ac8 100644 --- a/packages/e2e/extension/src/specs/network.spec.ts +++ b/packages/e2e/extension/src/specs/network.spec.ts @@ -8,9 +8,8 @@ test.describe("Network", () => { await extension.open() await expect(extension.network.networkSelector).toBeVisible() await extension.network.ensureAvailableNetworks([ - "Mainnet\nhttps://alpha-mainnet.starknet.io", - "Testnet\nhttps://alpha4.starknet.io", - "Testnet 2\nhttps://alpha4-2.starknet.io", + "Mainnet\nhttps://cloud.argent-api.com/v1/starknet/mainnet/rpc/v0.4", + "Testnet\nhttps://cloud.argent-api.com/v1/starknet/goerli/rpc/v0.4", "Localhost 5050\nhttp://localhost:5050", ]) }) @@ -28,7 +27,9 @@ test.describe("Network", () => { await extension.developerSettings.addNetwork.click() await extension.developerSettings.networkName.fill("My Network") await extension.developerSettings.chainId.fill("SN_GOERLI") - await extension.developerSettings.baseUrl.fill("https://alpha4.starknet.io") + await extension.developerSettings.sequencerUrl.fill( + "https://alpha4.starknet.io", + ) await extension.navigation.create.click() await expect( @@ -80,7 +81,9 @@ test.describe("Network", () => { await extension.developerSettings.addNetwork.click() await extension.developerSettings.networkName.fill("My Network") await extension.developerSettings.chainId.fill("SN_GOERLI") - await extension.developerSettings.baseUrl.fill("https://alpha4.starknet.io") + await extension.developerSettings.sequencerUrl.fill( + "https://alpha4.starknet.io", + ) await extension.navigation.create.click() await expect( @@ -92,7 +95,7 @@ test.describe("Network", () => { // add account await extension.network.selectNetwork("My Network") - await extension.account.addAccount({}) + await extension.account.addAccount({ firstAccount: true }) await extension.network.selectNetwork("Testnet") // try to restore networks diff --git a/packages/e2e/extension/src/specs/receiveFunds.spec.ts b/packages/e2e/extension/src/specs/receiveFunds.spec.ts deleted file mode 100644 index 928314a0e..000000000 --- a/packages/e2e/extension/src/specs/receiveFunds.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { expect } from "@playwright/test" - -import test from "../test" - -test.describe("Receive funds", () => { - test("Account balance should be updated after receiving funds", async ({ - extension, - secondExtension, - }) => { - //setup wallet 1 - await extension.wallet.newWalletOnboarding() - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1, accountAddress1] = await extension.account.addAccount( - {}, - ) - - if (!accountName1 || !accountAddress1) { - throw new Error("Invalid account info") - } - await extension.account.ensureAsset(accountName1, "ETH", "1.0") - - //setup wallet 2 - await secondExtension.wallet.newWalletOnboarding() - await secondExtension.open() - await expect(secondExtension.network.networkSelector).toBeVisible() - await secondExtension.network.selectNetwork("Localhost 5050") - const [accountName2, accountAddress2] = - await secondExtension.account.addAccount({}) - - if (!accountName2 || !accountAddress2) { - throw new Error("Invalid account info") - } - await secondExtension.account.ensureAsset(accountName1, "ETH", "1.0") - await extension.account.transfer({ - originAccountName: accountName1, - recepientAddress: accountAddress2, - tokenName: "Ethereum", - amount: 0.5, - }) - await extension.activity.checkActivity(1) - await extension.navigation.menuTokens.click() - await expect( - extension.navigation.menuPendingTransationsIndicator, - ).not.toBeVisible() - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.4988", - ) - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("0.4988") - - await secondExtension.account.token("Ethereum").click() - await secondExtension.account.back.click() - await expect(secondExtension.account.currentBalance("ETH")).toContainText( - "1.5", - ) - }) -}) diff --git a/packages/e2e/extension/src/specs/recovery.spec.ts b/packages/e2e/extension/src/specs/recovery.spec.ts index 8bd31f0fe..feead1738 100644 --- a/packages/e2e/extension/src/specs/recovery.spec.ts +++ b/packages/e2e/extension/src/specs/recovery.spec.ts @@ -7,22 +7,17 @@ test.describe("Recovery Wallet", () => { test("User should be able to recover wallet using seed phrase", async ({ extension, }) => { - await extension.open() - await extension.wallet.restoreExistingWallet.click() - await extension.setClipBoardContent(config.wallets[1].seed) - await extension.paste() - await extension.navigation.continue.click() - - await extension.wallet.password.fill(config.password) - await extension.wallet.repeatPassword.fill(config.password) - - await extension.navigation.continue.click() - await expect(extension.wallet.finish.first()).toBeVisible({ - timeout: 180000, + const { seed } = await extension.setupWallet({ + accountsToSetup: [ + { + initialBalance: 0.0005, + deploy: true, + }, + ], }) - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() + await extension.resetExtension() + await extension.recoverWallet(seed) }) test("Set up account recovery banner should not be visible after user copy phrase", async ({ @@ -31,10 +26,12 @@ test.describe("Recovery Wallet", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.account.setUpAccountRecovery.click() - await extension.account.saveTheRecoveryPhrase.click() - await extension.navigation.continue.click() - await extension.navigation.yes.click() + await extension.network.selectNetwork("Mainnet") + await extension.account.addAccountMainnet({ firstAccount: true }) + await expect(extension.account.showAccountRecovery).toBeVisible() + await extension.account.showAccountRecovery.click() + await extension.account.confirmTheSeedPhrase.click() + await extension.navigation.done.click() await expect(extension.account.setUpAccountRecovery).toBeHidden() }) @@ -42,25 +39,40 @@ test.describe("Recovery Wallet", () => { extension, }) => { await extension.open() - await extension.wallet.restoreExistingWallet.click() - await extension.setClipBoardContent(config.wallets[2].seed) - await extension.paste() - await extension.navigation.continue.click() - - await extension.wallet.password.fill(config.password) - await extension.wallet.repeatPassword.fill(config.password) + await extension.recoverWallet(config.testNetSeed1!) + await expect(extension.network.networkSelector).toBeVisible() + await extension.network.selectNetwork("Testnet") + await extension.account.selectAccount("Account 33") + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.0000097 ETH", + ) + }) - await extension.navigation.continue.click() - await expect(extension.wallet.finish.first()).toBeVisible({ - timeout: 180000, - }) + test("Copy phrase from account view when creating new wallet", async ({ + extension, + }) => { + await extension.wallet.newWalletOnboarding() + await extension.open() + await expect(extension.network.networkSelector).toBeVisible() + await extension.account.accountAddressFromAssetsView.click() + await extension.account.saveRecoveryPhrase() + await extension.account.copyAddress.click() + const accountAddress = await extension.getClipboard() + expect(accountAddress).toMatch(/^0x0/) + }) + test("Save your recovery phrase banner", async ({ extension }) => { + await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - await extension.account.selectAccount("Account 32") - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.9991 ETH", - ) + await extension.network.selectNetwork("Mainnet") + await extension.account.addAccountMainnet({ firstAccount: true }) + + await extension.account.showAccountRecovery.click() + await extension.account.saveRecoveryPhrase() + await extension.account.copyAddress.click() + const accountAddress = await extension.getClipboard() + expect(accountAddress).toMatch(/^0x0/) + await expect(extension.account.showAccountRecovery).toBeHidden() }) }) diff --git a/packages/e2e/extension/src/specs/sendFunds.spec.ts b/packages/e2e/extension/src/specs/sendFunds.spec.ts new file mode 100644 index 000000000..4b49ab77d --- /dev/null +++ b/packages/e2e/extension/src/specs/sendFunds.spec.ts @@ -0,0 +1,141 @@ +import { expect } from "@playwright/test" + +import config from "../config" +import test from "../test" + +test.describe("Send funds", () => { + test("send MAX funds to other self account", async ({ extension }) => { + const { accountAddresses } = await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.01 }, { initialBalance: 0 }], + }) + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: accountAddresses[1], + tokenName: "Ethereum", + amount: "MAX", + submit: false, + }) + + await extension.validateTx(accountAddresses[1]) + await extension.navigation.menuTokens.click() + + //ensure that balance is updated + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.00", + ) + let balance = await extension.account.currentBalance("Ethereum").innerText() + expect(parseFloat(balance)).toBeLessThan(0.01) + + await extension.account.ensureSelectedAccount( + extension.account.accountName2, + ) + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.01", + ) + balance = await extension.account.currentBalance("Ethereum").innerText() + expect(parseFloat(balance)).toBeGreaterThan(0.0001) + }) + + test("send MAX funds to other wallet/account", async ({ extension }) => { + await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.002 }], + }) + + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: config.destinationAddress!, + tokenName: "Ethereum", + amount: "MAX", + submit: false, + }) + + await extension.validateTx(config.destinationAddress!) + await extension.navigation.menuTokens.click() + + //ensure that balance is updated + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.000", + ) + const balance = await extension.account + .currentBalance("Ethereum") + .innerText() + expect(parseFloat(balance)).toBeLessThan(0.002) + }) + + test("send partial funds to other self account", async ({ extension }) => { + const { accountAddresses } = await extension.setupWallet({ + accountsToSetup: [{ initialBalance: 0.01 }, { initialBalance: 0 }], + }) + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: accountAddresses[1], + tokenName: "Ethereum", + amount: 0.005, + submit: false, + }) + await extension.validateTx(accountAddresses[1]) + await extension.navigation.menuTokens.click() + + //ensure that balance is updated + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.00", + ) + const balance = await extension.account + .currentBalance("Ethereum") + .innerText() + expect(parseFloat(balance)).toBeLessThan(0.01) + + await extension.account.ensureSelectedAccount( + extension.account.accountName2, + ) + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.005", + ) + }) + + test("send partial funds to other wallet/account", async ({ extension }) => { + await extension.setupWallet({ accountsToSetup: [{ initialBalance: 0.01 }] }) + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: config.destinationAddress!, + tokenName: "Ethereum", + amount: 0.005, + fillRecipientAddress: "typing", + submit: false, + }) + await extension.validateTx(config.destinationAddress!) + await extension.navigation.menuTokens.click() + + //ensure that balance is updated + await expect(extension.account.currentBalance("Ethereum")).toContainText( + "0.00", + ) + const balance = await extension.account + .currentBalance("Ethereum") + .innerText() + expect(parseFloat(balance)).toBeLessThan(0.01) + + //send back remaining funds + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: config.destinationAddress!, + tokenName: "Ethereum", + amount: "MAX", + }) + }) + + test("User should be able to send funds to starknet id", async ({ + extension, + }) => { + await extension.setupWallet({ accountsToSetup: [{ initialBalance: 0.01 }] }) + + await extension.account.transfer({ + originAccountName: extension.account.accountName1, + recipientAddress: "e2e-test.stark", + tokenName: "Ethereum", + amount: "MAX", + submit: false, + }) + await extension.validateTx(config.account1Seed3!) + }) +}) diff --git a/packages/e2e/extension/src/specs/sendFundsMax.spec.ts b/packages/e2e/extension/src/specs/sendFundsMax.spec.ts deleted file mode 100644 index 7e4eca6d9..000000000 --- a/packages/e2e/extension/src/specs/sendFundsMax.spec.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { expect } from "@playwright/test" - -import test from "../test" - -test.describe("Send MAX funds", () => { - const otherAccount = - "0x02c786C7b4708b476a3a7c012922e6C3a161096F71EC694D61b590dbD4051Faf" - const setupWallet = async (extension: any) => { - await extension.wallet.newWalletOnboarding() - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1, accountAddress1] = await extension.account.addAccount( - {}, - ) - const [accountName2, accountAddress2] = await extension.account.addAccount({ - firstAccount: false, - }) - if (!accountName1 || !accountName2 || !accountAddress2) { - throw new Error("Invalid account names") - } - await extension.account.ensureAsset(accountName1, "ETH", "1.0") - await extension.account.ensureAsset(accountName2, "ETH", "1.0") - - return { accountName1, accountAddress1, accountName2, accountAddress2 } - } - - test("send MAX funds to other self account", async ({ extension }) => { - const { accountName1, accountName2, accountAddress2 } = await setupWallet( - extension, - ) - await extension.account.transfer({ - originAccountName: accountName1, - recepientAddress: accountAddress2, - tokenName: "Ethereum", - amount: "MAX", - }) - await extension.activity.checkActivity(1) - await extension.navigation.menuTokens.click() - await expect( - extension.navigation.menuPendingTransationsIndicator, - ).not.toBeVisible() - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.0023", - ) - - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("0.0023") - await extension.account.back.click() - await extension.account.ensureSelectedAccount(accountName2) - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("1.9965") - await extension.account.back.click() - await expect(extension.account.currentBalance("ETH")).toContainText("1.9") - }) - - test("send MAX funds to other wallet/account", async ({ extension }) => { - const { accountName1 } = await setupWallet(extension) - - await extension.account.transfer({ - originAccountName: accountName1, - recepientAddress: otherAccount, - tokenName: "Ethereum", - amount: "MAX", - }) - await extension.activity.checkActivity(1) - await extension.navigation.menuTokens.click() - await expect( - extension.navigation.menuPendingTransationsIndicator, - ).not.toBeVisible() - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.0023", - ) - - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("0.0023") - }) -}) diff --git a/packages/e2e/extension/src/specs/sendFundsPartial.spec.ts b/packages/e2e/extension/src/specs/sendFundsPartial.spec.ts deleted file mode 100644 index 855986b07..000000000 --- a/packages/e2e/extension/src/specs/sendFundsPartial.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { expect } from "@playwright/test" - -import test from "../test" - -test.describe("Send partial funds", () => { - const otherAccount = - "0x02c786C7b4708b476a3a7c012922e6C3a161096F71EC694D61b590dbD4051Faf" - const setupWallet = async (extension: any) => { - await extension.wallet.newWalletOnboarding() - await extension.open() - await expect(extension.network.networkSelector).toBeVisible() - await extension.network.selectNetwork("Localhost 5050") - const [accountName1, accountAddress1] = await extension.account.addAccount( - {}, - ) - const [accountName2, accountAddress2] = await extension.account.addAccount({ - firstAccount: false, - }) - if (!accountName1 || !accountName2 || !accountAddress2) { - throw new Error("Invalid account names") - } - await extension.account.ensureAsset(accountName1, "ETH", "1.0") - await extension.account.ensureAsset(accountName2, "ETH", "1.0") - - return { accountName1, accountAddress1, accountName2, accountAddress2 } - } - - test("send partial funds to other self account", async ({ extension }) => { - const { accountName1, accountName2, accountAddress2 } = await setupWallet( - extension, - ) - await extension.account.transfer({ - originAccountName: accountName1, - recepientAddress: accountAddress2, - tokenName: "Ethereum", - amount: 0.5, - }) - await extension.activity.checkActivity(1) - await extension.navigation.menuTokens.click() - await expect( - extension.navigation.menuPendingTransationsIndicator, - ).not.toBeVisible() - - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.4988", - ) - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("0.4988") - await extension.account.back.click() - await extension.account.ensureSelectedAccount(accountName2) - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("1.5") - await extension.account.back.click() - await expect(extension.account.currentBalance("ETH")).toContainText("1.5") - }) - - test("send partial funds to other wallet/account", async ({ extension }) => { - const { accountName1 } = await setupWallet(extension) - await extension.account.ensureAsset(accountName1, "ETH", "1.0") - await extension.account.transfer({ - originAccountName: accountName1, - recepientAddress: otherAccount, - tokenName: "Ethereum", - amount: 0.5, - }) - await extension.activity.checkActivity(1) - await extension.navigation.menuTokens.click() - await expect( - extension.navigation.menuPendingTransationsIndicator, - ).not.toBeVisible() - await expect(extension.account.currentBalance("ETH")).toContainText( - "0.4988", - ) - await extension.account.token("Ethereum").click() - await expect(extension.account.balance).toContainText("0.4988") - }) -}) diff --git a/packages/e2e/extension/src/specs/welcome.spec.ts b/packages/e2e/extension/src/specs/welcome.spec.ts index de7ac03cf..8a3281582 100644 --- a/packages/e2e/extension/src/specs/welcome.spec.ts +++ b/packages/e2e/extension/src/specs/welcome.spec.ts @@ -36,5 +36,8 @@ test.describe("Welcome screen", () => { await extension.wallet.newWalletOnboarding() await extension.open() await expect(extension.network.networkSelector).toBeVisible() + await expect(extension.network.networkSelector).toHaveText( + extension.network.getDefaultNetworkName(), + ) }) }) diff --git a/packages/e2e/extension/src/test.ts b/packages/e2e/extension/src/test.ts index 979454025..8d511ce9b 100644 --- a/packages/e2e/extension/src/test.ts +++ b/packages/e2e/extension/src/test.ts @@ -1,6 +1,8 @@ import * as fs from "fs" import path from "path" +import dotenv from "dotenv" +dotenv.config() import { ChromiumBrowserContext, Page, @@ -8,13 +10,15 @@ import { chromium, test as testBase, } from "@playwright/test" +import { v4 as uuid } from "uuid" import config from "./config" import type { TestExtensions } from "./fixtures" import ExtensionPage from "./page-objects/ExtensionPage" +const isCI = Boolean(process.env.CI) const isExtensionURL = (url: string) => url.startsWith("chrome-extension://") - +let browserCtx: ChromiumBrowserContext const closePages = async (browserContext: ChromiumBrowserContext) => { const pages = browserContext?.pages() || [] for (const page of pages) { @@ -54,17 +58,18 @@ const keepArtifacts = async (testInfo: TestInfo, page: Page) => { } } } -const initBrowserWithExtension = async (testInfo: TestInfo) => { - const userDataDir = `/tmp/test-user-data-${Math.round( - new Date().getTime() / 1000, - )}-${(Math.random() + 1).toString(36).substring(7)}-${testInfo.workerIndex}` - const browserContext = (await chromium.launchPersistentContext(userDataDir, { + +const createBrowserContext = () => { + const userDataDir = `/tmp/test-user-data-${uuid()}` + return chromium.launchPersistentContext(userDataDir, { headless: false, args: [ + `${isCI ? "--headless=new" : ""}`, "--disable-dev-shm-usage", "--ipc=host", `--disable-extensions-except=${config.distDir}`, `--load-extension=${config.distDir}`, + "--disable-gp", ], recordVideo: { dir: config.artifactsDir, @@ -73,8 +78,11 @@ const initBrowserWithExtension = async (testInfo: TestInfo) => { height: 600, }, }, - })) as ChromiumBrowserContext + }) +} +const initBrowserWithExtension = async (testInfo: TestInfo) => { + const browserContext = await createBrowserContext() // save video browserContext.on("page", async (page) => { page.on("load", async (page) => { @@ -156,14 +164,23 @@ function createExtension() { const extension = new ExtensionPage(page, extensionURL) await keepArtifacts(testInfo, page) await closePages(browserContext) + browserCtx = browserContext await use(extension) await browserContext.close() } } + +function getContext() { + return async ({}, use: any, _testInfo: TestInfo) => { + await use(browserCtx) + } +} + let pageId = 0 const test = testBase.extend({ extension: createExtension(), secondExtension: createExtension(), + browserContext: getContext(), }) export default test diff --git a/packages/e2e/extension/src/utils/account.ts b/packages/e2e/extension/src/utils/account.ts new file mode 100644 index 000000000..9c805ea9f --- /dev/null +++ b/packages/e2e/extension/src/utils/account.ts @@ -0,0 +1,102 @@ +import { Account, SequencerProvider, constants, uint256 } from "starknet" +import { bigDecimal } from "@argent/shared" +import { Multicall } from "@argent/x-multicall" +import config from "../config" + +export interface AccountsToSetup { + initialBalance: number + deploy?: boolean +} + +const provider = new SequencerProvider({ + network: constants.NetworkName.SN_GOERLI, +}) +const tnkETH = + "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7" // address of ETH +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) + +const maxRetries = 4 + +const getTransaction = async (tx: string) => { + return fetch( + `${config.starknetTestNetUrl}/feeder_gateway/get_transaction?transactionHash=${tx}`, + { method: "GET" }, + ) +} + +export async function transferEth(amount: string, to: string) { + const account = new Account( + provider, + config.senderAddr!, + config.senderKey!, + "1", + ) + const initialBalance = await balanceEther(account.address) + const initialBalanceFormatted = parseFloat(initialBalance) * Math.pow(10, 18) + const { low, high } = uint256.bnToUint256(amount) + + if (initialBalanceFormatted < parseInt(amount)) { + throw `Failed to tranfer: Not enought balance ${initialBalanceFormatted} < ${amount}` + } + let placeTXAttempt = 0 + while (placeTXAttempt < maxRetries) { + try { + placeTXAttempt++ + const tx = await account.execute({ + contractAddress: tnkETH, + entrypoint: "transfer", + calldata: [to, low, high], + }) + let failed = true + let txSuccessAttempt = 0 + let txStatusResponse + while (failed && txSuccessAttempt < maxRetries) { + txSuccessAttempt++ + const txStatus = await getTransaction(tx.transaction_hash) + txStatusResponse = await txStatus.json() + if (txStatusResponse.execution_status === "REJECTED") { + console.error( + `Failed to place TX: ${config.starkscanTestNetUrl}/tx/${tx.transaction_hash}, execution_status: ${txStatusResponse.execution_status}, status: ${txStatusResponse.status}`, + ) + txSuccessAttempt = maxRetries + } else if ( + txStatusResponse.execution_status !== "SUCCEEDED" && + txStatusResponse.status !== "ACCEPTED_ON_L2" + ) { + console.log( + `TX not processed: hash: ${tx.transaction_hash}, execution_status: ${txStatusResponse.execution_status}, status: ${txStatusResponse.status}`, + ) + await sleep(5000) + } else { + failed = false + } + } + if (failed) { + throw `Failed to place TX: ${config.starkscanTestNetUrl}/tx/${tx.transaction_hash}, execution_status: ${txStatusResponse.execution_status}, status: ${txStatusResponse.status}` + } + + console.log( + `[Successful TX] ${config.starkscanTestNetUrl}/tx/${tx.transaction_hash}`, + ) + return tx.transaction_hash + } catch (e) { + //for debug only + console.log("Exception: ", e) + } + console.warn("Transfer failed, going to try again ") + } +} + +export async function balanceEther(accountAddress: string) { + const balanceOfCall = { + contractAddress: tnkETH, + entrypoint: "balanceOf", + calldata: [accountAddress], + } + + const multicall = new Multicall(provider) + const response = await multicall.call(balanceOfCall) + const [low, high] = response + const balance = bigDecimal.formatEther(uint256.uint256ToBN({ low, high })) + return balance +} diff --git a/packages/e2e/package.json b/packages/e2e/package.json index c32477a8f..ea85a1d27 100644 --- a/packages/e2e/package.json +++ b/packages/e2e/package.json @@ -1,15 +1,21 @@ { "name": "@argent-x/e2e", "private": true, - "version": "6.3.0", + "version": "6.3.2", "main": "index.js", "license": "MIT", "devDependencies": { - "@playwright/test": "^1.32.0", - "@types/node": "^18.15.11" + "@argent/shared": "workspace:^", + "@argent/x-multicall": "workspace:^", + "@playwright/test": "^1.37.1", + "@types/node": "^20.5.7", + "@types/uuid": "^9.0.3", + "dotenv": "^16.3.1", + "starknet": "5.18.0", + "uuid": "^9.0.0" }, "scripts": { - "test:e2e:extension": "playwright test ./extension", - "test:e2e": "yarn run test:e2e:extension" + "test:extension": "pnpm playwright test --config=./extension", + "test:webwallet": "pnpm playwright test --config=./webwallet" } } diff --git a/packages/e2e/playwright.config.ts b/packages/e2e/playwright.config.ts deleted file mode 100644 index 220201962..000000000 --- a/packages/e2e/playwright.config.ts +++ /dev/null @@ -1,53 +0,0 @@ -import path from "path" - -import type { PlaywrightTestConfig } from "@playwright/test" - -import config from "./extension/src/config" - -const isCI = Boolean(process.env.CI) - -const playwrightConfig: PlaywrightTestConfig = { - projects: [ - { - name: "chromium", - }, - ], - workers: 1, - timeout: 5 * 60e3, // 5 minutes - reportSlowTests: { - threshold: 1 * 60e3, // 1 minute - max: 5, - }, - expect: { timeout: 90 * 1000 }, // 90 seconds - reporter: isCI - ? [ - ["github"], - [ - "json", - { outputFile: path.join(config.reportsDir, "extension.json") }, - ], - ["list"], - [ - "html", - { - open: "never", - outputFolder: path.join(config.reportsDir, "playwright-report"), - }, - ], - ] - : "list", - forbidOnly: isCI, - testDir: "./extension/src/specs", - testMatch: /\.spec.ts$/, - retries: isCI ? 2 : 0, - use: { - trace: "on-first-retry", - viewport: { width: 360, height: 600 }, - actionTimeout: 60 * 1000, // 1 minute - permissions: ["clipboard-read", "clipboard-write"], - }, - outputDir: config.artifactsDir, - preserveOutput: isCI ? "failures-only" : "never", -} - -export default playwrightConfig diff --git a/packages/e2e/tsconfig.json b/packages/e2e/tsconfig.json index 826af4096..6a764dd01 100644 --- a/packages/e2e/tsconfig.json +++ b/packages/e2e/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "Esnext", + "module": "ESNext", "moduleResolution": "node", - "module": "commonjs", "allowSyntheticDefaultImports": true, "strict": true, "noImplicitAny": true, @@ -13,7 +13,8 @@ "inlineSources": true, "inlineSourceMap": true, "composite": true, - "types": ["node"] + "types": ["node"], + "noEmit": true }, "include": ["**/src"], "exclude": ["node_modules"] diff --git a/packages/e2e/webwallet/playwright.config.ts b/packages/e2e/webwallet/playwright.config.ts new file mode 100644 index 000000000..d4d2d962c --- /dev/null +++ b/packages/e2e/webwallet/playwright.config.ts @@ -0,0 +1,44 @@ +import type { PlaywrightTestConfig } from "@playwright/test" +import config from "./src/config" + +const isCI = Boolean(process.env.CI) + +const playwrightConfig: PlaywrightTestConfig = { + projects: [ + { + name: "WebWallet - Chrome", + use: { + browserName: "chromium", + }, + }, + { + name: "WebWallet - Firefox", + use: { + browserName: "firefox", + }, + }, + { + name: "WebWallet - WebKit", + use: { + browserName: "webkit", + }, + }, + ], + expect: { + timeout: 20 * 1000, // 20 seconds + }, + timeout: 1 * 60e3, // 1 minutes + retries: isCI ? 2 : 0, + workers: 1, + reportSlowTests: { + threshold: 2 * 60e3, // 2 minute + max: 5, + }, + reporter: isCI ? [["github"], ["blob"]] : "list", + + forbidOnly: isCI, + outputDir: config.artifactsDir, + preserveOutput: isCI ? "failures-only" : "never", +} + +export default playwrightConfig diff --git a/packages/e2e/webwallet/src/config.ts b/packages/e2e/webwallet/src/config.ts new file mode 100644 index 000000000..78ace2245 --- /dev/null +++ b/packages/e2e/webwallet/src/config.ts @@ -0,0 +1,12 @@ +import path from "path" + +export default { + validLogin: { + email: "testuser@mail.com", + pin: "1111111", + password: "myNewPass12!", + }, + url: "http://localhost:3005", + artifactsDir: path.resolve(__dirname, "../../artifacts/playwright"), + reportsDir: path.resolve(__dirname, "../../artifacts/reports"), +} diff --git a/packages/e2e/webwallet/src/fixtures.ts b/packages/e2e/webwallet/src/fixtures.ts new file mode 100644 index 000000000..6a7f1c148 --- /dev/null +++ b/packages/e2e/webwallet/src/fixtures.ts @@ -0,0 +1,5 @@ +import type WebWalletPage from "./page-objects/WebWalletPage" + +export interface TestPages { + webWallet: WebWalletPage +} diff --git a/packages/e2e/webwallet/src/page-objects/Login.ts b/packages/e2e/webwallet/src/page-objects/Login.ts new file mode 100644 index 000000000..b2f0ae1df --- /dev/null +++ b/packages/e2e/webwallet/src/page-objects/Login.ts @@ -0,0 +1,66 @@ +import { Page, expect } from "@playwright/test" + +import config from "../config" +import Navigation from "./Navigation" + +interface ICredentials { + email: string + pin: string + password: string +} + +export default class Login extends Navigation { + constructor(page: Page) { + super(page) + } + + get email() { + return this.page.locator("input[name=email]") + } + + get pinInput() { + return this.page.locator('[id^="pin-input"]') + } + + get password() { + return this.page.locator("input[name=password]") + } + + get wrongPassword() { + return this.page.locator( + '//input[@name="password"][@aria-invalid="true"]/following::label[contains(text(), "Wrong password")]', + ) + } + + get forgetPassword() { + return this.page.locator( + '//a[@href="/password"]//label[contains(text(), "Forgotten your password?")]', + ) + } + + get differentAccount() { + return this.page.locator('p:text-is("Use a different account")') + } + + async fillPin(pin: string) { + await Promise.all([ + this.page.waitForURL(`${config.url}/pin`), + this.continue.click(), + ]) + await this.pinInput.first().click() + await this.pinInput.first().fill(pin) + } + + async success(credentials: ICredentials = config.validLogin) { + await this.email.fill(credentials.email) + await this.fillPin(credentials.pin) + await this.password.fill(credentials.password) + await expect(this.forgetPassword).toBeVisible() + await expect(this.differentAccount).toBeVisible() + await Promise.all([ + this.page.waitForURL(`${config.url}/dashboard`), + this.continue.click(), + ]) + await expect(this.lock).toBeVisible() + } +} diff --git a/packages/e2e/webwallet/src/page-objects/Navigation.ts b/packages/e2e/webwallet/src/page-objects/Navigation.ts new file mode 100644 index 000000000..3937ea355 --- /dev/null +++ b/packages/e2e/webwallet/src/page-objects/Navigation.ts @@ -0,0 +1,40 @@ +import type { Page } from "@playwright/test" + +export default class Navigation { + page: Page + constructor(page: Page) { + this.page = page + } + + get continue() { + return this.page.locator(`button:text-is("Continue")`) + } + + get assets() { + return this.page.getByRole("link", { name: "Assets" }) + } + + get addFunds() { + return this.page.getByRole("link", { name: "Add funds" }) + } + + get send() { + return this.page.getByRole("link", { name: "Send" }) + } + + get authorizedDapps() { + return this.page.getByRole("link", { name: "Authorized dapps" }) + } + + get changePassword() { + return this.page.getByRole("link", { name: "Change password" }) + } + + get lock() { + return this.page.getByRole("heading", { name: "Lock" }) + } + + get switchTheme() { + return this.page.getByRole("button", { name: "Switch theme" }) + } +} diff --git a/packages/e2e/webwallet/src/page-objects/WebWalletPage.ts b/packages/e2e/webwallet/src/page-objects/WebWalletPage.ts new file mode 100644 index 000000000..3ddf03b3b --- /dev/null +++ b/packages/e2e/webwallet/src/page-objects/WebWalletPage.ts @@ -0,0 +1,21 @@ +import type { Page } from "@playwright/test" + +import config from "../config" +import Login from "./Login" +import Navigation from "./Navigation" + +export default class WebWalletPage { + page: Page + login: Login + navigation: Navigation + + constructor(page: Page) { + this.page = page + this.login = new Login(page) + this.navigation = new Navigation(page) + } + + open() { + return this.page.goto(config.url) + } +} diff --git a/packages/e2e/webwallet/src/specs/login.spec.ts b/packages/e2e/webwallet/src/specs/login.spec.ts new file mode 100644 index 000000000..d994d05a9 --- /dev/null +++ b/packages/e2e/webwallet/src/specs/login.spec.ts @@ -0,0 +1,18 @@ +import { expect } from "@playwright/test" + +import config from "../config" +import test from "../test" + +test.describe(`Login page`, () => { + test.skip("can log in", async ({ webWallet }) => { + await webWallet.login.success() + }) + + test.skip("wrong password", async ({ webWallet }) => { + await webWallet.login.email.fill(config.validLogin.email) + await webWallet.login.fillPin(config.validLogin.pin) + await webWallet.login.password.fill("VeryFake123!") + await webWallet.login.continue.click() + await expect(webWallet.login.wrongPassword).toBeVisible() + }) +}) diff --git a/packages/e2e/webwallet/src/test.ts b/packages/e2e/webwallet/src/test.ts new file mode 100644 index 000000000..b6753f254 --- /dev/null +++ b/packages/e2e/webwallet/src/test.ts @@ -0,0 +1,135 @@ +import * as fs from "fs" +import path from "path" + +import { Browser, Page, TestInfo, test as testBase } from "@playwright/test" + +import config from "./config" +import { TestPages } from "./fixtures" +import WebWalletPage from "./page-objects/WebWalletPage" + +const keepArtifacts = async (testInfo: TestInfo, page: Page) => { + if ( + testInfo.config.preserveOutput === "always" || + (testInfo.config.preserveOutput === "failures-only" && + testInfo.status !== "passed") + ) { + //save HTML + const folder = testInfo.title.replace(/\s+/g, "_").replace(/\W/g, "") + const filename = `${testInfo.retry}-${testInfo.status}-${pageId}-${testInfo.workerIndex}.html` + try { + const htmlContent = await page.content() + await fs.promises + .mkdir(path.resolve(config.artifactsDir, folder), { recursive: true }) + .catch((error) => { + console.error(error) + }) + await fs.promises + .writeFile( + path.resolve(config.artifactsDir, folder, filename), + htmlContent, + ) + .catch((error) => { + console.error(error) + }) + } catch (error) { + console.error("Error while saving HTML content", error) + } + } +} +let pageId = 0 + +async function createContext({ + browser, + baseURL, + name, + testInfo, +}: { + browser: Browser + baseURL: string + name: string + testInfo: TestInfo +}) { + const context = await browser.newContext({ + ignoreHTTPSErrors: true, + acceptDownloads: true, + recordVideo: process.env.CI + ? { + dir: config.artifactsDir, + size: { + width: 1366, + height: 768, + }, + } + : undefined, + baseURL, + viewport: { width: 1366, height: 768 }, + }) + context.on("page", async (page) => { + page.on("load", async (page) => { + try { + await page.title() + } catch (err) { + console.warn(err) + } + }) + + page.on("close", async (page) => { + if ( + testInfo.config.preserveOutput === "always" || + (testInfo.config.preserveOutput === "failures-only" && + testInfo.status === "failed") || + testInfo.status === "timedOut" + ) { + const folder = testInfo.title.replace(/\s+/g, "_").replace(/\W/g, "") + const filename = `${testInfo.retry}-${name}-${ + testInfo.status + }-${pageId++}-${testInfo.workerIndex}.webm` + + await page + .video() + ?.saveAs(path.resolve(config.artifactsDir, folder, filename)) + .catch((error) => { + console.error(error) + }) + } + page + .video() + ?.delete() + .catch((error) => { + console.error(error) + }) + }) + }) + + await context.addInitScript("window.PLAYWRIGHT = true;") + return context +} + +function createPage() { + return async ( + { browser }: { browser: Browser }, + use: any, + testInfo: TestInfo, + ) => { + const url = config.url + + const context = await createContext({ + browser, + testInfo, + name: "WebWallet", + baseURL: url, + }) + const page = await context.newPage() + + const webWalletPage = new WebWalletPage(page) + await webWalletPage.open() + await keepArtifacts(testInfo, page) + await use(webWalletPage) + await context.close() + } +} +const test = testBase.extend({ + webWallet: createPage(), +}) + +export default test diff --git a/packages/eslint-plugin-local/.eslintrc.js b/packages/eslint-plugin-local/.eslintrc.js new file mode 100644 index 000000000..acb0897e1 --- /dev/null +++ b/packages/eslint-plugin-local/.eslintrc.js @@ -0,0 +1,31 @@ +module.exports = { + env: { + node: true, + }, + extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"], + parser: "@typescript-eslint/parser", + parserOptions: { + ecmaVersion: "latest", + sourceType: "module", + project: "./tsconfig.json", + tsconfigRootDir: __dirname, + }, + ignorePatterns: ["**/dist/**", "**/node_modules/**"], + plugins: ["@typescript-eslint"], + rules: { + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-extra-semi": "off", + "@typescript-eslint/no-unused-vars": [ + "warn", + { + vars: "all", + ignoreRestSiblings: true, + argsIgnorePattern: "^_", + }, + ], + "@typescript-eslint/no-non-null-assertion": "error", + curly: "error", + "@typescript-eslint/no-misused-promises": "warn", + "@typescript-eslint/no-floating-promises": "warn", + }, +} diff --git a/packages/eslint-plugin-local/package.json b/packages/eslint-plugin-local/package.json new file mode 100644 index 000000000..ff1f0077a --- /dev/null +++ b/packages/eslint-plugin-local/package.json @@ -0,0 +1,24 @@ +{ + "name": "@argent/eslint-plugin-local", + "version": "6.3.1", + "license": "MIT", + "private": true, + "files": [ + "dist" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "devDependencies": { + "@types/eslint": "^8.7.0", + "@typescript-eslint/experimental-utils": "^5.59.7", + "eslint": "^8.7.0", + "minimatch": "^9.0.1", + "typescript": "^5.0.4" + }, + "scripts": { + "dev": "tsc --build --watch", + "build": "tsc --build", + "lint": "eslint . --cache --ext .ts", + "setup": "yarn build" + } +} diff --git a/packages/eslint-plugin-local/src/code-import-patterns.ts b/packages/eslint-plugin-local/src/code-import-patterns.ts new file mode 100644 index 000000000..fb31562ad --- /dev/null +++ b/packages/eslint-plugin-local/src/code-import-patterns.ts @@ -0,0 +1,91 @@ +import * as path from "path" + +import type { TSESTree } from "@typescript-eslint/experimental-utils" +import * as eslint from "eslint" +import { minimatch } from "minimatch" + +const REPO_ROOT = path.resolve(__dirname, "../../../") + +interface Option { + target: string + disallow: string[] + message?: string +} + +/** + * eslint rule to check imports are allowed against specific patterns + * + * @example + * ```json + * "local/code-import-patterns": [ + * "warn", + * { + * target: "packages/extension/src/ui/**", + * disallow: ["packages/extension/src/background/**"], + * message: "import background from ui is disallowed", + * }, + * ] + * ``` + */ + +const rule: eslint.Rule.RuleModule = { + meta: { + type: "problem", + messages: { + badImport: "{{message}}", + }, + docs: { + description: "Disallow imports e.g. UI code from background process", + recommended: true, + }, + }, + + create: (context) => { + const options: Option[] = context.options + const relativeFilename = path.relative(REPO_ROOT, context.getFilename()) + + for (const option of options) { + if (minimatch(relativeFilename, option.target)) { + return { + ImportDeclaration: (declarationNode) => { + const node = (declarationNode).source + if (node.type === "Literal" && typeof node.value === "string") { + checkImport(context, option, node) + } + }, + } + } + } + + return {} + }, +} + +function checkImport( + context: eslint.Rule.RuleContext, + option: Option, + node: TSESTree.StringLiteral, +) { + const importPath = node.value + const sourceFileBase = path.dirname(context.getFilename()) + const fullImportPath = path.resolve(sourceFileBase, importPath) + const rootBasedImportPath = path.relative(REPO_ROOT, fullImportPath) + + for (const pattern of option.disallow) { + if (minimatch(rootBasedImportPath, pattern)) { + const defaultMessage = `import ${option.disallow.join(" or ")} from ${ + option.target + } is disallowed` + context.report({ + loc: node.loc, + messageId: "badImport", + data: { + message: option.message || defaultMessage, + }, + }) + return + } + } +} + +export default rule diff --git a/packages/eslint-plugin-local/src/index.ts b/packages/eslint-plugin-local/src/index.ts new file mode 100644 index 000000000..ec2af33a6 --- /dev/null +++ b/packages/eslint-plugin-local/src/index.ts @@ -0,0 +1,5 @@ +import codeImportPatterns from "./code-import-patterns" + +exports.rules = { + "code-import-patterns": codeImportPatterns, +} diff --git a/packages/eslint-plugin-local/tsconfig.json b/packages/eslint-plugin-local/tsconfig.json new file mode 100644 index 000000000..4a755d8d6 --- /dev/null +++ b/packages/eslint-plugin-local/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "ts-node/node16/tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "declaration": true + }, + "include": ["src", ".eslintrc.js"] +} diff --git a/packages/extension/.env.example b/packages/extension/.env.example index 04c5ff7d3..4c1143a7e 100644 --- a/packages/extension/.env.example +++ b/packages/extension/.env.example @@ -2,8 +2,8 @@ SEGMENT_WRITE_KEY= SENTRY_AUTH_TOKEN= RAMP_API_KEY= ARGENT_API_BASE_URL= -ARGENT_TRANSACTION_REVIEW_API_BASE_URL= ARGENT_X_STATUS_URL= +ARGENT_X_ENVIRONMENT= # difference between commented and not commented variables is that the release CI will throw when a not commented env var is missing # this is used to ensure the ci release has everything we expect it to have without doing explicit testing of the result @@ -12,10 +12,16 @@ ARGENT_X_STATUS_URL= #FEATURE_BANXA= #FEATURE_LAYERSWAP= #FEATURE_PRIVACY_SETTINGS= -#ARGENT_EXPLORER_BASE_URL= #FEATURE_EXPERIMENTAL_SETTINGS= -#FEATURE_ARGENT_SHIELD= +#FEATURE_BETA_FEATURES= #ARGENT_SHIELD_NETWORK_ID= #FEATURE_VERIFIED_DAPPS= #FEATURE_MULTISIG= -#ARGENT_MULTISIG_BASE_URL= +#FEATURE_NEW_SEND= +#MULTICALL_MAX_BATCH_SIZE= +#FEATURE_HIDE_DEPRECATED_ACCOUNTS= + +FAST=20 +MEDIUM=60 +SLOW=60*5 +VERY_SLOW=24*60*60 \ No newline at end of file diff --git a/packages/extension/.eslintrc.base.js b/packages/extension/.eslintrc.base.js new file mode 100644 index 000000000..00d27c22c --- /dev/null +++ b/packages/extension/.eslintrc.base.js @@ -0,0 +1,55 @@ +module.exports = { + settings: { + react: { + version: "detect", + }, + }, + env: { + browser: true, + es2021: true, + node: true, + }, + extends: [ + "eslint:recommended", + "plugin:react/recommended", + "plugin:@typescript-eslint/recommended", + ], + parser: "@typescript-eslint/parser", + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + ecmaVersion: "latest", + sourceType: "module", + project: "./tsconfig.json", + tsconfigRootDir: __dirname, + }, + ignorePatterns: [ + ".eslintrc.base.js", + "**/dist/**", + "**/node_modules/**", + "vite.config.ts", + "webpack.config.js", + ], + plugins: ["react", "react-hooks", "@typescript-eslint"], + rules: { + "react/jsx-no-target-blank": "off", + "react/react-in-jsx-scope": "off", + "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks + "react-hooks/exhaustive-deps": "warn", // Checks effect dependencies + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-extra-semi": "off", + "@typescript-eslint/no-unused-vars": [ + "warn", + { + vars: "all", + ignoreRestSiblings: true, + argsIgnorePattern: "^_", + }, + ], + "@typescript-eslint/no-non-null-assertion": "error", + curly: "error", + "@typescript-eslint/no-misused-promises": "warn", + "@typescript-eslint/no-floating-promises": "warn", + }, +} diff --git a/packages/extension/.eslintrc.js b/packages/extension/.eslintrc.js index ff07fe963..5d148b59f 100644 --- a/packages/extension/.eslintrc.js +++ b/packages/extension/.eslintrc.js @@ -1,53 +1,7 @@ module.exports = { - settings: { - react: { - version: "detect", - }, - }, - env: { - browser: true, - es2021: true, - node: true, - }, - extends: [ - "eslint:recommended", - "plugin:react/recommended", - "plugin:@typescript-eslint/recommended", - ], - parser: "@typescript-eslint/parser", - parserOptions: { - ecmaFeatures: { - jsx: true, - }, - ecmaVersion: "latest", - sourceType: "module", - project: "./tsconfig.json", - tsconfigRootDir: __dirname, - }, - ignorePatterns: [ - "**/dist/**", - "**/node_modules/**", - "vite.config.ts", - "webpack.config.js", - ], - plugins: ["react", "react-hooks", "@typescript-eslint"], + extends: [".eslintrc.base.js", "prettier"], + plugins: ["@argent/eslint-plugin-local"], rules: { - "react/jsx-no-target-blank": "off", - "react/react-in-jsx-scope": "off", - "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks - "react-hooks/exhaustive-deps": "warn", // Checks effect dependencies - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-extra-semi": "off", - "@typescript-eslint/no-unused-vars": [ - "warn", - { - vars: "all", - ignoreRestSiblings: true, - argsIgnorePattern: "^_", - }, - ], - "@typescript-eslint/no-non-null-assertion": "error", - curly: "error", "@typescript-eslint/no-restricted-imports": [ "error", { @@ -60,7 +14,26 @@ module.exports = { ], }, ], - "@typescript-eslint/no-misused-promises": "warn", - "@typescript-eslint/no-floating-promises": "warn", + "@argent/local/code-import-patterns": [ + "warn", + { + target: "packages/extension/src/ui/**", + disallow: ["packages/extension/src/background/**"], + message: "import background from ui is disallowed", + }, + { + target: "packages/extension/src/background/**", + disallow: ["packages/extension/src/ui/**"], + message: "import ui from background is disallowed", + }, + { + target: "packages/extension/src/shared/**", + disallow: [ + "packages/extension/src/ui/**", + "packages/extension/src/background/**", + ], + message: "import ui or background from shared is disallowed", + }, + ], }, } diff --git a/packages/extension/.vscode/settings.json b/packages/extension/.vscode/settings.json new file mode 100644 index 000000000..cc43ff1bb --- /dev/null +++ b/packages/extension/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "json.schemaDownload.enable": true, + "typescript.tsdk": "../../node_modules/typescript/lib" +} diff --git a/packages/extension/CHANGELOG.md b/packages/extension/CHANGELOG.md new file mode 100644 index 000000000..91d0af921 --- /dev/null +++ b/packages/extension/CHANGELOG.md @@ -0,0 +1,152 @@ +# @argent-x/extension + +## 6.9.0 + +### Minor Changes + +- 281140dc5: Release + +### Patch Changes + +- Updated dependencies [5cfc58de7] + - @argent/x-multicall@6.4.1 + +## 6.8.6 + +### Minor Changes + +- a636b7a9b: Release + +## 6.8.5 + +### Patch Changes + +- 4cd0c97de: hotfix + +## 6.8.4 + +### Patch Changes + +- e9cad5187: laggy ui hotfix + +## 6.8.3 + +### Patch Changes + +- 965162852: hotfix network view + +## 6.8.2 + +### Patch Changes + +- 9c26e2df8: hotfix network update + +## 6.8.1 + +### Patch Changes + +- 833909902: Release + +## 6.8.0 + +### Minor Changes + +- 5cfe05efd: Release + +## 6.7.4 + +### Patch Changes + +- eaf315917: hotfix reenabling tx v0 + +## 6.7.3 + +### Patch Changes + +- 52b514811: Release + +## 6.7.2 + +### Patch Changes + +- 8e3690df8: Release + +## 6.7.1 + +### Patch Changes + +- 3bc9cc325: Release + +## 6.7.0 + +### Minor Changes + +- 66aca3030: Release + +## 6.6.1 + +### Patch Changes + +- 9a9f6467c: hotfix unlock + +## 6.6.0 + +### Minor Changes + +- cd61ea2e1: Release + +## 6.5.0 + +### Minor Changes + +- 3fb3228f5: Hotfix Firefox Extension + +## 6.4.7 + +### Patch Changes + +- 6c016a06e: bump extension to trigger npm packages release + +## 6.4.6 + +### Patch Changes + +- e7699b475: Fix darkmode + +## 6.4.5 + +### Patch Changes + +- 6977fa180: release npm packages +- Updated dependencies [712829411] + - @argent/shared@6.3.3 + +## 6.4.4 + +### Patch Changes + +- 93ae3ba6e: hotfix extension + +## 6.4.3 + +### Patch Changes + +- 3dbcf15cc: hotfix release + +## 6.4.2 + +### Patch Changes + +- d8c50c78a: extension hotfix + +## 6.4.1 + +### Patch Changes + +- 1c6a83c03: Hotfix release for recovery issues + +## 6.4.0 + +### Minor Changes + +- 6c7115e7: Trigger extension release diff --git a/packages/extension/manifest/v2.json b/packages/extension/manifest/v2.json index 78d56a968..bde8b036d 100644 --- a/packages/extension/manifest/v2.json +++ b/packages/extension/manifest/v2.json @@ -2,7 +2,7 @@ "$schema": "https://json.schemastore.org/chrome-manifest.json", "name": "Argent X", "description": "The security of Ethereum with the scale of StarkNet", - "version": "5.4.0", + "version": "5.9.0", "manifest_version": 2, "browser_action": { "default_icon": { diff --git a/packages/extension/manifest/v3.json b/packages/extension/manifest/v3.json index 8091866fb..3e636a09a 100644 --- a/packages/extension/manifest/v3.json +++ b/packages/extension/manifest/v3.json @@ -2,7 +2,7 @@ "$schema": "https://json.schemastore.org/chrome-manifest.json", "name": "Argent X", "description": "The security of Ethereum with the scale of StarkNet", - "version": "5.4.0", + "version": "5.9.0", "manifest_version": 3, "action": { "default_icon": { diff --git a/packages/extension/package.json b/packages/extension/package.json index 62b81e668..0a2d980ca 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -1,16 +1,17 @@ { "name": "@argent-x/extension", - "version": "6.3.0", + "version": "6.9.0", "main": "index.js", "private": true, "license": "MIT", "devDependencies": { - "@sentry/webpack-plugin": "^1.18.9", - "@svgr/webpack": "^6.0.0", - "@testing-library/jest-dom": "^5.16.5", + "@argent/eslint-plugin-local": "^6.3.0", + "@svgr/webpack": "^8.0.1", + "@testing-library/jest-dom": "^6.0.0", "@testing-library/react": "^14.0.0", "@types/async-retry": "^1.4.5", - "@types/chrome": "^0.0.218", + "@types/chrome": "^0.0.246", + "@types/fs-extra": "^11.0.1", "@types/lodash-es": "^4.17.6", "@types/object-hash": "^3.0.2", "@types/react": "^18.0.0", @@ -21,67 +22,66 @@ "@types/styled-components": "^5.1.25", "@types/url-join": "^4.0.1", "@types/ws": "^8.5.3", - "@typescript-eslint/eslint-plugin": "^5.10.1", - "@typescript-eslint/parser": "^5.10.1", - "@vitejs/plugin-react": "^3.0.0", - "@vitest/coverage-istanbul": "^0.31.0", + "@typescript-eslint/eslint-plugin": "^6.0.0", + "@typescript-eslint/parser": "^6.0.0", + "@vitejs/plugin-react-swc": "^3.3.1", + "@vitest/coverage-istanbul": "^0.34.0", + "@vitest/coverage-v8": "^0.34.0", "chokidar": "^3.5.2", - "concurrently": "^7.2.2", + "concurrently": "^8.0.1", "copy-webpack-plugin": "^11.0.0", - "cross-fetch": "^3.1.5", + "cross-fetch": "^4.0.0", + "dotenv": "^16.1.4", "dotenv-webpack": "^8.0.0", - "esbuild-loader": "^3.0.1", + "esbuild-loader": "^4.0.0", "eslint": "^8.7.0", "eslint-plugin-react": "^7.28.0", "eslint-plugin-react-hooks": "^4.6.0", - "eslint-webpack-plugin": "^4.0.0", "fetch-intercept": "^2.4.0", "file-loader": "^6.2.0", "fork-ts-checker-webpack-plugin": "^8.0.0", + "fs-extra": "^11.1.1", + "happy-dom": "^12.0.0", "html-webpack-plugin": "^5.5.0", "isomorphic-fetch": "^3.0.0", "jsdom": "^22.0.0", - "mitt": "^3.0.0", + "minimatch": "^9.0.1", "msw": "^1.0.0", "raw-loader": "^4.0.2", - "type-fest": "^3.9.0", - "typescript": "^4.9.4", + "ts-node": "^10.9.1", + "type-fest": "^4.0.0", + "typescript": "^5.0.4", "typescript-styled-plugin": "^0.18.2", "url-loader": "^4.1.1", - "vite": "^4.0.3", - "vitest": "^0.29.2", + "vite": "^4.3.8", + "vitest": "^0.33.0", "wait-for-expect": "^3.0.2", - "webpack": "^5.62.1", - "webpack-cli": "^5.0.1", + "webpack": "^5.88.0", + "webpack-cli": "^5.1.1", "ws": "^8.8.1" }, "scripts": { "build": "NODE_ENV=production webpack", - "build:sourcemaps": "GEN_SOURCE_MAPS=true yarn build", + "build:sourcemaps": "GEN_SOURCE_MAPS=true pnpm build", "start": "webpack", - "dev": "concurrently -k -r \"webpack --color --watch\" \"yarn dev:hot-reload-server\"", - "dev:ui": "SHOW_DEV_UI=true yarn dev", + "dev": "concurrently -k -r \"webpack --color --watch\" \"pnpm run dev:hot-reload-server\"", + "dev:ui": "SHOW_DEV_UI=true pnpm dev", "dev:hot-reload-server": "ts-node ./scripts/hot-reload-server.ts", "lint": "eslint . --cache --ext .ts,.tsx", "test": "vitest run", "test:watch": "vitest", "test:ci": "vitest run --coverage", - "version": "yarn run change-to-release-branch && yarn run commit-and-tag-version-changes && yarn run push-release-branch", - "change-to-release-branch": "git checkout -b release/v$npm_package_version", - "sync-manifest-version": "concurrently \"yarn sync-manifest-version:v2\" \"yarn sync-manifest-version:v3\"", - "sync-manifest-version:v2": "node -p \"JSON.stringify({...require('./manifest/v2.json'), version: '$npm_package_version'}, null, 2)\" > ./manifest/v2.temp.json && prettier --write ./manifest/v2.temp.json && mv ./manifest/v2.temp.json ./manifest/v2.json", - "sync-manifest-version:v3": "node -p \"JSON.stringify({...require('./manifest/v3.json'), version: '$npm_package_version'}, null, 2)\" > ./manifest/v3.temp.json && prettier --write ./manifest/v3.temp.json && mv ./manifest/v3.temp.json ./manifest/v3.json", - "commit-and-tag-version-changes": "git add --update && git commit -m v$npm_package_version && git tag -a v$npm_package_version -m \"v$npm_package_version\"", - "push-release-branch": "git push --set-upstream origin release/v$npm_package_version --follow-tags" + "export": "ts-node ./scripts/export.ts" }, "dependencies": { - "@argent/guardian": "^6.3.0", - "@argent/stack-router": "^6.3.0", - "@argent/ui": "^6.3.0", - "@argent/x-multicall": "^6.3.0", - "@argent/x-sessions": "^6.3.0", - "@argent/x-swap": "^6.3.0", - "@argent/x-window": "^6.3.0", + "@argent/guardian": "^6.3.1", + "@argent/shared": "^6.3.3", + "@argent/stack-router": "^6.3.1", + "@argent/ui": "^6.3.1", + "@argent/x-multicall": "^6.4.1", + "@argent/x-sessions": "^6.3.1", + "@argent/x-swap": "^6.3.1", + "@argent/x-window": "^6.3.1", "@chakra-ui/icons": "^2.0.15", "@chakra-ui/react": "^2.6.1", "@extend-chrome/messages": "^1.2.2", @@ -90,46 +90,49 @@ "@mui/icons-material": "^5.3.1", "@mui/material": "^5.1.0", "@mui/styled-engine-sc": "^5.10.3", - "@noble/hashes": "^1.1.3", - "@scure/bip39": "^1.2.0", + "@noble/curves": "^1.0.0", + "@noble/hashes": "^1.3.1", + "@scure/bip32": "^1.3.1", + "@scure/bip39": "^1.2.1", "@sentry/react": "^7.6.0", "@sentry/tracing": "^7.6.0", "@tippyjs/react": "^4.2.6", - "@trpc/client": "^10.20.0", - "@trpc/server": "^10.20.0", - "@vitest/coverage-istanbul": "^0.31.0", + "@trpc/client": "^10.28.0", + "@trpc/server": "^10.31.0", + "@vitest/coverage-istanbul": "^0.34.0", "async-retry": "^1.3.3", - "bignumber.js": "^9.0.2", "buffer": "^6.0.3", - "colord": "^2.9.2", + "colord": "^2.9.3", "dexie": "^3.2.2", "dexie-react-hooks": "^1.1.1", + "emittery": "^1.0.1", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.0", "ethers": "^5.5.1", "jose": "^4.3.6", "jotai": "^2.0.4", "lodash-es": "^4.17.21", "micro-starknet": "^0.2.3", - "nanoid": "^4.0.0", + "nanoid": "^5.0.0", "object-hash": "^3.0.0", "qr-code-styling": "^1.6.0-rc.1", "react": "^18.0.0", "react-copy-to-clipboard": "^5.0.4", "react-dom": "^18.0.0", "react-dropzone": "^14.0.0", - "react-hook-form": "^7.33.0", + "react-hook-form": "^7.44.2", "react-measure": "^2.5.2", "react-router-dom": "^6.0.1", "react-select": "^5.4.0", "react-textarea-autosize": "^8.3.4", - "semver": "^7.3.7", - "starknet": "^4.21.0", - "starknet3": "npm:starknet@3.18.2", - "starknet4": "npm:starknet@4.4.0", - "starknet5": "npm:starknet@5.7.0", + "semver": "^7.5.2", + "starknet": "5.18.0", + "starknet4": "npm:starknet@4.22.0", + "starknet4-deprecated": "npm:starknet@4.4.0", "styled-components": "^5.3.5", "styled-normalize": "^8.0.7", "swr": "^1.3.0", - "trpc-extension": "^1.1.0", + "trpc-browser": "^1.3.1", "url-join": "^5.0.0", "webextension-polyfill": "^0.10.0", "yup": "^1.0.0-beta.4", diff --git a/packages/extension/scripts/export.ts b/packages/extension/scripts/export.ts new file mode 100644 index 000000000..35df97c5c --- /dev/null +++ b/packages/extension/scripts/export.ts @@ -0,0 +1,110 @@ +import fs from "fs-extra" +import { minimatch } from "minimatch" +import path from "path" +import dotenv from "dotenv" +import childProcess from "child_process" + +const readme = `> This repo has been exported and configured to allow building from source without access to the main git repo + +Install \`pnpm\` - see https://pnpm.io/installation + +\`\`\`bash +pnpm run setup # setup dependencies +pnpm build # run build process for all packages +\`\`\` +` + +const manifestVersion = getManifestVersion() + +const source = path.resolve(__dirname, "../../..") +const destination = path.resolve( + source, + `../argent-x-exported-v${manifestVersion}`, +) + +const dotenvSource = path.resolve(__dirname, "../.env") +const dotenvDestination = path.resolve(destination, "packages/extension/.env") + +const readmeDestination = path.resolve(destination, "Readme.md") + +const exclude = [ + ".git**", + "**/.next", + "**/.env", + "**/dist**", + "**/.eslintcache", + "**.log**", + "**/node_modules**", + "packages/dapp**", + "packages/get-starknet**", + "packages/starknet-react-webwallet-connector**", + "packages/web**", +] + +function getCommitHash() { + const hash = childProcess.execSync("git rev-parse HEAD") + return hash.toString().trim() +} + +function getManifestVersion() { + const pkgRaw = fs.readFileSync( + path.resolve(__dirname, "../manifest/v2.json"), + "utf8", + ) + const pkg = JSON.parse(pkgRaw) + return pkg.version +} + +async function preflightCheck() { + console.log("🚨 CHECK: is the source .env file configured for production?") + console.log(` ${dotenvSource}\n`) + const dotEnvRaw = await fs.readFile(dotenvSource, "utf-8") + const dotEnvParsed = dotenv.parse(dotEnvRaw) + if (dotEnvParsed.ARGENT_X_ENVIRONMENT !== "prod") { + console.log( + `.env error - expected ARGENT_X_ENVIRONMENT to be "prod" but got "${dotEnvParsed.ARGENT_X_ENVIRONMENT}"`, + ) + process.exit(1) + } +} + +async function exportFiles() { + await fs.emptyDir(destination) + await fs.copy(source, destination, { + filter: (path) => { + const repoPath = path.substring(source.length + 1) + if (!repoPath.length) { + return true + } + const match = exclude.some((pattern) => minimatch(repoPath, pattern)) + return !match + }, + }) +} + +async function exportEnv() { + const dotEnvRaw = await fs.readFile(dotenvSource, "utf-8") + const filteredComments = dotEnvRaw.replace(/^#.*\n?/gm, "") + const filteredEmpty = filteredComments.replace(/\n+/gm, "\n") + const commitHash = getCommitHash() + const withCommitHash = `${filteredEmpty}\nCOMMIT_HASH_OVERRIDE=${commitHash}\n` + await fs.writeFile(dotenvDestination, withCommitHash) + console.log("👀 CHECK: Exported .env:\n") + console.log(withCommitHash) +} + +async function exportReadme() { + await fs.writeFile(readmeDestination, readme) +} + +async function exportForEndUserBuild() { + await preflightCheck() + await exportFiles() + await exportReadme() + await exportEnv() + console.log("✅ Buildable source and Readme exported to", destination) +} + +;(async () => { + await exportForEndUserBuild() +})() diff --git a/packages/extension/src/assets/default-tokens.json b/packages/extension/src/assets/default-tokens.json index 8c50ef6c2..ffaab4bc9 100644 --- a/packages/extension/src/assets/default-tokens.json +++ b/packages/extension/src/assets/default-tokens.json @@ -5,7 +5,7 @@ "symbol": "ETH", "decimals": "18", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", "showAlways": true }, { @@ -14,7 +14,7 @@ "symbol": "ETH", "decimals": "18", "network": "goerli-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", "showAlways": true }, { @@ -23,16 +23,7 @@ "symbol": "ETH", "decimals": "18", "network": "integration", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", - "showAlways": true - }, - { - "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", - "name": "Ether", - "symbol": "ETH", - "decimals": "18", - "network": "goerli-alpha-2", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", "showAlways": true }, { @@ -41,7 +32,7 @@ "symbol": "ETH", "decimals": "18", "network": "localhost", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/eth.png", "showAlways": true }, { @@ -50,7 +41,7 @@ "symbol": "DAI", "decimals": "18", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/dai.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/dai.png" }, { "address": "0x03e85bfbb8e2a42b7bead9e88e9a1b19dbccf661471061807292120462396ec9", @@ -58,7 +49,7 @@ "symbol": "DAI", "decimals": "18", "network": "goerli-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/dai.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/dai.png" }, { "address": "0x03fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac", @@ -66,7 +57,7 @@ "symbol": "WBTC", "decimals": "8", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/wbtc.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/wbtc.png" }, { "address": "0x12d537dc323c439dc65c976fad242d5610d27cfb5f31689a0a319b8be7f3d56", @@ -74,7 +65,7 @@ "symbol": "WBTC", "decimals": "8", "network": "goerli-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/wbtc.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/wbtc.png" }, { "address": "0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8", @@ -82,7 +73,7 @@ "symbol": "USDC", "decimals": "6", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdc.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdc.png" }, { "address": "0x005a643907b9a4bc6a55e9069c4fd5fd1f5c79a22470690f75556c4736e34426", @@ -90,7 +81,7 @@ "symbol": "USDC", "decimals": "6", "network": "goerli-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdc.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdc.png" }, { "address": "0x068f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8", @@ -98,7 +89,7 @@ "symbol": "USDT", "decimals": "6", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdt.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdt.png" }, { "address": "0x386e8d061177f19b3b485c20e31137e6f6bc497cc635ccdfcab96fadf5add6a", @@ -106,35 +97,30 @@ "symbol": "USDT", "decimals": "6", "network": "goerli-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdt.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/usdt.png" }, { - "address": "0x07394cbe418daa16e42b87ba67372d4ab4a5df0b05c6e554d158458ce245bc10", - "name": "Test Token", - "symbol": "TEST", + "address": "0x0148f970a06fc95ee0682140e23a980351be8fad26168c5f0465e63940c46514", + "name": "Angle agEUR", + "symbol": "agEUR", "decimals": "18", - "network": "goerli-alpha" + "network": "mainnet-alpha", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/ageur.png" }, { - "address": "0x06a09ccb1caaecf3d9683efe335a667b2169a409d19c589ba1eb771cd210af75", - "name": "Test Token", - "symbol": "TEST", + "address": "0x05ef98e7dc5865f49bcec200df508d27669b3ef7f9d2439decd127350359f291", + "name": "Wrapped Lido ETH", + "symbol": "wstETH", "decimals": "18", - "network": "mainnet-alpha" - }, - { - "address": "0x07a39a50bf689e9430fc81fba0f4d46e245e1657e77455548ed7e32c808cfc10", - "name": "SelfService", - "symbol": "SLF", - "decimals": "6", - "network": "goerli-alpha" + "network": "mainnet-alpha", + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/steth.png" }, { - "address": "0x0148f970a06fc95ee0682140e23a980351be8fad26168c5f0465e63940c46514", - "name": "Angle agEUR", - "symbol": "agEUR", + "address": "0x0319111a5037cbec2b3e638cc34a3474e2d2608299f3e62866e9cc683208c610", + "name": "Rocket Pool ETH", + "symbol": "rETH", "decimals": "18", "network": "mainnet-alpha", - "image": "https://dv3jj1unlp2jl.cloudfront.net/128/color/ageur.png" + "iconUrl": "https://dv3jj1unlp2jl.cloudfront.net/128/color/reth.png" } ] diff --git a/packages/extension/src/background/__new/procedures/account/create.ts b/packages/extension/src/background/__new/procedures/account/create.ts index e07f32aac..bd2084c5e 100644 --- a/packages/extension/src/background/__new/procedures/account/create.ts +++ b/packages/extension/src/background/__new/procedures/account/create.ts @@ -9,7 +9,11 @@ import { extensionOnlyProcedure } from "../permissions" const createAccountInputSchema = z.object({ networkId: z.string(), - type: z.union([z.literal("standard"), z.literal("multisig")]), + type: z.union([ + z.literal("standard"), + z.literal("multisig"), + z.literal("standardCairo0"), + ]), }) export const createAccountProcedure = extensionOnlyProcedure diff --git a/packages/extension/src/background/__new/procedures/account/deploy.ts b/packages/extension/src/background/__new/procedures/account/deploy.ts index 7d3609bcf..55bfdffa6 100644 --- a/packages/extension/src/background/__new/procedures/account/deploy.ts +++ b/packages/extension/src/background/__new/procedures/account/deploy.ts @@ -6,9 +6,16 @@ import { extensionOnlyProcedure } from "../permissions" export const deployAccountProcedure = extensionOnlyProcedure .use(openSessionMiddleware) .input(baseWalletAccountSchema) - .mutation(async ({ input: data, ctx: { services } }) => { - await deployAccountAction({ - account: data, - actionQueue: services.actionQueue, - }) - }) + .mutation( + async ({ + input, + ctx: { + services: { actionService }, + }, + }) => { + await deployAccountAction({ + account: input, + actionService, + }) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/account/index.ts b/packages/extension/src/background/__new/procedures/account/index.ts index cae8998de..9f6044d1b 100644 --- a/packages/extension/src/background/__new/procedures/account/index.ts +++ b/packages/extension/src/background/__new/procedures/account/index.ts @@ -1,10 +1,12 @@ import { router } from "../../trpc" import { createAccountProcedure } from "./create" import { deployAccountProcedure } from "./deploy" +import { selectAccountProcedure } from "./select" import { upgradeAccountProcedure } from "./upgrade" export const accountRouter = router({ create: createAccountProcedure, deploy: deployAccountProcedure, upgrade: upgradeAccountProcedure, + select: selectAccountProcedure, }) diff --git a/packages/extension/src/background/__new/procedures/account/select.ts b/packages/extension/src/background/__new/procedures/account/select.ts new file mode 100644 index 000000000..1722317f3 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/account/select.ts @@ -0,0 +1,21 @@ +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { respond } from "../../../respond" + +export const selectAccountProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(baseWalletAccountSchema.nullable()) + .mutation( + async ({ + input: baseWalletAccount, + ctx: { + services: { wallet }, + }, + }) => { + const account = await wallet.selectAccount(baseWalletAccount) + if (account) { + void respond({ type: "CONNECT_ACCOUNT_RES", data: account }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/account/upgrade.ts b/packages/extension/src/background/__new/procedures/account/upgrade.ts index a656e2acc..da9f7ec67 100644 --- a/packages/extension/src/background/__new/procedures/account/upgrade.ts +++ b/packages/extension/src/background/__new/procedures/account/upgrade.ts @@ -19,15 +19,15 @@ export const upgradeAccountProcedure = extensionOnlyProcedure async ({ input: { account, targetImplementationType }, ctx: { - services: { wallet, actionQueue }, + services: { wallet, actionService }, }, }) => { // TODO ⬇ should be a service await upgradeAccount({ account, wallet, + actionService, targetImplementationType, - actionQueue, }) }, ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/cancelEscape.ts b/packages/extension/src/background/__new/procedures/accountMessaging/cancelEscape.ts new file mode 100644 index 000000000..3a4d371f6 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/cancelEscape.ts @@ -0,0 +1,55 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { Account } from "starknet" +import { getEntryPointSafe } from "../../../../shared/utils/transactions" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" + +const cancelEscapeSchema = z.object({ + account: baseWalletAccountSchema, +}) + +export const cancelEscapeProcedure = extensionOnlyProcedure + .input(cancelEscapeSchema) + .mutation( + async ({ + input: { account }, + ctx: { + services: { actionService, wallet }, + }, + }) => { + try { + const starknetAccount = + (await wallet.getSelectedStarknetAccount()) as Account + await actionService.add( + { + type: "TRANSACTION", + payload: { + transactions: { + contractAddress: account.address, + entrypoint: getEntryPointSafe( + "cancelEscape", + starknetAccount.cairoVersion, + ), + calldata: [], + }, + meta: { + isCancelEscape: true, + title: "Cancel escape", + type: "INVOKE", + }, + }, + }, + { + origin, + }, + ) + } catch (error) { + throw new AccountMessagingError({ + options: { error }, + code: "ESCAPE_CANCELLATION_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/changeGuardian.ts b/packages/extension/src/background/__new/procedures/accountMessaging/changeGuardian.ts new file mode 100644 index 000000000..dd8915d38 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/changeGuardian.ts @@ -0,0 +1,61 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { constants, num, Account } from "starknet" +import { getEntryPointSafe } from "../../../../shared/utils/transactions" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" + +const changeGuardianSchema = z.object({ + guardian: z.string(), + account: baseWalletAccountSchema, +}) + +export const changeGuardianProcedure = extensionOnlyProcedure + .input(changeGuardianSchema) + .mutation( + async ({ + input: { account, guardian }, + ctx: { + services: { actionService, wallet }, + }, + }) => { + try { + const newGuardian = num.hexToDecimalString(guardian) + const starknetAccount = + (await wallet.getSelectedStarknetAccount()) as Account // Old accounts are not supported + + await actionService.add( + { + type: "TRANSACTION", + payload: { + transactions: { + contractAddress: account.address, + entrypoint: getEntryPointSafe( + "changeGuardian", + starknetAccount.cairoVersion, + ), + calldata: [newGuardian], + }, + meta: { + isChangeGuardian: true, + title: "Change account guardian", + type: + num.toBigInt(newGuardian) === constants.ZERO // if guardian is 0, it's a remove guardian action + ? "REMOVE_ARGENT_SHIELD" + : "ADD_ARGENT_SHIELD", + }, + }, + }, + { + origin, + }, + ) + } catch (error) { + throw new AccountMessagingError({ + options: { error }, + code: "CHANGE_GUARDIAN_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/escapeAndChangeGuardian.ts b/packages/extension/src/background/__new/procedures/accountMessaging/escapeAndChangeGuardian.ts new file mode 100644 index 000000000..54d76ff48 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/escapeAndChangeGuardian.ts @@ -0,0 +1,110 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { isEqualAddress } from "../../../../ui/services/addresses" +import { constants, num, Account } from "starknet" +import { getEntryPointSafe } from "../../../../shared/utils/transactions" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" +import { AccountError } from "../../../../shared/errors/account" + +const escapeAndChangeGuardianSchema = z.object({ + account: baseWalletAccountSchema, +}) + +export const escapeAndChangeGuardianProcedure = extensionOnlyProcedure + .input(escapeAndChangeGuardianSchema) + .mutation( + async ({ + input: { account }, + ctx: { + services: { actionService, wallet }, + }, + }) => { + try { + /** + * This is a two-stage process + * + * 1. call escapeGuardian with current signer key as new guardian key + * 2. changeGuardian to ZERO, signed twice by same signer key (like 2/2 multisig with same key) + */ + + const selectedAccount = await wallet.getAccount(account) + const starknetAccount = + (await wallet.getSelectedStarknetAccount()) as Account // Old accounts are not supported + + if (!selectedAccount) { + throw new AccountError({ + code: "NOT_FOUND", + }) + } + + const { publicKey } = await wallet.getPublicKey(account) + + if ( + selectedAccount.guardian && + isEqualAddress(selectedAccount.guardian, publicKey) + ) { + /** + * Account already used `escapeGuardian` to change guardian to this account publicKey + * Call `changeGuardian` to ZERO + */ + + await actionService.add( + { + type: "TRANSACTION", + payload: { + transactions: { + contractAddress: account.address, + entrypoint: getEntryPointSafe( + "changeGuardian", + starknetAccount.cairoVersion, + ), + calldata: [num.hexToDecimalString(constants.ZERO.toString())], + }, + meta: { + isChangeGuardian: true, + title: "Change account guardian", + type: "INVOKE", + }, + }, + }, + { + origin, + }, + ) + } else { + /** + * Call `escapeGuardian` to change guardian to this account publicKey + */ + await actionService.add( + { + type: "TRANSACTION", + payload: { + transactions: { + contractAddress: account.address, + entrypoint: "escapeGuardian", + calldata: [num.hexToDecimalString(publicKey)], + }, + meta: { + isChangeGuardian: true, + title: "Escape account guardian", + type: "INVOKE", + }, + }, + }, + { + origin, + }, + ) + } + } catch (error) { + throw new AccountMessagingError({ + options: { + error, + }, + code: "ESCAPE_AND_CHANGE_GUARDIAN_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedPrivateKey.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedPrivateKey.ts new file mode 100644 index 000000000..9e10ab0e9 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedPrivateKey.ts @@ -0,0 +1,42 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { encryptForUi } from "../../../crypto" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" +import { SessionError } from "../../../../shared/errors/session" + +const getEncryptedPrivateKeySchema = z.object({ + encryptedSecret: z.string(), + account: baseWalletAccountSchema, +}) + +export const getEncryptedPrivateKeyProcedure = extensionOnlyProcedure + .input(getEncryptedPrivateKeySchema) + .output(z.string()) + .mutation( + async ({ + input: { account, encryptedSecret }, + ctx: { + services: { wallet, messagingKeys }, + }, + }) => { + if (!(await wallet.isSessionOpen())) { + throw new SessionError({ + code: "NO_OPEN_SESSION", + }) + } + try { + return await encryptForUi( + await wallet.getPrivateKey(account), + encryptedSecret, + messagingKeys.privateKey, + ) + } catch (e) { + throw new AccountMessagingError({ + options: { error: e }, + code: "GET_ENCRYPTED_KEY_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedSeedPhrase.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedSeedPhrase.ts new file mode 100644 index 000000000..16b8e40fd --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/getEncryptedSeedPhrase.ts @@ -0,0 +1,41 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { encryptForUi } from "../../../crypto" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" +import { SessionError } from "../../../../shared/errors/session" + +const getEncryptedSeedPhraseSchema = z.object({ + encryptedSecret: z.string(), +}) + +export const getEncryptedSeedPhraseProcedure = extensionOnlyProcedure + .input(getEncryptedSeedPhraseSchema) + .output(z.string()) + .mutation( + async ({ + input: { encryptedSecret }, + ctx: { + services: { wallet, messagingKeys }, + }, + }) => { + if (!(await wallet.isSessionOpen())) { + throw new SessionError({ + code: "NO_OPEN_SESSION", + }) + } + + try { + return await encryptForUi( + await wallet.getSeedPhrase(), + encryptedSecret, + messagingKeys.privateKey, + ) + } catch (e) { + throw new AccountMessagingError({ + options: { error: e }, + code: "GET_SEEDPHRASE_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKey.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKey.ts new file mode 100644 index 000000000..e69de29bb diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKeyForMultisig.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKeyForMultisig.ts new file mode 100644 index 000000000..b0efb4bbe --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/getNextPublicKeyForMultisig.ts @@ -0,0 +1,31 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { PubKeyError } from "../../../../shared/errors/pubKey" + +const getNextPublicKeyForMultisigSchema = z.object({ + networkId: z.string(), +}) + +export const getNextPublicKeyForMultisigProcedure = extensionOnlyProcedure + .input(getNextPublicKeyForMultisigSchema) + .output(z.string()) + .mutation( + async ({ + input: { networkId }, + ctx: { + services: { wallet }, + }, + }) => { + try { + const { publicKey } = await wallet.getNextPublicKeyForMultisig( + networkId, + ) + return publicKey + } catch (error) { + throw new PubKeyError({ + code: "FAILED_NEXT_PUB_KEY_GENERATION", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKey.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKey.ts new file mode 100644 index 000000000..2d0d94cae --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKey.ts @@ -0,0 +1,31 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" + +const getPublicKeySchema = z.object({ + account: z.optional(baseWalletAccountSchema), +}) + +export const getPublicKeyProcedure = extensionOnlyProcedure + .input(getPublicKeySchema) + .output(z.string()) + .query( + async ({ + input: { account }, + ctx: { + services: { wallet }, + }, + }) => { + try { + const { publicKey } = await wallet.getPublicKey(account) + return publicKey + } catch (error) { + throw new AccountMessagingError({ + options: { error }, + code: "GET_PUBLIC_KEY_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKeysBufferForMultisig.ts b/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKeysBufferForMultisig.ts new file mode 100644 index 000000000..2f6da5b9c --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/getPublicKeysBufferForMultisig.ts @@ -0,0 +1,33 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { PubKeyError } from "../../../../shared/errors/pubKey" + +const getPublicKeysBufferForMultisigSchema = z.object({ + start: z.number(), + buffer: z.number(), +}) + +export const getPublicKeysBufferForMultisigProcedure = extensionOnlyProcedure + .input(getPublicKeysBufferForMultisigSchema) + .output(z.array(z.string())) + .query( + async ({ + input: { start, buffer }, + ctx: { + services: { wallet }, + }, + }) => { + try { + const pubKeys = await wallet.getPublicKeysBufferForMultisig( + start, + buffer, + ) + return pubKeys + } catch (error) { + throw new PubKeyError({ + code: "FAILED_BUFFER_GENERATION", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/index.ts b/packages/extension/src/background/__new/procedures/accountMessaging/index.ts new file mode 100644 index 000000000..7d0906624 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/index.ts @@ -0,0 +1,22 @@ +import { router } from "../../trpc" +import { getEncryptedPrivateKeyProcedure } from "./getEncryptedPrivateKey" +import { getEncryptedSeedPhraseProcedure } from "./getEncryptedSeedPhrase" +import { changeGuardianProcedure } from "./changeGuardian" +import { cancelEscapeProcedure } from "./cancelEscape" +import { triggerEscapeGuardianProcedure } from "./triggerEscapeGuardian" +import { escapeAndChangeGuardianProcedure } from "./escapeAndChangeGuardian" +import { getPublicKeyProcedure } from "./getPublicKey" +import { getNextPublicKeyForMultisigProcedure } from "./getNextPublicKeyForMultisig" +import { getPublicKeysBufferForMultisigProcedure } from "./getPublicKeysBufferForMultisig" + +export const accountMessagingRouter = router({ + getEncryptedPrivateKey: getEncryptedPrivateKeyProcedure, + getEncryptedSeedPhrase: getEncryptedSeedPhraseProcedure, + changeGuardian: changeGuardianProcedure, + cancelEscape: cancelEscapeProcedure, + triggerEscapeGuardian: triggerEscapeGuardianProcedure, + escapeAndChangeGuardian: escapeAndChangeGuardianProcedure, + getPublicKey: getPublicKeyProcedure, + getNextPublicKeyForMultisig: getNextPublicKeyForMultisigProcedure, + getPublicKeysBufferForMultisig: getPublicKeysBufferForMultisigProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/accountMessaging/triggerEscapeGuardian.ts b/packages/extension/src/background/__new/procedures/accountMessaging/triggerEscapeGuardian.ts new file mode 100644 index 000000000..3b2574a4d --- /dev/null +++ b/packages/extension/src/background/__new/procedures/accountMessaging/triggerEscapeGuardian.ts @@ -0,0 +1,48 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" +import { AccountMessagingError } from "../../../../shared/errors/accountMessaging" + +const triggerEscapeGuardianSchema = z.object({ + account: baseWalletAccountSchema, +}) + +export const triggerEscapeGuardianProcedure = extensionOnlyProcedure + .input(triggerEscapeGuardianSchema) + .mutation( + async ({ + input: { account }, + ctx: { + services: { actionService }, + }, + }) => { + try { + await actionService.add( + { + type: "TRANSACTION", + payload: { + transactions: { + contractAddress: account.address, + entrypoint: "triggerEscapeGuardian", + calldata: [], + }, + meta: { + isCancelEscape: true, + title: "Trigger escape guardian", + type: "INVOKE", + }, + }, + }, + { + origin, + }, + ) + } catch (error) { + throw new AccountMessagingError({ + options: { error }, + code: "TRIGGER_ESCAPE_FAILED", + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/action/approve.ts b/packages/extension/src/background/__new/procedures/action/approve.ts new file mode 100644 index 000000000..bc4a3068e --- /dev/null +++ b/packages/extension/src/background/__new/procedures/action/approve.ts @@ -0,0 +1,18 @@ +import { z } from "zod" + +import { + actionHashSchema, + actionQueueItemSchema, +} from "../../../../shared/actionQueue/schema" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const approveActionSchema = z.union([actionQueueItemSchema, actionHashSchema]) + +export const approveActionProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(approveActionSchema) + .mutation(async ({ input, ctx: { services } }) => { + const { actionService } = services + return actionService.approve(input) + }) diff --git a/packages/extension/src/background/__new/procedures/action/approveAndWait.ts b/packages/extension/src/background/__new/procedures/action/approveAndWait.ts new file mode 100644 index 000000000..84719a495 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/action/approveAndWait.ts @@ -0,0 +1,18 @@ +import { z } from "zod" + +import { + actionHashSchema, + actionQueueItemSchema, +} from "../../../../shared/actionQueue/schema" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const approveActionSchema = z.union([actionQueueItemSchema, actionHashSchema]) + +export const approveAndWaitActionProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(approveActionSchema) + .mutation(async ({ input, ctx: { services } }) => { + const { actionService } = services + return actionService.approveAndWait(input) + }) diff --git a/packages/extension/src/background/__new/procedures/action/index.ts b/packages/extension/src/background/__new/procedures/action/index.ts new file mode 100644 index 000000000..3a3deca7a --- /dev/null +++ b/packages/extension/src/background/__new/procedures/action/index.ts @@ -0,0 +1,12 @@ +import { router } from "../../trpc" +import { approveActionProcedure } from "./approve" +import { approveAndWaitActionProcedure } from "./approveAndWait" +import { rejectActionProcedure } from "./reject" +import { rejectAllActionsProcedure } from "./rejectAll" + +export const actionRouter = router({ + approve: approveActionProcedure, + approveAndWait: approveAndWaitActionProcedure, + reject: rejectActionProcedure, + rejectAll: rejectAllActionsProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/action/reject.ts b/packages/extension/src/background/__new/procedures/action/reject.ts new file mode 100644 index 000000000..4d8fa6b6f --- /dev/null +++ b/packages/extension/src/background/__new/procedures/action/reject.ts @@ -0,0 +1,18 @@ +import { z } from "zod" + +import { actionHashSchema } from "../../../../shared/actionQueue/schema" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const rejectActionSchema = z.union([ + actionHashSchema, + z.array(actionHashSchema), +]) + +export const rejectActionProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(rejectActionSchema) + .mutation(async ({ input, ctx: { services } }) => { + const { actionService } = services + return actionService.reject(input) + }) diff --git a/packages/extension/src/background/__new/procedures/action/rejectAll.ts b/packages/extension/src/background/__new/procedures/action/rejectAll.ts new file mode 100644 index 000000000..546fa2bf8 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/action/rejectAll.ts @@ -0,0 +1,9 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const rejectAllActionsProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .mutation(async ({ ctx: { services } }) => { + const { actionService } = services + return actionService.rejectAll() + }) diff --git a/packages/extension/src/background/__new/procedures/addressBook/add.ts b/packages/extension/src/background/__new/procedures/addressBook/add.ts new file mode 100644 index 000000000..314360d95 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/addressBook/add.ts @@ -0,0 +1,17 @@ +import { z } from "zod" + +import { + addressBookContactNoIdSchema, + addressBookContactSchema, +} from "../../../../shared/addressBook/schema" +import { addressBookService } from "../../../../shared/addressBook/service" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const addAddressBookContactProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(z.union([addressBookContactNoIdSchema, addressBookContactSchema])) + .output(addressBookContactSchema) + .mutation(async ({ input }) => { + return addressBookService.add(input) + }) diff --git a/packages/extension/src/background/__new/procedures/addressBook/index.ts b/packages/extension/src/background/__new/procedures/addressBook/index.ts new file mode 100644 index 000000000..b55204376 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/addressBook/index.ts @@ -0,0 +1,10 @@ +import { router } from "../../trpc" +import { addAddressBookContactProcedure } from "./add" +import { removeAddressBookContactProcedure } from "./remove" +import { updateAddressBookContactProcedure } from "./update" + +export const addressBookRouter = router({ + add: addAddressBookContactProcedure, + update: updateAddressBookContactProcedure, + remove: removeAddressBookContactProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/addressBook/remove.ts b/packages/extension/src/background/__new/procedures/addressBook/remove.ts new file mode 100644 index 000000000..b25922c3d --- /dev/null +++ b/packages/extension/src/background/__new/procedures/addressBook/remove.ts @@ -0,0 +1,12 @@ +import { addressBookContactSchema } from "../../../../shared/addressBook/schema" +import { addressBookService } from "../../../../shared/addressBook/service" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const removeAddressBookContactProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addressBookContactSchema) + .output(addressBookContactSchema) + .mutation(async ({ input }) => { + return addressBookService.remove(input) + }) diff --git a/packages/extension/src/background/__new/procedures/addressBook/update.ts b/packages/extension/src/background/__new/procedures/addressBook/update.ts new file mode 100644 index 000000000..e5c570756 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/addressBook/update.ts @@ -0,0 +1,12 @@ +import { addressBookContactSchema } from "../../../../shared/addressBook/schema" +import { addressBookService } from "../../../../shared/addressBook/service" +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const updateAddressBookContactProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addressBookContactSchema) + .output(addressBookContactSchema) + .mutation(async ({ input }) => { + return addressBookService.update(input) + }) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/addAccount.ts b/packages/extension/src/background/__new/procedures/argentAccount/addAccount.ts new file mode 100644 index 000000000..742cc0122 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/addAccount.ts @@ -0,0 +1,17 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const addAccountProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .output(z.string()) + .mutation( + async ({ + ctx: { + services: { argentAccountService }, + }, + }) => { + return await argentAccountService.addAccount() + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/confirmEmail.ts b/packages/extension/src/background/__new/procedures/argentAccount/confirmEmail.ts new file mode 100644 index 000000000..260e442d1 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/confirmEmail.ts @@ -0,0 +1,22 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const confirmEmailSchema = z.object({ + code: z.string(), +}) + +export const confirmEmailProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(confirmEmailSchema) + .mutation( + async ({ + input: { code }, + ctx: { + services: { argentAccountService }, + }, + }) => { + return await argentAccountService.confirmEmail(code) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/getPreferences.ts b/packages/extension/src/background/__new/procedures/argentAccount/getPreferences.ts new file mode 100644 index 000000000..ff8102594 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/getPreferences.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { preferencesEndpointPayload } from "./updatePreferences.model" + +export const getPreferencesProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .output(preferencesEndpointPayload.optional()) + .query( + async ({ + ctx: { + services: { argentAccountService }, + }, + }) => { + const response = await argentAccountService.getPreferences() + return response + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/index.ts b/packages/extension/src/background/__new/procedures/argentAccount/index.ts new file mode 100644 index 000000000..b0e8c851e --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/index.ts @@ -0,0 +1,20 @@ +import { router } from "../../trpc" +import { addAccountProcedure } from "./addAccount" +import { requestEmailProcedure } from "./requestEmail" +import { confirmEmailProcedure } from "./confirmEmail" +import { validateAccountProcedure } from "./validateAccount" +import { isTokenExpiredProcedure } from "./isTokenExpired" +import { logoutProcedure } from "./logout" +import { updatePreferencesProcedure } from "./updatePreferences" +import { getPreferencesProcedure } from "./getPreferences" + +export const argentAccountRouter = router({ + addAccount: addAccountProcedure, + validateAccount: validateAccountProcedure, + requestEmail: requestEmailProcedure, + confirmEmail: confirmEmailProcedure, + isTokenExpired: isTokenExpiredProcedure, + logout: logoutProcedure, + updatePreferences: updatePreferencesProcedure, + getPreferences: getPreferencesProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/isTokenExpired.ts b/packages/extension/src/background/__new/procedures/argentAccount/isTokenExpired.ts new file mode 100644 index 000000000..7798ca1b3 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/isTokenExpired.ts @@ -0,0 +1,17 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const isTokenExpiredProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .output(z.boolean()) + .query( + async ({ + ctx: { + services: { argentAccountService }, + }, + }) => { + return await argentAccountService.isTokenExpired() + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/logout.ts b/packages/extension/src/background/__new/procedures/argentAccount/logout.ts new file mode 100644 index 000000000..e55a59a5f --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/logout.ts @@ -0,0 +1,14 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { resetDevice } from "../../../../shared/shield/jwt" + +export const logoutProcedure = extensionOnlyProcedure + .output(z.void()) + .mutation(async () => { + try { + await resetDevice() + } catch (error) { + throw new Error("Error while logging out", { cause: error }) + } + }) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/requestEmail.ts b/packages/extension/src/background/__new/procedures/argentAccount/requestEmail.ts new file mode 100644 index 000000000..a3ca64135 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/requestEmail.ts @@ -0,0 +1,22 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const requestEmailSchema = z.object({ + email: z.string(), +}) + +export const requestEmailProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(requestEmailSchema) + .mutation( + async ({ + input: { email }, + ctx: { + services: { argentAccountService }, + }, + }) => { + return await argentAccountService.requestEmail(email) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.model.ts b/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.model.ts new file mode 100644 index 000000000..be639cae1 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.model.ts @@ -0,0 +1,14 @@ +import { z } from "zod" + +export const preferencesSchema = z.object({ + value: z.string(), + platform: z.enum(["ios", "argentx", "android"]).nullable(), +}) + +export type Preferences = z.infer + +export const preferencesEndpointPayload = z.object({ + preferences: z.record(preferencesSchema), +}) + +export type PreferencesPayload = z.infer diff --git a/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.ts b/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.ts new file mode 100644 index 000000000..51d961106 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/updatePreferences.ts @@ -0,0 +1,19 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { preferencesEndpointPayload } from "./updatePreferences.model" + +export const updatePreferencesProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(preferencesEndpointPayload) + .output(preferencesEndpointPayload.optional()) + .mutation( + async ({ + input: data, + ctx: { + services: { argentAccountService }, + }, + }) => { + const response = await argentAccountService.updatePreferences(data) + return response + }, + ) diff --git a/packages/extension/src/background/__new/procedures/argentAccount/validateAccount.ts b/packages/extension/src/background/__new/procedures/argentAccount/validateAccount.ts new file mode 100644 index 000000000..ae5f3ab16 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/argentAccount/validateAccount.ts @@ -0,0 +1,14 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +export const validateAccountProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .mutation( + async ({ + ctx: { + services: { argentAccountService }, + }, + }) => { + return await argentAccountService.validateAccount() + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/addAccount.ts b/packages/extension/src/background/__new/procedures/multisig/addAccount.ts new file mode 100644 index 000000000..205f08b08 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/addAccount.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { addAccountSchema } from "../../../../shared/multisig/multisig.model" + +export const addAccountProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addAccountSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.addAccount(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/addOwner.ts b/packages/extension/src/background/__new/procedures/multisig/addOwner.ts new file mode 100644 index 000000000..23d877ed8 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/addOwner.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { addOwnerMultisigSchema } from "../../../../shared/multisig/multisig.model" + +export const addOwnerProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addOwnerMultisigSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.addOwner(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/addPendingAccount.ts b/packages/extension/src/background/__new/procedures/multisig/addPendingAccount.ts new file mode 100644 index 000000000..f94a253dd --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/addPendingAccount.ts @@ -0,0 +1,22 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const addPendingAccountSchema = z.object({ + networkId: z.string(), +}) + +export const addPendingAccountProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addPendingAccountSchema) + .mutation( + async ({ + input: { networkId }, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.addPendingAccount(networkId) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/addTransactionSignature.ts b/packages/extension/src/background/__new/procedures/multisig/addTransactionSignature.ts new file mode 100644 index 000000000..5f917c13a --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/addTransactionSignature.ts @@ -0,0 +1,22 @@ +import { z } from "zod" + +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" + +const addTransactionSignatureSchema = z.object({ + requestId: z.string(), +}) + +export const addTransactionSignatureProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(addTransactionSignatureSchema) + .mutation( + async ({ + input: { requestId }, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.addTransactionSignature(requestId) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/deploy.ts b/packages/extension/src/background/__new/procedures/multisig/deploy.ts new file mode 100644 index 000000000..5775481f8 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/deploy.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { baseWalletAccountSchema } from "../../../../shared/wallet.model" + +export const deployProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(baseWalletAccountSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.deploy(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/index.ts b/packages/extension/src/background/__new/procedures/multisig/index.ts new file mode 100644 index 000000000..12761464f --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/index.ts @@ -0,0 +1,20 @@ +import { router } from "../../trpc" +import { addAccountProcedure } from "./addAccount" +import { addOwnerProcedure } from "./addOwner" +import { removeOwnerProcedure } from "./removeOwner" +import { updateThresholdProcedure } from "./updateThreshold" +import { deployProcedure } from "./deploy" +import { addPendingAccountProcedure } from "./addPendingAccount" +import { addTransactionSignatureProcedure } from "./addTransactionSignature" +import { replaceOwnerProcedure } from "./replaceOwner" + +export const multisigRouter = router({ + addAccount: addAccountProcedure, + addPendingAccount: addPendingAccountProcedure, + addOwner: addOwnerProcedure, + removeOwner: removeOwnerProcedure, + replaceOwner: replaceOwnerProcedure, + updateThreshold: updateThresholdProcedure, + deploy: deployProcedure, + addTransactionSignature: addTransactionSignatureProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/multisig/removeOwner.ts b/packages/extension/src/background/__new/procedures/multisig/removeOwner.ts new file mode 100644 index 000000000..8c2f29881 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/removeOwner.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { removeOwnerMultisigSchema } from "../../../../shared/multisig/multisig.model" + +export const removeOwnerProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(removeOwnerMultisigSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.removeOwner(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/replaceOwner.ts b/packages/extension/src/background/__new/procedures/multisig/replaceOwner.ts new file mode 100644 index 000000000..52744e297 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/replaceOwner.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { replaceOwnerMultisigSchema } from "../../../../shared/multisig/multisig.model" + +export const replaceOwnerProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(replaceOwnerMultisigSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.replaceOwner(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/multisig/updateThreshold.ts b/packages/extension/src/background/__new/procedures/multisig/updateThreshold.ts new file mode 100644 index 000000000..9a4e5a505 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/multisig/updateThreshold.ts @@ -0,0 +1,17 @@ +import { openSessionMiddleware } from "../../middleware/session" +import { extensionOnlyProcedure } from "../permissions" +import { updateMultisigThresholdSchema } from "../../../../shared/multisig/multisig.model" + +export const updateThresholdProcedure = extensionOnlyProcedure + .use(openSessionMiddleware) + .input(updateMultisigThresholdSchema) + .mutation( + async ({ + input, + ctx: { + services: { multisigService }, + }, + }) => { + return await multisigService.updateThreshold(input) + }, + ) diff --git a/packages/extension/src/background/__new/procedures/network/add.ts b/packages/extension/src/background/__new/procedures/network/add.ts deleted file mode 100644 index e8a845c67..000000000 --- a/packages/extension/src/background/__new/procedures/network/add.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { addNetwork, networkSchema } from "../../../../shared/network" -import { openSessionMiddleware } from "../../middleware/session" -import { extensionOnlyProcedure } from "../permissions" - -export const addNetworkProcedure = extensionOnlyProcedure - .use(openSessionMiddleware) - .input(networkSchema) - .mutation(async ({ input }) => { - await addNetwork(input) - return true - }) diff --git a/packages/extension/src/background/__new/procedures/network/index.ts b/packages/extension/src/background/__new/procedures/network/index.ts deleted file mode 100644 index 84b83e578..000000000 --- a/packages/extension/src/background/__new/procedures/network/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { router } from "../../trpc" -import { addNetworkProcedure } from "./add" - -export const networkRouter = router({ - add: addNetworkProcedure, -}) diff --git a/packages/extension/src/background/__new/procedures/recovery/recoverSeedphrase.ts b/packages/extension/src/background/__new/procedures/recovery/recoverSeedphrase.ts index 07da90069..be27d8031 100644 --- a/packages/extension/src/background/__new/procedures/recovery/recoverSeedphrase.ts +++ b/packages/extension/src/background/__new/procedures/recovery/recoverSeedphrase.ts @@ -1,7 +1,6 @@ import { compactDecrypt } from "jose" import { z } from "zod" -import { accountService } from "../../../../shared/account/service" import { bytesToUft8 } from "../../../../shared/utils/encode" import { getMessagingKeys } from "../../../keys/messagingKeys" import { extensionOnlyProcedure } from "../permissions" @@ -10,12 +9,8 @@ const recoverSeedphraseSchema = z.object({ jwe: z.string(), }) -const recoverSeedphraseResponseSchema = z.object({ - isSuccess: z.boolean(), -}) export const recoverSeedphraseProcedure = extensionOnlyProcedure .input(recoverSeedphraseSchema) - .output(recoverSeedphraseResponseSchema) .mutation( async ({ input: { jwe }, @@ -35,7 +30,7 @@ export const recoverSeedphraseProcedure = extensionOnlyProcedure } = JSON.parse(bytesToUft8(plaintext)) await wallet.restoreSeedPhrase(seedPhrase, newPassword) - void transactionTracker.loadHistory(await accountService.get()) + void transactionTracker.loadHistory() return { isSuccess: true } }, ) diff --git a/packages/extension/src/background/__new/procedures/session/checkPassword.ts b/packages/extension/src/background/__new/procedures/session/checkPassword.ts new file mode 100644 index 000000000..8fec02090 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/session/checkPassword.ts @@ -0,0 +1,36 @@ +import { z } from "zod" +import { extensionOnlyProcedure } from "../permissions" +import { compactDecrypt } from "jose" +import { BUGGY_bytesToUft8 } from "../../../../shared/utils/encode" +import { SessionError } from "../../../../shared/errors/session" + +const checkPasswordSchema = z.string() + +export const checkPasswordProcedure = extensionOnlyProcedure + .input(checkPasswordSchema) + .output(z.boolean()) + .mutation( + async ({ + input: encryptedPassword, + ctx: { + services: { wallet, messagingKeys }, + }, + }) => { + try { + const { plaintext } = await compactDecrypt( + encryptedPassword, + messagingKeys.privateKey, + ) + const password = BUGGY_bytesToUft8(plaintext) + if (await wallet.checkPassword(password)) { + return true + } + return false + } catch (error) { + throw new SessionError({ + code: "PASSWORD_CHECK_FAILED", + options: { error }, + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/session/index.ts b/packages/extension/src/background/__new/procedures/session/index.ts new file mode 100644 index 000000000..22280991c --- /dev/null +++ b/packages/extension/src/background/__new/procedures/session/index.ts @@ -0,0 +1,12 @@ +import { router } from "../../trpc" +import { checkPasswordProcedure } from "./checkPassword" +import { isPasswordSetProcedure } from "./isPasswordSet" +import { startProcedure } from "./start" +import { stopProcedure } from "./stop" + +export const sessionRouter = router({ + start: startProcedure, + stop: stopProcedure, + checkPassword: checkPasswordProcedure, + isPasswordSet: isPasswordSetProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/session/isPasswordSet.ts b/packages/extension/src/background/__new/procedures/session/isPasswordSet.ts new file mode 100644 index 000000000..fe1a62f91 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/session/isPasswordSet.ts @@ -0,0 +1,14 @@ +import { z } from "zod" +import { extensionOnlyProcedure } from "../permissions" + +export const isPasswordSetProcedure = extensionOnlyProcedure + .output(z.boolean()) + .query( + async ({ + ctx: { + services: { wallet }, + }, + }) => { + return wallet.isSessionOpen() + }, + ) diff --git a/packages/extension/src/background/__new/procedures/session/start.ts b/packages/extension/src/background/__new/procedures/session/start.ts new file mode 100644 index 000000000..a1736a00e --- /dev/null +++ b/packages/extension/src/background/__new/procedures/session/start.ts @@ -0,0 +1,73 @@ +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" +import { compactDecrypt } from "jose" +import { BUGGY_bytesToUft8, bytesToUft8 } from "../../../../shared/utils/encode" +import { respond } from "../../../respond" +import { walletAccountSchema } from "../../../../shared/wallet.model" +import { SessionError } from "../../../../shared/errors/session" + +const startSchema = z.string() + +export const startProcedure = extensionOnlyProcedure + .input(startSchema) + .output(walletAccountSchema.optional()) + .mutation( + async ({ + input: encryptedPassword, + ctx: { + services: { wallet, messagingKeys }, + }, + }) => { + try { + const { plaintext } = await compactDecrypt( + encryptedPassword, + messagingKeys.privateKey, + ) + + const [BUGGY_sessionPassword, sessionPassword] = [ + BUGGY_bytesToUft8(plaintext), + bytesToUft8(plaintext), + ] + + const progressCallback = (percent: number) => + void respond({ type: "LOADING_PROGRESS", data: percent }) + + try { + // Check for the buggy bytesToUtf8 first because most users will have the buggy version. + const result = await wallet.startSession( + BUGGY_sessionPassword, + progressCallback, + ) + + if (!result) { + throw new SessionError({ + code: "START_SESSION_FAILED_BUGGY", + }) + } + } catch (error) { + // For users who have superscript characters in their password, the buggy version of bytesToUtf8 will fail. + // That's why we try the correct version here. + const result = await wallet.startSession( + sessionPassword, + progressCallback, + ) + + if (!result) { + throw new SessionError({ + code: "START_SESSION_FAILED", + options: { error }, + }) + } + } + + const selectedAccount = await wallet.getSelectedAccount() + return selectedAccount + } catch (error) { + throw new SessionError({ + code: "START_SESSION_FAILED", + options: { error }, + }) + } + }, + ) diff --git a/packages/extension/src/background/__new/procedures/session/stop.ts b/packages/extension/src/background/__new/procedures/session/stop.ts new file mode 100644 index 000000000..38ee0814e --- /dev/null +++ b/packages/extension/src/background/__new/procedures/session/stop.ts @@ -0,0 +1,13 @@ +import { extensionOnlyProcedure } from "../permissions" +import { respond } from "../../../respond" + +export const stopProcedure = extensionOnlyProcedure.mutation( + async ({ + ctx: { + services: { wallet }, + }, + }) => { + void wallet.lock() + return respond({ type: "DISCONNECT_ACCOUNT" }) + }, +) diff --git a/packages/extension/src/background/__new/procedures/tokens/addToken.ts b/packages/extension/src/background/__new/procedures/tokens/addToken.ts new file mode 100644 index 000000000..c8e397ff7 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/addToken.ts @@ -0,0 +1,10 @@ +import { extensionOnlyProcedure } from "../permissions" +import { TokenSchema } from "../../../../shared/token/__new/types/token.model" +import { tokenService } from "../../../../shared/token/__new/service" + +export const addTokenProcedure = extensionOnlyProcedure + .input(TokenSchema) + .mutation(async ({ input: token }) => { + // tokens that are added from the UI should always be shown with custom flag, even if the balance is 0 + return await tokenService.addToken({ ...token, custom: true }) + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/fetchAccountBalance.ts b/packages/extension/src/background/__new/procedures/tokens/fetchAccountBalance.ts new file mode 100644 index 000000000..7ed30b4da --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/fetchAccountBalance.ts @@ -0,0 +1,36 @@ +import { addressSchema } from "@argent/shared" +import { z } from "zod" +import { extensionOnlyProcedure } from "../permissions" +import { tokenService } from "../../../../shared/token/__new/service" +import { equalToken } from "../../../../shared/token/__new/utils" +import { TokenError } from "../../../../shared/errors/token" + +const fetchTokenBalanceSchema = z.object({ + tokenAddress: addressSchema, + accountAddress: addressSchema, + networkId: z.string(), +}) + +export const fetchTokenBalanceProcedure = extensionOnlyProcedure + .input(fetchTokenBalanceSchema) + .output(z.string()) + .mutation(async ({ input: { tokenAddress, accountAddress, networkId } }) => { + const account = { address: accountAddress, networkId } + const baseToken = { address: tokenAddress, networkId } + const [token] = await tokenService.getTokens((t) => + equalToken(t, baseToken), + ) + + if (!token) { + throw new TokenError({ + code: "TOKEN_NOT_FOUND", + message: `Token ${tokenAddress} not found`, + }) + } + const [tokenBalance] = await tokenService.fetchTokenBalancesFromOnChain( + account, + token, + ) + + return tokenBalance.balance + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/fetchDetails.ts b/packages/extension/src/background/__new/procedures/tokens/fetchDetails.ts new file mode 100644 index 000000000..b040893a2 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/fetchDetails.ts @@ -0,0 +1,13 @@ +import { extensionOnlyProcedure } from "../permissions" +import { + BaseTokenSchema, + RequestTokenSchema, +} from "../../../../shared/token/__new/types/token.model" +import { tokenService } from "../../../../shared/token/__new/service" + +export const fetchDetailsProcedure = extensionOnlyProcedure + .input(BaseTokenSchema) + .output(RequestTokenSchema) + .query(async ({ input: baseToken }) => { + return await tokenService.fetchTokenDetails(baseToken) + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/getAccountBalance.ts b/packages/extension/src/background/__new/procedures/tokens/getAccountBalance.ts new file mode 100644 index 000000000..d8221f324 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/getAccountBalance.ts @@ -0,0 +1,34 @@ +import { addressSchema } from "@argent/shared" +import { z } from "zod" +import { extensionOnlyProcedure } from "../permissions" +import { tokenService } from "../../../../shared/token/__new/service" +import { equalToken } from "../../../../shared/token/__new/utils" +import { BaseTokenWithBalanceSchema } from "../../../../shared/token/__new/types/tokenBalance.model" +import { TokenError } from "../../../../shared/errors/token" + +const getAccountBalanceSchema = z.object({ + tokenAddress: addressSchema, + accountAddress: addressSchema, + networkId: z.string(), +}) + +export const getAccountBalanceProcedure = extensionOnlyProcedure + .input(getAccountBalanceSchema) + .output(BaseTokenWithBalanceSchema) + .query(async ({ input: { tokenAddress, accountAddress, networkId } }) => { + const [token] = await tokenService.getTokens((t) => + equalToken(t, { address: tokenAddress, networkId }), + ) + if (!token) { + throw new TokenError({ + code: "TOKEN_NOT_FOUND", + message: `Token ${tokenAddress} not found`, + }) + } + const account = { address: accountAddress, networkId } + const [tokenBalance] = await tokenService.getTokenBalancesForAccount( + account, + [token], + ) + return tokenBalance + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/getAllTokenBalances.ts b/packages/extension/src/background/__new/procedures/tokens/getAllTokenBalances.ts new file mode 100644 index 000000000..a327d554e --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/getAllTokenBalances.ts @@ -0,0 +1,30 @@ +import { addressSchema } from "@argent/shared" + +import { z } from "zod" +import { extensionOnlyProcedure } from "../permissions" +import { tokenService } from "../../../../shared/token/__new/service" +import { equalToken } from "../../../../shared/token/__new/utils" +import { BaseTokenWithBalanceSchema } from "../../../../shared/token/__new/types/tokenBalance.model" + +const getAllTokenBalancesSchema = z.object({ + tokenAddresses: z.array(addressSchema), + accountAddress: addressSchema, + networkId: z.string(), +}) + +export const getAllTokenBalancesProcedure = extensionOnlyProcedure + .input(getAllTokenBalancesSchema) + .output(z.array(BaseTokenWithBalanceSchema)) + .query(async ({ input: { tokenAddresses, accountAddress, networkId } }) => { + const tokens = await tokenService.getTokens((t) => + tokenAddresses.some((tokenAddress) => + equalToken(t, { address: tokenAddress, networkId }), + ), + ) + const account = { address: accountAddress, networkId } + const tokenBalances = await tokenService.getTokenBalancesForAccount( + account, + tokens, + ) + return tokenBalances + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/getCurrencyValueForTokens.ts b/packages/extension/src/background/__new/procedures/tokens/getCurrencyValueForTokens.ts new file mode 100644 index 000000000..cd578d6be --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/getCurrencyValueForTokens.ts @@ -0,0 +1,15 @@ +import { z } from "zod" +import { BaseTokenWithBalanceSchema } from "../../../../shared/token/__new/types/tokenBalance.model" +import { TokenWithBalanceAndPriceSchema } from "../../../../shared/token/__new/types/tokenPrice.model" +import { extensionOnlyProcedure } from "../permissions" +import { tokenService } from "../../../../shared/token/__new/service" + +export const getCurrencyValueForTokensProcedure = extensionOnlyProcedure + .input(z.array(BaseTokenWithBalanceSchema)) + .output(z.array(TokenWithBalanceAndPriceSchema)) + .query(async ({ input: tokenWithBalances }) => { + const tokensWithBalancesAndPrice = + await tokenService.getCurrencyValueForTokens(tokenWithBalances) + + return tokensWithBalancesAndPrice + }) diff --git a/packages/extension/src/background/__new/procedures/tokens/index.ts b/packages/extension/src/background/__new/procedures/tokens/index.ts new file mode 100644 index 000000000..a031eb8cf --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/index.ts @@ -0,0 +1,18 @@ +import { router } from "../../trpc" +import { addTokenProcedure } from "./addToken" +import { fetchTokenBalanceProcedure } from "./fetchAccountBalance" +import { fetchDetailsProcedure } from "./fetchDetails" +import { getAccountBalanceProcedure } from "./getAccountBalance" +import { getAllTokenBalancesProcedure } from "./getAllTokenBalances" +import { getCurrencyValueForTokensProcedure } from "./getCurrencyValueForTokens" +import { removeTokenProcedure } from "./removeToken" + +export const tokensRouter = router({ + addToken: addTokenProcedure, + removeToken: removeTokenProcedure, + fetchDetails: fetchDetailsProcedure, + fetchTokenBalance: fetchTokenBalanceProcedure, + getAccountBalance: getAccountBalanceProcedure, + getAllTokenBalances: getAllTokenBalancesProcedure, + getCurrencyValueForTokens: getCurrencyValueForTokensProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/tokens/removeToken.ts b/packages/extension/src/background/__new/procedures/tokens/removeToken.ts new file mode 100644 index 000000000..c704eebdb --- /dev/null +++ b/packages/extension/src/background/__new/procedures/tokens/removeToken.ts @@ -0,0 +1,9 @@ +import { extensionOnlyProcedure } from "../permissions" +import { BaseTokenSchema } from "../../../../shared/token/__new/types/token.model" +import { tokenService } from "../../../../shared/token/__new/service" + +export const removeTokenProcedure = extensionOnlyProcedure + .input(BaseTokenSchema) + .mutation(async ({ input: baseToken }) => { + return await tokenService.removeToken(baseToken) + }) diff --git a/packages/extension/src/background/__new/procedures/transfer/index.ts b/packages/extension/src/background/__new/procedures/transfer/index.ts new file mode 100644 index 000000000..1abeaa62d --- /dev/null +++ b/packages/extension/src/background/__new/procedures/transfer/index.ts @@ -0,0 +1,6 @@ +import { router } from "../../trpc" +import { sendProcedure } from "./send" + +export const transferRouter = router({ + send: sendProcedure, +}) diff --git a/packages/extension/src/background/__new/procedures/transfer/send.ts b/packages/extension/src/background/__new/procedures/transfer/send.ts new file mode 100644 index 000000000..fde4c0854 --- /dev/null +++ b/packages/extension/src/background/__new/procedures/transfer/send.ts @@ -0,0 +1,33 @@ +import { addressSchema } from "@argent/shared" +import { z } from "zod" + +import { extensionOnlyProcedure } from "../permissions" + +const sendSchema = z.object({ + transactions: z.object({ + contractAddress: addressSchema, + entrypoint: z.string(), + calldata: z.string().array(), + }), +}) + +export const sendProcedure = extensionOnlyProcedure + .input(sendSchema) + .output(z.string()) + .mutation( + async ({ + input: { transactions }, + ctx: { + services: { actionService }, + }, + }) => { + const { meta } = await actionService.add({ + type: "TRANSACTION", + payload: { + transactions, + }, + }) + + return meta.hash + }, + ) diff --git a/packages/extension/src/background/__new/procedures/udc/getConstructorParams.ts b/packages/extension/src/background/__new/procedures/udc/getConstructorParams.ts new file mode 100644 index 000000000..d6658071f --- /dev/null +++ b/packages/extension/src/background/__new/procedures/udc/getConstructorParams.ts @@ -0,0 +1,51 @@ +import { LegacyContractClass } from "starknet" +import { z } from "zod" + +import { getProvider } from "../../../../shared/network" +import { networkService } from "../../../../shared/network/service" +import { extensionOnlyProcedure } from "../permissions" +import { UdcError } from "../../../../shared/errors/udc" + +const getConstructorParamsSchema = z.object({ + networkId: z.string(), + classHash: z.string(), +}) + +const basicContractClassSchema = z.object({ + abi: z.array(z.any()), +}) + +export const getConstructorParamsProcedure = extensionOnlyProcedure + .input(getConstructorParamsSchema) + .output( + z.custom((item) => { + return basicContractClassSchema.parse(item) + }), + ) + .query(async ({ input: { networkId, classHash } }) => { + const network = await networkService.getById(networkId) + const provider = getProvider(network) + + try { + if (!("getClassByHash" in provider)) { + throw new UdcError({ + code: "FETCH_CONTRACT_CONTRUCTOR_PARAMS", + }) + } + + const contract = await provider.getClassByHash(classHash) + + if ("sierra_program" in contract) { + throw new UdcError({ + code: "CAIRO_1_NOT_SUPPORTED", + }) + } + + return contract + } catch (error) { + throw new UdcError({ + options: { error }, + code: "FETCH_CONTRACT_CONTRUCTOR_PARAMS", + }) + } + }) diff --git a/packages/extension/src/background/__new/procedures/udc/index.ts b/packages/extension/src/background/__new/procedures/udc/index.ts new file mode 100644 index 000000000..60bd6b88c --- /dev/null +++ b/packages/extension/src/background/__new/procedures/udc/index.ts @@ -0,0 +1,7 @@ +import { router } from "../../trpc" + +import { getConstructorParamsProcedure } from "./getConstructorParams" + +export const udcRouter = router({ + getConstructorParams: getConstructorParamsProcedure, +}) diff --git a/packages/extension/src/background/__new/router.ts b/packages/extension/src/background/__new/router.ts index c81f6bb13..a2507f13e 100644 --- a/packages/extension/src/background/__new/router.ts +++ b/packages/extension/src/background/__new/router.ts @@ -1,19 +1,36 @@ -import { createChromeHandler } from "trpc-extension/adapter" +import { createChromeHandler } from "trpc-browser/adapter" -import { globalActionQueueStore } from "../../shared/actionQueue/store" -import { ActionItem } from "../../shared/actionQueue/types" -import { getQueue } from "../actionQueue" -import { transactionTracker } from "../transactions/tracking" +import { getMessagingKeys } from "../keys/messagingKeys" +import { transactionTrackerWorker } from "../transactions/service/worker" import { walletSingleton } from "../walletSingleton" import { accountRouter } from "./procedures/account" -import { networkRouter } from "./procedures/network" +import { accountMessagingRouter } from "./procedures/accountMessaging" +import { actionRouter } from "./procedures/action" +import { addressBookRouter } from "./procedures/addressBook" +import { argentAccountRouter } from "./procedures/argentAccount" +import { multisigRouter } from "./procedures/multisig" import { recoveryRouter } from "./procedures/recovery" +import { sessionRouter } from "./procedures/session" +import { tokensRouter } from "./procedures/tokens" +import { transferRouter } from "./procedures/transfer" +import { udcRouter } from "./procedures/udc" +import { backgroundActionService } from "./services/action" +import { backgroundArgentAccountService } from "./services/argentAccount" +import { backgroundMultisigService } from "./services/multisig" import { router } from "./trpc" const appRouter = router({ account: accountRouter, - network: networkRouter, + accountMessaging: accountMessagingRouter, + action: actionRouter, + addressBook: addressBookRouter, recovery: recoveryRouter, + tokens: tokensRouter, + transfer: transferRouter, + argentAccount: argentAccountRouter, + multisig: multisigRouter, + session: sessionRouter, + udc: udcRouter, }) export type AppRouter = typeof appRouter @@ -25,8 +42,11 @@ createChromeHandler({ services: { // services can be shared accross requests, as we usually only handle one user at a time wallet: walletSingleton, // wallet "service" is obviously way too big and should be split up - actionQueue: await getQueue(globalActionQueueStore), - transactionTracker, + transactionTracker: transactionTrackerWorker, + actionService: backgroundActionService, + messagingKeys: await getMessagingKeys(), + argentAccountService: backgroundArgentAccountService, + multisigService: backgroundMultisigService, }, }), }) diff --git a/packages/extension/src/background/__new/services/action/background.ts b/packages/extension/src/background/__new/services/action/background.ts new file mode 100644 index 000000000..d88522d74 --- /dev/null +++ b/packages/extension/src/background/__new/services/action/background.ts @@ -0,0 +1,155 @@ +import { isObject, isString } from "lodash-es" + +import { IActionQueue } from "../../../../shared/actionQueue/queue/interface" +import type { + ActionHash, + ActionQueueItemMeta, +} from "../../../../shared/actionQueue/schema" +import type { + ActionItem, + ExtQueueItem, + ExtensionActionItem, +} from "../../../../shared/actionQueue/types" +import { MessageType } from "../../../../shared/messages" +import { + handleActionApproval, + handleActionRejection, +} from "../../../actionHandlers" +import type { Respond } from "../../../respond" +import { Wallet } from "../../../wallet" +import type { IBackgroundActionService } from "./interface" +import { ActionError } from "../../../../shared/errors/action" + +const getResultData = (resultMessage?: MessageType) => { + if (resultMessage && "data" in resultMessage) { + return resultMessage.data + } +} + +const getResultDataError = (resultMessage?: MessageType) => { + const data = getResultData(resultMessage) + if (isObject(data) && "error" in data) { + return isString(data.error) ? data.error : "Unknown error" + } +} + +export default class BackgroundActionService + implements IBackgroundActionService +{ + constructor( + private queue: IActionQueue, + private wallet: Wallet, + private respond: Respond, + ) {} + + async approve(input: ExtensionActionItem | ActionHash) { + const actionHash = isString(input) ? input : input.meta.hash + const action = await this.queue.get(actionHash) + await this.queue.updateMeta(actionHash, { + startedApproving: Date.now(), + errorApproving: undefined, + }) + if (!action) { + throw new ActionError({ code: "NOT_FOUND" }) + } + /** + * Don't await handleActionApproval, this allows for existing patterns to use 'waitForMessage' after calling await clientActionService.approve(...) + */ + handleActionApproval(action, this.wallet) + .then((resultMessage) => { + const error = getResultDataError(resultMessage) + if (error) { + void this.queue.updateMeta(actionHash, { + startedApproving: undefined, + errorApproving: error, + }) + } else { + void this.queue.remove(actionHash) + } + if (resultMessage) { + void this.respond(resultMessage) + } + }) + .catch((e) => { + /** handleActionApproval catches exceptions internally so this should never happen */ + throw e + }) + } + + async approveAndWait(input: ExtensionActionItem | ActionHash) { + const actionHash = isString(input) ? input : input.meta.hash + const action = await this.queue.get(actionHash) + if (!action) { + throw new ActionError({ code: "NOT_FOUND" }) + } + await this.queue.updateMeta(actionHash, { + startedApproving: Date.now(), + errorApproving: undefined, + }) + const resultMessage = await handleActionApproval(action, this.wallet) + const error = getResultDataError(resultMessage) + if (error) { + await this.queue.updateMeta(actionHash, { + startedApproving: undefined, + errorApproving: error, + }) + } else { + await this.queue.remove(actionHash) + } + if (resultMessage) { + try { + await this.respond(resultMessage) + } catch (e) { + console.warn("Error sending response", e) + throw e + } + } + /** return just the data like waitForMessage() */ + const data = getResultData(resultMessage) + return data + } + + async reject(input: string | string[]) { + const actionHashes = isString(input) ? [input] : input + return this.rejectAllActionHashes(actionHashes) + } + + async rejectAll() { + const actions = await this.queue.getAll() + const actionHashes = actions.map((action) => action.meta.hash) + return this.rejectAllActionHashes(actionHashes) + } + + async rejectAllActionHashes(actionHashes: ActionHash[]) { + for (const actionHash of actionHashes) { + const action = await this.queue.remove(actionHash) + if (!action) { + throw new ActionError({ code: "NOT_FOUND" }) + } + /** + * Don't await handleActionRejection, this allows for existing patterns to use 'waitForMessage' after calling await clientActionService.reject(...) + */ + handleActionRejection(action) + .then((resultMessage) => { + if (resultMessage) { + void this.respond(resultMessage) + } + }) + .catch((e) => { + /** handleActionRejection catches exceptions internally so this should never happen */ + throw e + }) + } + } + + async add( + action: T, + meta?: Partial, + ): Promise> { + return this.queue.add(action, meta) + } + + async remove(actionHash: string): Promise | null> { + return this.queue.remove(actionHash) + } +} diff --git a/packages/extension/src/background/__new/services/action/index.ts b/packages/extension/src/background/__new/services/action/index.ts new file mode 100644 index 000000000..4ec7fa3a1 --- /dev/null +++ b/packages/extension/src/background/__new/services/action/index.ts @@ -0,0 +1,10 @@ +import { actionQueue } from "../../../../shared/actionQueue" +import { respond } from "../../../respond" +import { walletSingleton } from "../../../walletSingleton" +import BackgroundActionService from "./background" + +export const backgroundActionService = new BackgroundActionService( + actionQueue, + walletSingleton, + respond, +) diff --git a/packages/extension/src/background/__new/services/action/interface.ts b/packages/extension/src/background/__new/services/action/interface.ts new file mode 100644 index 000000000..aee69b794 --- /dev/null +++ b/packages/extension/src/background/__new/services/action/interface.ts @@ -0,0 +1,17 @@ +import { + ActionHash, + ActionQueueItemMeta, +} from "../../../../shared/actionQueue/schema" +import type { IActionService } from "../../../../shared/actionQueue/service/interface" +import type { + ActionItem, + ExtQueueItem, +} from "../../../../shared/actionQueue/types" + +export interface IBackgroundActionService extends IActionService { + add( + action: T, + meta?: Partial, + ): Promise> + remove(actionHash: ActionHash): Promise | null> +} diff --git a/packages/extension/src/background/__new/services/analytics/index.ts b/packages/extension/src/background/__new/services/analytics/index.ts new file mode 100644 index 000000000..7f4dadaa5 --- /dev/null +++ b/packages/extension/src/background/__new/services/analytics/index.ts @@ -0,0 +1,8 @@ +import { activeStore } from "../../../../shared/analytics" +import { backgroundUIService } from "../ui" +import { AnalyticsWorker } from "./worker" + +export const analyticsWorker = new AnalyticsWorker( + activeStore, + backgroundUIService, +) diff --git a/packages/extension/src/background/__new/services/analytics/worker.ts b/packages/extension/src/background/__new/services/analytics/worker.ts new file mode 100644 index 000000000..d52deff79 --- /dev/null +++ b/packages/extension/src/background/__new/services/analytics/worker.ts @@ -0,0 +1,17 @@ +import type { IActiveStore } from "../../../../shared/analytics" +import type { IBackgroundUIService } from "../ui/interface" +import { Opened } from "../ui/interface" + +export class AnalyticsWorker { + constructor( + private readonly activeStore: IActiveStore, + private readonly backgroundUIService: IBackgroundUIService, + ) { + this.backgroundUIService.emitter.on(Opened, (opened) => { + if (!opened) { + /** Extension was closed */ + this.activeStore.getState().update("lastClosed") + } + }) + } +} diff --git a/packages/extension/src/background/__new/services/argentAccount/implementation.ts b/packages/extension/src/background/__new/services/argentAccount/implementation.ts new file mode 100644 index 000000000..3f06c064b --- /dev/null +++ b/packages/extension/src/background/__new/services/argentAccount/implementation.ts @@ -0,0 +1,206 @@ +import { IArgentAccountServiceBackground } from "../../../../shared/argentAccount/service/interface" +import { ARGENT_SHIELD_NETWORK_ID } from "../../../../shared/shield/constants" +import { + addBackendAccount, + emailVerificationStatusErrorSchema, + getBackendAccounts, + isTokenExpired, + register, + requestEmailAuthentication, + verifyEmail, +} from "../../../../shared/shield/backend/account" +import { encode, num } from "starknet" +import { keccak, pedersen, sign, Signature } from "micro-starknet" +import { stringToBytes } from "@scure/base" +import { Wallet } from "../../../wallet" +import { accountService } from "../../../../shared/account/service" +import { + getNetworkSelector, + withGuardianSelector, +} from "../../../../shared/account/selectors" +import { validateEmailForAccounts } from "../../../../shared/shield/validation/validateAccount" +import { + PreferencesPayload, + preferencesEndpointPayload, +} from "../../procedures/argentAccount/updatePreferences.model" +import { IHttpService } from "@argent/shared" +import urlJoin from "url-join" +import { ARGENT_ACCOUNT_URL } from "../../../../shared/api/constants" +import { generateJwt } from "../../../../shared/shield/jwt" +import { BaseError } from "../../../../shared/errors/baseError" + +export default class BackgroundArgentAccountService + implements IArgentAccountServiceBackground +{ + constructor(private wallet: Wallet, private httpService: IHttpService) {} + + async addAccount() { + if (!ARGENT_SHIELD_NETWORK_ID) { + /** should never happen */ + throw new BaseError({ + message: "ARGENT_SHIELD_NETWORK_ID is not defined", + }) + } + const selectedAccount = await this.wallet.getSelectedAccount() + if (!selectedAccount) { + throw new BaseError({ message: "No account selected" }) + } + + /** Check if this account already exists in backend */ + const backendAccounts = await getBackendAccounts() + + const existingAccount = backendAccounts.find( + (x) => + num.hexToDecimalString(x.address) === + num.hexToDecimalString(selectedAccount.address), + ) + + let guardianAddress: string | undefined + + if (existingAccount) { + guardianAddress = existingAccount.guardianAddresses[0] + } else { + /** Add account to backend */ + const keyPair = await this.wallet.getKeyPairByDerivationPath( + selectedAccount?.signer.derivationPath, + ) + const privateKey = keyPair.getPrivate() + const publicKey = keyPair.pubKey + const privateKeyHex = num.toHex(privateKey) + + const deploySignature = sign( + pedersen(keccak(stringToBytes("utf8", "starknet")), publicKey), + privateKeyHex, + ) + + const { r, s } = Signature.fromDER(deploySignature.toDERHex()) + const response = await addBackendAccount( + publicKey, + selectedAccount.address, + [ + encode.addHexPrefix(r.toString(16)), + encode.addHexPrefix(s.toString(16)), + ], + ) + guardianAddress = response.guardianAddress + } + if (!guardianAddress) { + throw new BaseError({ + message: "Unable to add account", + }) + } + return guardianAddress + } + + async requestEmail(email: string) { + try { + await requestEmailAuthentication(email) + } catch (error) { + throw new BaseError({ + message: "Error while requesting email for argent account", + options: { + error, + context: { email }, + }, + }) + } + } + + async confirmEmail(code: string) { + try { + const { userRegistrationStatus } = await verifyEmail(code) + + if (userRegistrationStatus === "notRegistered") { + await register() + } + } catch (error) { + let message = "Error while confirming email for argent account" + const emailVerificationStatusError = + emailVerificationStatusErrorSchema.safeParse(error) + if (emailVerificationStatusError.success) { + message = emailVerificationStatusError.data.responseJson.status + } + throw new BaseError({ + message, + options: { + error, + context: { code }, + }, + }) + } + } + + async validateAccount() { + if (!ARGENT_SHIELD_NETWORK_ID) { + /** should never happen */ + throw new BaseError({ + message: "ARGENT_SHIELD_NETWORK_ID is not defined", + }) + } + + /** Check if account is valid for current wallet */ + const selectedAccount = await this.wallet.getSelectedAccount() + const starknetAccount = await this.wallet.getSelectedStarknetAccount() + + if (!starknetAccount || !selectedAccount) { + throw new BaseError({ message: "no accounts" }) + } + + /** Get current account state */ + + const localAccounts = await accountService.get( + getNetworkSelector(ARGENT_SHIELD_NETWORK_ID), + ) + const localAccountsWithGuardian = await accountService.get( + withGuardianSelector, + ) + const backendAccounts = await getBackendAccounts() + + /** Validate email against account state */ + + validateEmailForAccounts({ + localAccounts, + localAccountsWithGuardian, + backendAccounts, + }) + } + + async isTokenExpired() { + return await isTokenExpired() + } + + async updatePreferences(preferences: PreferencesPayload) { + if (!ARGENT_ACCOUNT_URL) { + throw new Error("ARGENT_ACCOUNT_URL is not defined") + } + // TODO move this one layer above in next ticket + const jwt = await generateJwt() + return await this.httpService.post( + urlJoin(ARGENT_ACCOUNT_URL, "/preferences"), + { + body: JSON.stringify(preferences), + headers: { + Authorization: `Bearer ${jwt}`, + "Content-Type": "application/json", + }, + }, + preferencesEndpointPayload, + ) + } + + async getPreferences() { + if (!ARGENT_ACCOUNT_URL) { + throw new Error("ARGENT_ACCOUNT_URL is not defined") + } + const jwt = await generateJwt() + return await this.httpService.get( + urlJoin(ARGENT_ACCOUNT_URL, "/preferences"), + { + headers: { + Authorization: `Bearer ${jwt}`, + "Content-Type": "application/json", + }, + }, + ) + } +} diff --git a/packages/extension/src/background/__new/services/argentAccount/index.ts b/packages/extension/src/background/__new/services/argentAccount/index.ts new file mode 100644 index 000000000..7b9771313 --- /dev/null +++ b/packages/extension/src/background/__new/services/argentAccount/index.ts @@ -0,0 +1,6 @@ +import BackgroundArgentAccountService from "./implementation" +import { walletSingleton } from "../../../walletSingleton" +import { httpService } from "../http/singleton" + +export const backgroundArgentAccountService = + new BackgroundArgentAccountService(walletSingleton, httpService) diff --git a/packages/extension/src/background/__new/services/http/singleton.ts b/packages/extension/src/background/__new/services/http/singleton.ts new file mode 100644 index 000000000..6324f80ad --- /dev/null +++ b/packages/extension/src/background/__new/services/http/singleton.ts @@ -0,0 +1,3 @@ +import { HTTPService } from "@argent/shared" + +export const httpService = new HTTPService() diff --git a/packages/extension/src/background/__new/services/multisig/implementation.ts b/packages/extension/src/background/__new/services/multisig/implementation.ts new file mode 100644 index 000000000..c5d936cf0 --- /dev/null +++ b/packages/extension/src/background/__new/services/multisig/implementation.ts @@ -0,0 +1,212 @@ +import { + AddAccountResponse, + IMultisigService, +} from "../../../../shared/multisig/service/messaging/interface" +import { tryToMintFeeToken } from "../../../../shared/devnet/mintFeeToken" +import { analytics } from "../../../analytics" +import { getMultisigAccounts } from "../../../../shared/multisig/utils/baseMultisig" +import { + AddAccountPayload, + AddOwnerMultisigPayload, + RemoveOwnerMultisigPayload, + ReplaceOwnerMultisigPayload, + UpdateMultisigThresholdPayload, +} from "../../../../shared/multisig/multisig.model" +import { Wallet } from "../../../wallet" +import { CallData } from "starknet" +import { IBackgroundActionService } from "../action/interface" +import { BaseWalletAccount } from "../../../../shared/wallet.model" +import { + MultisigEntryPointType, + MultisigTransactionType, + PendingMultisig, +} from "../../../../shared/multisig/types" +import { MultisigAccount } from "../../../../shared/multisig/account" +import { decodeBase58, decodeBase58Array } from "@argent/shared" +import { AccountError } from "../../../../shared/errors/account" +import { getMultisigPendingTransaction } from "../../../../shared/multisig/pendingTransactionsStore" +import { MultisigError } from "../../../../shared/errors/multisig" + +export default class BackgroundMultisigService implements IMultisigService { + constructor( + private wallet: Wallet, + private actionService: IBackgroundActionService, + ) {} + async addAccount(payload: AddAccountPayload): Promise { + const { networkId, signers, threshold, creator, publicKey, updatedAt } = + payload + try { + const account = await this.wallet.newAccount(networkId, "multisig", { + signers, + threshold, + creator, + publicKey, + updatedAt, + }) + await tryToMintFeeToken(account) + + void analytics.track("createAccount", { + status: "success", + networkId, + type: "multisig", + }) + + const accounts = await getMultisigAccounts() + + return { + account, + accounts, + } + } catch (error) { + void analytics.track("createAccount", { + status: "failure", + networkId: networkId, + type: "multisig", + errorMessage: `${error}`, + }) + + throw error + } + } + + async addOwner(payload: AddOwnerMultisigPayload): Promise { + const { address, signersToAdd, newThreshold } = payload + + const signersPayload = { + entrypoint: MultisigEntryPointType.ADD_SIGNERS, + calldata: CallData.compile({ + new_threshold: newThreshold.toString(), + signers_to_add: decodeBase58Array(signersToAdd), + }), + contractAddress: address, + } + + await this.actionService.add({ + type: "TRANSACTION", + payload: { + transactions: signersPayload, + meta: { + title: "Add signers", + type: MultisigTransactionType.MULTISIG_ADD_SIGNERS, + }, + }, + }) + } + + async removeOwner(payload: RemoveOwnerMultisigPayload): Promise { + const { address, signerToRemove, newThreshold } = payload + + const signersToRemove = [decodeBase58(signerToRemove)] + + const signersPayload = { + entrypoint: MultisigEntryPointType.REMOVE_SIGNERS, + calldata: CallData.compile({ + new_threshold: newThreshold.toString(), + signers_to_remove: signersToRemove, + }), + contractAddress: address, + } + + await this.actionService.add({ + type: "TRANSACTION", + payload: { + transactions: signersPayload, + meta: { + title: "Remove signers", + type: MultisigTransactionType.MULTISIG_REMOVE_SIGNERS, + }, + }, + }) + } + + async replaceOwner(payload: ReplaceOwnerMultisigPayload): Promise { + const { signerToRemove, signerToAdd, address } = payload + + const decodedSignerToRemove = decodeBase58(signerToRemove) + const decodedSignerToAdd = decodeBase58(signerToAdd) + + const signersPayload = { + entrypoint: MultisigEntryPointType.REPLACE_SIGNER, + calldata: CallData.compile({ + signer_to_remove: decodedSignerToRemove, + signer_to_add: decodedSignerToAdd, + }), + contractAddress: address, + } + + await this.actionService.add({ + type: "TRANSACTION", + payload: { + transactions: signersPayload, + meta: { + title: "Replace signer", + type: MultisigTransactionType.MULTISIG_REPLACE_SIGNER, + }, + }, + }) + } + + async addPendingAccount(networkId: string): Promise { + return await this.wallet.newPendingMultisig(networkId) + } + + async addTransactionSignature(requestId: string): Promise { + const selectedAccount = await this.wallet.getSelectedAccount() + + if (!selectedAccount) { + throw new AccountError({ code: "NOT_SELECTED" }) + } + + const multisigStarknetAccount = await this.wallet.getStarknetAccount( + selectedAccount, + ) + + if (!MultisigAccount.isMultisig(multisigStarknetAccount)) { + throw new AccountError({ code: "NOT_MULTISIG" }) + } + + const transactionToSign = await getMultisigPendingTransaction(requestId) + + if (!transactionToSign) { + throw new MultisigError({ + code: "PENDING_MULTISIG_TRANSACTION_NOT_FOUND", + message: `Pending Multisig transaction ${requestId} not found`, + }) + } + + const { transaction_hash } = + await multisigStarknetAccount.addRequestSignature(transactionToSign) + + return transaction_hash + } + + async deploy(account: BaseWalletAccount): Promise { + await this.actionService.add({ + type: "DEPLOY_MULTISIG_ACTION", + payload: account, + }) + } + + async updateThreshold( + payload: UpdateMultisigThresholdPayload, + ): Promise { + const { address, newThreshold } = payload + + const thresholdPayload = { + entrypoint: MultisigEntryPointType.CHANGE_THRESHOLD, + calldata: [newThreshold.toString()], + contractAddress: address, + } + + await this.actionService.add({ + type: "TRANSACTION", + payload: { + transactions: thresholdPayload, + meta: { + title: "Change threshold", + type: MultisigTransactionType.MULTISIG_CHANGE_THRESHOLD, + }, + }, + }) + } +} diff --git a/packages/extension/src/background/__new/services/multisig/index.ts b/packages/extension/src/background/__new/services/multisig/index.ts new file mode 100644 index 000000000..7ca35d7a3 --- /dev/null +++ b/packages/extension/src/background/__new/services/multisig/index.ts @@ -0,0 +1,8 @@ +import BackgroundMultisigService from "./implementation" +import { walletSingleton } from "../../../walletSingleton" +import { backgroundActionService } from "../action" + +export const backgroundMultisigService = new BackgroundMultisigService( + walletSingleton, + backgroundActionService, +) diff --git a/packages/extension/src/background/__new/services/network/background.test.ts b/packages/extension/src/background/__new/services/network/background.test.ts new file mode 100644 index 000000000..5734c5e18 --- /dev/null +++ b/packages/extension/src/background/__new/services/network/background.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test, vi } from "vitest" + +import { Network } from "../../../../shared/network" +import { defaultReadonlyNetworks } from "../../../../shared/network/defaults" +import { networkSelector } from "../../../../shared/network/selectors" +import { networksEqual } from "../../../../shared/network/store" +import { InMemoryRepository } from "../../../../shared/storage/__new/__test__/inmemoryImplementations" +import BackgroundNetworkService from "./background" +import { NetworkWithStatus } from "../../../../shared/network/type" + +describe("BackgroundNetworkService", () => { + const makeService = () => { + const networkRepo = new InMemoryRepository({ + namespace: "core:allNetworks", + compare: networksEqual, + }) + const networkWithStatusRepo = new InMemoryRepository({ + namespace: "core:allNetworkStatus", + compare: networksEqual, + }) + const getNetworkStatuses = vi.fn() + const backgroundNetworkService = new BackgroundNetworkService( + networkRepo, + networkWithStatusRepo, + defaultReadonlyNetworks, + getNetworkStatuses, + ) + return { + backgroundNetworkService, + networkWithStatusRepo, + getNetworkStatuses, + } + } + test("updateStatuses", async () => { + const { + backgroundNetworkService, + networkWithStatusRepo, + getNetworkStatuses, + } = makeService() + + getNetworkStatuses.mockResolvedValueOnce({ + "mainnet-alpha": "ok", + "goerli-alpha": "degraded", + }) + + await backgroundNetworkService.updateStatuses() + expect(getNetworkStatuses).toHaveBeenCalled() + + const [ok] = await networkWithStatusRepo.get( + networkSelector("mainnet-alpha"), + ) + expect(ok).toHaveProperty("status", "ok") + + const [degraded] = await networkWithStatusRepo.get( + networkSelector("goerli-alpha"), + ) + expect(degraded).toHaveProperty("status", "degraded") + }) +}) diff --git a/packages/extension/src/background/__new/services/network/background.ts b/packages/extension/src/background/__new/services/network/background.ts new file mode 100644 index 000000000..995d43771 --- /dev/null +++ b/packages/extension/src/background/__new/services/network/background.ts @@ -0,0 +1,38 @@ +import { uniqWith } from "lodash-es" + +import { Network } from "../../../../shared/network" +import { INetworkRepo, networksEqual } from "../../../../shared/network/store" +import { GetNetworkStatusesFn, IBackgroundNetworkService } from "./interface" +import { INetworkWithStatusRepo } from "../../../../shared/network/statusStore" + +export default class BackgroundNetworkService + implements IBackgroundNetworkService +{ + constructor( + private readonly networkRepo: INetworkRepo, + private readonly networkWithStatusRepo: INetworkWithStatusRepo, + readonly defaultNetworks: Network[], + private readonly getNetworkStatuses: GetNetworkStatusesFn, + ) {} + + private async loadNetworks() { + const allNetworks = uniqWith( + [...(await this.networkRepo.get()), ...this.defaultNetworks], + networksEqual, + ) + return allNetworks + } + + async updateStatuses() { + const networks = await this.loadNetworks() + const networkStatuses = await this.getNetworkStatuses(networks) + const networkWithUpdatedStatuses = networks.map((network) => { + return { + id: network.id, + status: networkStatuses[network.id] ?? "unknown", + } + }) + + await this.networkWithStatusRepo.upsert(networkWithUpdatedStatuses) + } +} diff --git a/packages/extension/src/background/__new/services/network/index.ts b/packages/extension/src/background/__new/services/network/index.ts new file mode 100644 index 000000000..c2f9d585f --- /dev/null +++ b/packages/extension/src/background/__new/services/network/index.ts @@ -0,0 +1,21 @@ +import { defaultNetworks } from "../../../../shared/network" +import { networkStatusRepo } from "../../../../shared/network/statusStore" +import { networkRepo } from "../../../../shared/network/store" +import { chromeScheduleService } from "../../../../shared/schedule" +import { backgroundUIService } from "../ui" +import BackgroundNetworkService from "./background" +import { getNetworkStatuses } from "./status" +import { NetworkWorker } from "./worker" + +export const backgroundNetworkService = new BackgroundNetworkService( + networkRepo, + networkStatusRepo, + defaultNetworks, + getNetworkStatuses, +) + +export const networkWorker = new NetworkWorker( + backgroundNetworkService, + backgroundUIService, + chromeScheduleService, +) diff --git a/packages/extension/src/background/__new/services/network/interface.ts b/packages/extension/src/background/__new/services/network/interface.ts new file mode 100644 index 000000000..7c68df6a9 --- /dev/null +++ b/packages/extension/src/background/__new/services/network/interface.ts @@ -0,0 +1,9 @@ +import { Network, NetworkStatus } from "../../../../shared/network" + +export interface IBackgroundNetworkService { + updateStatuses(): Promise +} + +export type GetNetworkStatusesFn = ( + networks: Network[], +) => Promise> diff --git a/packages/extension/src/background/__new/services/network/status.ts b/packages/extension/src/background/__new/services/network/status.ts new file mode 100644 index 000000000..749a31023 --- /dev/null +++ b/packages/extension/src/background/__new/services/network/status.ts @@ -0,0 +1,75 @@ +import urljoin from "url-join" + +import { Network, NetworkStatus } from "../../../../shared/network" +import { fetchWithTimeout } from "../../../utils/fetchWithTimeout" +import { z } from "zod" +import { NetworkError } from "../../../../shared/errors/network" + +const checklyNetworkNames = { + "Goerli - Contract call": "goerli-alpha", + "Goerli 2 - Contract call": "goerli-alpha-2", + "Mainnet - Contract call": "mainnet-alpha", + "Integration - Goerli - Get state update": "integration", +} +const checklySchema = z.object({ + results: z.array( + z.object({ + id: z.string(), + name: z.string(), + status: z.object({ + hasErrors: z.boolean(), + hasFailures: z.boolean(), + isDegraded: z.boolean(), + }), + }), + ), +}) + +export const getNetworkStatuses = async () => { + try { + const response = await fetchWithTimeout( + urljoin( + "https://api.checklyhq.com/v1/status-page/4054/statuses?page=1&limit=15", + ), + { timeout: 5000, method: "GET" }, + ) + const data = await response.json() + const parsedData = checklySchema.safeParse(data) + if (!parsedData.success) { + throw new NetworkError({ + message: "NETWORK_STATUS_RESPONSE_PARSING_FAILED", + }) + } + const networkStatuses: Record = {} + parsedData.data.results.forEach((result) => { + let status: NetworkStatus = "unknown" + if (result.status.hasErrors) { + status = "error" + } else if (result.status.hasFailures) { + status = "error" + } else if (result.status.isDegraded) { + status = "degraded" + } else if (result.status.isDegraded === false) { + status = "ok" + } + if (result.name in checklyNetworkNames) { + const key = result.name as keyof typeof checklyNetworkNames + networkStatuses[checklyNetworkNames[key]] = status + } + }) + + return networkStatuses + } catch (error) { + console.warn({ error }) + const networkStatuses: Record = {} + Object.values(checklyNetworkNames).map((value) => { + networkStatuses[value] = "unknown" + }) + // Gracefully returning unknown statuses + return networkStatuses + throw new NetworkError({ + message: "NETWORK_STATUS_RESPONSE_PARSING_FAILED", + options: { error }, + }) + } +} diff --git a/packages/extension/src/background/__new/services/network/worker.ts b/packages/extension/src/background/__new/services/network/worker.ts new file mode 100644 index 000000000..663283a4b --- /dev/null +++ b/packages/extension/src/background/__new/services/network/worker.ts @@ -0,0 +1,56 @@ +import { IScheduleService } from "../../../../shared/schedule/interface" +import { IBackgroundUIService, Opened } from "../ui/interface" +import { IBackgroundNetworkService } from "./interface" +import { RefreshInterval } from "../../../../shared/config" + +const TASK_ID = "NetworkWorker.updateStatuses" +const REFRESH_PERIOD_MINUTES = Math.floor(RefreshInterval.MEDIUM / 60) + +export class NetworkWorker { + private isUpdating = false + private lastUpdatedTimestamp = 0 + + constructor( + private readonly backgroundNetworkService: IBackgroundNetworkService, + private readonly backgroundUIService: IBackgroundUIService, + private readonly scheduleService: IScheduleService, + ) { + void this.scheduleService.registerImplementation({ + id: TASK_ID, + callback: this.updateNetworkStatuses.bind(this), + }) + + this.backgroundUIService.emitter.on(Opened, this.onOpened.bind(this)) + } + + async updateNetworkStatuses() { + if (this.isUpdating) { + return + } + this.isUpdating = true + this.lastUpdatedTimestamp = Date.now() + await this.backgroundNetworkService.updateStatuses() + this.isUpdating = false + } + + onOpened(opened: boolean) { + if (opened) { + const currentTimestamp = Date.now() + const differenceInMilliseconds = + currentTimestamp - this.lastUpdatedTimestamp + const differenceInMinutes = differenceInMilliseconds / (1000 * 60) + + if (differenceInMinutes > REFRESH_PERIOD_MINUTES) { + void this.updateNetworkStatuses() + } + + void this.scheduleService.every(RefreshInterval.MEDIUM, { + id: TASK_ID, + }) + } else { + void this.scheduleService.delete({ + id: TASK_ID, + }) + } + } +} diff --git a/packages/extension/src/background/__new/services/onboarding/implementation.test.ts b/packages/extension/src/background/__new/services/onboarding/implementation.test.ts index 4187cb4be..82f6ccd0c 100644 --- a/packages/extension/src/background/__new/services/onboarding/implementation.test.ts +++ b/packages/extension/src/background/__new/services/onboarding/implementation.test.ts @@ -10,8 +10,6 @@ describe("OnboardingService", () => { closePopup: vi.fn(), createTab: vi.fn(), focusTab: vi.fn(), - getPopup: vi.fn(), - getTab: vi.fn(), hasPopup: vi.fn(), hasTab: vi.fn(), setDefaultPopup: vi.fn(), diff --git a/packages/extension/src/background/__new/services/onboarding/implementation.ts b/packages/extension/src/background/__new/services/onboarding/implementation.ts index 269261de2..6072b1673 100644 --- a/packages/extension/src/background/__new/services/onboarding/implementation.ts +++ b/packages/extension/src/background/__new/services/onboarding/implementation.ts @@ -1,11 +1,23 @@ import type { IUIService } from "../../../../shared/__new/services/ui/interface" import type { KeyValueStorage } from "../../../../shared/storage" +import { DeepPick } from "../../../../shared/types/deepPick" import type { WalletStorageProps } from "../../../../shared/wallet/walletStore" import type { IOnboardingService } from "./interface" +type MinimalUIService = DeepPick< + IUIService, + | "closePopup" + | "createTab" + | "focusTab" + | "hasPopup" + | "hasTab" + | "setDefaultPopup" + | "unsetDefaultPopup" +> + export default class OnboardingService implements IOnboardingService { constructor( - private uiService: IUIService, + private uiService: MinimalUIService, private walletStore: KeyValueStorage, ) {} diff --git a/packages/extension/src/background/__new/services/ui/background.test.ts b/packages/extension/src/background/__new/services/ui/background.test.ts new file mode 100644 index 000000000..34ab603f6 --- /dev/null +++ b/packages/extension/src/background/__new/services/ui/background.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, test, vi } from "vitest" + +import BackgroundUIService from "./background" +import { Opened } from "./interface" + +describe("BackgroundUIService", () => { + const makeService = () => { + const browser = { + runtime: { + connect: vi.fn(), + onConnect: { + addListener: vi.fn(), + }, + onDisconnect: { + addListener: vi.fn(), + }, + }, + } + const uiService = { + connectId: "test-connect-id", + hasTab: vi.fn(), + } + const emitter = { + anyEvent: vi.fn(), + bindMethods: vi.fn(), + clearListeners: vi.fn(), + debug: vi.fn(), + emit: vi.fn(), + emitSerial: vi.fn(), + events: vi.fn(), + listenerCount: vi.fn(), + off: vi.fn(), + offAny: vi.fn(), + on: vi.fn(), + onAny: vi.fn(), + once: vi.fn(), + } + const sessionService = { + locked: false, + emitter, + } + + const backgroundUIService = new BackgroundUIService( + emitter, + browser, + uiService, + sessionService, + ) + return { + backgroundUIService, + uiService, + browser, + emitter, + } + } + test("open / close lifecycle", async () => { + const { backgroundUIService, uiService, emitter } = makeService() + const port = { + name: uiService.connectId, + onDisconnect: { + addListener: vi.fn(), + }, + } + + /** open */ + backgroundUIService.onConnectPort(port) + expect(backgroundUIService.opened).toBeTruthy() + expect(port.onDisconnect.addListener).toHaveBeenCalled() + expect(emitter.emit).toHaveBeenCalledWith(Opened, true) + + /** should not fire again */ + emitter.emit.mockReset() + backgroundUIService.onConnectPort(port) + expect(emitter.emit).not.toHaveBeenCalled() + + /** close */ + await backgroundUIService.onDisconnectPort() + expect(backgroundUIService.opened).toBeFalsy() + expect(emitter.emit).toHaveBeenCalledWith(Opened, false) + + /** should not fire again */ + emitter.emit.mockReset() + await backgroundUIService.onDisconnectPort() + expect(emitter.emit).not.toHaveBeenCalled() + }) +}) diff --git a/packages/extension/src/background/__new/services/ui/background.ts b/packages/extension/src/background/__new/services/ui/background.ts new file mode 100644 index 000000000..1651e2bc1 --- /dev/null +++ b/packages/extension/src/background/__new/services/ui/background.ts @@ -0,0 +1,100 @@ +import Emittery from "emittery" +import browser from "webextension-polyfill" + +import { IUIService } from "../../../../shared/__new/services/ui/interface" +import { DeepPick } from "../../../../shared/types/deepPick" +import { openUi } from "../../../openUi" +import { Locked } from "../../../wallet/session/interface" +import type { WalletSessionService } from "../../../wallet/session/session.service" +import type { Events, IBackgroundUIService } from "./interface" +import { Opened } from "./interface" + +type MinimalBrowser = DeepPick< + typeof chrome, + "runtime.connect" | "runtime.onConnect.addListener" +> + +type MinimalIUIService = Pick + +type MinimalPort = DeepPick< + browser.runtime.Port, + "name" | "onDisconnect.addListener" +> + +type MinimalIWalletSessionService = Pick< + WalletSessionService, + "emitter" | "locked" +> + +export default class BackgroundUIService implements IBackgroundUIService { + private _opened = false + + constructor( + readonly emitter: Emittery, + private browser: MinimalBrowser, + private uiService: MinimalIUIService, + private sessionService: MinimalIWalletSessionService, + ) { + this.initListeners() + } + + /* + * There is no usable 'close' event on an extension + * + * instead we open a message port to the extension and simply listen for it to be disconnected + * as a side-effect of the extension being closed + */ + + private initListeners() { + this.browser.runtime.onConnect.addListener(this.onConnectPort.bind(this)) + } + + /** listen for the port connection from the UI, then detect disconnection */ + onConnectPort(port: MinimalPort) { + if (port.name !== this.uiService.connectId) { + return + } + this.opened = true + // eslint-disable-next-line @typescript-eslint/no-misused-promises + port.onDisconnect.addListener(this.onDisconnectPort.bind(this)) + } + + async onDisconnectPort() { + /** An instance of the UI was closed */ + const hasTab = await this.uiService.hasTab() + if (!hasTab) { + /** There are no more instances left open */ + this.opened = false + } + } + + get opened() { + return this._opened + } + + private set opened(opened: boolean) { + if (this._opened === opened) { + return + } + this._opened = opened + void this.emitter.emit(Opened, this.opened) + } + + async openUiAndUnlock() { + if (!this.opened) { + await openUi() + /** wait for Opened state to update */ + await this.emitter.once(Opened) + } + if (!this.sessionService.locked) { + return true + } + /** wait for change in either Locked or Opened state */ + await Promise.race([ + this.emitter.once(Opened), + this.sessionService.emitter.once(Locked), + ]) + const unlocked = !this.sessionService.locked + return unlocked + } +} diff --git a/packages/extension/src/background/__new/services/ui/index.ts b/packages/extension/src/background/__new/services/ui/index.ts new file mode 100644 index 000000000..a96c28eee --- /dev/null +++ b/packages/extension/src/background/__new/services/ui/index.ts @@ -0,0 +1,18 @@ +import Emittery from "emittery" +import browser from "webextension-polyfill" + +import { uiService } from "../../../../shared/__new/services/ui" +import { sessionService } from "../../../walletSingleton" +import BackgroundUIService from "./background" +import type { Events } from "./interface" + +export { Opened } from "./interface" + +const emitter = new Emittery() + +export const backgroundUIService = new BackgroundUIService( + emitter, + browser, + uiService, + sessionService, +) diff --git a/packages/extension/src/background/__new/services/ui/interface.ts b/packages/extension/src/background/__new/services/ui/interface.ts new file mode 100644 index 000000000..53519d7d7 --- /dev/null +++ b/packages/extension/src/background/__new/services/ui/interface.ts @@ -0,0 +1,24 @@ +import Emittery from "emittery" + +export const Opened = Symbol("Opened") + +export type Events = { + /** + * Fired when UI state changes to/from having any open windows or tabs + */ + [Opened]: boolean +} + +export interface IBackgroundUIService { + readonly emitter: Emittery + /** + * Flag for if there are one or more UI windows or tabs open currently + */ + readonly opened: boolean + /** + * Opens ui + * returns true if already unlocked, or if the user proceeded to unlock the wallet + * returns false if the wallet was locked and the user closed the wallet + */ + openUiAndUnlock(): Promise +} diff --git a/packages/extension/src/background/__new/trpc.ts b/packages/extension/src/background/__new/trpc.ts index 019c09568..1ca4b937a 100644 --- a/packages/extension/src/background/__new/trpc.ts +++ b/packages/extension/src/background/__new/trpc.ts @@ -1,22 +1,61 @@ import { initTRPC } from "@trpc/server" -import { ActionItem } from "../../shared/actionQueue/types" -import { Queue } from "../actionQueue" -import { TransactionTracker } from "../transactions/tracking" +import type { IArgentAccountServiceBackground } from "../../shared/argentAccount/service/interface" +import { BaseError } from "../../shared/errors/baseError" +import type { IMultisigService } from "../../shared/multisig/service/messaging/interface" +import { MessagingKeys } from "../keys/messagingKeys" +import { TransactionTrackerWorker } from "../transactions/service/starknet.service" import { Wallet } from "../wallet" +import type { IBackgroundActionService } from "./services/action/interface" interface Context { sender?: chrome.runtime.MessageSender services: { wallet: Wallet - actionQueue: Queue - transactionTracker: TransactionTracker + transactionTracker: TransactionTrackerWorker + actionService: IBackgroundActionService + messagingKeys: MessagingKeys + argentAccountService: IArgentAccountServiceBackground + multisigService: IMultisigService } } const t = initTRPC.context().create({ isServer: false, allowOutsideOfServer: true, + errorFormatter: (opts) => { + const { shape, error } = opts + const { cause } = error + + if (cause instanceof BaseError) { + return { + ...shape, + data: { + ...shape.data, + code: cause.code, + name: cause.name, + message: cause.message, + context: cause.context, + }, + } + } else if (cause?.cause instanceof BaseError) { + // The production build is nesting the error in another cause + const nestedCause = cause.cause + + return { + ...shape, + data: { + ...shape.data, + code: nestedCause.code, + name: nestedCause.name, + message: nestedCause.message, + context: nestedCause.context, + }, + } + } + + return shape + }, }) export const router = t.router diff --git a/packages/extension/src/background/accountDeploy.ts b/packages/extension/src/background/accountDeploy.ts index 916e5c4cf..e17cc420c 100644 --- a/packages/extension/src/background/accountDeploy.ts +++ b/packages/extension/src/background/accountDeploy.ts @@ -1,35 +1,28 @@ -import { ActionItem } from "../shared/actionQueue/types" +import { BlockNumber, num } from "starknet" import { BaseWalletAccount, WalletAccount } from "../shared/wallet.model" -import { Queue } from "./actionQueue" +import { IBackgroundActionService } from "./__new/services/action/interface" export interface IDeployAccount { account: BaseWalletAccount - actionQueue: Queue + actionService: IBackgroundActionService } export const deployAccountAction = async ({ - actionQueue, account, + actionService, }: IDeployAccount) => { - await actionQueue.push({ + await actionService.add({ type: "DEPLOY_ACCOUNT_ACTION", payload: account, }) } -export const deployMultisigAction = async ({ - actionQueue, - account, -}: IDeployAccount) => { - await actionQueue.push({ - type: "DEPLOY_MULTISIG_ACTION", - payload: account, - }) -} - export const isAccountDeployed = async ( account: WalletAccount, - getClassAt: (address: string, blockIdentifier?: unknown) => Promise, + getClassAt: ( + address: string, + blockIdentifier?: BlockNumber | num.BigNumberish, // from starknet.js due to missing export + ) => Promise, ) => { if (!account.needsDeploy) { return true @@ -38,6 +31,7 @@ export const isAccountDeployed = async ( await getClassAt(account.address) return true } catch (e) { + console.error(e) return false } } diff --git a/packages/extension/src/background/accountDeployAction.ts b/packages/extension/src/background/accountDeployAction.ts index 04f6e025f..5a4f1aade 100644 --- a/packages/extension/src/background/accountDeployAction.ts +++ b/packages/extension/src/background/accountDeployAction.ts @@ -1,8 +1,8 @@ import { ExtQueueItem } from "../shared/actionQueue/types" import { BaseWalletAccount } from "../shared/wallet.model" -import { BackgroundService } from "./background" import { addTransaction } from "./transactions/store" import { checkTransactionHash } from "./transactions/transactionExecution" +import { Wallet } from "./wallet" type DeployAccountAction = ExtQueueItem<{ type: "DEPLOY_ACCOUNT_ACTION" @@ -11,14 +11,14 @@ type DeployAccountAction = ExtQueueItem<{ export const accountDeployAction = async ( { payload: baseAccount }: DeployAccountAction, - { wallet }: BackgroundService, + wallet: Wallet, ) => { if (!(await wallet.isSessionOpen())) { throw Error("you need an open session") } const selectedAccount = await wallet.getAccount(baseAccount) - const accountNeedsDeploy = selectedAccount.needsDeploy + const accountNeedsDeploy = selectedAccount?.needsDeploy if (!accountNeedsDeploy) { throw Error("Account already deployed") diff --git a/packages/extension/src/background/accountMessaging.ts b/packages/extension/src/background/accountMessaging.ts index c0c18c3ec..6258824df 100644 --- a/packages/extension/src/background/accountMessaging.ts +++ b/packages/extension/src/background/accountMessaging.ts @@ -1,301 +1,14 @@ -import { constants, number } from "starknet" - -import { accountService } from "../shared/account/service" import { AccountMessage } from "../shared/messages/AccountMessage" -import { isEqualAddress } from "../ui/services/addresses" -import { upgradeAccount } from "./accountUpgrade" -import { sendMessageToUi } from "./activeTabs" import { HandleMessage, UnhandledMessage } from "./background" -import { encryptForUi } from "./crypto" -import { addTransaction } from "./transactions/store" export const handleAccountMessage: HandleMessage = async ({ msg, - background: { wallet, actionQueue }, - messagingKeys: { privateKey }, + background: { actionService }, }) => { switch (msg.type) { - case "GET_SELECTED_ACCOUNT": { - const selectedAccount = await wallet.getSelectedAccount() - return sendMessageToUi({ - type: "GET_SELECTED_ACCOUNT_RES", - data: selectedAccount, - }) - } - - case "UPGRADE_ACCOUNT": { - try { - await upgradeAccount({ - account: msg.data.wallet, - wallet, - actionQueue, - targetImplementationType: msg.data.targetImplementationType, - }) - return sendMessageToUi({ type: "UPGRADE_ACCOUNT_RES" }) - } catch { - return sendMessageToUi({ type: "UPGRADE_ACCOUNT_REJ" }) - } - } - - case "REDEPLOY_ACCOUNT": { - try { - const account = msg.data - const fullAccount = await wallet.getAccount(account) - const { txHash } = await wallet.redeployAccount(fullAccount) - void addTransaction({ - hash: txHash, - account: fullAccount, - meta: { title: "Redeploy wallet", type: "DEPLOY_ACCOUNT" }, - }) - return sendMessageToUi({ - type: "REDEPLOY_ACCOUNT_RES", - data: { - txHash, - address: account.address, - }, - }) - } catch { - return sendMessageToUi({ type: "REDEPLOY_ACCOUNT_REJ" }) - } - } - - case "DELETE_ACCOUNT": { - try { - await accountService.remove(msg.data) - return sendMessageToUi({ type: "DELETE_ACCOUNT_RES" }) - } catch { - return sendMessageToUi({ type: "DELETE_ACCOUNT_REJ" }) - } - } - - case "GET_ENCRYPTED_PRIVATE_KEY": { - if (!(await wallet.isSessionOpen())) { - throw Error("you need an open session") - } - - const encryptedPrivateKey = await encryptForUi( - await wallet.getPrivateKey(msg.data.account), - msg.data.encryptedSecret, - privateKey, - ) - - return sendMessageToUi({ - type: "GET_ENCRYPTED_PRIVATE_KEY_RES", - data: { encryptedPrivateKey }, - }) - } - - case "GET_PUBLIC_KEY": { - const { publicKey, account } = await wallet.getPublicKey(msg.data) - - return sendMessageToUi({ - type: "GET_PUBLIC_KEY_RES", - data: { publicKey, account }, - }) - } - - case "GET_ENCRYPTED_SEED_PHRASE": { - if (!(await wallet.isSessionOpen())) { - throw Error("you need an open session") - } - - const encryptedSeedPhrase = await encryptForUi( - await wallet.getSeedPhrase(), - msg.data.encryptedSecret, - privateKey, - ) - - return sendMessageToUi({ - type: "GET_ENCRYPTED_SEED_PHRASE_RES", - data: { encryptedSeedPhrase }, - }) - } - - case "GET_NEXT_PUBLIC_KEY": { - try { - const { publicKey } = await wallet.getNextPublicKey(msg.data.networkId) - - return sendMessageToUi({ - type: "GET_NEXT_PUBLIC_KEY_RES", - data: { publicKey }, - }) - } catch (e) { - console.error(e) - return sendMessageToUi({ - type: "GET_NEXT_PUBLIC_KEY_REJ", - }) - } - } - + // TODO: refactor after we refactor actionHandlers.ts case "DEPLOY_ACCOUNT_ACTION_FAILED": { - return await actionQueue.remove(msg.data.actionHash) - } - - case "ACCOUNT_CHANGE_GUARDIAN": { - try { - const { account, guardian } = msg.data - - const newGuardian = number.hexToDecimalString(guardian) - - await actionQueue.push({ - type: "TRANSACTION", - payload: { - transactions: { - contractAddress: account.address, - entrypoint: "changeGuardian", - calldata: [newGuardian], - }, - meta: { - isChangeGuardian: true, - title: "Change account guardian", - type: number.toBN(newGuardian).isZero() // if guardian is 0, it's a remove guardian action - ? "REMOVE_ARGENT_SHIELD" - : "ADD_ARGENT_SHIELD", - }, - }, - }) - return sendMessageToUi({ - type: "ACCOUNT_CHANGE_GUARDIAN_RES", - }) - } catch (error) { - return sendMessageToUi({ - type: "ACCOUNT_CHANGE_GUARDIAN_REJ", - data: `${error}`, - }) - } - } - - case "ACCOUNT_CANCEL_ESCAPE": { - try { - const { account } = msg.data - await actionQueue.push({ - type: "TRANSACTION", - payload: { - transactions: { - contractAddress: account.address, - entrypoint: "cancelEscape", - calldata: [], - }, - meta: { - isCancelEscape: true, - title: "Cancel escape", - type: "INVOKE_FUNCTION", - }, - }, - }) - return sendMessageToUi({ - type: "ACCOUNT_CANCEL_ESCAPE_RES", - }) - } catch (error) { - return sendMessageToUi({ - type: "ACCOUNT_CANCEL_ESCAPE_REJ", - data: `${error}`, - }) - } - } - - case "ACCOUNT_TRIGGER_ESCAPE_GUARDIAN": { - try { - const { account } = msg.data - await actionQueue.push({ - type: "TRANSACTION", - payload: { - transactions: { - contractAddress: account.address, - entrypoint: "triggerEscapeGuardian", - calldata: [], - }, - meta: { - isCancelEscape: true, - title: "Trigger escape guardian", - type: "INVOKE_FUNCTION", - }, - }, - }) - return sendMessageToUi({ - type: "ACCOUNT_TRIGGER_ESCAPE_GUARDIAN_RES", - }) - } catch (error) { - return sendMessageToUi({ - type: "ACCOUNT_TRIGGER_ESCAPE_GUARDIAN_REJ", - data: `${error}`, - }) - } - } - - case "ACCOUNT_ESCAPE_AND_CHANGE_GUARDIAN": { - try { - const { account } = msg.data - /** - * This is a two-stage process - * - * 1. call escapeGuardian with current signer key as new guardian key - * 2. changeGuardian to ZERO, signed twice by same signer key (like 2/2 multisig with same key) - */ - - const selectedAccount = await wallet.getAccount(account) - if (!selectedAccount) { - throw Error("no account selected") - } - - const { publicKey } = await wallet.getPublicKey(account) - - if ( - selectedAccount.guardian && - isEqualAddress(selectedAccount.guardian, publicKey) - ) { - /** - * Account already used `escapeGuardian` to change guardian to this account publicKey - * Call `changeGuardian` to ZERO - */ - - await actionQueue.push({ - type: "TRANSACTION", - payload: { - transactions: { - contractAddress: account.address, - entrypoint: "changeGuardian", - calldata: [ - number.hexToDecimalString(constants.ZERO.toString()), - ], - }, - meta: { - isChangeGuardian: true, - title: "Change account guardian", - type: "INVOKE_FUNCTION", - }, - }, - }) - } else { - /** - * Call `escapeGuardian` to change guardian to this account publicKey - */ - await actionQueue.push({ - type: "TRANSACTION", - payload: { - transactions: { - contractAddress: account.address, - entrypoint: "escapeGuardian", - calldata: [number.hexToDecimalString(publicKey)], - }, - meta: { - isChangeGuardian: true, - title: "Escape account guardian", - type: "INVOKE_FUNCTION", - }, - }, - }) - } - - return sendMessageToUi({ - type: "ACCOUNT_ESCAPE_AND_CHANGE_GUARDIAN_RES", - }) - } catch (error) { - return sendMessageToUi({ - type: "ACCOUNT_ESCAPE_AND_CHANGE_GUARDIAN_REJ", - data: `${error}`, - }) - } + return await actionService.remove(msg.data.actionHash) } } diff --git a/packages/extension/src/background/accountUpgrade.ts b/packages/extension/src/background/accountUpgrade.ts index 1e9150062..de8604c16 100644 --- a/packages/extension/src/background/accountUpgrade.ts +++ b/packages/extension/src/background/accountUpgrade.ts @@ -1,30 +1,34 @@ -import { stark } from "starknet" +import { CallData } from "starknet" -import { ActionItem } from "../shared/actionQueue/types" -import { getNetwork } from "../shared/network" +import { networkService } from "../shared/network/service" import { ArgentAccountType, BaseWalletAccount } from "../shared/wallet.model" -import { Queue } from "./actionQueue" +import { IBackgroundActionService } from "./__new/services/action/interface" import { Wallet } from "./wallet" +import { isAccountV5 } from "../shared/utils/accountv4" +import { AccountError } from "../shared/errors/account" export interface IUpgradeAccount { account: BaseWalletAccount wallet: Wallet - actionQueue: Queue + actionService: IBackgroundActionService targetImplementationType?: ArgentAccountType } export const upgradeAccount = async ({ account, wallet, - actionQueue, + actionService, targetImplementationType, }: IUpgradeAccount) => { const fullAccount = await wallet.getAccount(account) + if (!fullAccount) { + throw new AccountError({ code: "NOT_FOUND" }) + } const starknetAccount = await wallet.getStarknetAccount(account) const accountType = targetImplementationType ?? fullAccount.type - const { accountClassHash: newImplementation } = await getNetwork( + const { accountClassHash: newImplementation } = await networkService.getById( fullAccount.network.id, ) @@ -32,19 +36,23 @@ export const upgradeAccount = async ({ throw "Cannot upgrade account without a new contract implementation" } + const accountTypeWithCairo0Check = + accountType === "standardCairo0" ? "standard" : accountType const implementationClassHash = - newImplementation[accountType] ?? newImplementation.standard + newImplementation[accountTypeWithCairo0Check] ?? newImplementation.standard - const calldata = stark.compileCalldata({ - implementation: implementationClassHash, - }) + if (!isAccountV5(starknetAccount)) { + throw new AccountError({ code: "UPGRADE_NOT_SUPPORTED" }) + } - if ("estimateAccountDeployFee" in starknetAccount) { + const upgradeCalldata = { + implementation: implementationClassHash, // new starknet accounts have a new upgrade interface to allow for transactions right after upgrade - calldata.push("0") + calldata: [0], } - await actionQueue.push({ + const calldata = CallData.compile(upgradeCalldata) + await actionService.add({ type: "TRANSACTION", payload: { transactions: { diff --git a/packages/extension/src/background/actionHandlers.ts b/packages/extension/src/background/actionHandlers.ts index 79efcd132..d6176aa10 100644 --- a/packages/extension/src/background/actionHandlers.ts +++ b/packages/extension/src/background/actionHandlers.ts @@ -1,29 +1,31 @@ +import { stark } from "starknet" + import { accountService } from "../shared/account/service" -import { ActionItem, ExtQueueItem } from "../shared/actionQueue/types" +import { ExtensionActionItem } from "../shared/actionQueue/types" import { MessageType } from "../shared/messages" -import { addNetwork, getNetworks } from "../shared/network" +import { networkService } from "../shared/network/service" import { preAuthorize } from "../shared/preAuthorizations" import { isEqualWalletAddress } from "../shared/wallet.service" import { assertNever } from "../ui/services/assertNever" import { accountDeployAction } from "./accountDeployAction" import { analytics } from "./analytics" -import { BackgroundService } from "./background" -import { multisigDeployAction } from "./multisigDeployAction" +import { multisigDeployAction } from "./multisig/multisigDeployAction" import { openUi } from "./openUi" import { executeTransactionAction } from "./transactions/transactionExecution" import { udcDeclareContract, udcDeployContract } from "./udcAction" +import { Wallet } from "./wallet" export const handleActionApproval = async ( - action: ExtQueueItem, - background: BackgroundService, + action: ExtensionActionItem, + wallet: Wallet, ): Promise => { - const { wallet } = background const actionHash = action.meta.hash + const selectedAccount = await wallet.getSelectedAccount() + const networkId = selectedAccount?.networkId || "unknown" switch (action.type) { case "CONNECT_DAPP": { const { host } = action.payload - const selectedAccount = await wallet.getSelectedAccount() if (!selectedAccount) { void openUi() @@ -32,7 +34,7 @@ export const handleActionApproval = async ( void analytics.track("preauthorizeDapp", { host, - networkId: selectedAccount.networkId, + networkId, }) await preAuthorize(selectedAccount, host) @@ -41,14 +43,32 @@ export const handleActionApproval = async ( } case "TRANSACTION": { + const host = action.meta.origin try { - const response = await executeTransactionAction(action, background) + void analytics.track("signedTransaction", { + networkId, + host, + }) + + const response = await executeTransactionAction(action, wallet) + + void analytics.track("sentTransaction", { + success: true, + networkId, + host, + }) return { type: "TRANSACTION_SUBMITTED", data: { txHash: response.transaction_hash, actionHash }, } - } catch (error: unknown) { + } catch (error) { + void analytics.track("sentTransaction", { + success: false, + networkId, + host, + }) + return { type: "TRANSACTION_FAILED", data: { actionHash, error: `${error}` }, @@ -58,7 +78,11 @@ export const handleActionApproval = async ( case "DEPLOY_ACCOUNT_ACTION": { try { - const txHash = await accountDeployAction(action, background) + void analytics.track("signedTransaction", { + networkId, + }) + + const txHash = await accountDeployAction(action, wallet) void analytics.track("deployAccount", { status: "success", @@ -66,16 +90,26 @@ export const handleActionApproval = async ( networkId: action.payload.networkId, }) + void analytics.track("sentTransaction", { + success: true, + networkId, + }) + return { type: "DEPLOY_ACCOUNT_ACTION_SUBMITTED", data: { txHash, actionHash }, } - } catch (exception: unknown) { + } catch (exception) { let error = `${exception}` if (error.includes("403")) { error = `${error}\n\nA 403 error means there's already something running on the selected port. On macOS, AirPlay is using port 5000 by default, so please try running your node on another port and changing the port in Argent X settings.` } + void analytics.track("sentTransaction", { + success: false, + networkId, + }) + void analytics.track("deployAccount", { status: "failure", networkId: action.payload.networkId, @@ -91,7 +125,11 @@ export const handleActionApproval = async ( case "DEPLOY_MULTISIG_ACTION": { try { - const txHash = await multisigDeployAction(action, background) + void analytics.track("signedTransaction", { + networkId, + }) + + const txHash = await multisigDeployAction(action, wallet) void analytics.track("deployMultisig", { status: "success", @@ -99,26 +137,29 @@ export const handleActionApproval = async ( networkId: action.payload.networkId, }) - return { - type: "DEPLOY_MULTISIG_ACTION_SUBMITTED", - data: { txHash, actionHash }, - } - } catch (exception: unknown) { + void analytics.track("sentTransaction", { + success: true, + networkId, + }) + break + } catch (exception) { let error = `${exception}` + console.error(error) if (error.includes("403")) { error = `${error}\n\nA 403 error means there's already something running on the selected port. On macOS, AirPlay is using port 5000 by default, so please try running your node on another port and changing the port in Argent X settings.` } + void analytics.track("sentTransaction", { + success: false, + networkId, + }) + void analytics.track("deployMultisig", { status: "failure", networkId: action.payload.networkId, errorMessage: `${error}`, }) - - return { - type: "DEPLOY_MULTISIG_ACTION_FAILED", - data: { actionHash, error: `${error}` }, - } + break } } @@ -128,13 +169,19 @@ export const handleActionApproval = async ( throw Error("you need an open session") } const starknetAccount = await wallet.getSelectedStarknetAccount() + const selectedAccount = await wallet.getSelectedAccount() const signature = await starknetAccount.signMessage(typedData) + const formattedSignature = stark.signatureToDecimalArray(signature) + + await analytics.track("signedMessage", { + networkId: selectedAccount?.networkId || "unknown", + }) return { type: "SIGNATURE_SUCCESS", data: { - signature, + signature: formattedSignature, actionHash, }, } @@ -147,13 +194,26 @@ export const handleActionApproval = async ( } } - case "REQUEST_SWITCH_CUSTOM_NETWORK": { + case "REQUEST_ADD_CUSTOM_NETWORK": { try { - const networks = await getNetworks() + await networkService.add(action.payload) + return { + type: "APPROVE_REQUEST_ADD_CUSTOM_NETWORK", + data: { actionHash }, + } + } catch (error) { + return { + type: "REJECT_REQUEST_ADD_CUSTOM_NETWORK", + data: { actionHash }, + } + } + } + case "REQUEST_SWITCH_CUSTOM_NETWORK": { + try { const { chainId } = action.payload - const network = networks.find((n) => n.chainId === chainId) + const network = await networkService.getByChainId(chainId) if (!network) { throw Error(`Network with chainId ${chainId} not found`) @@ -197,21 +257,32 @@ export const handleActionApproval = async ( case "DECLARE_CONTRACT_ACTION": { try { - const { classHash, txHash } = await udcDeclareContract( - action, - background, - ) + void analytics.track("signedDeclareTransaction", { + networkId, + }) + + const { classHash, txHash } = await udcDeclareContract(action, wallet) + + void analytics.track("sentTransaction", { + success: true, + networkId, + }) return { type: "DECLARE_CONTRACT_ACTION_SUBMITTED", data: { txHash, actionHash, classHash }, } - } catch (exception: unknown) { + } catch (exception) { let error = `${exception}` if (error.includes("403")) { error = `${error}\n\nA 403 error means there's already something running on the selected port. On macOS, AirPlay is using port 5000 by default, so please try running your node on another port and changing the port in Argent X settings.` } + void analytics.track("sentTransaction", { + success: false, + networkId, + }) + return { type: "DECLARE_CONTRACT_ACTION_FAILED", data: { actionHash, error: `${error}` }, @@ -221,11 +292,20 @@ export const handleActionApproval = async ( case "DEPLOY_CONTRACT_ACTION": { try { + void analytics.track("signedDeployTransaction", { + networkId, + }) + const { txHash, contractAddress } = await udcDeployContract( action, - background, + wallet, ) + void analytics.track("sentTransaction", { + success: true, + networkId, + }) + return { type: "DEPLOY_CONTRACT_ACTION_SUBMITTED", data: { @@ -234,12 +314,17 @@ export const handleActionApproval = async ( actionHash, }, } - } catch (exception: unknown) { + } catch (exception) { let error = `${exception}` if (error.includes("403")) { error = `${error}\n\nA 403 error means there's already something running on the selected port. On macOS, AirPlay is using port 5000 by default, so please try running your node on another port and changing the port in Argent X settings.` } + void analytics.track("sentTransaction", { + success: false, + networkId, + }) + return { type: "DEPLOY_CONTRACT_ACTION_FAILED", data: { actionHash, error: `${error}` }, @@ -253,8 +338,7 @@ export const handleActionApproval = async ( } export const handleActionRejection = async ( - action: ExtQueueItem, - _: BackgroundService, + action: ExtensionActionItem, ): Promise => { const actionHash = action.meta.hash @@ -284,10 +368,7 @@ export const handleActionRejection = async ( } case "DEPLOY_MULTISIG_ACTION": { - return { - type: "DEPLOY_MULTISIG_ACTION_FAILED", - data: { actionHash }, - } + break } case "SIGN": { @@ -304,6 +385,13 @@ export const handleActionRejection = async ( } } + case "REQUEST_ADD_CUSTOM_NETWORK": { + return { + type: "REJECT_REQUEST_ADD_CUSTOM_NETWORK", + data: { actionHash }, + } + } + case "REQUEST_SWITCH_CUSTOM_NETWORK": { return { type: "REJECT_REQUEST_SWITCH_CUSTOM_NETWORK", diff --git a/packages/extension/src/background/actionMessaging.ts b/packages/extension/src/background/actionMessaging.ts index 585dc22ac..dd4ebed55 100644 --- a/packages/extension/src/background/actionMessaging.ts +++ b/packages/extension/src/background/actionMessaging.ts @@ -1,62 +1,24 @@ import { ActionMessage } from "../shared/messages/ActionMessage" -import { handleActionApproval, handleActionRejection } from "./actionHandlers" -import { sendMessageToUi } from "./activeTabs" import { UnhandledMessage } from "./background" import { HandleMessage } from "./background" export const handleActionMessage: HandleMessage = async ({ msg, - background, + origin, + background: { actionService }, respond, }) => { - const { actionQueue } = background - switch (msg.type) { - case "GET_ACTIONS": { - const actions = await actionQueue.getAll() - return sendMessageToUi({ - type: "GET_ACTIONS_RES", - data: actions, - }) - } - - case "APPROVE_ACTION": { - const { actionHash } = msg.data - const action = await actionQueue.remove(actionHash) - if (!action) { - throw new Error("Action not found") - } - const resultMessage = await handleActionApproval(action, background) - - if (resultMessage) { - respond(resultMessage) - } - return - } - - case "REJECT_ACTION": { - const payload = msg.data.actionHash - - const actionHashes = Array.isArray(payload) ? payload : [payload] - - for (const actionHash of actionHashes) { - const action = await actionQueue.remove(actionHash) - if (!action) { - throw new Error("Action not found") - } - const resultMessage = await handleActionRejection(action, background) - if (resultMessage) { - respond(resultMessage) - } - } - return - } - case "SIGN_MESSAGE": { - const { meta } = await actionQueue.push({ - type: "SIGN", - payload: msg.data, - }) + const { meta } = await actionService.add( + { + type: "SIGN", + payload: msg.data, + }, + { + origin, + }, + ) return respond({ type: "SIGN_MESSAGE_RES", @@ -67,7 +29,7 @@ export const handleActionMessage: HandleMessage = async ({ } case "SIGNATURE_FAILURE": { - return await actionQueue.remove(msg.data.actionHash) + return await actionService.remove(msg.data.actionHash) } } diff --git a/packages/extension/src/background/actionQueue.ts b/packages/extension/src/background/actionQueue.ts deleted file mode 100644 index f8c730a20..000000000 --- a/packages/extension/src/background/actionQueue.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { partition } from "lodash-es" -import oHash from "object-hash" - -import { ExtQueueItem } from "../shared/actionQueue/types" -import type { IArrayStorage } from "../shared/storage/array" - -function objectHash(obj: object | null) { - return oHash(obj, { unorderedArrays: true }) -} - -type AllObjects = Record - -export interface Queue { - getAll: () => Promise[]> - push: (item: T, expires?: number) => Promise> - remove: (hash: string) => Promise | null> -} - -export async function getQueue( - storage: IArrayStorage>, -): Promise> { - async function getAll(): Promise[]> { - const allInQueue = await storage.get() - const [notExpiredQueue, expiredItems] = partition( - allInQueue, - (item) => item.meta.expires > Date.now(), - ) - - // set queue to storage if it has changed - if (expiredItems.length) { - await storage.remove(expiredItems) - } - - return notExpiredQueue - } - - async function push( - item: T, - expires: number = 5 * 60 * 60 * 1000, // 5 hours - ): Promise> { - const hash = objectHash(item) - const newItem = { - ...item, - meta: { - hash, - expires: Date.now() + expires, - }, - } - - await storage.unshift(newItem) - - return newItem - } - - async function remove(hash: string): Promise | null> { - const [item] = await storage.remove((item) => item.meta.hash === hash) - return item ?? null - } - - return { - getAll, - push, - remove, - } -} diff --git a/packages/extension/src/background/activeTabs.ts b/packages/extension/src/background/activeTabs.ts index 4400935e8..3db2636d8 100644 --- a/packages/extension/src/background/activeTabs.ts +++ b/packages/extension/src/background/activeTabs.ts @@ -1,52 +1,52 @@ import browser from "webextension-polyfill" import { MessageType, sendMessage } from "../shared/messages" -import { ArrayStorage } from "../shared/storage" +import { UniqueSet } from "./utils/uniqueSet" interface Tab { id: number host: string port: browser.runtime.Port } -const activeTabs = new ArrayStorage([], { - namespace: "core:activeTabs", - areaName: "session", - compare(a, b) { - return a.id === b.id - }, -}) + +// do not store the port in any storage, like ArrayStorage. +// it is not serializable and will cause errors +// ports also get closed when the background worker is reloaded, and they should automatically reconnect +const activeTabs = new UniqueSet((t) => t.id) browser.tabs.onRemoved.addListener(removeTab) export async function addTab(tab: Tab) { if (tab.id !== undefined) { - return activeTabs.push(tab) + return activeTabs.add(tab) } } export function removeTab(tabId?: number) { - return activeTabs.remove((tab) => tab.id === tabId) + if (tabId === undefined) { + return false + } + return activeTabs.delete(tabId) } export async function hasTab(tabId?: number) { if (tabId === undefined) { return false } - const [hit] = await activeTabs.get((tab) => tab.id === tabId) - return Boolean(hit) + return activeTabs.has(tabId) } -export async function getTabIdsOfHost(host: string) { - const hits = await activeTabs.get((tab) => tab.host === host) - return hits ? hits.map((tab) => tab.id) : [] +async function getTabsOfHost(host: string) { + const allTabs = activeTabs.getAll() + const hits = allTabs.filter((tab) => tab.host === host) + return hits } export async function sendMessageToHost( message: MessageType, host: string, ): Promise { - const tabIds = await getTabIdsOfHost(host) - const tabs = await activeTabs.get((tab) => tabIds.includes(tab.id)) + const tabs = await getTabsOfHost(host) for (const tab of tabs) { try { @@ -60,7 +60,7 @@ export async function sendMessageToHost( export async function sendMessageToActiveTabs( message: MessageType, ): Promise { - const tabs = await activeTabs.get() + const tabs = activeTabs.getAll() for (const tab of tabs) { try { diff --git a/packages/extension/src/background/background.ts b/packages/extension/src/background/background.ts index ec8350b1d..6794900ad 100644 --- a/packages/extension/src/background/background.ts +++ b/packages/extension/src/background/background.ts @@ -1,16 +1,15 @@ import browser from "webextension-polyfill" -import { ActionItem } from "../shared/actionQueue/types" -import { MessageType } from "../shared/messages" -import { Queue } from "./actionQueue" -import { MessagingKeys } from "./keys/messagingKeys" -import { TransactionTracker } from "./transactions/tracking" +import { IBackgroundActionService } from "./__new/services/action/interface" +import type { MessagingKeys } from "./keys/messagingKeys" +import type { Respond } from "./respond" import { Wallet } from "./wallet" +import { TransactionTrackerWorker } from "./transactions/service/starknet.service" export interface BackgroundService { wallet: Wallet - transactionTracker: TransactionTracker - actionQueue: Queue + transactionTrackerWorker: TransactionTrackerWorker + actionService: IBackgroundActionService } export class UnhandledMessage extends Error { @@ -23,10 +22,11 @@ export class UnhandledMessage extends Error { interface HandlerParams { msg: T sender: browser.runtime.MessageSender + origin: string port?: browser.runtime.Port background: BackgroundService messagingKeys: MessagingKeys - respond: (msg: MessageType) => Promise + respond: Respond } export type HandleMessage = (params: HandlerParams) => Promise diff --git a/packages/extension/src/background/devnet/declareAccounts.ts b/packages/extension/src/background/devnet/declareAccounts.ts index d55af0a75..bdbbf1794 100644 --- a/packages/extension/src/background/devnet/declareAccounts.ts +++ b/packages/extension/src/background/devnet/declareAccounts.ts @@ -1,14 +1,14 @@ import { memoize } from "lodash-es" -import { Account, AccountInterface, ec } from "starknet" -import { hash } from "starknet5" +import { Account, AccountInterface, hash } from "starknet" import urlJoin from "url-join" import { Network, getProvider } from "../../shared/network" -import { LoadContracts } from "../accounts" +import { LoadContracts } from "../wallet/loadContracts" import { ARGENT_ACCOUNT_CONTRACT_CLASS_HASHES, PROXY_CONTRACT_CLASS_HASHES, -} from "../wallet" +} from "../wallet/starknet.constants" +import { getNetworkUrl } from "../../shared/network/utils" interface PreDeployedAccount { address: string @@ -20,8 +20,10 @@ export const getPreDeployedAccount = async ( index = 0, ): Promise => { try { + const networkUrl = getNetworkUrl(network) + const preDeployedAccounts = await fetch( - urlJoin(network.baseUrl, "predeployed_accounts"), + urlJoin(networkUrl, "predeployed_accounts"), ).then((x) => x.json() as Promise) const preDeployedAccount = preDeployedAccounts[index] @@ -30,8 +32,13 @@ export const getPreDeployedAccount = async ( } const provider = getProvider(network) - const keypair = ec.getKeyPair(preDeployedAccount.private_key) - return new Account(provider, preDeployedAccount.address, keypair) + + return new Account( + provider, + preDeployedAccount.address, + preDeployedAccount.private_key, + "0", // Devnet is currently supporting only cairo 0 + ) } catch (e) { console.warn(`Failed to get pre-deployed account: ${e}`) return null @@ -69,7 +76,9 @@ export const declareContracts = memoize( contract: proxyContract, }) - await deployAccount.waitForTransaction(proxy.transaction_hash, 1e3) + await deployAccount.waitForTransaction(proxy.transaction_hash, { + retryInterval: 1e3, + }) proxyClassHash = proxy.class_hash } @@ -80,7 +89,9 @@ export const declareContracts = memoize( contract: accountContract, }) - await deployAccount.waitForTransaction(account.transaction_hash, 1e3) + await deployAccount.waitForTransaction(account.transaction_hash, { + retryInterval: 1e3, + }) accountClassHash = account.class_hash } @@ -90,7 +101,7 @@ export const declareContracts = memoize( accountClassHash: accountClassHash ?? computedAccountClassHash, } }, - (network) => `${network.baseUrl}`, + (network) => `${network.sequencerUrl}`, ) export const checkIfClassIsDeclared = async ( diff --git a/packages/extension/src/background/download.ts b/packages/extension/src/background/download.ts deleted file mode 100644 index 1c860e588..000000000 --- a/packages/extension/src/background/download.ts +++ /dev/null @@ -1,5 +0,0 @@ -import browser from "webextension-polyfill" - -export async function downloadFile(data: { url: string; filename: string }) { - browser.downloads.download(data) -} diff --git a/packages/extension/src/background/index.ts b/packages/extension/src/background/index.ts index ebb8e4b51..ba91148fb 100644 --- a/packages/extension/src/background/index.ts +++ b/packages/extension/src/background/index.ts @@ -1,324 +1,26 @@ import "./__new/router" +import "./transactions/service/worker" +import "./migrations" -import { StarknetMethodArgumentsSchemas } from "@argent/x-window" -import browser from "webextension-polyfill" - -import { accountService } from "../shared/account/service" -import { globalActionQueueStore } from "../shared/actionQueue/store" -import { ActionItem } from "../shared/actionQueue/types" -import { MessageType, messageStream } from "../shared/messages" -import { multisigTracker } from "../shared/multisig/tracking" -import { - isPreAuthorized, - migratePreAuthorizations, -} from "../shared/preAuthorizations" -import { delay } from "../shared/utils/delay" -import { migrateWallet } from "../shared/wallet/storeMigration" -import { handleAccountMessage } from "./accountMessaging" -import { handleActionMessage } from "./actionMessaging" -import { getQueue } from "./actionQueue" -import { - hasTab, - sendMessageToActiveTabs, - sendMessageToActiveTabsAndUi, - sendMessageToUi, -} from "./activeTabs" -import { - BackgroundService, - HandleMessage, - UnhandledMessage, -} from "./background" -import { getMessagingKeys } from "./keys/messagingKeys" -import { handleMiscellaneousMessage } from "./miscellaneousMessaging" -import { handleMultisigMessage } from "./multisigMessaging" -import { networkService } from "./network/network.service" -import { handleNetworkMessage } from "./networkMessaging" -import { initOnboarding } from "./onboarding" -import { - getOriginFromSender, - handlePreAuthorizationMessage, -} from "./preAuthorizationMessaging" -import { handleSessionMessage } from "./sessionMessaging" -import { handleShieldMessage } from "./shieldMessaging" -import { handleTokenMessaging } from "./tokenMessaging" +import { messageStream } from "../shared/messages" +import { initWorkers } from "./workers" import { initBadgeText } from "./transactions/badgeText" -import { transactionTracker } from "./transactions/tracking" -import { handleTransactionMessage } from "./transactions/transactionMessaging" -import { handleUdcMessaging } from "./udcMessaging" -import { walletSingleton } from "./walletSingleton" - -const DEFAULT_POLLING_INTERVAL = 15 -const LOCAL_POLLING_INTERVAL = 5 - -const enum ALARM_NAMES { - TRANSACTION_TRACKER_HISTORY = "core:transactionTracker:history", - TRANSACTION_TRACKER_UPDATE = "core:transactionTracker:update", - MULTISIG_ACCOUNT_UPDATE = "core:multisig:updateDataForAccounts", - MULTISIG_PENDING_UPDATE = "core:multisig:updateDataForPendingMultisig", - MULTISIG_TRANSACTION_TRACKER = "core:multisig:transactionTracker", - NETWORK_STATUS_TRACKER = "core:networkStatusTracker:update", -} - -browser.alarms.create(ALARM_NAMES.TRANSACTION_TRACKER_HISTORY, { - periodInMinutes: 5, // fetch history transactions every 5 minutes from voyager -}) -browser.alarms.create(ALARM_NAMES.TRANSACTION_TRACKER_UPDATE, { - periodInMinutes: 1, // fetch transaction updates of existing transactions every minute from onchain -}) -browser.alarms.create(ALARM_NAMES.MULTISIG_ACCOUNT_UPDATE, { - periodInMinutes: 5, // fetch multisig updates of existing multisigs every 5 minutes from backend -}) -browser.alarms.create(ALARM_NAMES.MULTISIG_PENDING_UPDATE, { - periodInMinutes: 3, // fetch pending multisig updates of existing multisigs every 3 minutes from backend -}) -browser.alarms.create(ALARM_NAMES.MULTISIG_TRANSACTION_TRACKER, { - periodInMinutes: 2, // fetch transaction updates of existing multisig every 2 minutes from backend -}) - -// eslint-disable-next-line @typescript-eslint/no-misused-promises -browser.alarms.onAlarm.addListener(async (alarm) => { - switch (alarm.name) { - case ALARM_NAMES.TRANSACTION_TRACKER_HISTORY: { - console.info("~> fetching transaction history") - await transactionTracker.loadHistory(await accountService.get()) - break - } - - case ALARM_NAMES.MULTISIG_ACCOUNT_UPDATE: { - console.info("~> fetching multisig account updates") - await multisigTracker.updateDataForAccounts() - break - } - - case ALARM_NAMES.MULTISIG_PENDING_UPDATE: { - console.info("~> fetching pending multisig account updates") - await multisigTracker.updateDataForPendingMultisig() - break - } - - case ALARM_NAMES.MULTISIG_TRANSACTION_TRACKER: { - console.info("~> fetching multisig transaction updates") - await multisigTracker.updateTransactions() - break - } - - case ALARM_NAMES.TRANSACTION_TRACKER_UPDATE: { - console.info("~> fetching transaction updates") - let inFlightTransactions = await transactionTracker.update() - // the config below will run transaction updates 4x per minute, if there are in-flight transactions - // By default it will update on second 0, 15, 30 and 45 but by updating WAIT_TIME we can change the number of executions - const maxExecutionTimeInMs = 60000 // 1 minute max execution time - let transactionPollingIntervalInS = DEFAULT_POLLING_INTERVAL - const startTime = Date.now() - - while ( - inFlightTransactions.length > 0 && - Date.now() - startTime < maxExecutionTimeInMs - ) { - const localTransaction = inFlightTransactions.find( - (tx) => tx.account.networkId === "localhost", - ) - if (localTransaction) { - transactionPollingIntervalInS = LOCAL_POLLING_INTERVAL - } else { - transactionPollingIntervalInS = DEFAULT_POLLING_INTERVAL - } - console.info( - `~> waiting ${transactionPollingIntervalInS}s for transaction updates`, - ) - await delay(transactionPollingIntervalInS * 1000) - console.info( - "~> fetching transaction updates as pending transactions were detected", - ) - inFlightTransactions = await transactionTracker.update() - } - break - } - - case ALARM_NAMES.NETWORK_STATUS_TRACKER: { - await networkService.updateStatuses() - break - } - - default: - break - } -}) +import { transactionTrackerWorker } from "./transactions/service/worker" +import { handleMessage } from "./messageHandling/handle" +import { addMessageListeners } from "./messageHandling/addMessageListeners" // badge shown on extension icon - initBadgeText() -// runs on startup - -const handlers = [ - handleAccountMessage, - handleActionMessage, - handleMiscellaneousMessage, - handleNetworkMessage, - handlePreAuthorizationMessage, - handleSessionMessage, - handleTransactionMessage, - handleTokenMessaging, - handleUdcMessaging, - handleShieldMessage, - handleMultisigMessage, -] as Array> - -accountService - .get() - .then((x) => transactionTracker.loadHistory(x)) +// load transaction history +transactionTrackerWorker + .loadHistory() .catch(() => console.warn("failed to load transaction history")) -const safeMessages: MessageType["type"][] = [ - "IS_PREAUTHORIZED", - "CONNECT_DAPP", - "DISCONNECT_ACCOUNT", - "OPEN_UI", - // answers - "EXECUTE_TRANSACTION_RES", - "TRANSACTION_SUBMITTED", - "TRANSACTION_FAILED", - "SIGN_MESSAGE_RES", - "SIGNATURE_SUCCESS", - "SIGNATURE_FAILURE", - "IS_PREAUTHORIZED_RES", - "REQUEST_TOKEN_RES", - "APPROVE_REQUEST_TOKEN", - "REJECT_REQUEST_TOKEN", - "REQUEST_ADD_CUSTOM_NETWORK_RES", - "APPROVE_REQUEST_ADD_CUSTOM_NETWORK", - "REJECT_REQUEST_ADD_CUSTOM_NETWORK", - "REQUEST_SWITCH_CUSTOM_NETWORK_RES", - "APPROVE_REQUEST_SWITCH_CUSTOM_NETWORK", - "REJECT_REQUEST_SWITCH_CUSTOM_NETWORK", - "CONNECT_DAPP_RES", - "CONNECT_ACCOUNT_RES", - "REJECT_PREAUTHORIZATION", - "REQUEST_DECLARE_CONTRACT_RES", - "DECLARE_CONTRACT_ACTION_FAILED", - "DECLARE_CONTRACT_ACTION_SUBMITTED", -] - -const safeIfPreauthorizedMessages: MessageType["type"][] = [ - "EXECUTE_TRANSACTION", - "SIGN_MESSAGE", - "REQUEST_TOKEN", - "REQUEST_SWITCH_CUSTOM_NETWORK", - "REQUEST_DECLARE_CONTRACT", -] - -const handleMessage = async ( - [msg, sender]: [MessageType, browser.runtime.MessageSender], - port?: browser.runtime.Port, -) => { - await Promise.all([migrateWallet(), migratePreAuthorizations()]) // do migrations before handling messages - - const messagingKeys = await getMessagingKeys() - - const actionQueue = await getQueue(globalActionQueueStore) - - const background: BackgroundService = { - wallet: walletSingleton, - transactionTracker, - actionQueue, - } - - const extensionUrl = browser.extension.getURL("") - const safeOrigin = extensionUrl.replace(/\/$/, "") - const origin = getOriginFromSender(sender) - const isSafeOrigin = Boolean(origin === safeOrigin) - - const currentAccount = await walletSingleton.getSelectedAccount() - const senderIsPreauthorized = - !!currentAccount && (await isPreAuthorized(currentAccount, origin)) - - if ( - !isSafeOrigin && // allow all messages from the extension itself - !safeMessages.includes(msg.type) && // allow messages that are needed to get into preauthorization state - !(senderIsPreauthorized && safeIfPreauthorizedMessages.includes(msg.type)) // allow additional messages if sender is preauthorized - ) { - console.warn( - `received message of type ${msg.type} from ${origin} but it is not allowed`, - ) - return // this return must not be removed - } - - // forward UI messages to rest of the tabs - if (isSafeOrigin) { - if (await hasTab(sender.tab?.id)) { - await sendMessageToActiveTabs(msg) - } - } - - const respond = async (msg: MessageType) => { - if (safeMessages.includes(msg.type)) { - await sendMessageToActiveTabsAndUi(msg) - } else { - await sendMessageToUi(msg) - } - } - - for (const handleMessage of handlers) { - try { - await handleMessage({ - msg, - sender, - background, - messagingKeys, - port, - respond, - }) - } catch (error) { - if (error instanceof UnhandledMessage) { - continue - } - throw error - } - break - } -} - -browser.runtime.onConnect.addListener((port) => { - // eslint-disable-next-line @typescript-eslint/no-misused-promises - port.onMessage.addListener(async (msg: MessageType, port) => { - const sender = port.sender - if (sender) { - switch (msg.type) { - case "EXECUTE_TRANSACTION": { - const [transactions, abis, transactionsDetail] = - await StarknetMethodArgumentsSchemas.execute.parseAsync([ - msg.data.transactions, - msg.data.abis, - msg.data.transactionsDetail, - ]) - return handleMessage( - [ - { ...msg, data: { transactions, abis, transactionsDetail } }, - sender, - ], - port, - ) - } - - case "SIGN_MESSAGE": { - const [message] = - await StarknetMethodArgumentsSchemas.signMessage.parseAsync([ - msg.data, - ]) - return handleMessage([{ ...msg, data: message }, sender], port) - } - - default: - return handleMessage([msg, sender], port) - } - } - }) -}) +addMessageListeners() // eslint-disable-next-line @typescript-eslint/no-misused-promises messageStream.subscribe(handleMessage) -// open onboarding flow on initial install - -initOnboarding() +// start workers +initWorkers() diff --git a/packages/extension/src/background/keys/keyDerivation.ts b/packages/extension/src/background/keys/keyDerivation.ts index 48bef3907..21d49152a 100644 --- a/packages/extension/src/background/keys/keyDerivation.ts +++ b/packages/extension/src/background/keys/keyDerivation.ts @@ -1,23 +1,93 @@ -import { BigNumber, BigNumberish, utils } from "ethers" -import { isNumber } from "lodash-es" -import { KeyPair, ec, number } from "starknet" +import { Hex, bytesToHex, hexToBytes } from "@noble/curves/abstract/utils" +import { sha256 } from "@noble/hashes/sha256" +import { HDKey } from "@scure/bip32" +import { isFunction, isNumber } from "lodash-es" +import { encode, num } from "starknet" +import { getStarkKey, grindKey as microGrindKey } from "micro-starknet" + +const { addHexPrefix } = encode + +export interface KeyPair { + pubKey: string + getPrivate: () => string +} + +export interface KeyPairWithIndex extends KeyPair { + index: number +} + +export interface PublicKeyWithIndex { + pubKey: string + index: number +} export function getStarkPair( indexOrPath: T, - secret: BigNumberish, + secret: string, ...[baseDerivationPath]: T extends string ? [] : [string] ): KeyPair { - const masterNode = utils.HDNode.fromSeed(BigNumber.from(secret).toHexString()) + const hex = encode.removeHexPrefix(num.toHex(secret)) + + // Bytes must be a multiple of 2 and default is multiple of 8 + // sanitizeHex should not be used because of leading 0x + const sanitized = encode.sanitizeBytes(hex, 2) + + const masterNode = HDKey.fromMasterSeed(hexToBytes(sanitized)) // baseDerivationPath will never be undefined because of the extends statement below, // but somehow TS doesnt get this. As this will be removed in the near future I didnt bother const path: string = isNumber(indexOrPath) ? getPathForIndex(indexOrPath, baseDerivationPath ?? "") : indexOrPath - const childNode = masterNode.derivePath(path) + const childNode = masterNode.derive(path) + + if (!childNode.privateKey) { + throw "childNode.privateKey is undefined" + } + const groundKey = grindKey(childNode.privateKey) - const starkPair = ec.getKeyPair(groundKey) - return starkPair + + return { + pubKey: encode.sanitizeHex(getStarkKey(groundKey)), + getPrivate: () => encode.sanitizeHex(groundKey), + } +} + +/** + * Grinds a private key to a valid StarkNet private key + * @param privateKey + * @returns Unsantized hex string + */ +export function grindKey(privateKey: Hex): string { + return addHexPrefix(microGrindKey(privateKey)) +} + +export function generateStarkKeyPairs( + secret: string, + start: number, + numberOfPairs: number, + baseDerivationPath: string, +): KeyPairWithIndex[] { + const keyPairs: KeyPairWithIndex[] = [] + for (let index = start; index < start + numberOfPairs; index++) { + keyPairs.push({ ...getStarkPair(index, secret, baseDerivationPath), index }) + } + return keyPairs +} + +export function generatePublicKeys( + secret: string, + start: number, + numberOfPairs: number, + baseDerivationPath: string, +): PublicKeyWithIndex[] { + const keyPairs = generateStarkKeyPairs( + secret, + start, + numberOfPairs, + baseDerivationPath, + ) + return keyPairs.map(({ pubKey, index }) => ({ pubKey, index })) } export function getPathForIndex( @@ -47,41 +117,15 @@ export function getNextPathIndex( return paths.length } -// inspired/copied from https://github.com/authereum/starkware-monorepo/blob/51c5df19e7f98399a2f7e63d564210d761d138d1/packages/starkware-crypto/src/keyDerivation.ts#L85 -export function grindKey(keySeed: string): string { - const keyValueLimit = ec.ec.n - if (!keyValueLimit) { - return keySeed - } - const sha256EcMaxDigest = number.toBN( - "1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000", - 16, - ) - const maxAllowedVal = sha256EcMaxDigest.sub( - sha256EcMaxDigest.mod(keyValueLimit), +export function pathHash(name: string): number { + const bigHash = BigInt.asUintN( + 31, + BigInt(addHexPrefix(bytesToHex(sha256(name)))), ) - // Make sure the produced key is devided by the Stark EC order, - // and falls within the range [0, maxAllowedVal). - let i = 0 - let key - do { - key = hashKeyWithIndex(keySeed, i) - i++ - } while (!key.lt(maxAllowedVal)) - - return "0x" + key.umod(keyValueLimit).toString("hex") + return Number(bigHash) } -function hashKeyWithIndex(key: string, index: number) { - const payload = utils.concat([utils.arrayify(key), utils.arrayify(index)]) - const hash = utils.sha256(payload) - return number.toBN(hash) -} - -export function pathHash(name: string): number { - return number - .toBN(utils.sha256(utils.toUtf8Bytes(name))) - .maskn(31) - .toNumber() +export function isKeyPair(val: any): val is KeyPair { + return val && val.pubKey && isFunction(val.getPrivate) } diff --git a/packages/extension/src/background/messageHandling/addMessageListeners.ts b/packages/extension/src/background/messageHandling/addMessageListeners.ts new file mode 100644 index 000000000..640273ecb --- /dev/null +++ b/packages/extension/src/background/messageHandling/addMessageListeners.ts @@ -0,0 +1,43 @@ +import browser from "webextension-polyfill" +import { StarknetMethodArgumentsSchemas } from "@argent/x-window" +import { MessageType } from "../../shared/messages" +import { handleMessage } from "./handle" + +export const addMessageListeners = () => { + browser.runtime.onConnect.addListener((port) => { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + port.onMessage.addListener(async (msg: MessageType, port) => { + const sender = port.sender + if (sender) { + switch (msg.type) { + case "EXECUTE_TRANSACTION": { + const [transactions, abis, transactionsDetail] = + await StarknetMethodArgumentsSchemas.execute.parseAsync([ + msg.data.transactions, + msg.data.abis, + msg.data.transactionsDetail, + ]) + return handleMessage( + [ + { ...msg, data: { transactions, abis, transactionsDetail } }, + sender, + ], + port, + ) + } + + case "SIGN_MESSAGE": { + const [message] = + await StarknetMethodArgumentsSchemas.signMessage.parseAsync([ + msg.data, + ]) + return handleMessage([{ ...msg, data: message }, sender], port) + } + + default: + return handleMessage([msg, sender], port) + } + } + }) + }) +} diff --git a/packages/extension/src/background/messageHandling/handle.ts b/packages/extension/src/background/messageHandling/handle.ts new file mode 100644 index 000000000..d3170a001 --- /dev/null +++ b/packages/extension/src/background/messageHandling/handle.ts @@ -0,0 +1,104 @@ +import { MessageType } from "../../shared/messages" +import { + migratePreAuthorizations, + isPreAuthorized, +} from "../../shared/preAuthorizations" +import { migrateWallet } from "../../shared/wallet/storeMigration" +import { backgroundActionService } from "../__new/services/action" +import { handleAccountMessage } from "../accountMessaging" +import { handleActionMessage } from "../actionMessaging" +import { hasTab, sendMessageToActiveTabs } from "../activeTabs" +import { + BackgroundService, + HandleMessage, + UnhandledMessage, +} from "../background" +import { getMessagingKeys } from "../keys/messagingKeys" +import { handleMiscellaneousMessage } from "../miscellaneousMessaging" +import { handleNetworkMessage } from "../networkMessaging" +import { + getOriginFromSender, + handlePreAuthorizationMessage, +} from "../preAuthorizationMessaging" +import { respond } from "../respond" +import { handleTokenMessaging } from "../tokenMessaging" +import { transactionTrackerWorker } from "../transactions/service/worker" +import { handleTransactionMessage } from "../transactions/transactionMessaging" +import { handleUdcMessaging } from "../udcMessaging" +import { walletSingleton } from "../walletSingleton" +import { safeMessages, safeIfPreauthorizedMessages } from "./messages" +import browser from "webextension-polyfill" + +const handlers = [ + handleAccountMessage, + handleActionMessage, + handleMiscellaneousMessage, + handleNetworkMessage, + handlePreAuthorizationMessage, + handleTransactionMessage, + handleTokenMessaging, + handleUdcMessaging, +] as Array> + +export const handleMessage = async ( + [msg, sender]: [MessageType, browser.runtime.MessageSender], + port?: browser.runtime.Port, +) => { + await Promise.all([migrateWallet(), migratePreAuthorizations()]) // do migrations before handling messages + + const messagingKeys = await getMessagingKeys() + + /** TODO: refactor into background service singleton pattern */ + const background: BackgroundService = { + wallet: walletSingleton, + transactionTrackerWorker: transactionTrackerWorker, + actionService: backgroundActionService, + } + + const extensionUrl = browser.extension.getURL("") + const safeOrigin = extensionUrl.replace(/\/$/, "") + const origin = getOriginFromSender(sender) + const isSafeOrigin = Boolean(origin === safeOrigin) + + const currentAccount = await walletSingleton.getSelectedAccount() + const senderIsPreauthorized = + !!currentAccount && (await isPreAuthorized(currentAccount, origin)) + + if ( + !isSafeOrigin && // allow all messages from the extension itself + !safeMessages.includes(msg.type) && // allow messages that are needed to get into preauthorization state + !(senderIsPreauthorized && safeIfPreauthorizedMessages.includes(msg.type)) // allow additional messages if sender is preauthorized + ) { + console.warn( + `received message of type ${msg.type} from ${origin} but it is not allowed`, + ) + return // this return must not be removed + } + + // forward UI messages to rest of the tabs + if (isSafeOrigin) { + if (await hasTab(sender.tab?.id)) { + await sendMessageToActiveTabs(msg) + } + } + + for (const handleMessage of handlers) { + try { + await handleMessage({ + msg, + sender, + origin, + background, + messagingKeys, + port, + respond, + }) + } catch (error) { + if (error instanceof UnhandledMessage) { + continue + } + throw error + } + break + } +} diff --git a/packages/extension/src/background/messageHandling/messages.ts b/packages/extension/src/background/messageHandling/messages.ts new file mode 100644 index 000000000..1db62915d --- /dev/null +++ b/packages/extension/src/background/messageHandling/messages.ts @@ -0,0 +1,40 @@ +import { MessageType } from "../../shared/messages" + +export const safeMessages: MessageType["type"][] = [ + "IS_PREAUTHORIZED", + "CONNECT_DAPP", + "DISCONNECT_ACCOUNT", + "OPEN_UI", + // answers + "EXECUTE_TRANSACTION_RES", + "TRANSACTION_SUBMITTED", + "TRANSACTION_FAILED", + "SIGN_MESSAGE_RES", + "SIGNATURE_SUCCESS", + "SIGNATURE_FAILURE", + "IS_PREAUTHORIZED_RES", + "REQUEST_TOKEN_RES", + "APPROVE_REQUEST_TOKEN", + "REJECT_REQUEST_TOKEN", + "REQUEST_ADD_CUSTOM_NETWORK_RES", + "APPROVE_REQUEST_ADD_CUSTOM_NETWORK", + "REJECT_REQUEST_ADD_CUSTOM_NETWORK", + "REQUEST_SWITCH_CUSTOM_NETWORK_RES", + "APPROVE_REQUEST_SWITCH_CUSTOM_NETWORK", + "REJECT_REQUEST_SWITCH_CUSTOM_NETWORK", + "CONNECT_DAPP_RES", + "CONNECT_ACCOUNT_RES", + "REJECT_PREAUTHORIZATION", + "REQUEST_DECLARE_CONTRACT_RES", + "DECLARE_CONTRACT_ACTION_FAILED", + "DECLARE_CONTRACT_ACTION_SUBMITTED", +] + +export const safeIfPreauthorizedMessages: MessageType["type"][] = [ + "EXECUTE_TRANSACTION", + "SIGN_MESSAGE", + "REQUEST_TOKEN", + "REQUEST_ADD_CUSTOM_NETWORK", + "REQUEST_SWITCH_CUSTOM_NETWORK", + "REQUEST_DECLARE_CONTRACT", +] diff --git a/packages/extension/src/background/messagingDocs.md b/packages/extension/src/background/messagingDocs.md index 676c651a9..31b7841ed 100644 --- a/packages/extension/src/background/messagingDocs.md +++ b/packages/extension/src/background/messagingDocs.md @@ -1,147 +1,70 @@ # Messaging -Direct communication from frontend and background service is not allowed and it's done through `messages`. +Direct communication from frontend and background service is not allowed and it's done through `messages`. We use [trpc](https://trpc.io/) alongside the [trpc-chrome](https://github.com/jlalmes/trpc-chrome) dependency to make these messages type-safe and keep the architecture clean and modular. -The React component will call a function defined into a `service` first (located in `/src/ui/services`) +## Mutations / writes ```js const Component = () => { -useEffect(() => { - serviceFunction(argument) -}, []) - -const onClick = () => { - serviceFunction2(argument) -} + const onClick = () => { + someService.doSomethingInTheBackground(argument) + } -return