@aptos-labs/wallet-adapter-core 7.10.2 → 8.0.0-xchaininit.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/WalletCore.d.ts +9 -1
- package/dist/WalletCore.d.ts.map +1 -1
- package/dist/index.d.mts +12 -3
- package/dist/index.d.ts +9 -482
- package/dist/index.js +39 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +33 -22
- package/dist/index.mjs.map +1 -1
- package/dist/registry.d.ts +2 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
- package/src/WalletCore.ts +45 -35
- package/src/registry.ts +24 -18
- package/src/version.ts +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/WalletCore.ts","../src/ga/index.ts","../src/error/index.ts","../src/constants.ts","../src/utils/helpers.ts"],"names":[],"mappings":"","sourcesContent":["export const WALLET_ADAPTER_CORE_VERSION = \"7.10.1\";\n","import EventEmitter from \"eventemitter3\";\nimport {\n AccountAddress,\n AccountAuthenticator,\n AnyRawTransaction,\n Aptos,\n InputSubmitTransactionData,\n Network,\n NetworkToChainId,\n PendingTransactionResponse,\n TransactionSubmitter,\n} from \"@aptos-labs/ts-sdk\";\nimport {\n AptosWallet,\n getAptosWallets,\n isWalletWithRequiredFeatureSet,\n UserResponseStatus,\n AptosSignAndSubmitTransactionOutput,\n UserResponse,\n AptosSignTransactionOutputV1_1,\n AptosSignTransactionInputV1_1,\n AptosSignTransactionMethod,\n AptosSignTransactionMethodV1_1,\n NetworkInfo,\n AccountInfo,\n AptosSignMessageInput,\n AptosSignMessageOutput,\n AptosChangeNetworkOutput,\n AptosSignInInput,\n AptosSignInOutput,\n} from \"@aptos-labs/wallet-standard\";\nimport { AptosConnectWalletConfig } from \"@aptos-connect/wallet-adapter-plugin\";\n\nexport type {\n NetworkInfo,\n AccountInfo,\n AptosSignAndSubmitTransactionOutput,\n AptosSignTransactionOutputV1_1,\n AptosSignMessageInput,\n AptosSignMessageOutput,\n AptosChangeNetworkOutput,\n} from \"@aptos-labs/wallet-standard\";\nexport type {\n AccountAuthenticator,\n AnyRawTransaction,\n InputGenerateTransactionOptions,\n PendingTransactionResponse,\n InputSubmitTransactionData,\n Network,\n AnyPublicKey,\n AccountAddress,\n TransactionSubmitter,\n} from \"@aptos-labs/ts-sdk\";\n\nimport { GA4 } from \"./ga\";\nimport {\n WalletChangeNetworkError,\n WalletAccountChangeError,\n WalletAccountError,\n WalletConnectionError,\n WalletGetNetworkError,\n WalletNetworkChangeError,\n WalletNotConnectedError,\n WalletNotReadyError,\n WalletNotSelectedError,\n WalletSignAndSubmitMessageError,\n WalletSignMessageError,\n WalletSignTransactionError,\n WalletSignMessageAndVerifyError,\n WalletDisconnectionError,\n WalletSubmitTransactionError,\n WalletNotSupportedMethod,\n WalletNotFoundError,\n} from \"./error\";\nimport { ChainIdToAnsSupportedNetworkMap, WalletReadyState } from \"./constants\";\nimport { WALLET_ADAPTER_CORE_VERSION } from \"./version\";\nimport {\n fetchDevnetChainId,\n generalizedErrorMessage,\n getAptosConfig,\n handlePublishPackageTransaction,\n isAptosNetwork,\n isRedirectable,\n removeLocalStorage,\n setLocalStorage,\n} from \"./utils\";\nimport {\n aptosStandardSupportedWalletList,\n crossChainStandardSupportedWalletList,\n} from \"./registry\";\nimport { getSDKWallets } from \"./sdkWallets\";\nimport {\n AvailableWallets,\n AptosStandardSupportedWallet,\n InputTransactionData,\n} from \"./utils/types\";\n\n// An adapter wallet types is a wallet that is compatible with the wallet standard and the wallet adapter properties\nexport type AdapterWallet = AptosWallet & {\n readyState?: WalletReadyState;\n isAptosNativeWallet?: boolean;\n};\n\n// An adapter not detected wallet types is a wallet that is compatible with the wallet standard but not detected\nexport type AdapterNotDetectedWallet = Omit<\n AdapterWallet,\n \"features\" | \"version\" | \"chains\" | \"accounts\"\n> & {\n readyState: WalletReadyState.NotDetected;\n};\n\nexport interface DappConfig {\n network: Network;\n /**\n * If provided, the wallet adapter will submit transactions using the provided\n * transaction submitter rather than via the wallet.\n */\n transactionSubmitter?: TransactionSubmitter;\n aptosApiKeys?: Partial<Record<Network, string>>;\n aptosConnectDappId?: string;\n aptosConnect?: Omit<AptosConnectWalletConfig, \"network\">;\n /**\n * @deprecated will be removed in a future version\n */\n mizuwallet?: {\n manifestURL: string;\n appId?: string;\n };\n /**\n * @deprecated will be removed in a future version\n */\n msafeWalletConfig?: {\n appId?: string;\n appUrl?: string;\n };\n crossChainWallets?: boolean;\n}\n\nexport declare interface WalletCoreEvents {\n connect(account: AccountInfo | null): void;\n disconnect(): void;\n standardWalletsAdded(wallets: AdapterWallet): void;\n standardNotDetectedWalletAdded(wallets: AdapterNotDetectedWallet): void;\n networkChange(network: NetworkInfo | null): void;\n accountChange(account: AccountInfo | null): void;\n}\n\nexport type AdapterAccountInfo = Omit<AccountInfo, \"ansName\"> & {\n // ansName is a read-only property on the standard AccountInfo type\n ansName?: string;\n};\n\nexport class WalletCore extends EventEmitter<WalletCoreEvents> {\n // Local private variable to hold the wallet that is currently connected\n private _wallet: AdapterWallet | null = null;\n\n // Local private variable to hold SDK wallets in the adapter\n private readonly _sdkWallets: AdapterWallet[] = [];\n\n // Local array that holds all the wallets that are AIP-62 standard compatible\n private _standard_wallets: AdapterWallet[] = [];\n\n // Local array that holds all the wallets that are AIP-62 standard compatible but are not installed on the user machine\n private _standard_not_detected_wallets: AdapterNotDetectedWallet[] = [];\n\n // Local private variable to hold the network that is currently connected\n private _network: NetworkInfo | null = null;\n\n // Local private variable to hold the wallet connected state\n private _connected: boolean = false;\n\n // Local private variable to hold the connecting state\n private _connecting: boolean = false;\n\n // Local private variable to hold the account that is currently connected\n private _account: AdapterAccountInfo | null = null;\n\n // JSON configuration for AptosConnect\n private _dappConfig: DappConfig | undefined;\n\n // Private array that holds all the Wallets a dapp decided to opt-in to\n private _optInWallets: ReadonlyArray<AvailableWallets> = [];\n\n // Local flag to disable the adapter telemetry tool\n private _disableTelemetry: boolean = false;\n\n // Google Analytics 4 module\n private readonly ga4: GA4 | null = null;\n\n constructor(\n optInWallets?: ReadonlyArray<AvailableWallets>,\n dappConfig?: DappConfig,\n disableTelemetry?: boolean,\n ) {\n super();\n this._optInWallets = optInWallets || [];\n this._dappConfig = dappConfig;\n this._disableTelemetry = disableTelemetry ?? false;\n this._sdkWallets = getSDKWallets(this._dappConfig);\n\n // If disableTelemetry set to false (by default), start GA4\n if (!this._disableTelemetry) {\n this.ga4 = new GA4();\n }\n // Strategy to detect AIP-62 standard compatible extension wallets\n this.fetchExtensionAIP62AptosWallets();\n // Strategy to detect AIP-62 standard compatible SDK wallets.\n // We separate the extension and sdk detection process so we dont refetch sdk wallets everytime a new\n // extension wallet is detected\n this.fetchSDKAIP62AptosWallets();\n // Strategy to append not detected AIP-62 standard compatible extension wallets\n this.appendNotDetectedStandardSupportedWallets();\n }\n\n private fetchExtensionAIP62AptosWallets(): void {\n let { aptosWallets, on } = getAptosWallets();\n this.setExtensionAIP62Wallets(aptosWallets);\n\n if (typeof window === \"undefined\") return;\n // Adds an event listener for new wallets that get registered after the dapp has been loaded,\n // receiving an unsubscribe function, which it can later use to remove the listener\n const that = this;\n const removeRegisterListener = on(\"register\", function () {\n let { aptosWallets } = getAptosWallets();\n that.setExtensionAIP62Wallets(aptosWallets);\n });\n\n const removeUnregisterListener = on(\"unregister\", function () {\n let { aptosWallets } = getAptosWallets();\n that.setExtensionAIP62Wallets(aptosWallets);\n });\n }\n\n /**\n * Set AIP-62 extension wallets\n *\n * @param extensionwWallets\n */\n private setExtensionAIP62Wallets(\n extensionwWallets: readonly AptosWallet[],\n ): void {\n extensionwWallets.map((wallet: AdapterWallet) => {\n if (this.excludeWallet(wallet)) {\n return;\n }\n\n // Rimosafe is not supported anymore, so hiding it\n if (wallet.name === \"Rimosafe\") {\n return;\n }\n\n const isValid = isWalletWithRequiredFeatureSet(wallet);\n\n if (isValid) {\n // check if we already have this wallet as a not detected wallet\n const index = this._standard_not_detected_wallets.findIndex(\n (notDetctedWallet) => notDetctedWallet.name == wallet.name,\n );\n // if we do, remove it from the not detected wallets array as it is now become detected\n if (index !== -1) {\n this._standard_not_detected_wallets.splice(index, 1);\n }\n\n // ✅ Check if wallet already exists in _standard_wallets\n const alreadyExists = this._standard_wallets.some(\n (w) => w.name === wallet.name,\n );\n if (!alreadyExists) {\n wallet.readyState = WalletReadyState.Installed;\n wallet.isAptosNativeWallet = this.isAptosNativeWallet(wallet);\n this._standard_wallets.push(wallet);\n this.emit(\"standardWalletsAdded\", wallet);\n }\n }\n });\n }\n\n /**\n * Set AIP-62 SDK wallets\n */\n private fetchSDKAIP62AptosWallets(): void {\n this._sdkWallets.map((wallet: AdapterWallet) => {\n if (this.excludeWallet(wallet)) {\n return;\n }\n const isValid = isWalletWithRequiredFeatureSet(wallet);\n\n if (isValid) {\n wallet.readyState = WalletReadyState.Installed;\n wallet.isAptosNativeWallet = this.isAptosNativeWallet(wallet);\n this._standard_wallets.push(wallet);\n }\n });\n }\n\n // Aptos native wallets do not have an authenticationFunction property\n private isAptosNativeWallet(wallet: AptosWallet): boolean {\n return !(\"authenticationFunction\" in wallet);\n }\n\n // Since we can't discover AIP-62 wallets that are not installed on the user machine,\n // we hold a AIP-62 wallets registry to show on the wallet selector modal for the users.\n // Append wallets from wallet standard support registry to the `_standard_not_detected_wallets` array\n // when wallet is not installed on the user machine\n private appendNotDetectedStandardSupportedWallets(): void {\n const walletRegistry = this._dappConfig?.crossChainWallets\n ? [\n ...aptosStandardSupportedWalletList,\n ...crossChainStandardSupportedWalletList,\n ]\n : aptosStandardSupportedWalletList;\n // Loop over the registry map\n walletRegistry.map((supportedWallet: AptosStandardSupportedWallet) => {\n // Check if we already have this wallet as a detected AIP-62 wallet standard\n const existingStandardWallet = this._standard_wallets.find(\n (wallet) => wallet.name == supportedWallet.name,\n );\n // If it is detected, it means the user has the wallet installed, so dont add it to the wallets array\n if (existingStandardWallet) {\n return;\n }\n // If AIP-62 wallet detected but it is excluded by the dapp, dont add it to the wallets array\n if (this.excludeWallet(supportedWallet)) {\n return;\n }\n // If AIP-62 wallet does not exist, append it to the wallet selector modal\n // as an undetected wallet\n if (!existingStandardWallet) {\n // Aptos native wallets do not have an authenticationFunction property\n supportedWallet.isAptosNativeWallet = !(\n \"authenticationFunction\" in supportedWallet\n );\n this._standard_not_detected_wallets.push(supportedWallet);\n this.emit(\"standardNotDetectedWalletAdded\", supportedWallet);\n }\n });\n }\n\n /**\n * A function that excludes an AIP-62 compatible wallet the dapp doesnt want to include\n *\n * @param wallet AdapterWallet | AdapterNotDetectedWallet\n * @returns boolean\n */\n excludeWallet(wallet: AdapterWallet | AdapterNotDetectedWallet): boolean {\n // If _optInWallets is not empty, and does not include the provided wallet,\n // return true to exclude the wallet, otherwise return false\n if (\n this._optInWallets.length > 0 &&\n !this._optInWallets.includes(wallet.name as AvailableWallets)\n ) {\n return true;\n }\n return false;\n }\n\n private recordEvent(eventName: string, additionalInfo?: object): void {\n this.ga4?.gtag(\"event\", `wallet_adapter_${eventName}`, {\n wallet: this._wallet?.name,\n network: this._network?.name,\n network_url: this._network?.url,\n adapter_core_version: WALLET_ADAPTER_CORE_VERSION,\n send_to: process.env.GAID,\n ...additionalInfo,\n });\n }\n\n /**\n * Helper function to ensure wallet exists\n *\n * @param wallet A wallet\n */\n private ensureWalletExists(\n wallet: AdapterWallet | null,\n ): asserts wallet is AdapterWallet {\n if (!wallet) {\n throw new WalletNotConnectedError().name;\n }\n if (!(wallet.readyState === WalletReadyState.Installed))\n throw new WalletNotReadyError(\"Wallet is not set\").name;\n }\n\n /**\n * Helper function to ensure account exists\n *\n * @param account An account\n */\n private ensureAccountExists(\n account: AccountInfo | null,\n ): asserts account is AccountInfo {\n if (!account) {\n throw new WalletAccountError(\"Account is not set\").name;\n }\n }\n\n /**\n * Queries and sets ANS name for the current connected wallet account\n */\n private async setAnsName(): Promise<void> {\n if (this._network?.chainId && this._account) {\n if (this._account.ansName) return;\n // ANS supports only MAINNET or TESTNET\n if (\n !ChainIdToAnsSupportedNetworkMap[this._network.chainId] ||\n !isAptosNetwork(this._network)\n ) {\n this._account.ansName = undefined;\n return;\n }\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n try {\n const name = await aptos.ans.getPrimaryName({\n address: this._account.address.toString(),\n });\n this._account.ansName = name;\n } catch (error: any) {\n console.log(`Error setting ANS name ${error}`);\n }\n }\n }\n\n /**\n * Function to cleat wallet adapter data.\n *\n * - Removes current connected wallet state\n * - Removes current connected account state\n * - Removes current connected network state\n * - Removes autoconnect local storage value\n */\n private clearData(): void {\n this._connected = false;\n this.setWallet(null);\n this.setAccount(null);\n this.setNetwork(null);\n removeLocalStorage();\n }\n\n /**\n * Sets the connected wallet\n *\n * @param wallet A wallet\n */\n setWallet(wallet: AptosWallet | null): void {\n this._wallet = wallet;\n }\n\n /**\n * Sets the connected account\n *\n * @param account An account\n */\n setAccount(account: AccountInfo | null): void {\n this._account = account;\n }\n\n /**\n * Sets the connected network\n *\n * @param network A network\n */\n setNetwork(network: NetworkInfo | null): void {\n this._network = network;\n }\n\n /**\n * Helper function to detect whether a wallet is connected\n *\n * @returns boolean\n */\n isConnected(): boolean {\n return this._connected;\n }\n\n /**\n * Getter to fetch all detected wallets\n */\n get wallets(): ReadonlyArray<AptosWallet> {\n return this._standard_wallets;\n }\n\n get notDetectedWallets(): ReadonlyArray<AdapterNotDetectedWallet> {\n return this._standard_not_detected_wallets;\n }\n\n /**\n * Getter for the current connected wallet\n *\n * @return wallet info\n * @throws WalletNotSelectedError\n */\n get wallet(): AptosWallet | null {\n try {\n if (!this._wallet) return null;\n return this._wallet;\n } catch (error: any) {\n throw new WalletNotSelectedError(error).message;\n }\n }\n\n /**\n * Getter for the current connected account\n *\n * @return account info\n * @throws WalletAccountError\n */\n get account(): AccountInfo | null {\n try {\n return this._account;\n } catch (error: any) {\n throw new WalletAccountError(error).message;\n }\n }\n\n /**\n * Getter for the current wallet network\n *\n * @return network info\n * @throws WalletGetNetworkError\n */\n get network(): NetworkInfo | null {\n try {\n return this._network;\n } catch (error: any) {\n throw new WalletGetNetworkError(error).message;\n }\n }\n\n /**\n * Helper function to run some checks before we connect with a wallet.\n *\n * @param walletName. The wallet name we want to connect with.\n */\n async connect(walletName: string): Promise<void | string> {\n // First, handle mobile case\n // Check if we are in a redirectable view (i.e on mobile AND not in an in-app browser)\n if (isRedirectable()) {\n const selectedWallet = this._standard_not_detected_wallets.find(\n (wallet: AdapterNotDetectedWallet) => wallet.name === walletName,\n );\n\n if (selectedWallet) {\n // If wallet has a deeplinkProvider property, use it\n const uninstalledWallet =\n selectedWallet as unknown as AptosStandardSupportedWallet;\n if (uninstalledWallet.deeplinkProvider) {\n let parameter = \"\";\n if (uninstalledWallet.name.includes(\"Phantom\")) {\n // Phantom required parameters https://docs.phantom.com/phantom-deeplinks/other-methods/browse#parameters\n let url = encodeURIComponent(window.location.href);\n let ref = encodeURIComponent(window.location.origin);\n parameter = `${url}?ref=${ref}`;\n } else if (uninstalledWallet.name.includes(\"Metamask\")) {\n // Metamask expects the raw URL as a path parameter\n // Format: https://link.metamask.io/dapp/aptos-labs.github.io\n parameter = window.location.href;\n } else {\n parameter = encodeURIComponent(window.location.href);\n }\n const location = uninstalledWallet.deeplinkProvider.concat(parameter);\n window.location.href = location;\n return;\n }\n }\n }\n\n // Checks the wallet exists in the detected wallets array\n const allDetectedWallets = this._standard_wallets;\n\n const selectedWallet = allDetectedWallets.find(\n (wallet: AdapterWallet) => wallet.name === walletName,\n );\n\n if (!selectedWallet) return;\n\n // Check if wallet is already connected\n if (this._connected && this._account) {\n // if the selected wallet is already connected, we don't need to connect again\n if (this._wallet?.name === walletName)\n throw new WalletConnectionError(\n `${walletName} wallet is already connected`,\n ).message;\n }\n\n await this.connectWallet(selectedWallet, async () => {\n const response = await selectedWallet.features[\"aptos:connect\"].connect();\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return { account: response.args, output: undefined };\n });\n }\n\n /**\n * Signs into the wallet by connecting and signing an authentication messages.\n *\n * For more information, visit: https://siwa.aptos.dev\n *\n * @param args\n * @param args.input The AptosSignInInput which defines how the SIWA Message should be constructed\n * @param args.walletName The name of the wallet to sign into\n * @returns The AptosSignInOutput which contains the account and signature information\n */\n async signIn(args: {\n input: AptosSignInInput;\n walletName: string;\n }): Promise<AptosSignInOutput> {\n const { input, walletName } = args;\n\n const allDetectedWallets = this._standard_wallets;\n const selectedWallet = allDetectedWallets.find(\n (wallet: AdapterWallet) => wallet.name === walletName,\n );\n\n if (!selectedWallet) {\n throw new WalletNotFoundError(`Wallet ${walletName} not found`).message;\n }\n\n if (!selectedWallet.features[\"aptos:signIn\"]) {\n throw new WalletNotSupportedMethod(\n `aptos:signIn is not supported by ${walletName}`,\n ).message;\n }\n\n return await this.connectWallet(selectedWallet, async () => {\n if (!selectedWallet.features[\"aptos:signIn\"]) {\n throw new WalletNotSupportedMethod(\n `aptos:signIn is not supported by ${selectedWallet.name}`,\n ).message;\n }\n\n const response =\n await selectedWallet.features[\"aptos:signIn\"].signIn(input);\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return { account: response.args.account, output: response.args };\n });\n }\n\n /**\n * Connects a wallet to the dapp.\n * On connect success, we set the current account and the network, and keeping the selected wallet\n * name in LocalStorage to support autoConnect function.\n *\n * @param selectedWallet. The wallet we want to connect.\n * @emit emits \"connect\" event\n * @throws WalletConnectionError\n */\n private async connectWallet<T>(\n selectedWallet: AdapterWallet,\n onConnect: () => Promise<{ account: AccountInfo; output: T }>,\n ): Promise<T> {\n try {\n this._connecting = true;\n this.setWallet(selectedWallet);\n const { account, output } = await onConnect();\n this.setAccount(account);\n const network = await selectedWallet.features[\"aptos:network\"].network();\n this.setNetwork(network);\n await this.setAnsName();\n setLocalStorage(selectedWallet.name);\n this._connected = true;\n this.recordEvent(\"wallet_connect\");\n this.emit(\"connect\", account);\n return output;\n } catch (error: any) {\n this.clearData();\n const errMsg = generalizedErrorMessage(error);\n throw new WalletConnectionError(errMsg).message;\n } finally {\n this._connecting = false;\n }\n }\n\n /**\n * Disconnect the current connected wallet. On success, we clear the\n * current account, current network and LocalStorage data.\n *\n * @emit emits \"disconnect\" event\n * @throws WalletDisconnectionError\n */\n async disconnect(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:disconnect\"].disconnect();\n this.clearData();\n this.recordEvent(\"wallet_disconnect\");\n this.emit(\"disconnect\");\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletDisconnectionError(errMsg).message;\n }\n }\n\n /**\n * Signs and submits a transaction to chain\n *\n * @param transactionInput InputTransactionData\n * @returns AptosSignAndSubmitTransactionOutput\n */\n async signAndSubmitTransaction(\n transactionInput: InputTransactionData,\n ): Promise<AptosSignAndSubmitTransactionOutput> {\n try {\n if (\"function\" in transactionInput.data) {\n if (\n transactionInput.data.function ===\n \"0x1::account::rotate_authentication_key_call\"\n ) {\n throw new WalletSignAndSubmitMessageError(\"SCAM SITE DETECTED\")\n .message;\n }\n\n if (\n transactionInput.data.function === \"0x1::code::publish_package_txn\"\n ) {\n ({\n metadataBytes: transactionInput.data.functionArguments[0],\n byteCode: transactionInput.data.functionArguments[1],\n } = handlePublishPackageTransaction(transactionInput));\n }\n }\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_and_submit_transaction\");\n\n // We'll submit ourselves if a custom transaction submitter has been provided.\n const shouldUseTxnSubmitter = !!(\n this._dappConfig?.transactionSubmitter ||\n transactionInput.transactionSubmitter\n );\n\n if (\n this._wallet.features[\"aptos:signAndSubmitTransaction\"] &&\n !shouldUseTxnSubmitter\n ) {\n // check for backward compatibility. before version 1.1.0 the standard expected\n // AnyRawTransaction input so the adapter built the transaction before sending it to the wallet\n if (\n this._wallet.features[\"aptos:signAndSubmitTransaction\"].version !==\n \"1.1.0\"\n ) {\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n\n const aptos = new Aptos(aptosConfig);\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address.toString(),\n data: transactionInput.data,\n options: transactionInput.options,\n });\n\n type AptosSignAndSubmitTransactionV1Method = (\n transaction: AnyRawTransaction,\n ) => Promise<UserResponse<AptosSignAndSubmitTransactionOutput>>;\n\n const signAndSubmitTransactionMethod = this._wallet.features[\n \"aptos:signAndSubmitTransaction\"\n ]\n .signAndSubmitTransaction as unknown as AptosSignAndSubmitTransactionV1Method;\n\n const response = (await signAndSubmitTransactionMethod(\n transaction,\n )) as UserResponse<AptosSignAndSubmitTransactionOutput>;\n\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return response.args;\n }\n\n const response = await this._wallet.features[\n \"aptos:signAndSubmitTransaction\"\n ].signAndSubmitTransaction({\n payload: transactionInput.data,\n gasUnitPrice: transactionInput.options?.gasUnitPrice,\n maxGasAmount: transactionInput.options?.maxGasAmount,\n });\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n }\n\n // If wallet does not support signAndSubmitTransaction or a transaction submitter\n // is provided, the adapter will sign and submit it for the dapp.\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address.toString(),\n data: transactionInput.data,\n options: transactionInput.options,\n withFeePayer: shouldUseTxnSubmitter,\n });\n\n const signTransactionResponse = await this.signTransaction({\n transactionOrPayload: transaction,\n });\n const response = await this.submitTransaction({\n transaction,\n senderAuthenticator: signTransactionResponse.authenticator,\n transactionSubmitter: transactionInput.transactionSubmitter,\n pluginParams: transactionInput.pluginParams,\n });\n return { hash: response.hash };\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignAndSubmitMessageError(errMsg).message;\n }\n }\n\n /**\n * Signs a transaction\n *\n * This method supports 2 input types -\n * 1. A raw transaction that was already built by the dapp,\n * 2. A transaction data input as JSON. This is for the wallet to be able to simulate before signing\n *\n * @param transactionOrPayload AnyRawTransaction | InputTransactionData\n * @param asFeePayer optional. A flag indicates to sign the transaction as the fee payer\n * @param options optional. Transaction options\n *\n * @returns AccountAuthenticator\n */\n async signTransaction(args: {\n transactionOrPayload: AnyRawTransaction | InputTransactionData;\n asFeePayer?: boolean;\n }): Promise<{\n authenticator: AccountAuthenticator;\n rawTransaction: Uint8Array;\n }> {\n const { transactionOrPayload, asFeePayer } = args;\n /**\n * All standard compatible wallets should support AnyRawTransaction for signTransaction version 1.0.0\n * For standard signTransaction version 1.1.0, the standard expects a transaction input\n *\n * So, if the input is AnyRawTransaction, we can directly call the wallet's signTransaction method\n *\n *\n * If the input is InputTransactionData, we need to\n * 1. check if the wallet supports signTransaction version 1.1.0 - if so, we convert the input to the standard expected input\n * 2. if it does not support signTransaction version 1.1.0, we convert it to a rawTransaction input and call the wallet's signTransaction method\n */\n\n try {\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_transaction\");\n\n // dapp sends a generated transaction (i.e AnyRawTransaction), which is supported by the wallet standard at signTransaction version 1.0.0\n if (\"rawTransaction\" in transactionOrPayload) {\n const response = (await this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction(\n transactionOrPayload,\n asFeePayer,\n )) as UserResponse<AccountAuthenticator>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return {\n authenticator: response.args,\n rawTransaction: transactionOrPayload.rawTransaction.bcsToBytes(),\n };\n } // dapp sends a transaction data input (i.e InputTransactionData), which is supported by the wallet standard at signTransaction version 1.1.0\n else if (\n this._wallet.features[\"aptos:signTransaction\"]?.version === \"1.1.0\"\n ) {\n // convert input to standard expected input\n const signTransactionV1_1StandardInput: AptosSignTransactionInputV1_1 =\n {\n payload: transactionOrPayload.data,\n expirationTimestamp:\n transactionOrPayload.options?.expirationTimestamp,\n expirationSecondsFromNow:\n transactionOrPayload.options?.expirationSecondsFromNow,\n gasUnitPrice: transactionOrPayload.options?.gasUnitPrice,\n maxGasAmount: transactionOrPayload.options?.maxGasAmount,\n sequenceNumber: transactionOrPayload.options?.accountSequenceNumber,\n sender: transactionOrPayload.sender\n ? { address: AccountAddress.from(transactionOrPayload.sender) }\n : undefined,\n };\n\n const walletSignTransactionMethod = this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction as AptosSignTransactionMethod &\n AptosSignTransactionMethodV1_1;\n\n const response = (await walletSignTransactionMethod(\n signTransactionV1_1StandardInput,\n )) as UserResponse<AptosSignTransactionOutputV1_1>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return {\n authenticator: response.args.authenticator,\n rawTransaction: response.args.rawTransaction.bcsToBytes(),\n };\n } else {\n // dapp input is InputTransactionData but the wallet does not support it, so we convert it to a rawTransaction\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address,\n data: transactionOrPayload.data,\n options: transactionOrPayload.options,\n withFeePayer: transactionOrPayload.withFeePayer,\n });\n\n const response = (await this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction(\n transaction,\n asFeePayer,\n )) as UserResponse<AccountAuthenticator>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return {\n authenticator: response.args,\n rawTransaction: transaction.bcsToBytes(),\n };\n }\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignTransactionError(errMsg).message;\n }\n }\n\n /**\n * Sign a message (doesnt submit to chain).\n *\n * @param message - AptosSignMessageInput\n *\n * @return response from the wallet's signMessage function\n * @throws WalletSignMessageError\n */\n async signMessage(\n message: AptosSignMessageInput,\n ): Promise<AptosSignMessageOutput> {\n try {\n this.ensureWalletExists(this._wallet);\n this.recordEvent(\"sign_message\");\n\n const response =\n await this._wallet?.features[\"aptos:signMessage\"]?.signMessage(message);\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignMessageError(errMsg).message;\n }\n }\n\n /**\n * Submits transaction to chain\n *\n * @param transaction - InputSubmitTransactionData\n * @returns PendingTransactionResponse\n */\n async submitTransaction(\n transaction: InputSubmitTransactionData,\n ): Promise<PendingTransactionResponse> {\n // The standard does not support submitTransaction, so we use the adapter to submit the transaction\n try {\n this.ensureWalletExists(this._wallet);\n\n const { additionalSignersAuthenticators } = transaction;\n const transactionType =\n additionalSignersAuthenticators !== undefined\n ? \"multi-agent\"\n : \"simple\";\n this.recordEvent(\"submit_transaction\", {\n transaction_type: transactionType,\n });\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n if (additionalSignersAuthenticators !== undefined) {\n const multiAgentTxn = {\n ...transaction,\n additionalSignersAuthenticators,\n };\n return aptos.transaction.submit.multiAgent(multiAgentTxn);\n } else {\n return aptos.transaction.submit.simple(transaction);\n }\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSubmitTransactionError(errMsg).message;\n }\n }\n\n /**\n Event for when account has changed on the wallet\n @return the new account info\n @throws WalletAccountChangeError\n */\n async onAccountChange(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:onAccountChange\"]?.onAccountChange(\n async (data: AccountInfo) => {\n this.setAccount(data);\n await this.setAnsName();\n this.recordEvent(\"account_change\");\n this.emit(\"accountChange\", this._account);\n },\n );\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletAccountChangeError(errMsg).message;\n }\n }\n\n /**\n Event for when network has changed on the wallet\n @return the new network info\n @throws WalletNetworkChangeError\n */\n async onNetworkChange(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:onNetworkChange\"]?.onNetworkChange(\n async (data: NetworkInfo) => {\n this.setNetwork(data);\n await this.setAnsName();\n this.emit(\"networkChange\", this._network);\n },\n );\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletNetworkChangeError(errMsg).message;\n }\n }\n\n /**\n * Sends a change network request to the wallet to change the connected network\n *\n * @param network - Network\n * @returns AptosChangeNetworkOutput\n */\n async changeNetwork(network: Network): Promise<AptosChangeNetworkOutput> {\n try {\n this.ensureWalletExists(this._wallet);\n this.recordEvent(\"change_network_request\", {\n from: this._network?.name,\n to: network,\n });\n const chainId =\n network === Network.DEVNET\n ? await fetchDevnetChainId()\n : NetworkToChainId[network];\n\n const networkInfo: NetworkInfo = {\n name: network,\n chainId,\n };\n\n if (this._wallet.features[\"aptos:changeNetwork\"]) {\n const response =\n await this._wallet.features[\"aptos:changeNetwork\"].changeNetwork(\n networkInfo,\n );\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n }\n\n throw new WalletChangeNetworkError(\n `${this._wallet.name} does not support changing network request`,\n ).message;\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletChangeNetworkError(errMsg).message;\n }\n }\n\n /**\n * Signs a message and verifies the signer\n * @param message - AptosSignMessageInput\n * @returns boolean\n */\n async signMessageAndVerify(message: AptosSignMessageInput): Promise<boolean> {\n try {\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_message_and_verify\");\n\n // sign the message\n const response = (await this._wallet.features[\n \"aptos:signMessage\"\n ].signMessage(message)) as UserResponse<AptosSignMessageOutput>;\n\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"Failed to sign a message\").message;\n }\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const signingMessage = new TextEncoder().encode(\n response.args.fullMessage,\n );\n if (\"verifySignatureAsync\" in (this._account.publicKey as Object)) {\n return await this._account.publicKey.verifySignatureAsync({\n aptosConfig,\n message: signingMessage,\n signature: response.args.signature,\n options: { throwErrorWithReason: true },\n });\n }\n return this._account.publicKey.verifySignature({\n message: signingMessage,\n signature: response.args.signature,\n });\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignMessageAndVerifyError(errMsg).message;\n }\n }\n}\n","export class GA4 {\n readonly aptosGAID: string | undefined = process.env.GAID;\n\n constructor() {\n // Inject Aptos Google Analytics 4 script\n this.injectGA(this.aptosGAID);\n }\n\n gtag(a: string, b: string | object, c?: object) {\n let dataLayer = (window as any).dataLayer || [];\n dataLayer.push(arguments);\n }\n\n private injectGA(gaID?: string) {\n if (typeof window === \"undefined\") return;\n if (!gaID) return;\n\n const head = document.getElementsByTagName(\"head\")[0];\n\n var myScript = document.createElement(\"script\");\n\n myScript.setAttribute(\n \"src\",\n `https://www.googletagmanager.com/gtag/js?id=${gaID}`,\n );\n\n const that = this;\n myScript.onload = function () {\n that.gtag(\"js\", new Date());\n that.gtag(\"config\", `${gaID}`, {\n send_page_view: false,\n });\n };\n\n head.insertBefore(myScript, head.children[1]);\n }\n}\n","export class WalletError extends Error {\n public error: any;\n\n constructor(message?: string, error?: any) {\n super(message);\n this.error = error;\n }\n}\n\nexport class WalletNotSelectedError extends WalletError {\n name = \"WalletNotSelectedError\";\n}\n\nexport class WalletNotReadyError extends WalletError {\n name = \"WalletNotReadyError\";\n}\n\nexport class WalletLoadError extends WalletError {\n name = \"WalletLoadError\";\n}\n\nexport class WalletConfigError extends WalletError {\n name = \"WalletConfigError\";\n}\n\nexport class WalletConnectionError extends WalletError {\n name = \"WalletConnectionError\";\n}\n\nexport class WalletDisconnectedError extends WalletError {\n name = \"WalletDisconnectedError\";\n}\n\nexport class WalletDisconnectionError extends WalletError {\n name = \"WalletDisconnectionError\";\n}\n\nexport class WalletAccountError extends WalletError {\n name = \"WalletAccountError\";\n}\nexport class WalletGetNetworkError extends WalletError {\n name = \"WalletGetNetworkError\";\n}\n\nexport class WalletAccountChangeError extends WalletError {\n name = \"WalletAccountChangeError\";\n}\n\nexport class WalletNetworkChangeError extends WalletError {\n name = \"WalletNetworkChangeError\";\n}\n\nexport class WalletPublicKeyError extends WalletError {\n name = \"WalletPublicKeyError\";\n}\n\nexport class WalletKeypairError extends WalletError {\n name = \"WalletKeypairError\";\n}\n\nexport class WalletNotConnectedError extends WalletError {\n name = \"WalletNotConnectedError\";\n}\n\nexport class WalletSendTransactionError extends WalletError {\n name = \"WalletSendTransactionError\";\n}\n\nexport class WalletSignMessageError extends WalletError {\n name = \"WalletSignMessageError\";\n}\n\nexport class WalletSignMessageAndVerifyError extends WalletError {\n name = \"WalletSignMessageAndVerifyError\";\n}\n\nexport class WalletSignAndSubmitMessageError extends WalletError {\n name = \"WalletSignAndSubmitMessageError\";\n}\n\nexport class WalletSignTransactionError extends WalletError {\n name = \"WalletSignTransactionError\";\n}\n\nexport class WalletTimeoutError extends WalletError {\n name = \"WalletTimeoutError\";\n}\n\nexport class WalletWindowBlockedError extends WalletError {\n name = \"WalletWindowBlockedError\";\n}\n\nexport class WalletWindowClosedError extends WalletError {\n name = \"WalletWindowClosedError\";\n}\n\nexport class WalletResponseError extends WalletError {\n name = \"WalletResponseError\";\n}\n\nexport class WalletNotSupportedMethod extends WalletError {\n name = \"WalletNotSupportedMethod\";\n}\n\nexport class WalletChangeNetworkError extends WalletError {\n name = \"WalletChangeNetworkError\";\n}\n\nexport class WalletSubmitTransactionError extends WalletError {\n name = \"WalletSubmitTransactionError\";\n}\n\nexport class WalletNotFoundError extends WalletError {\n name = \"WalletNotFoundError\";\n}\n","export enum WalletReadyState {\n /**\n * Wallet can only be in one of two states - installed or not installed\n * Installed: wallets are detected by the browser event listeners and means they are installed on the user's browser.\n * NotDetected: wallets are not detected by the browser event listeners and means they are not installed on the user's browser.\n */\n Installed = \"Installed\",\n NotDetected = \"NotDetected\",\n}\n\nexport enum NetworkName {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n Devnet = \"devnet\",\n}\n\nexport const ChainIdToAnsSupportedNetworkMap: Record<string, string> = {\n \"1\": \"mainnet\", // mainnet\n \"2\": \"testnet\", // testnet\n};\n\n/**\n * The base URL for all Aptos Connect wallets.\n *\n * @deprecated Use {@link PETRA_WEB_BASE_URL} instead.\n */\nexport const APTOS_CONNECT_BASE_URL = \"https://aptosconnect.app\";\n\n/** The base URL for all Petra Web wallets. */\nexport const PETRA_WEB_BASE_URL = \"https://web.petra.app\";\n\n/**\n * The URL to the Aptos Connect account page if the user is signed in to Aptos Connect.\n *\n * @deprecated Use {@link PETRA_WEB_ACCOUNT_URL} instead.\n */\nexport const APTOS_CONNECT_ACCOUNT_URL =\n \"https://aptosconnect.app/dashboard/main-account\";\n\n/** The URL to the Petra Web account page if the user is signed in to Petra Web. */\nexport const PETRA_WEB_ACCOUNT_URL =\n \"https://web.petra.app/dashboard/main-account\";\n","import {\n Aptos,\n AptosConfig,\n Hex,\n Network,\n NetworkToNodeAPI,\n PluginSettings,\n} from \"@aptos-labs/ts-sdk\";\nimport {\n NetworkInfo,\n NetworkInfo as StandardNetworkInfo,\n} from \"@aptos-labs/wallet-standard\";\n\nimport { DappConfig } from \"../WalletCore\";\nimport { WalletSignAndSubmitMessageError } from \"../error\";\nimport { InputTransactionData } from \"./types\";\n\nexport function isMobile(): boolean {\n return /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/i.test(\n navigator.userAgent,\n );\n}\n\nexport function isInAppBrowser(): boolean {\n const isIphone = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(\n navigator.userAgent,\n );\n\n const isAndroid = /(Android).*Version\\/[\\d.]+.*Chrome\\/[^\\s]+ Mobile/i.test(\n navigator.userAgent,\n );\n\n return isIphone || isAndroid;\n}\n\nexport function isRedirectable(): boolean {\n // SSR: return false\n if (typeof navigator === \"undefined\" || !navigator) return false;\n\n // if we are on mobile and NOT in a in-app browser we will redirect to a wallet app\n\n return isMobile() && !isInAppBrowser();\n}\n\nexport function generalizedErrorMessage(error: any): string {\n return typeof error === \"object\" && \"message\" in error\n ? error.message\n : error;\n}\n\n/**\n * Helper function to get AptosConfig that supports Aptos and Custom networks\n *\n * @param networkInfo\n * @param dappConfig\n * @returns AptosConfig\n */\nexport const getAptosConfig = (\n networkInfo: NetworkInfo | null,\n dappConfig: DappConfig | undefined,\n): AptosConfig => {\n if (!networkInfo) {\n throw new Error(\"Undefined network\");\n }\n\n const pluginSettings: PluginSettings = {\n TRANSACTION_SUBMITTER: dappConfig?.transactionSubmitter,\n };\n\n if (isAptosNetwork(networkInfo)) {\n const currentNetwork = convertNetwork(networkInfo);\n\n if (isAptosLiveNetwork(currentNetwork)) {\n const apiKey = dappConfig?.aptosApiKeys;\n return new AptosConfig({\n network: currentNetwork,\n clientConfig: { API_KEY: apiKey ? apiKey[currentNetwork] : undefined },\n pluginSettings,\n });\n }\n\n return new AptosConfig({\n network: currentNetwork,\n pluginSettings,\n });\n }\n\n const knownNetworks = {\n okx: \"https://wallet.okx.com/fullnode/aptos/discover/rpc\",\n };\n\n if (networkInfo.url) {\n const isKnownNetwork = Object.values(knownNetworks).includes(\n networkInfo.url,\n );\n\n if (isKnownNetwork) {\n return new AptosConfig({\n network: Network.CUSTOM,\n fullnode: networkInfo.url,\n pluginSettings,\n });\n }\n }\n\n // Custom networks are not supported, please ensure that the wallet is returning the appropriate network Mainnet, Testnet, Devnet, Local\n throw new Error(\n `Invalid network, network ${networkInfo.name} not supported with Aptos wallet adapter to prevent user from using an unexpected network.`,\n );\n};\n\n/**\n * Helper function to resolve if the current connected network is an Aptos network\n *\n * @param networkInfo\n * @returns boolean\n */\nexport const isAptosNetwork = (\n networkInfo: NetworkInfo | StandardNetworkInfo | null,\n): boolean => {\n if (!networkInfo) {\n throw new Error(\"Undefined network\");\n }\n return NetworkToNodeAPI[networkInfo.name] !== undefined;\n};\n\nexport const isAptosLiveNetwork = (networkInfo: Network): boolean => {\n return (\n networkInfo === \"devnet\" ||\n networkInfo === \"testnet\" ||\n networkInfo === \"mainnet\"\n );\n};\n\n/**\n * Helper function to fetch Devnet chain id\n */\nexport const fetchDevnetChainId = async (): Promise<number> => {\n const aptos = new Aptos(); // default to devnet\n return await aptos.getChainId();\n};\n\n/**\n * A helper function to handle the publish package transaction.\n * The Aptos SDK expects the metadataBytes and byteCode to be Uint8Array, but in case the arguments are passed in\n * as a string, this function converts the string to Uint8Array.\n */\nexport const handlePublishPackageTransaction = (\n transactionInput: InputTransactionData,\n) => {\n // convert the first argument, metadataBytes, to uint8array if is a string\n let metadataBytes = transactionInput.data.functionArguments[0];\n if (typeof metadataBytes === \"string\") {\n metadataBytes = Hex.fromHexInput(metadataBytes).toUint8Array();\n }\n\n // convert the second argument, byteCode, to uint8array if is a string\n let byteCode = transactionInput.data.functionArguments[1];\n if (Array.isArray(byteCode)) {\n byteCode = byteCode.map((byte) => {\n if (typeof byte === \"string\") {\n return Hex.fromHexInput(byte).toUint8Array();\n }\n return byte;\n });\n } else {\n throw new WalletSignAndSubmitMessageError(\n \"The bytecode argument must be an array.\",\n ).message;\n }\n\n return { metadataBytes, byteCode };\n};\n\n// old => new\nexport function convertNetwork(networkInfo: NetworkInfo | null): Network {\n switch (networkInfo?.name) {\n case \"mainnet\" as Network:\n return Network.MAINNET;\n case \"testnet\" as Network:\n return Network.TESTNET;\n case \"devnet\" as Network:\n return Network.DEVNET;\n case \"local\" as Network:\n return Network.LOCAL;\n case \"shelbynet\" as Network:\n return Network.SHELBYNET;\n default:\n throw new Error(\"Invalid Aptos network name\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/WalletCore.ts","../src/ga/index.ts","../src/error/index.ts","../src/constants.ts","../src/utils/helpers.ts"],"names":[],"mappings":"","sourcesContent":["export const WALLET_ADAPTER_CORE_VERSION = \"7.10.2\";\n","import EventEmitter from \"eventemitter3\";\nimport {\n AccountAddress,\n AccountAuthenticator,\n AnyRawTransaction,\n Aptos,\n InputSubmitTransactionData,\n Network,\n NetworkToChainId,\n PendingTransactionResponse,\n TransactionSubmitter,\n} from \"@aptos-labs/ts-sdk\";\nimport {\n AptosWallet,\n getAptosWallets,\n isWalletWithRequiredFeatureSet,\n UserResponseStatus,\n AptosSignAndSubmitTransactionOutput,\n UserResponse,\n AptosSignTransactionOutputV1_1,\n AptosSignTransactionInputV1_1,\n AptosSignTransactionMethod,\n AptosSignTransactionMethodV1_1,\n NetworkInfo,\n AccountInfo,\n AptosSignMessageInput,\n AptosSignMessageOutput,\n AptosChangeNetworkOutput,\n AptosSignInInput,\n AptosSignInOutput,\n} from \"@aptos-labs/wallet-standard\";\nimport { AptosConnectWalletConfig } from \"@aptos-connect/wallet-adapter-plugin\";\n\nexport type {\n NetworkInfo,\n AccountInfo,\n AptosSignAndSubmitTransactionOutput,\n AptosSignTransactionOutputV1_1,\n AptosSignMessageInput,\n AptosSignMessageOutput,\n AptosChangeNetworkOutput,\n} from \"@aptos-labs/wallet-standard\";\nexport type {\n AccountAuthenticator,\n AnyRawTransaction,\n InputGenerateTransactionOptions,\n PendingTransactionResponse,\n InputSubmitTransactionData,\n Network,\n AnyPublicKey,\n AccountAddress,\n TransactionSubmitter,\n} from \"@aptos-labs/ts-sdk\";\n\nimport { GA4 } from \"./ga\";\nimport {\n WalletChangeNetworkError,\n WalletAccountChangeError,\n WalletAccountError,\n WalletConnectionError,\n WalletGetNetworkError,\n WalletNetworkChangeError,\n WalletNotConnectedError,\n WalletNotReadyError,\n WalletNotSelectedError,\n WalletSignAndSubmitMessageError,\n WalletSignMessageError,\n WalletSignTransactionError,\n WalletSignMessageAndVerifyError,\n WalletDisconnectionError,\n WalletSubmitTransactionError,\n WalletNotSupportedMethod,\n WalletNotFoundError,\n} from \"./error\";\nimport { ChainIdToAnsSupportedNetworkMap, WalletReadyState } from \"./constants\";\nimport { WALLET_ADAPTER_CORE_VERSION } from \"./version\";\nimport {\n fetchDevnetChainId,\n generalizedErrorMessage,\n getAptosConfig,\n handlePublishPackageTransaction,\n isAptosNetwork,\n isRedirectable,\n removeLocalStorage,\n setLocalStorage,\n} from \"./utils\";\nimport {\n aptosStandardSupportedWalletList,\n evmStandardSupportedWalletList,\n solanaStandardSupportedWalletList,\n} from \"./registry\";\nimport { getSDKWallets } from \"./sdkWallets\";\nimport {\n AvailableWallets,\n AptosStandardSupportedWallet,\n InputTransactionData,\n} from \"./utils/types\";\n\n// An adapter wallet types is a wallet that is compatible with the wallet standard and the wallet adapter properties\nexport type AdapterWallet = AptosWallet & {\n readyState?: WalletReadyState;\n isAptosNativeWallet?: boolean;\n};\n\n// An adapter not detected wallet types is a wallet that is compatible with the wallet standard but not detected\nexport type AdapterNotDetectedWallet = Omit<\n AdapterWallet,\n \"features\" | \"version\" | \"chains\" | \"accounts\"\n> & {\n readyState: WalletReadyState.NotDetected;\n};\n\nexport interface DappConfig {\n network: Network;\n /**\n * If provided, the wallet adapter will submit transactions using the provided\n * transaction submitter rather than via the wallet.\n */\n transactionSubmitter?: TransactionSubmitter;\n aptosApiKeys?: Partial<Record<Network, string>>;\n aptosConnectDappId?: string;\n aptosConnect?: Omit<AptosConnectWalletConfig, \"network\">;\n /**\n * @deprecated will be removed in a future version\n */\n mizuwallet?: {\n manifestURL: string;\n appId?: string;\n };\n /**\n * @deprecated will be removed in a future version\n */\n msafeWalletConfig?: {\n appId?: string;\n appUrl?: string;\n };\n /**\n * A flag to indicate that the dapp supports cross-chain transactions.\n * If enabled, the adapter will show cross-chain wallets in the wallet selector modal.\n * @default false\n */\n crossChainWallets?: {\n solana?: boolean;\n evm?: boolean;\n };\n}\n\nexport declare interface WalletCoreEvents {\n connect(account: AccountInfo | null): void;\n disconnect(): void;\n standardWalletsAdded(wallets: AdapterWallet): void;\n standardNotDetectedWalletAdded(wallets: AdapterNotDetectedWallet): void;\n networkChange(network: NetworkInfo | null): void;\n accountChange(account: AccountInfo | null): void;\n}\n\nexport type AdapterAccountInfo = Omit<AccountInfo, \"ansName\"> & {\n // ansName is a read-only property on the standard AccountInfo type\n ansName?: string;\n};\n\nexport class WalletCore extends EventEmitter<WalletCoreEvents> {\n // Local private variable to hold the wallet that is currently connected\n private _wallet: AdapterWallet | null = null;\n\n // Local private variable to hold SDK wallets in the adapter\n private readonly _sdkWallets: AdapterWallet[] = [];\n\n // Local array that holds all the wallets that are AIP-62 standard compatible\n private _standard_wallets: AdapterWallet[] = [];\n\n // Local array that holds all the wallets that are AIP-62 standard compatible but are not installed on the user machine\n private _standard_not_detected_wallets: AdapterNotDetectedWallet[] = [];\n\n // Local private variable to hold the network that is currently connected\n private _network: NetworkInfo | null = null;\n\n // Local private variable to hold the wallet connected state\n private _connected: boolean = false;\n\n // Local private variable to hold the connecting state\n private _connecting: boolean = false;\n\n // Local private variable to hold the account that is currently connected\n private _account: AdapterAccountInfo | null = null;\n\n // JSON configuration for AptosConnect\n private _dappConfig: DappConfig | undefined;\n\n // Private array that holds all the Wallets a dapp decided to opt-in to\n private _optInWallets: ReadonlyArray<AvailableWallets> = [];\n\n // Local flag to disable the adapter telemetry tool\n private _disableTelemetry: boolean = false;\n\n // Google Analytics 4 module\n private readonly ga4: GA4 | null = null;\n\n constructor(\n optInWallets?: ReadonlyArray<AvailableWallets>,\n dappConfig?: DappConfig,\n disableTelemetry?: boolean\n ) {\n super();\n this._optInWallets = optInWallets || [];\n this._dappConfig = dappConfig;\n this._disableTelemetry = disableTelemetry ?? false;\n this._sdkWallets = getSDKWallets(this._dappConfig);\n\n // If disableTelemetry set to false (by default), start GA4\n if (!this._disableTelemetry) {\n this.ga4 = new GA4();\n }\n // Strategy to detect AIP-62 standard compatible extension wallets\n this.fetchExtensionAIP62AptosWallets();\n // Strategy to detect AIP-62 standard compatible SDK wallets.\n // We separate the extension and sdk detection process so we dont refetch sdk wallets everytime a new\n // extension wallet is detected\n this.fetchSDKAIP62AptosWallets();\n // Strategy to append not detected AIP-62 standard compatible extension wallets\n this.appendNotDetectedStandardSupportedWallets();\n }\n\n private fetchExtensionAIP62AptosWallets(): void {\n let { aptosWallets, on } = getAptosWallets();\n this.setExtensionAIP62Wallets(aptosWallets);\n\n if (typeof window === \"undefined\") return;\n // Adds an event listener for new wallets that get registered after the dapp has been loaded,\n // receiving an unsubscribe function, which it can later use to remove the listener\n const that = this;\n const removeRegisterListener = on(\"register\", function () {\n let { aptosWallets } = getAptosWallets();\n that.setExtensionAIP62Wallets(aptosWallets);\n });\n\n const removeUnregisterListener = on(\"unregister\", function () {\n let { aptosWallets } = getAptosWallets();\n that.setExtensionAIP62Wallets(aptosWallets);\n });\n }\n\n /**\n * Set AIP-62 extension wallets\n *\n * @param extensionwWallets\n */\n private setExtensionAIP62Wallets(\n extensionwWallets: readonly AptosWallet[]\n ): void {\n extensionwWallets.map((wallet: AdapterWallet) => {\n if (this.excludeWallet(wallet)) {\n return;\n }\n\n // Rimosafe is not supported anymore, so hiding it\n if (wallet.name === \"Rimosafe\") {\n return;\n }\n\n const isValid = isWalletWithRequiredFeatureSet(wallet);\n\n if (isValid) {\n // check if we already have this wallet as a not detected wallet\n const index = this._standard_not_detected_wallets.findIndex(\n (notDetctedWallet) => notDetctedWallet.name == wallet.name\n );\n // if we do, remove it from the not detected wallets array as it is now become detected\n if (index !== -1) {\n this._standard_not_detected_wallets.splice(index, 1);\n }\n\n // ✅ Check if wallet already exists in _standard_wallets\n const alreadyExists = this._standard_wallets.some(\n (w) => w.name === wallet.name\n );\n if (!alreadyExists) {\n wallet.readyState = WalletReadyState.Installed;\n wallet.isAptosNativeWallet = this.isAptosNativeWallet(wallet);\n this._standard_wallets.push(wallet);\n this.emit(\"standardWalletsAdded\", wallet);\n }\n }\n });\n }\n\n /**\n * Set AIP-62 SDK wallets\n */\n private fetchSDKAIP62AptosWallets(): void {\n this._sdkWallets.map((wallet: AdapterWallet) => {\n if (this.excludeWallet(wallet)) {\n return;\n }\n const isValid = isWalletWithRequiredFeatureSet(wallet);\n\n if (isValid) {\n wallet.readyState = WalletReadyState.Installed;\n wallet.isAptosNativeWallet = this.isAptosNativeWallet(wallet);\n this._standard_wallets.push(wallet);\n }\n });\n }\n\n // Aptos native wallets do not have an authenticationFunction property\n private isAptosNativeWallet(wallet: AptosWallet): boolean {\n return !(\"authenticationFunction\" in wallet);\n }\n\n // Since we can't discover AIP-62 wallets that are not installed on the user machine,\n // we hold a AIP-62 wallets registry to show on the wallet selector modal for the users.\n // Append wallets from wallet standard support registry to the `_standard_not_detected_wallets` array\n // when wallet is not installed on the user machine\n private appendNotDetectedStandardSupportedWallets(): void {\n const walletRegistry = [...aptosStandardSupportedWalletList];\n if (this._dappConfig?.crossChainWallets?.solana) {\n walletRegistry.push(...solanaStandardSupportedWalletList);\n }\n if (this._dappConfig?.crossChainWallets?.evm) {\n walletRegistry.push(...evmStandardSupportedWalletList);\n }\n // Loop over the registry map\n walletRegistry.map((supportedWallet: AptosStandardSupportedWallet) => {\n // Check if we already have this wallet as a detected AIP-62 wallet standard\n const existingStandardWallet = this._standard_wallets.find(\n (wallet) => wallet.name == supportedWallet.name\n );\n // If it is detected, it means the user has the wallet installed, so dont add it to the wallets array\n if (existingStandardWallet) {\n return;\n }\n // If AIP-62 wallet detected but it is excluded by the dapp, dont add it to the wallets array\n if (this.excludeWallet(supportedWallet)) {\n return;\n }\n // If AIP-62 wallet does not exist, append it to the wallet selector modal\n // as an undetected wallet\n if (!existingStandardWallet) {\n // Aptos native wallets do not have an authenticationFunction property\n supportedWallet.isAptosNativeWallet = !(\n \"authenticationFunction\" in supportedWallet\n );\n this._standard_not_detected_wallets.push(supportedWallet);\n this.emit(\"standardNotDetectedWalletAdded\", supportedWallet);\n }\n });\n }\n\n /**\n * A function that excludes an AIP-62 compatible wallet the dapp doesnt want to include\n *\n * @param wallet AdapterWallet | AdapterNotDetectedWallet\n * @returns boolean\n */\n excludeWallet(wallet: AdapterWallet | AdapterNotDetectedWallet): boolean {\n // If _optInWallets is not empty, and does not include the provided wallet,\n // return true to exclude the wallet, otherwise return false\n if (\n this._optInWallets.length > 0 &&\n !this._optInWallets.includes(wallet.name as AvailableWallets)\n ) {\n return true;\n }\n return false;\n }\n\n private recordEvent(eventName: string, additionalInfo?: object): void {\n this.ga4?.gtag(\"event\", `wallet_adapter_${eventName}`, {\n wallet: this._wallet?.name,\n network: this._network?.name,\n network_url: this._network?.url,\n adapter_core_version: WALLET_ADAPTER_CORE_VERSION,\n send_to: process.env.GAID,\n ...additionalInfo,\n });\n }\n\n /**\n * Helper function to ensure wallet exists\n *\n * @param wallet A wallet\n */\n private ensureWalletExists(\n wallet: AdapterWallet | null\n ): asserts wallet is AdapterWallet {\n if (!wallet) {\n throw new WalletNotConnectedError().name;\n }\n if (!(wallet.readyState === WalletReadyState.Installed))\n throw new WalletNotReadyError(\"Wallet is not set\").name;\n }\n\n /**\n * Helper function to ensure account exists\n *\n * @param account An account\n */\n private ensureAccountExists(\n account: AccountInfo | null\n ): asserts account is AccountInfo {\n if (!account) {\n throw new WalletAccountError(\"Account is not set\").name;\n }\n }\n\n /**\n * Queries and sets ANS name for the current connected wallet account\n */\n private async setAnsName(): Promise<void> {\n if (this._network?.chainId && this._account) {\n if (this._account.ansName) return;\n // ANS supports only MAINNET or TESTNET\n if (\n !ChainIdToAnsSupportedNetworkMap[this._network.chainId] ||\n !isAptosNetwork(this._network)\n ) {\n this._account.ansName = undefined;\n return;\n }\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n try {\n const name = await aptos.ans.getPrimaryName({\n address: this._account.address.toString(),\n });\n this._account.ansName = name;\n } catch (error: any) {\n console.log(`Error setting ANS name ${error}`);\n }\n }\n }\n\n /**\n * Function to cleat wallet adapter data.\n *\n * - Removes current connected wallet state\n * - Removes current connected account state\n * - Removes current connected network state\n * - Removes autoconnect local storage value\n */\n private clearData(): void {\n this._connected = false;\n this.setWallet(null);\n this.setAccount(null);\n this.setNetwork(null);\n removeLocalStorage();\n }\n\n /**\n * Sets the connected wallet\n *\n * @param wallet A wallet\n */\n setWallet(wallet: AptosWallet | null): void {\n this._wallet = wallet;\n }\n\n /**\n * Sets the connected account\n *\n * @param account An account\n */\n setAccount(account: AccountInfo | null): void {\n this._account = account;\n }\n\n /**\n * Sets the connected network\n *\n * @param network A network\n */\n setNetwork(network: NetworkInfo | null): void {\n this._network = network;\n }\n\n /**\n * Helper function to detect whether a wallet is connected\n *\n * @returns boolean\n */\n isConnected(): boolean {\n return this._connected;\n }\n\n /**\n * Getter to fetch all detected wallets\n */\n get wallets(): ReadonlyArray<AptosWallet> {\n return this._standard_wallets;\n }\n\n get notDetectedWallets(): ReadonlyArray<AdapterNotDetectedWallet> {\n return this._standard_not_detected_wallets;\n }\n\n /**\n * Getter for the current connected wallet\n *\n * @return wallet info\n * @throws WalletNotSelectedError\n */\n get wallet(): AptosWallet | null {\n try {\n if (!this._wallet) return null;\n return this._wallet;\n } catch (error: any) {\n throw new WalletNotSelectedError(error).message;\n }\n }\n\n /**\n * Getter for the current connected account\n *\n * @return account info\n * @throws WalletAccountError\n */\n get account(): AccountInfo | null {\n try {\n return this._account;\n } catch (error: any) {\n throw new WalletAccountError(error).message;\n }\n }\n\n /**\n * Getter for the current wallet network\n *\n * @return network info\n * @throws WalletGetNetworkError\n */\n get network(): NetworkInfo | null {\n try {\n return this._network;\n } catch (error: any) {\n throw new WalletGetNetworkError(error).message;\n }\n }\n\n /**\n * Helper function to run some checks before we connect with a wallet.\n *\n * @param walletName. The wallet name we want to connect with.\n */\n async connect(walletName: string): Promise<void | string> {\n // First, handle mobile case\n // Check if we are in a redirectable view (i.e on mobile AND not in an in-app browser)\n if (isRedirectable()) {\n const selectedWallet = this._standard_not_detected_wallets.find(\n (wallet: AdapterNotDetectedWallet) => wallet.name === walletName\n );\n\n if (selectedWallet) {\n // If wallet has a deeplinkProvider property, use it\n const uninstalledWallet =\n selectedWallet as unknown as AptosStandardSupportedWallet;\n if (uninstalledWallet.deeplinkProvider) {\n let parameter = \"\";\n if (uninstalledWallet.name.includes(\"Phantom\")) {\n // Phantom required parameters https://docs.phantom.com/phantom-deeplinks/other-methods/browse#parameters\n let url = encodeURIComponent(window.location.href);\n let ref = encodeURIComponent(window.location.origin);\n parameter = `${url}?ref=${ref}`;\n } else if (uninstalledWallet.name.includes(\"Metamask\")) {\n // Metamask expects the raw URL as a path parameter\n // Format: https://link.metamask.io/dapp/aptos-labs.github.io\n parameter = window.location.href;\n } else {\n parameter = encodeURIComponent(window.location.href);\n }\n const location = uninstalledWallet.deeplinkProvider.concat(parameter);\n window.location.href = location;\n return;\n }\n }\n }\n\n // Checks the wallet exists in the detected wallets array\n const allDetectedWallets = this._standard_wallets;\n\n const selectedWallet = allDetectedWallets.find(\n (wallet: AdapterWallet) => wallet.name === walletName\n );\n\n if (!selectedWallet) return;\n\n // Check if wallet is already connected\n if (this._connected && this._account) {\n // if the selected wallet is already connected, we don't need to connect again\n if (this._wallet?.name === walletName)\n throw new WalletConnectionError(\n `${walletName} wallet is already connected`\n ).message;\n }\n\n await this.connectWallet(selectedWallet, async () => {\n const response = await selectedWallet.features[\"aptos:connect\"].connect();\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return { account: response.args, output: undefined };\n });\n }\n\n /**\n * Signs into the wallet by connecting and signing an authentication messages.\n *\n * For more information, visit: https://siwa.aptos.dev\n *\n * @param args\n * @param args.input The AptosSignInInput which defines how the SIWA Message should be constructed\n * @param args.walletName The name of the wallet to sign into\n * @returns The AptosSignInOutput which contains the account and signature information\n */\n async signIn(args: {\n input: AptosSignInInput;\n walletName: string;\n }): Promise<AptosSignInOutput> {\n const { input, walletName } = args;\n\n const allDetectedWallets = this._standard_wallets;\n const selectedWallet = allDetectedWallets.find(\n (wallet: AdapterWallet) => wallet.name === walletName\n );\n\n if (!selectedWallet) {\n throw new WalletNotFoundError(`Wallet ${walletName} not found`).message;\n }\n\n if (!selectedWallet.features[\"aptos:signIn\"]) {\n throw new WalletNotSupportedMethod(\n `aptos:signIn is not supported by ${walletName}`\n ).message;\n }\n\n return await this.connectWallet(selectedWallet, async () => {\n if (!selectedWallet.features[\"aptos:signIn\"]) {\n throw new WalletNotSupportedMethod(\n `aptos:signIn is not supported by ${selectedWallet.name}`\n ).message;\n }\n\n const response =\n await selectedWallet.features[\"aptos:signIn\"].signIn(input);\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return { account: response.args.account, output: response.args };\n });\n }\n\n /**\n * Connects a wallet to the dapp.\n * On connect success, we set the current account and the network, and keeping the selected wallet\n * name in LocalStorage to support autoConnect function.\n *\n * @param selectedWallet. The wallet we want to connect.\n * @emit emits \"connect\" event\n * @throws WalletConnectionError\n */\n private async connectWallet<T>(\n selectedWallet: AdapterWallet,\n onConnect: () => Promise<{ account: AccountInfo; output: T }>\n ): Promise<T> {\n try {\n this._connecting = true;\n this.setWallet(selectedWallet);\n const { account, output } = await onConnect();\n this.setAccount(account);\n const network = await selectedWallet.features[\"aptos:network\"].network();\n this.setNetwork(network);\n await this.setAnsName();\n setLocalStorage(selectedWallet.name);\n this._connected = true;\n this.recordEvent(\"wallet_connect\");\n this.emit(\"connect\", account);\n return output;\n } catch (error: any) {\n this.clearData();\n const errMsg = generalizedErrorMessage(error);\n throw new WalletConnectionError(errMsg).message;\n } finally {\n this._connecting = false;\n }\n }\n\n /**\n * Disconnect the current connected wallet. On success, we clear the\n * current account, current network and LocalStorage data.\n *\n * @emit emits \"disconnect\" event\n * @throws WalletDisconnectionError\n */\n async disconnect(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:disconnect\"].disconnect();\n this.clearData();\n this.recordEvent(\"wallet_disconnect\");\n this.emit(\"disconnect\");\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletDisconnectionError(errMsg).message;\n }\n }\n\n /**\n * Signs and submits a transaction to chain\n *\n * @param transactionInput InputTransactionData\n * @returns AptosSignAndSubmitTransactionOutput\n */\n async signAndSubmitTransaction(\n transactionInput: InputTransactionData\n ): Promise<AptosSignAndSubmitTransactionOutput> {\n try {\n if (\"function\" in transactionInput.data) {\n if (\n transactionInput.data.function ===\n \"0x1::account::rotate_authentication_key_call\"\n ) {\n throw new WalletSignAndSubmitMessageError(\"SCAM SITE DETECTED\")\n .message;\n }\n\n if (\n transactionInput.data.function === \"0x1::code::publish_package_txn\"\n ) {\n ({\n metadataBytes: transactionInput.data.functionArguments[0],\n byteCode: transactionInput.data.functionArguments[1],\n } = handlePublishPackageTransaction(transactionInput));\n }\n }\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_and_submit_transaction\");\n\n // We'll submit ourselves if a custom transaction submitter has been provided.\n const shouldUseTxnSubmitter = !!(\n this._dappConfig?.transactionSubmitter ||\n transactionInput.transactionSubmitter\n );\n\n if (\n this._wallet.features[\"aptos:signAndSubmitTransaction\"] &&\n !shouldUseTxnSubmitter\n ) {\n // check for backward compatibility. before version 1.1.0 the standard expected\n // AnyRawTransaction input so the adapter built the transaction before sending it to the wallet\n if (\n this._wallet.features[\"aptos:signAndSubmitTransaction\"].version !==\n \"1.1.0\"\n ) {\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n\n const aptos = new Aptos(aptosConfig);\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address.toString(),\n data: transactionInput.data,\n options: transactionInput.options,\n });\n\n type AptosSignAndSubmitTransactionV1Method = (\n transaction: AnyRawTransaction\n ) => Promise<UserResponse<AptosSignAndSubmitTransactionOutput>>;\n\n const signAndSubmitTransactionMethod = this._wallet.features[\n \"aptos:signAndSubmitTransaction\"\n ]\n .signAndSubmitTransaction as unknown as AptosSignAndSubmitTransactionV1Method;\n\n const response = (await signAndSubmitTransactionMethod(\n transaction\n )) as UserResponse<AptosSignAndSubmitTransactionOutput>;\n\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return response.args;\n }\n\n const response = await this._wallet.features[\n \"aptos:signAndSubmitTransaction\"\n ].signAndSubmitTransaction({\n payload: transactionInput.data,\n gasUnitPrice: transactionInput.options?.gasUnitPrice,\n maxGasAmount: transactionInput.options?.maxGasAmount,\n });\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n }\n\n // If wallet does not support signAndSubmitTransaction or a transaction submitter\n // is provided, the adapter will sign and submit it for the dapp.\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address.toString(),\n data: transactionInput.data,\n options: transactionInput.options,\n withFeePayer: shouldUseTxnSubmitter,\n });\n\n const signTransactionResponse = await this.signTransaction({\n transactionOrPayload: transaction,\n });\n const response = await this.submitTransaction({\n transaction,\n senderAuthenticator: signTransactionResponse.authenticator,\n transactionSubmitter: transactionInput.transactionSubmitter,\n pluginParams: transactionInput.pluginParams,\n });\n return { hash: response.hash };\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignAndSubmitMessageError(errMsg).message;\n }\n }\n\n /**\n * Signs a transaction\n *\n * This method supports 2 input types -\n * 1. A raw transaction that was already built by the dapp,\n * 2. A transaction data input as JSON. This is for the wallet to be able to simulate before signing\n *\n * @param transactionOrPayload AnyRawTransaction | InputTransactionData\n * @param asFeePayer optional. A flag indicates to sign the transaction as the fee payer\n * @param options optional. Transaction options\n *\n * @returns AccountAuthenticator\n */\n async signTransaction(args: {\n transactionOrPayload: AnyRawTransaction | InputTransactionData;\n asFeePayer?: boolean;\n }): Promise<{\n authenticator: AccountAuthenticator;\n rawTransaction: Uint8Array;\n }> {\n const { transactionOrPayload, asFeePayer } = args;\n /**\n * All standard compatible wallets should support AnyRawTransaction for signTransaction version 1.0.0\n * For standard signTransaction version 1.1.0, the standard expects a transaction input\n *\n * So, if the input is AnyRawTransaction, we can directly call the wallet's signTransaction method\n *\n *\n * If the input is InputTransactionData, we need to\n * 1. check if the wallet supports signTransaction version 1.1.0 - if so, we convert the input to the standard expected input\n * 2. if it does not support signTransaction version 1.1.0, we convert it to a rawTransaction input and call the wallet's signTransaction method\n */\n\n try {\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_transaction\");\n\n // dapp sends a generated transaction (i.e AnyRawTransaction), which is supported by the wallet standard at signTransaction version 1.0.0\n if (\"rawTransaction\" in transactionOrPayload) {\n const response = (await this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction(\n transactionOrPayload,\n asFeePayer\n )) as UserResponse<AccountAuthenticator>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return {\n authenticator: response.args,\n rawTransaction: transactionOrPayload.rawTransaction.bcsToBytes(),\n };\n } // dapp sends a transaction data input (i.e InputTransactionData), which is supported by the wallet standard at signTransaction version 1.1.0\n else if (\n this._wallet.features[\"aptos:signTransaction\"]?.version === \"1.1.0\"\n ) {\n // convert input to standard expected input\n const signTransactionV1_1StandardInput: AptosSignTransactionInputV1_1 =\n {\n payload: transactionOrPayload.data,\n expirationTimestamp:\n transactionOrPayload.options?.expirationTimestamp,\n expirationSecondsFromNow:\n transactionOrPayload.options?.expirationSecondsFromNow,\n gasUnitPrice: transactionOrPayload.options?.gasUnitPrice,\n maxGasAmount: transactionOrPayload.options?.maxGasAmount,\n sequenceNumber: transactionOrPayload.options?.accountSequenceNumber,\n sender: transactionOrPayload.sender\n ? { address: AccountAddress.from(transactionOrPayload.sender) }\n : undefined,\n };\n\n const walletSignTransactionMethod = this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction as AptosSignTransactionMethod &\n AptosSignTransactionMethodV1_1;\n\n const response = (await walletSignTransactionMethod(\n signTransactionV1_1StandardInput\n )) as UserResponse<AptosSignTransactionOutputV1_1>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return {\n authenticator: response.args.authenticator,\n rawTransaction: response.args.rawTransaction.bcsToBytes(),\n };\n } else {\n // dapp input is InputTransactionData but the wallet does not support it, so we convert it to a rawTransaction\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n\n const transaction = await aptos.transaction.build.simple({\n sender: this._account.address,\n data: transactionOrPayload.data,\n options: transactionOrPayload.options,\n withFeePayer: transactionOrPayload.withFeePayer,\n });\n\n const response = (await this._wallet?.features[\n \"aptos:signTransaction\"\n ].signTransaction(\n transaction,\n asFeePayer\n )) as UserResponse<AccountAuthenticator>;\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n\n return {\n authenticator: response.args,\n rawTransaction: transaction.bcsToBytes(),\n };\n }\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignTransactionError(errMsg).message;\n }\n }\n\n /**\n * Sign a message (doesnt submit to chain).\n *\n * @param message - AptosSignMessageInput\n *\n * @return response from the wallet's signMessage function\n * @throws WalletSignMessageError\n */\n async signMessage(\n message: AptosSignMessageInput\n ): Promise<AptosSignMessageOutput> {\n try {\n this.ensureWalletExists(this._wallet);\n this.recordEvent(\"sign_message\");\n\n const response =\n await this._wallet?.features[\"aptos:signMessage\"]?.signMessage(message);\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignMessageError(errMsg).message;\n }\n }\n\n /**\n * Submits transaction to chain\n *\n * @param transaction - InputSubmitTransactionData\n * @returns PendingTransactionResponse\n */\n async submitTransaction(\n transaction: InputSubmitTransactionData\n ): Promise<PendingTransactionResponse> {\n // The standard does not support submitTransaction, so we use the adapter to submit the transaction\n try {\n this.ensureWalletExists(this._wallet);\n\n const { additionalSignersAuthenticators } = transaction;\n const transactionType =\n additionalSignersAuthenticators !== undefined\n ? \"multi-agent\"\n : \"simple\";\n this.recordEvent(\"submit_transaction\", {\n transaction_type: transactionType,\n });\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const aptos = new Aptos(aptosConfig);\n if (additionalSignersAuthenticators !== undefined) {\n const multiAgentTxn = {\n ...transaction,\n additionalSignersAuthenticators,\n };\n return aptos.transaction.submit.multiAgent(multiAgentTxn);\n } else {\n return aptos.transaction.submit.simple(transaction);\n }\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSubmitTransactionError(errMsg).message;\n }\n }\n\n /**\n Event for when account has changed on the wallet\n @return the new account info\n @throws WalletAccountChangeError\n */\n async onAccountChange(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:onAccountChange\"]?.onAccountChange(\n async (data: AccountInfo) => {\n this.setAccount(data);\n await this.setAnsName();\n this.recordEvent(\"account_change\");\n this.emit(\"accountChange\", this._account);\n }\n );\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletAccountChangeError(errMsg).message;\n }\n }\n\n /**\n Event for when network has changed on the wallet\n @return the new network info\n @throws WalletNetworkChangeError\n */\n async onNetworkChange(): Promise<void> {\n try {\n this.ensureWalletExists(this._wallet);\n await this._wallet.features[\"aptos:onNetworkChange\"]?.onNetworkChange(\n async (data: NetworkInfo) => {\n this.setNetwork(data);\n await this.setAnsName();\n this.emit(\"networkChange\", this._network);\n }\n );\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletNetworkChangeError(errMsg).message;\n }\n }\n\n /**\n * Sends a change network request to the wallet to change the connected network\n *\n * @param network - Network\n * @returns AptosChangeNetworkOutput\n */\n async changeNetwork(network: Network): Promise<AptosChangeNetworkOutput> {\n try {\n this.ensureWalletExists(this._wallet);\n this.recordEvent(\"change_network_request\", {\n from: this._network?.name,\n to: network,\n });\n const chainId =\n network === Network.DEVNET\n ? await fetchDevnetChainId()\n : NetworkToChainId[network];\n\n const networkInfo: NetworkInfo = {\n name: network,\n chainId,\n };\n\n if (this._wallet.features[\"aptos:changeNetwork\"]) {\n const response =\n await this._wallet.features[\"aptos:changeNetwork\"].changeNetwork(\n networkInfo\n );\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"User has rejected the request\")\n .message;\n }\n return response.args;\n }\n\n throw new WalletChangeNetworkError(\n `${this._wallet.name} does not support changing network request`\n ).message;\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletChangeNetworkError(errMsg).message;\n }\n }\n\n /**\n * Signs a message and verifies the signer\n * @param message - AptosSignMessageInput\n * @returns boolean\n */\n async signMessageAndVerify(message: AptosSignMessageInput): Promise<boolean> {\n try {\n this.ensureWalletExists(this._wallet);\n this.ensureAccountExists(this._account);\n this.recordEvent(\"sign_message_and_verify\");\n\n // sign the message\n const response = (await this._wallet.features[\n \"aptos:signMessage\"\n ].signMessage(message)) as UserResponse<AptosSignMessageOutput>;\n\n if (response.status === UserResponseStatus.REJECTED) {\n throw new WalletConnectionError(\"Failed to sign a message\").message;\n }\n\n const aptosConfig = getAptosConfig(this._network, this._dappConfig);\n const signingMessage = new TextEncoder().encode(\n response.args.fullMessage\n );\n if (\"verifySignatureAsync\" in (this._account.publicKey as Object)) {\n return await this._account.publicKey.verifySignatureAsync({\n aptosConfig,\n message: signingMessage,\n signature: response.args.signature,\n options: { throwErrorWithReason: true },\n });\n }\n return this._account.publicKey.verifySignature({\n message: signingMessage,\n signature: response.args.signature,\n });\n } catch (error: any) {\n const errMsg = generalizedErrorMessage(error);\n throw new WalletSignMessageAndVerifyError(errMsg).message;\n }\n }\n}\n","export class GA4 {\n readonly aptosGAID: string | undefined = process.env.GAID;\n\n constructor() {\n // Inject Aptos Google Analytics 4 script\n this.injectGA(this.aptosGAID);\n }\n\n gtag(a: string, b: string | object, c?: object) {\n let dataLayer = (window as any).dataLayer || [];\n dataLayer.push(arguments);\n }\n\n private injectGA(gaID?: string) {\n if (typeof window === \"undefined\") return;\n if (!gaID) return;\n\n const head = document.getElementsByTagName(\"head\")[0];\n\n var myScript = document.createElement(\"script\");\n\n myScript.setAttribute(\n \"src\",\n `https://www.googletagmanager.com/gtag/js?id=${gaID}`,\n );\n\n const that = this;\n myScript.onload = function () {\n that.gtag(\"js\", new Date());\n that.gtag(\"config\", `${gaID}`, {\n send_page_view: false,\n });\n };\n\n head.insertBefore(myScript, head.children[1]);\n }\n}\n","export class WalletError extends Error {\n public error: any;\n\n constructor(message?: string, error?: any) {\n super(message);\n this.error = error;\n }\n}\n\nexport class WalletNotSelectedError extends WalletError {\n name = \"WalletNotSelectedError\";\n}\n\nexport class WalletNotReadyError extends WalletError {\n name = \"WalletNotReadyError\";\n}\n\nexport class WalletLoadError extends WalletError {\n name = \"WalletLoadError\";\n}\n\nexport class WalletConfigError extends WalletError {\n name = \"WalletConfigError\";\n}\n\nexport class WalletConnectionError extends WalletError {\n name = \"WalletConnectionError\";\n}\n\nexport class WalletDisconnectedError extends WalletError {\n name = \"WalletDisconnectedError\";\n}\n\nexport class WalletDisconnectionError extends WalletError {\n name = \"WalletDisconnectionError\";\n}\n\nexport class WalletAccountError extends WalletError {\n name = \"WalletAccountError\";\n}\nexport class WalletGetNetworkError extends WalletError {\n name = \"WalletGetNetworkError\";\n}\n\nexport class WalletAccountChangeError extends WalletError {\n name = \"WalletAccountChangeError\";\n}\n\nexport class WalletNetworkChangeError extends WalletError {\n name = \"WalletNetworkChangeError\";\n}\n\nexport class WalletPublicKeyError extends WalletError {\n name = \"WalletPublicKeyError\";\n}\n\nexport class WalletKeypairError extends WalletError {\n name = \"WalletKeypairError\";\n}\n\nexport class WalletNotConnectedError extends WalletError {\n name = \"WalletNotConnectedError\";\n}\n\nexport class WalletSendTransactionError extends WalletError {\n name = \"WalletSendTransactionError\";\n}\n\nexport class WalletSignMessageError extends WalletError {\n name = \"WalletSignMessageError\";\n}\n\nexport class WalletSignMessageAndVerifyError extends WalletError {\n name = \"WalletSignMessageAndVerifyError\";\n}\n\nexport class WalletSignAndSubmitMessageError extends WalletError {\n name = \"WalletSignAndSubmitMessageError\";\n}\n\nexport class WalletSignTransactionError extends WalletError {\n name = \"WalletSignTransactionError\";\n}\n\nexport class WalletTimeoutError extends WalletError {\n name = \"WalletTimeoutError\";\n}\n\nexport class WalletWindowBlockedError extends WalletError {\n name = \"WalletWindowBlockedError\";\n}\n\nexport class WalletWindowClosedError extends WalletError {\n name = \"WalletWindowClosedError\";\n}\n\nexport class WalletResponseError extends WalletError {\n name = \"WalletResponseError\";\n}\n\nexport class WalletNotSupportedMethod extends WalletError {\n name = \"WalletNotSupportedMethod\";\n}\n\nexport class WalletChangeNetworkError extends WalletError {\n name = \"WalletChangeNetworkError\";\n}\n\nexport class WalletSubmitTransactionError extends WalletError {\n name = \"WalletSubmitTransactionError\";\n}\n\nexport class WalletNotFoundError extends WalletError {\n name = \"WalletNotFoundError\";\n}\n","export enum WalletReadyState {\n /**\n * Wallet can only be in one of two states - installed or not installed\n * Installed: wallets are detected by the browser event listeners and means they are installed on the user's browser.\n * NotDetected: wallets are not detected by the browser event listeners and means they are not installed on the user's browser.\n */\n Installed = \"Installed\",\n NotDetected = \"NotDetected\",\n}\n\nexport enum NetworkName {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n Devnet = \"devnet\",\n}\n\nexport const ChainIdToAnsSupportedNetworkMap: Record<string, string> = {\n \"1\": \"mainnet\", // mainnet\n \"2\": \"testnet\", // testnet\n};\n\n/**\n * The base URL for all Aptos Connect wallets.\n *\n * @deprecated Use {@link PETRA_WEB_BASE_URL} instead.\n */\nexport const APTOS_CONNECT_BASE_URL = \"https://aptosconnect.app\";\n\n/** The base URL for all Petra Web wallets. */\nexport const PETRA_WEB_BASE_URL = \"https://web.petra.app\";\n\n/**\n * The URL to the Aptos Connect account page if the user is signed in to Aptos Connect.\n *\n * @deprecated Use {@link PETRA_WEB_ACCOUNT_URL} instead.\n */\nexport const APTOS_CONNECT_ACCOUNT_URL =\n \"https://aptosconnect.app/dashboard/main-account\";\n\n/** The URL to the Petra Web account page if the user is signed in to Petra Web. */\nexport const PETRA_WEB_ACCOUNT_URL =\n \"https://web.petra.app/dashboard/main-account\";\n","import {\n Aptos,\n AptosConfig,\n Hex,\n Network,\n NetworkToNodeAPI,\n PluginSettings,\n} from \"@aptos-labs/ts-sdk\";\nimport {\n NetworkInfo,\n NetworkInfo as StandardNetworkInfo,\n} from \"@aptos-labs/wallet-standard\";\n\nimport { DappConfig } from \"../WalletCore\";\nimport { WalletSignAndSubmitMessageError } from \"../error\";\nimport { InputTransactionData } from \"./types\";\n\nexport function isMobile(): boolean {\n return /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/i.test(\n navigator.userAgent,\n );\n}\n\nexport function isInAppBrowser(): boolean {\n const isIphone = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(\n navigator.userAgent,\n );\n\n const isAndroid = /(Android).*Version\\/[\\d.]+.*Chrome\\/[^\\s]+ Mobile/i.test(\n navigator.userAgent,\n );\n\n return isIphone || isAndroid;\n}\n\nexport function isRedirectable(): boolean {\n // SSR: return false\n if (typeof navigator === \"undefined\" || !navigator) return false;\n\n // if we are on mobile and NOT in a in-app browser we will redirect to a wallet app\n\n return isMobile() && !isInAppBrowser();\n}\n\nexport function generalizedErrorMessage(error: any): string {\n return typeof error === \"object\" && \"message\" in error\n ? error.message\n : error;\n}\n\n/**\n * Helper function to get AptosConfig that supports Aptos and Custom networks\n *\n * @param networkInfo\n * @param dappConfig\n * @returns AptosConfig\n */\nexport const getAptosConfig = (\n networkInfo: NetworkInfo | null,\n dappConfig: DappConfig | undefined,\n): AptosConfig => {\n if (!networkInfo) {\n throw new Error(\"Undefined network\");\n }\n\n const pluginSettings: PluginSettings = {\n TRANSACTION_SUBMITTER: dappConfig?.transactionSubmitter,\n };\n\n if (isAptosNetwork(networkInfo)) {\n const currentNetwork = convertNetwork(networkInfo);\n\n if (isAptosLiveNetwork(currentNetwork)) {\n const apiKey = dappConfig?.aptosApiKeys;\n return new AptosConfig({\n network: currentNetwork,\n clientConfig: { API_KEY: apiKey ? apiKey[currentNetwork] : undefined },\n pluginSettings,\n });\n }\n\n return new AptosConfig({\n network: currentNetwork,\n pluginSettings,\n });\n }\n\n const knownNetworks = {\n okx: \"https://wallet.okx.com/fullnode/aptos/discover/rpc\",\n };\n\n if (networkInfo.url) {\n const isKnownNetwork = Object.values(knownNetworks).includes(\n networkInfo.url,\n );\n\n if (isKnownNetwork) {\n return new AptosConfig({\n network: Network.CUSTOM,\n fullnode: networkInfo.url,\n pluginSettings,\n });\n }\n }\n\n // Custom networks are not supported, please ensure that the wallet is returning the appropriate network Mainnet, Testnet, Devnet, Local\n throw new Error(\n `Invalid network, network ${networkInfo.name} not supported with Aptos wallet adapter to prevent user from using an unexpected network.`,\n );\n};\n\n/**\n * Helper function to resolve if the current connected network is an Aptos network\n *\n * @param networkInfo\n * @returns boolean\n */\nexport const isAptosNetwork = (\n networkInfo: NetworkInfo | StandardNetworkInfo | null,\n): boolean => {\n if (!networkInfo) {\n throw new Error(\"Undefined network\");\n }\n return NetworkToNodeAPI[networkInfo.name] !== undefined;\n};\n\nexport const isAptosLiveNetwork = (networkInfo: Network): boolean => {\n return (\n networkInfo === \"devnet\" ||\n networkInfo === \"testnet\" ||\n networkInfo === \"mainnet\"\n );\n};\n\n/**\n * Helper function to fetch Devnet chain id\n */\nexport const fetchDevnetChainId = async (): Promise<number> => {\n const aptos = new Aptos(); // default to devnet\n return await aptos.getChainId();\n};\n\n/**\n * A helper function to handle the publish package transaction.\n * The Aptos SDK expects the metadataBytes and byteCode to be Uint8Array, but in case the arguments are passed in\n * as a string, this function converts the string to Uint8Array.\n */\nexport const handlePublishPackageTransaction = (\n transactionInput: InputTransactionData,\n) => {\n // convert the first argument, metadataBytes, to uint8array if is a string\n let metadataBytes = transactionInput.data.functionArguments[0];\n if (typeof metadataBytes === \"string\") {\n metadataBytes = Hex.fromHexInput(metadataBytes).toUint8Array();\n }\n\n // convert the second argument, byteCode, to uint8array if is a string\n let byteCode = transactionInput.data.functionArguments[1];\n if (Array.isArray(byteCode)) {\n byteCode = byteCode.map((byte) => {\n if (typeof byte === \"string\") {\n return Hex.fromHexInput(byte).toUint8Array();\n }\n return byte;\n });\n } else {\n throw new WalletSignAndSubmitMessageError(\n \"The bytecode argument must be an array.\",\n ).message;\n }\n\n return { metadataBytes, byteCode };\n};\n\n// old => new\nexport function convertNetwork(networkInfo: NetworkInfo | null): Network {\n switch (networkInfo?.name) {\n case \"mainnet\" as Network:\n return Network.MAINNET;\n case \"testnet\" as Network:\n return Network.TESTNET;\n case \"devnet\" as Network:\n return Network.DEVNET;\n case \"local\" as Network:\n return Network.LOCAL;\n case \"shelbynet\" as Network:\n return Network.SHELBYNET;\n default:\n throw new Error(\"Invalid Aptos network name\");\n }\n}\n"]}
|
package/dist/registry.d.ts
CHANGED
|
@@ -14,5 +14,6 @@ import { AptosStandardSupportedWallet } from "./utils/types";
|
|
|
14
14
|
* @example "https://myWallet.app/explore?link="
|
|
15
15
|
*/
|
|
16
16
|
export declare const aptosStandardSupportedWalletList: Array<AptosStandardSupportedWallet>;
|
|
17
|
-
export declare const
|
|
17
|
+
export declare const solanaStandardSupportedWalletList: Array<AptosStandardSupportedWallet>;
|
|
18
|
+
export declare const evmStandardSupportedWalletList: Array<AptosStandardSupportedWallet>;
|
|
18
19
|
//# sourceMappingURL=registry.d.ts.map
|
package/dist/registry.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAC;AAE7D;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gCAAgC,EAAE,KAAK,CAAC,4BAA4B,CA6D9E,CAAC;AAEJ,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAC;AAE7D;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gCAAgC,EAAE,KAAK,CAAC,4BAA4B,CA6D9E,CAAC;AAEJ,eAAO,MAAM,iCAAiC,EAAE,KAAK,CAAC,4BAA4B,CA0B/E,CAAC;AAEJ,eAAO,MAAM,8BAA8B,EAAE,KAAK,CAAC,4BAA4B,CA4B5E,CAAC"}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const WALLET_ADAPTER_CORE_VERSION = "7.10.
|
|
1
|
+
export declare const WALLET_ADAPTER_CORE_VERSION = "7.10.2";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/package.json
CHANGED
package/src/WalletCore.ts
CHANGED
|
@@ -86,7 +86,8 @@ import {
|
|
|
86
86
|
} from "./utils";
|
|
87
87
|
import {
|
|
88
88
|
aptosStandardSupportedWalletList,
|
|
89
|
-
|
|
89
|
+
evmStandardSupportedWalletList,
|
|
90
|
+
solanaStandardSupportedWalletList,
|
|
90
91
|
} from "./registry";
|
|
91
92
|
import { getSDKWallets } from "./sdkWallets";
|
|
92
93
|
import {
|
|
@@ -133,7 +134,15 @@ export interface DappConfig {
|
|
|
133
134
|
appId?: string;
|
|
134
135
|
appUrl?: string;
|
|
135
136
|
};
|
|
136
|
-
|
|
137
|
+
/**
|
|
138
|
+
* A flag to indicate that the dapp supports cross-chain transactions.
|
|
139
|
+
* If enabled, the adapter will show cross-chain wallets in the wallet selector modal.
|
|
140
|
+
* @default false
|
|
141
|
+
*/
|
|
142
|
+
crossChainWallets?: {
|
|
143
|
+
solana?: boolean;
|
|
144
|
+
evm?: boolean;
|
|
145
|
+
};
|
|
137
146
|
}
|
|
138
147
|
|
|
139
148
|
export declare interface WalletCoreEvents {
|
|
@@ -190,7 +199,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
190
199
|
constructor(
|
|
191
200
|
optInWallets?: ReadonlyArray<AvailableWallets>,
|
|
192
201
|
dappConfig?: DappConfig,
|
|
193
|
-
disableTelemetry?: boolean
|
|
202
|
+
disableTelemetry?: boolean
|
|
194
203
|
) {
|
|
195
204
|
super();
|
|
196
205
|
this._optInWallets = optInWallets || [];
|
|
@@ -237,7 +246,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
237
246
|
* @param extensionwWallets
|
|
238
247
|
*/
|
|
239
248
|
private setExtensionAIP62Wallets(
|
|
240
|
-
extensionwWallets: readonly AptosWallet[]
|
|
249
|
+
extensionwWallets: readonly AptosWallet[]
|
|
241
250
|
): void {
|
|
242
251
|
extensionwWallets.map((wallet: AdapterWallet) => {
|
|
243
252
|
if (this.excludeWallet(wallet)) {
|
|
@@ -254,7 +263,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
254
263
|
if (isValid) {
|
|
255
264
|
// check if we already have this wallet as a not detected wallet
|
|
256
265
|
const index = this._standard_not_detected_wallets.findIndex(
|
|
257
|
-
(notDetctedWallet) => notDetctedWallet.name == wallet.name
|
|
266
|
+
(notDetctedWallet) => notDetctedWallet.name == wallet.name
|
|
258
267
|
);
|
|
259
268
|
// if we do, remove it from the not detected wallets array as it is now become detected
|
|
260
269
|
if (index !== -1) {
|
|
@@ -263,7 +272,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
263
272
|
|
|
264
273
|
// ✅ Check if wallet already exists in _standard_wallets
|
|
265
274
|
const alreadyExists = this._standard_wallets.some(
|
|
266
|
-
(w) => w.name === wallet.name
|
|
275
|
+
(w) => w.name === wallet.name
|
|
267
276
|
);
|
|
268
277
|
if (!alreadyExists) {
|
|
269
278
|
wallet.readyState = WalletReadyState.Installed;
|
|
@@ -303,17 +312,18 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
303
312
|
// Append wallets from wallet standard support registry to the `_standard_not_detected_wallets` array
|
|
304
313
|
// when wallet is not installed on the user machine
|
|
305
314
|
private appendNotDetectedStandardSupportedWallets(): void {
|
|
306
|
-
const walletRegistry =
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
315
|
+
const walletRegistry = [...aptosStandardSupportedWalletList];
|
|
316
|
+
if (this._dappConfig?.crossChainWallets?.solana) {
|
|
317
|
+
walletRegistry.push(...solanaStandardSupportedWalletList);
|
|
318
|
+
}
|
|
319
|
+
if (this._dappConfig?.crossChainWallets?.evm) {
|
|
320
|
+
walletRegistry.push(...evmStandardSupportedWalletList);
|
|
321
|
+
}
|
|
312
322
|
// Loop over the registry map
|
|
313
323
|
walletRegistry.map((supportedWallet: AptosStandardSupportedWallet) => {
|
|
314
324
|
// Check if we already have this wallet as a detected AIP-62 wallet standard
|
|
315
325
|
const existingStandardWallet = this._standard_wallets.find(
|
|
316
|
-
(wallet) => wallet.name == supportedWallet.name
|
|
326
|
+
(wallet) => wallet.name == supportedWallet.name
|
|
317
327
|
);
|
|
318
328
|
// If it is detected, it means the user has the wallet installed, so dont add it to the wallets array
|
|
319
329
|
if (existingStandardWallet) {
|
|
@@ -371,7 +381,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
371
381
|
* @param wallet A wallet
|
|
372
382
|
*/
|
|
373
383
|
private ensureWalletExists(
|
|
374
|
-
wallet: AdapterWallet | null
|
|
384
|
+
wallet: AdapterWallet | null
|
|
375
385
|
): asserts wallet is AdapterWallet {
|
|
376
386
|
if (!wallet) {
|
|
377
387
|
throw new WalletNotConnectedError().name;
|
|
@@ -386,7 +396,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
386
396
|
* @param account An account
|
|
387
397
|
*/
|
|
388
398
|
private ensureAccountExists(
|
|
389
|
-
account: AccountInfo | null
|
|
399
|
+
account: AccountInfo | null
|
|
390
400
|
): asserts account is AccountInfo {
|
|
391
401
|
if (!account) {
|
|
392
402
|
throw new WalletAccountError("Account is not set").name;
|
|
@@ -537,7 +547,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
537
547
|
// Check if we are in a redirectable view (i.e on mobile AND not in an in-app browser)
|
|
538
548
|
if (isRedirectable()) {
|
|
539
549
|
const selectedWallet = this._standard_not_detected_wallets.find(
|
|
540
|
-
(wallet: AdapterNotDetectedWallet) => wallet.name === walletName
|
|
550
|
+
(wallet: AdapterNotDetectedWallet) => wallet.name === walletName
|
|
541
551
|
);
|
|
542
552
|
|
|
543
553
|
if (selectedWallet) {
|
|
@@ -569,7 +579,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
569
579
|
const allDetectedWallets = this._standard_wallets;
|
|
570
580
|
|
|
571
581
|
const selectedWallet = allDetectedWallets.find(
|
|
572
|
-
(wallet: AdapterWallet) => wallet.name === walletName
|
|
582
|
+
(wallet: AdapterWallet) => wallet.name === walletName
|
|
573
583
|
);
|
|
574
584
|
|
|
575
585
|
if (!selectedWallet) return;
|
|
@@ -579,7 +589,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
579
589
|
// if the selected wallet is already connected, we don't need to connect again
|
|
580
590
|
if (this._wallet?.name === walletName)
|
|
581
591
|
throw new WalletConnectionError(
|
|
582
|
-
`${walletName} wallet is already connected
|
|
592
|
+
`${walletName} wallet is already connected`
|
|
583
593
|
).message;
|
|
584
594
|
}
|
|
585
595
|
|
|
@@ -612,7 +622,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
612
622
|
|
|
613
623
|
const allDetectedWallets = this._standard_wallets;
|
|
614
624
|
const selectedWallet = allDetectedWallets.find(
|
|
615
|
-
(wallet: AdapterWallet) => wallet.name === walletName
|
|
625
|
+
(wallet: AdapterWallet) => wallet.name === walletName
|
|
616
626
|
);
|
|
617
627
|
|
|
618
628
|
if (!selectedWallet) {
|
|
@@ -621,14 +631,14 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
621
631
|
|
|
622
632
|
if (!selectedWallet.features["aptos:signIn"]) {
|
|
623
633
|
throw new WalletNotSupportedMethod(
|
|
624
|
-
`aptos:signIn is not supported by ${walletName}
|
|
634
|
+
`aptos:signIn is not supported by ${walletName}`
|
|
625
635
|
).message;
|
|
626
636
|
}
|
|
627
637
|
|
|
628
638
|
return await this.connectWallet(selectedWallet, async () => {
|
|
629
639
|
if (!selectedWallet.features["aptos:signIn"]) {
|
|
630
640
|
throw new WalletNotSupportedMethod(
|
|
631
|
-
`aptos:signIn is not supported by ${selectedWallet.name}
|
|
641
|
+
`aptos:signIn is not supported by ${selectedWallet.name}`
|
|
632
642
|
).message;
|
|
633
643
|
}
|
|
634
644
|
|
|
@@ -654,7 +664,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
654
664
|
*/
|
|
655
665
|
private async connectWallet<T>(
|
|
656
666
|
selectedWallet: AdapterWallet,
|
|
657
|
-
onConnect: () => Promise<{ account: AccountInfo; output: T }
|
|
667
|
+
onConnect: () => Promise<{ account: AccountInfo; output: T }>
|
|
658
668
|
): Promise<T> {
|
|
659
669
|
try {
|
|
660
670
|
this._connecting = true;
|
|
@@ -705,7 +715,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
705
715
|
* @returns AptosSignAndSubmitTransactionOutput
|
|
706
716
|
*/
|
|
707
717
|
async signAndSubmitTransaction(
|
|
708
|
-
transactionInput: InputTransactionData
|
|
718
|
+
transactionInput: InputTransactionData
|
|
709
719
|
): Promise<AptosSignAndSubmitTransactionOutput> {
|
|
710
720
|
try {
|
|
711
721
|
if ("function" in transactionInput.data) {
|
|
@@ -756,7 +766,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
756
766
|
});
|
|
757
767
|
|
|
758
768
|
type AptosSignAndSubmitTransactionV1Method = (
|
|
759
|
-
transaction: AnyRawTransaction
|
|
769
|
+
transaction: AnyRawTransaction
|
|
760
770
|
) => Promise<UserResponse<AptosSignAndSubmitTransactionOutput>>;
|
|
761
771
|
|
|
762
772
|
const signAndSubmitTransactionMethod = this._wallet.features[
|
|
@@ -765,7 +775,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
765
775
|
.signAndSubmitTransaction as unknown as AptosSignAndSubmitTransactionV1Method;
|
|
766
776
|
|
|
767
777
|
const response = (await signAndSubmitTransactionMethod(
|
|
768
|
-
transaction
|
|
778
|
+
transaction
|
|
769
779
|
)) as UserResponse<AptosSignAndSubmitTransactionOutput>;
|
|
770
780
|
|
|
771
781
|
if (response.status === UserResponseStatus.REJECTED) {
|
|
@@ -861,7 +871,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
861
871
|
"aptos:signTransaction"
|
|
862
872
|
].signTransaction(
|
|
863
873
|
transactionOrPayload,
|
|
864
|
-
asFeePayer
|
|
874
|
+
asFeePayer
|
|
865
875
|
)) as UserResponse<AccountAuthenticator>;
|
|
866
876
|
if (response.status === UserResponseStatus.REJECTED) {
|
|
867
877
|
throw new WalletConnectionError("User has rejected the request")
|
|
@@ -897,7 +907,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
897
907
|
AptosSignTransactionMethodV1_1;
|
|
898
908
|
|
|
899
909
|
const response = (await walletSignTransactionMethod(
|
|
900
|
-
signTransactionV1_1StandardInput
|
|
910
|
+
signTransactionV1_1StandardInput
|
|
901
911
|
)) as UserResponse<AptosSignTransactionOutputV1_1>;
|
|
902
912
|
if (response.status === UserResponseStatus.REJECTED) {
|
|
903
913
|
throw new WalletConnectionError("User has rejected the request")
|
|
@@ -923,7 +933,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
923
933
|
"aptos:signTransaction"
|
|
924
934
|
].signTransaction(
|
|
925
935
|
transaction,
|
|
926
|
-
asFeePayer
|
|
936
|
+
asFeePayer
|
|
927
937
|
)) as UserResponse<AccountAuthenticator>;
|
|
928
938
|
if (response.status === UserResponseStatus.REJECTED) {
|
|
929
939
|
throw new WalletConnectionError("User has rejected the request")
|
|
@@ -950,7 +960,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
950
960
|
* @throws WalletSignMessageError
|
|
951
961
|
*/
|
|
952
962
|
async signMessage(
|
|
953
|
-
message: AptosSignMessageInput
|
|
963
|
+
message: AptosSignMessageInput
|
|
954
964
|
): Promise<AptosSignMessageOutput> {
|
|
955
965
|
try {
|
|
956
966
|
this.ensureWalletExists(this._wallet);
|
|
@@ -976,7 +986,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
976
986
|
* @returns PendingTransactionResponse
|
|
977
987
|
*/
|
|
978
988
|
async submitTransaction(
|
|
979
|
-
transaction: InputSubmitTransactionData
|
|
989
|
+
transaction: InputSubmitTransactionData
|
|
980
990
|
): Promise<PendingTransactionResponse> {
|
|
981
991
|
// The standard does not support submitTransaction, so we use the adapter to submit the transaction
|
|
982
992
|
try {
|
|
@@ -1022,7 +1032,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
1022
1032
|
await this.setAnsName();
|
|
1023
1033
|
this.recordEvent("account_change");
|
|
1024
1034
|
this.emit("accountChange", this._account);
|
|
1025
|
-
}
|
|
1035
|
+
}
|
|
1026
1036
|
);
|
|
1027
1037
|
} catch (error: any) {
|
|
1028
1038
|
const errMsg = generalizedErrorMessage(error);
|
|
@@ -1043,7 +1053,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
1043
1053
|
this.setNetwork(data);
|
|
1044
1054
|
await this.setAnsName();
|
|
1045
1055
|
this.emit("networkChange", this._network);
|
|
1046
|
-
}
|
|
1056
|
+
}
|
|
1047
1057
|
);
|
|
1048
1058
|
} catch (error: any) {
|
|
1049
1059
|
const errMsg = generalizedErrorMessage(error);
|
|
@@ -1077,7 +1087,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
1077
1087
|
if (this._wallet.features["aptos:changeNetwork"]) {
|
|
1078
1088
|
const response =
|
|
1079
1089
|
await this._wallet.features["aptos:changeNetwork"].changeNetwork(
|
|
1080
|
-
networkInfo
|
|
1090
|
+
networkInfo
|
|
1081
1091
|
);
|
|
1082
1092
|
if (response.status === UserResponseStatus.REJECTED) {
|
|
1083
1093
|
throw new WalletConnectionError("User has rejected the request")
|
|
@@ -1087,7 +1097,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
1087
1097
|
}
|
|
1088
1098
|
|
|
1089
1099
|
throw new WalletChangeNetworkError(
|
|
1090
|
-
`${this._wallet.name} does not support changing network request
|
|
1100
|
+
`${this._wallet.name} does not support changing network request`
|
|
1091
1101
|
).message;
|
|
1092
1102
|
} catch (error: any) {
|
|
1093
1103
|
const errMsg = generalizedErrorMessage(error);
|
|
@@ -1117,7 +1127,7 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
|
|
|
1117
1127
|
|
|
1118
1128
|
const aptosConfig = getAptosConfig(this._network, this._dappConfig);
|
|
1119
1129
|
const signingMessage = new TextEncoder().encode(
|
|
1120
|
-
response.args.fullMessage
|
|
1130
|
+
response.args.fullMessage
|
|
1121
1131
|
);
|
|
1122
1132
|
if ("verifySignatureAsync" in (this._account.publicKey as Object)) {
|
|
1123
1133
|
return await this._account.publicKey.verifySignatureAsync({
|