@aptos-labs/wallet-adapter-core 7.10.3-xchaininit3.2 → 8.0.0-xchaininit2.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/index.js CHANGED
@@ -485,7 +485,7 @@ __export(index_exports, {
485
485
  });
486
486
  module.exports = __toCommonJS(index_exports);
487
487
  // src/version.ts
488
- var WALLET_ADAPTER_CORE_VERSION = "7.10.3-xchaininit3.0";
488
+ var WALLET_ADAPTER_CORE_VERSION = "8.0.0-xchaininit2.0";
489
489
  // src/WalletCore.ts
490
490
  var import_eventemitter3 = __toESM(require("eventemitter3"));
491
491
  var import_ts_sdk2 = require("@aptos-labs/ts-sdk");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/WalletCore.ts","../src/ga/index.ts","../src/version.ts","../src/error/index.ts"],"names":[],"mappings":"","sourcesContent":["import { AptosSignInBoundFields } from \"@aptos-labs/wallet-standard\";\nimport { WALLET_ADAPTER_CORE_VERSION } from \"./version\";\n\nexport type {\n AptosSignInOutput,\n AptosSignInInput,\n AptosSignInBoundFields,\n} from \"@aptos-labs/wallet-standard\";\n/**\n * @deprecated Use `AptosSignInBoundFields` instead. This will be removed in future versions.\n */\nexport type AptosSignInRequiredFields = AptosSignInBoundFields;\n\nexport * from \"./WalletCore\";\nexport * from \"./constants\";\nexport * from \"./utils\";\nexport * from \"./sdkWallets\";\nexport * from \"./registry\";\n\n// inject adapter core version to the window\nif (typeof window !== \"undefined\") {\n (window as any).WALLET_ADAPTER_CORE_VERSION = WALLET_ADAPTER_CORE_VERSION;\n}\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 const WALLET_ADAPTER_CORE_VERSION = \"7.10.3-xchaininit3.0\";\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"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/WalletCore.ts","../src/ga/index.ts","../src/version.ts","../src/error/index.ts"],"names":[],"mappings":"","sourcesContent":["import { AptosSignInBoundFields } from \"@aptos-labs/wallet-standard\";\nimport { WALLET_ADAPTER_CORE_VERSION } from \"./version\";\n\nexport type {\n AptosSignInOutput,\n AptosSignInInput,\n AptosSignInBoundFields,\n} from \"@aptos-labs/wallet-standard\";\n/**\n * @deprecated Use `AptosSignInBoundFields` instead. This will be removed in future versions.\n */\nexport type AptosSignInRequiredFields = AptosSignInBoundFields;\n\nexport * from \"./WalletCore\";\nexport * from \"./constants\";\nexport * from \"./utils\";\nexport * from \"./sdkWallets\";\nexport * from \"./registry\";\n\n// inject adapter core version to the window\nif (typeof window !== \"undefined\") {\n (window as any).WALLET_ADAPTER_CORE_VERSION = WALLET_ADAPTER_CORE_VERSION;\n}\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 const WALLET_ADAPTER_CORE_VERSION = \"8.0.0-xchaininit2.0\";\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"]}
package/dist/index.mjs CHANGED
@@ -319,7 +319,7 @@ function _ts_generator(thisArg, body) {
319
319
  };
320
320
  }
321
321
  }
322
- var WALLET_ADAPTER_CORE_VERSION = "7.10.3-xchaininit3.0";
322
+ var WALLET_ADAPTER_CORE_VERSION = "8.0.0-xchaininit2.0";
323
323
  // src/WalletCore.ts
324
324
  import EventEmitter from "eventemitter3";
325
325
  import { AccountAddress, Aptos as Aptos2, Network as Network2, NetworkToChainId } from "@aptos-labs/ts-sdk";
@@ -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.3-xchaininit3.0\";\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"]}
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 = \"8.0.0-xchaininit2.0\";\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/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const WALLET_ADAPTER_CORE_VERSION = "7.10.3-xchaininit3.0";
1
+ export declare const WALLET_ADAPTER_CORE_VERSION = "8.0.0-xchaininit2.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,2BAA2B,yBAAyB,CAAC"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,2BAA2B,wBAAwB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aptos-labs/wallet-adapter-core",
3
- "version": "7.10.3-xchaininit3.2",
3
+ "version": "8.0.0-xchaininit2.0",
4
4
  "description": "Aptos Wallet Adapter Core",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -36,8 +36,8 @@
36
36
  "ts-jest": "^29.0.3",
37
37
  "tsup": "^8.4.0",
38
38
  "typescript": "^5.8.3",
39
- "@aptos-labs/wallet-adapter-tsconfig": "0.0.2",
40
- "@aptos-labs/eslint-config-adapter": "0.0.2"
39
+ "@aptos-labs/eslint-config-adapter": "0.0.2",
40
+ "@aptos-labs/wallet-adapter-tsconfig": "0.0.2"
41
41
  },
42
42
  "dependencies": {
43
43
  "@aptos-connect/wallet-adapter-plugin": "^3.0.1",
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const WALLET_ADAPTER_CORE_VERSION = "7.10.3-xchaininit3.0";
1
+ export const WALLET_ADAPTER_CORE_VERSION = "8.0.0-xchaininit2.0";