@dynamic-labs-sdk/client 1.8.1 → 1.9.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.
Files changed (154) hide show
  1. package/android/src/main/java/xyz/dynamic/client/DynamicClientPackage.kt +10 -0
  2. package/android/src/main/java/xyz/dynamic/client/screenshot/ScreenshotProtectionModule.kt +48 -0
  3. package/dist/{InvalidParamError-DGBih-LJ.cjs → InvalidParamError-C7LLi2cZ.cjs} +91 -13
  4. package/dist/InvalidParamError-C7LLi2cZ.cjs.map +1 -0
  5. package/dist/{InvalidParamError-BKnC9rcJ.esm.js → InvalidParamError-DIPFT3sS.esm.js} +73 -13
  6. package/dist/InvalidParamError-DIPFT3sS.esm.js.map +1 -0
  7. package/dist/{InvalidParamError-Btv8VGSa.native.esm.js → InvalidParamError-YG7yXCq5.native.esm.js} +294 -13
  8. package/dist/InvalidParamError-YG7yXCq5.native.esm.js.map +1 -0
  9. package/dist/NotWaasWalletAccountError-BWrDQFe8.esm.js +18 -0
  10. package/dist/NotWaasWalletAccountError-BWrDQFe8.esm.js.map +1 -0
  11. package/dist/NotWaasWalletAccountError-C8ex1YA_.cjs +23 -0
  12. package/dist/NotWaasWalletAccountError-C8ex1YA_.cjs.map +1 -0
  13. package/dist/NotWaasWalletAccountError-Cd2o0wr0.native.esm.js +18 -0
  14. package/dist/NotWaasWalletAccountError-Cd2o0wr0.native.esm.js.map +1 -0
  15. package/dist/client/core/createCore/getInitialState.d.ts +1 -1
  16. package/dist/client/core/createCore/getInitialState.d.ts.map +1 -1
  17. package/dist/client/createDynamicClient/createDynamicClient.d.ts.map +1 -1
  18. package/dist/client/types/DynamicClient.d.ts +9 -0
  19. package/dist/client/types/DynamicClient.d.ts.map +1 -1
  20. package/dist/core.cjs +24 -5
  21. package/dist/core.cjs.map +1 -1
  22. package/dist/core.esm.js +24 -6
  23. package/dist/core.esm.js.map +1 -1
  24. package/dist/core.native.esm.js +34 -9
  25. package/dist/core.native.esm.js.map +1 -1
  26. package/dist/exports/core.d.ts +4 -0
  27. package/dist/exports/core.d.ts.map +1 -1
  28. package/dist/exports/index.d.ts +0 -7
  29. package/dist/exports/index.d.ts.map +1 -1
  30. package/dist/exports/waasCore.d.ts +2 -0
  31. package/dist/exports/waasCore.d.ts.map +1 -1
  32. package/dist/{getNetworkProviderFromNetworkId-Bm41knUq.native.esm.js → getNetworkProviderFromNetworkId-C46TeXs8.native.esm.js} +17 -12
  33. package/dist/getNetworkProviderFromNetworkId-C46TeXs8.native.esm.js.map +1 -0
  34. package/dist/{getNetworkProviderFromNetworkId-BdgI7g5U.cjs → getNetworkProviderFromNetworkId-CBGWQS_K.cjs} +4 -4
  35. package/dist/{getNetworkProviderFromNetworkId-BdgI7g5U.cjs.map → getNetworkProviderFromNetworkId-CBGWQS_K.cjs.map} +1 -1
  36. package/dist/{getNetworkProviderFromNetworkId-CRuh5pgc.esm.js → getNetworkProviderFromNetworkId-D-wj5mPl.esm.js} +3 -3
  37. package/dist/{getNetworkProviderFromNetworkId-CRuh5pgc.esm.js.map → getNetworkProviderFromNetworkId-D-wj5mPl.esm.js.map} +1 -1
  38. package/dist/{getSignedSessionId-Cwmt4BkY.cjs → getSignedSessionId-CCHKjoeP.cjs} +3 -3
  39. package/dist/{getSignedSessionId-Cwmt4BkY.cjs.map → getSignedSessionId-CCHKjoeP.cjs.map} +1 -1
  40. package/dist/{getSignedSessionId-S6CBWkOn.native.esm.js → getSignedSessionId-DdKTM3Rh.native.esm.js} +3 -3
  41. package/dist/{getSignedSessionId-S6CBWkOn.native.esm.js.map → getSignedSessionId-DdKTM3Rh.native.esm.js.map} +1 -1
  42. package/dist/{getSignedSessionId-D2w_IRdt.esm.js → getSignedSessionId-Dy04984p.esm.js} +3 -3
  43. package/dist/{getSignedSessionId-D2w_IRdt.esm.js.map → getSignedSessionId-Dy04984p.esm.js.map} +1 -1
  44. package/dist/{getVerifiedCredentialForWalletAccount-QwfkKHfr.esm.js → getVerifiedCredentialForWalletAccount-BFCM2wnx.esm.js} +3 -10
  45. package/dist/getVerifiedCredentialForWalletAccount-BFCM2wnx.esm.js.map +1 -0
  46. package/dist/{getVerifiedCredentialForWalletAccount-CDuP1kaI.cjs → getVerifiedCredentialForWalletAccount-BtIVDer3.cjs} +4 -17
  47. package/dist/getVerifiedCredentialForWalletAccount-BtIVDer3.cjs.map +1 -0
  48. package/dist/{getVerifiedCredentialForWalletAccount-D33r7Drd.native.esm.js → getVerifiedCredentialForWalletAccount-Dsca691m.native.esm.js} +3 -236
  49. package/dist/getVerifiedCredentialForWalletAccount-Dsca691m.native.esm.js.map +1 -0
  50. package/dist/getWaasWalletProviderFromWalletAccount-5-EJK6a_.cjs +19 -0
  51. package/dist/getWaasWalletProviderFromWalletAccount-5-EJK6a_.cjs.map +1 -0
  52. package/dist/getWaasWalletProviderFromWalletAccount-AhhyxkKQ.esm.js +14 -0
  53. package/dist/getWaasWalletProviderFromWalletAccount-AhhyxkKQ.esm.js.map +1 -0
  54. package/dist/getWaasWalletProviderFromWalletAccount-EnCRdI3w.native.esm.js +14 -0
  55. package/dist/getWaasWalletProviderFromWalletAccount-EnCRdI3w.native.esm.js.map +1 -0
  56. package/dist/index.cjs +65 -15
  57. package/dist/index.cjs.map +1 -1
  58. package/dist/index.esm.js +61 -11
  59. package/dist/index.esm.js.map +1 -1
  60. package/dist/index.native.esm.js +64 -14
  61. package/dist/index.native.esm.js.map +1 -1
  62. package/dist/{isMfaRequiredForAction-5p3i98-Z.esm.js → isMfaRequiredForAction-BrmFODJQ.esm.js} +2 -2
  63. package/dist/{isMfaRequiredForAction-5p3i98-Z.esm.js.map → isMfaRequiredForAction-BrmFODJQ.esm.js.map} +1 -1
  64. package/dist/{isMfaRequiredForAction-cmElIVof.native.esm.js → isMfaRequiredForAction-DAfjBLvz.native.esm.js} +2 -2
  65. package/dist/{isMfaRequiredForAction-cmElIVof.native.esm.js.map → isMfaRequiredForAction-DAfjBLvz.native.esm.js.map} +1 -1
  66. package/dist/{isMfaRequiredForAction-z74isCQ7.cjs → isMfaRequiredForAction-aX0vdwv-.cjs} +2 -2
  67. package/dist/{isMfaRequiredForAction-z74isCQ7.cjs.map → isMfaRequiredForAction-aX0vdwv-.cjs.map} +1 -1
  68. package/dist/modules/balances/getBalances/getBalances.d.ts +5 -2
  69. package/dist/modules/balances/getBalances/getBalances.d.ts.map +1 -1
  70. package/dist/modules/balances/getMultichainBalances/getMultichainBalances.d.ts +6 -3
  71. package/dist/modules/balances/getMultichainBalances/getMultichainBalances.d.ts.map +1 -1
  72. package/dist/modules/checkout/checkout.types.d.ts +6 -6
  73. package/dist/modules/checkout/checkout.types.d.ts.map +1 -1
  74. package/dist/modules/initializeClient/initializeClient.d.ts.map +1 -1
  75. package/dist/modules/initializeClient/state.d.ts +9 -0
  76. package/dist/modules/initializeClient/state.d.ts.map +1 -1
  77. package/dist/modules/screenshotProtection/setScreenshotProtection/setScreenshotProtection.d.ts +15 -0
  78. package/dist/modules/screenshotProtection/setScreenshotProtection/setScreenshotProtection.d.ts.map +1 -0
  79. package/dist/modules/screenshotProtection/setScreenshotProtection/setScreenshotProtection.types.d.ts +14 -0
  80. package/dist/modules/screenshotProtection/setScreenshotProtection/setScreenshotProtection.types.d.ts.map +1 -0
  81. package/dist/modules/state/raiseStateEvents/events.d.ts +4 -0
  82. package/dist/modules/state/raiseStateEvents/events.d.ts.map +1 -1
  83. package/dist/modules/waas/createWaasClient/createNativeWaasSDKContainer.d.ts +15 -0
  84. package/dist/modules/waas/createWaasClient/createNativeWaasSDKContainer.d.ts.map +1 -0
  85. package/dist/modules/waas/createWaasProvider/createWaasProvider.d.ts.map +1 -1
  86. package/dist/modules/waas/exportWaasPrivateKeyToContainer/exportWaasPrivateKeyToContainer.d.ts +33 -0
  87. package/dist/modules/waas/exportWaasPrivateKeyToContainer/exportWaasPrivateKeyToContainer.d.ts.map +1 -0
  88. package/dist/modules/waas/exportWaasPrivateKeyToContainer/index.d.ts +2 -0
  89. package/dist/modules/waas/exportWaasPrivateKeyToContainer/index.d.ts.map +1 -0
  90. package/dist/modules/waas/waas.types.d.ts +3 -1
  91. package/dist/modules/waas/waas.types.d.ts.map +1 -1
  92. package/dist/modules/wallets/networks/getBalance/getBalance.d.ts +5 -1
  93. package/dist/modules/wallets/networks/getBalance/getBalance.d.ts.map +1 -1
  94. package/dist/{NotWaasWalletAccountError-CHr72wTH.esm.js → refreshAuth-B2kFf0pl.native.esm.js} +4 -18
  95. package/dist/refreshAuth-B2kFf0pl.native.esm.js.map +1 -0
  96. package/dist/{NotWaasWalletAccountError-CRmyVoB3.native.esm.js → refreshAuth-B8xd2JUm.esm.js} +4 -18
  97. package/dist/refreshAuth-B8xd2JUm.esm.js.map +1 -0
  98. package/dist/{NotWaasWalletAccountError-i1FozGep.cjs → refreshAuth-BMtIp1do.cjs} +3 -23
  99. package/dist/refreshAuth-BMtIp1do.cjs.map +1 -0
  100. package/dist/services/instrumentation/connectLoggerToInstrumentation/connectLoggerToInstrumentation.d.ts.map +1 -1
  101. package/dist/services/instrumentation/instrumentFunction/instrumentFunction.d.ts.map +1 -1
  102. package/dist/services/instrumentation/instrumentation.types.d.ts +6 -0
  103. package/dist/services/instrumentation/instrumentation.types.d.ts.map +1 -1
  104. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  105. package/dist/utils/getNonce/fetchAndStoreNonces/fetchAndStoreNonces.d.ts +4 -0
  106. package/dist/utils/getNonce/fetchAndStoreNonces/fetchAndStoreNonces.d.ts.map +1 -1
  107. package/dist/utils/getNonce/state.d.ts +5 -0
  108. package/dist/utils/getNonce/state.d.ts.map +1 -1
  109. package/dist/utils/getOperatingSystem/getOperatingSystem.d.ts +13 -0
  110. package/dist/utils/getOperatingSystem/getOperatingSystem.d.ts.map +1 -0
  111. package/dist/utils/getOperatingSystem/getOperatingSystem.types.d.ts +8 -0
  112. package/dist/utils/getOperatingSystem/getOperatingSystem.types.d.ts.map +1 -0
  113. package/dist/utils/getPlatform/getPlatform.d.ts +11 -0
  114. package/dist/utils/getPlatform/getPlatform.d.ts.map +1 -0
  115. package/dist/utils/getPlatform/getPlatform.types.d.ts +8 -0
  116. package/dist/utils/getPlatform/getPlatform.types.d.ts.map +1 -0
  117. package/dist/waas.cjs +20 -28
  118. package/dist/waas.cjs.map +1 -1
  119. package/dist/waas.esm.js +4 -12
  120. package/dist/waas.esm.js.map +1 -1
  121. package/dist/waas.native.esm.js +4 -12
  122. package/dist/waas.native.esm.js.map +1 -1
  123. package/dist/waasCore.cjs +39 -4
  124. package/dist/waasCore.cjs.map +1 -1
  125. package/dist/waasCore.esm.js +39 -5
  126. package/dist/waasCore.esm.js.map +1 -1
  127. package/dist/waasCore.native.esm.js +68 -10
  128. package/dist/waasCore.native.esm.js.map +1 -1
  129. package/ios/DynamicClientScreenshotProtection.h +4 -0
  130. package/ios/DynamicClientScreenshotProtection.mm +137 -0
  131. package/package.json +14 -7
  132. package/src/turboModules/NativeScreenshotProtection.native.spec.ts +57 -0
  133. package/src/turboModules/NativeScreenshotProtection.ts +26 -0
  134. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  135. package/android/gradle/wrapper/gradle-wrapper.properties +0 -7
  136. package/android/gradlew +0 -251
  137. package/android/gradlew.bat +0 -94
  138. package/android/settings.gradle +0 -30
  139. package/android/src/test/java/xyz/dynamic/client/keychain/KeyStoreKeyManagerTest.kt +0 -288
  140. package/android/src/test/java/xyz/dynamic/client/webview/DynamicWebViewClientTest.kt +0 -196
  141. package/android/src/test/java/xyz/dynamic/client/webview/DynamicWebViewHostOpenTest.kt +0 -347
  142. package/android/src/test/java/xyz/dynamic/client/webview/DynamicWebViewHostTest.kt +0 -171
  143. package/android/src/test/java/xyz/dynamic/client/webview/DynamicWebViewModuleTest.kt +0 -191
  144. package/dist/InvalidParamError-BKnC9rcJ.esm.js.map +0 -1
  145. package/dist/InvalidParamError-Btv8VGSa.native.esm.js.map +0 -1
  146. package/dist/InvalidParamError-DGBih-LJ.cjs.map +0 -1
  147. package/dist/NotWaasWalletAccountError-CHr72wTH.esm.js.map +0 -1
  148. package/dist/NotWaasWalletAccountError-CRmyVoB3.native.esm.js.map +0 -1
  149. package/dist/NotWaasWalletAccountError-i1FozGep.cjs.map +0 -1
  150. package/dist/getNetworkProviderFromNetworkId-Bm41knUq.native.esm.js.map +0 -1
  151. package/dist/getVerifiedCredentialForWalletAccount-CDuP1kaI.cjs.map +0 -1
  152. package/dist/getVerifiedCredentialForWalletAccount-D33r7Drd.native.esm.js.map +0 -1
  153. package/dist/getVerifiedCredentialForWalletAccount-QwfkKHfr.esm.js.map +0 -1
  154. package/react-native.config.cjs +0 -14
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","names":["timeoutId: ReturnType<typeof setTimeout> | null","clearExpirationTimeout: VoidFunction | null","logoutWithReason","blob: LegacySessionKeysBlob","stateChanges: Partial<DynamicCoreState>","eventEmitter: AsyncTrackEmitter","EventEmitter","track: AsyncTrack['track']","name","waitForAll: AsyncTrack['waitForAll']","getTracker: AsyncTrack['getTracker']","transport: InstrumentationTransport | undefined","config: InstrumentationConfig","queue: InstrumentationEvent[]","resolutionPromise","getInitialState","logoutWithReason","numberArray: number[]","checkout","urlObject: URL","fieldsMissingVerification: FieldMissingVerificationForCoinbaseOnramp[]","groups: Record<string, WalletConnectCatalogGroup>","wallets: Record<string, WalletConnectCatalogWallet>","normalize","wallets: WalletConnectCatalog['wallets']","groups: WalletConnectCatalog['groups']","result: ConnectionOptionForWalletOption[]","METAMASK_SDK_URI_SUPPORTED_CHAINS: readonly Chain[]","WALLETCONNECT_SUPPORTED_CHAINS: ReadonlySet<Chain>","result: ConnectionOptionForWalletOption[]","result: WithWalletProviderOptionForWalletOption[]","EXCLUDED_WALLET_OPTION_KEYS: ReadonlySet<string>","CONNECTION_OPTION_PRIORITY: Record<WalletConnectionOption['type'], number>","PRIORITY_WALLET_KEYS: readonly string[]","installed: WalletOption[]","connectable: WalletOption[]","installOnly: WalletOption[]","EMPTY_WALLET_BOOK: WalletBookSchema","allConnectionOptions: ConnectionOptionForWalletOption[]","installationUrlsByKey: Map<string, InstallationUrls>","walletOptions: WalletOption[]","formattedOptions: PublicKeyCredentialRequestOptionsJSON","supportedCountries: CountryPhoneData","verifyRequest:\n | EmailVerificationVerifyRequest\n | SmsVerificationVerifyRequest","from: SwapStatusRequestChain | undefined","to: SwapStatusRequestChain | undefined","proveWalletAccountOwnership","isMobile","packageName","packageVersion"],"sources":["../src/modules/state/raiseStateEvents/events.ts","../src/utils/appendConnectionUriToDeeplink/appendConnectionUriToDeeplink.ts","../src/utils/getNonce/prefetchNoncesIfNeeded/prefetchNoncesIfNeeded.ts","../src/services/runtimeServices/createRuntimeServices/createRuntimeServices.ts","../src/modules/auth/initializeAuth/setLongTimeout/setLongTimeout.ts","../src/modules/auth/initializeAuth/initializeAuth.ts","../src/modules/crossTabEventSync/setupCrossTabEventSync/setupCrossTabEventSync.ts","../src/modules/wallets/unverifiedWalletAccounts/schema.ts","../src/modules/wallets/walletProvider/walletProviderKeyMap/schema.ts","../src/modules/storageSync/schema.ts","../src/modules/keychainMigration/migrateSessionKeyToKeychain/KeyMigrationError.ts","../src/modules/keychainMigration/migrateSessionKeyToKeychain/migrateSessionKeyToKeychain.ts","../src/modules/state/raiseStateEvents/raiseStateEvents.ts","../src/modules/storageSync/hydrateStateWithStorage/hydrateStateWithStorage.ts","../src/modules/storageSync/syncStateWithStorage/syncStateWithStorage.ts","../src/modules/storageSync/initializeStorageSync.ts","../src/modules/user/refreshUser/refreshUser.ts","../src/errors/ClientAlreadyInitializedError.ts","../src/modules/initializeClient/initializeClient.ts","../src/services/asyncTrack/createAsyncTrack.ts","../src/services/eventEmitter/createEventEmitter.ts","../src/errors/UnavailableInServerSideError.ts","../src/services/fetch/createWebFetch.ts","../src/services/instrumentation/connectLoggerToInstrumentation/connectLoggerToInstrumentation.ts","../src/services/instrumentation/createInstrumentation/createInstrumentation.ts","../src/services/instrumentation/transports/createDynamicTransport/createDynamicTransport.ts","../src/services/navigate/createNavigationHandler/createNavigationHandler.ts","../src/services/openDeeplink/createWebDeeplinkOpener/createWebDeeplinkOpener.ts","../src/services/passkey/createPasskeyService/createPasskeyService.ts","../src/utils/debouncedMutex/createDebouncedMutex/createDebouncedMutex.ts","../src/errors/InvalidStorageValue.ts","../src/utils/observable/createObservableState/createObservableState.ts","../src/client/consts.ts","../src/client/core/createCore/getInitialState.ts","../src/client/core/createCore/createCore.ts","../src/client/createDynamicClient/createDynamicClient.ts","../src/errors/CheckoutSessionTokenMissingError.ts","../src/errors/DeeplinkConnectAndVerifyUnsupportedError.ts","../src/errors/FeeEstimationFailedError.ts","../src/errors/InvalidDeviceRegistrationRedirectError.ts","../src/errors/InvalidRedirectStorageStateError.ts","../src/errors/InvalidSocialCallbackOriginError.ts","../src/errors/UserCancelledSocialPopUpError.ts","../src/errors/MissingRedirectStorageStateError.ts","../src/errors/MissingSocialUrlParamError.ts","../src/errors/MissingUserVerificationError.ts","../src/errors/NetworkAddingUnavailableError.ts","../src/errors/NetworkNotAddedError.ts","../src/errors/NetworkSwitchingUnavailableError.ts","../src/errors/NoAddressFoundError.ts","../src/errors/NoPasskeyCredentialsFoundError.ts","../src/errors/NoSmartWalletAccountSignerFoundError.ts","../src/errors/NoWebAuthNSupportError.ts","../src/errors/SimulationFailedError.ts","../src/errors/TokenSwapError.ts","../src/errors/UnrecognizedNetworkError.ts","../src/errors/UserNotAuthenticatedError.ts","../src/errors/UserRejectedError.ts","../src/errors/WalletAccountAlreadyVerifiedError.ts","../src/errors/WalletAccountNotSelectedError.ts","../src/errors/WalletProviderMethodUnavailableError.ts","../src/modules/auth/checkStepUpAuth/checkStepUpAuth.ts","../src/modules/auth/externalAuth/requestExternalAuthElevatedToken/requestExternalAuthElevatedToken.ts","../src/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.ts","../src/modules/auth/logout/logout.ts","../src/modules/auth/passkeys/deletePasskey/deletePasskey.ts","../src/modules/auth/passkeys/getPasskeys/getPasskeys.ts","../src/modules/auth/passkeys/getPasskeyRegistrationOptions/getPasskeyRegistrationOptions.ts","../src/modules/auth/passkeys/serverRegisterPasskey/serverRegisterPasskey.ts","../src/modules/auth/passkeys/registerPasskey/registerPasskey.ts","../src/modules/auth/passkeys/getPasskeyAuthenticationSignInOptions/getPasskeyAuthenticationSignInOptions.ts","../src/modules/auth/passkeys/serverSigninPasskey/serverSigninPasskey.ts","../src/modules/auth/passkeys/signInWithPasskey/signInWithPasskey.ts","../src/modules/auth/social/getUserSocialAccounts/getUserSocialAccounts.ts","../src/modules/auth/social/removeDynamicOauthParamsFromUrl/removeDynamicOauthParamsFromUrl.ts","../src/modules/auth/social/oauth/redirectStateStorageSchema/redirectStateStorageSchema.ts","../src/utils/digestSHA256/digestSHA256.ts","../src/utils/encodeBase64Url/encodeBase64Url.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/addOAuthUrlParams/addOAuthUrlParams.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/getOAuthBaseUrl/getOAuthBaseUrl.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/buildOAuthUrl.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/signInWithSocialRedirect.ts","../src/modules/auth/social/oauth/signInWithSocialPopUp/signInWithSocialPopUp.ts","../src/modules/auth/social/oauth/detectSocialRedirectUrl/detectSocialRedirectUrl.ts","../src/modules/auth/social/oauth/processSocialCallback/processSocialCallback.ts","../src/modules/auth/social/oauth/completeSocialRedirect/completeSocialRedirect.ts","../src/modules/auth/social/oauth/authenticateWithSocial/authenticateWithSocial.ts","../src/modules/auth/social/oauth/completeSocialAuthentication/completeSocialAuthentication.ts","../src/modules/auth/social/oauth/detectOAuthRedirect/detectOAuthRedirect.ts","../src/modules/wallets/primaryWalletAccount/getPrimaryWalletAccount/getPrimaryWalletAccount.ts","../src/modules/auth/social/oauth/unlinkSocialAccount/unlinkSocialAccount.ts","../src/modules/balances/getTokenBalances/getTokenBalances.ts","../src/modules/balances/getMultichainTokenBalances/getMultichainTokenBalances.ts","../src/modules/checkout/utils/createCheckoutSessionTokenStorageKey/createCheckoutSessionTokenStorageKey.ts","../src/modules/checkout/utils/createCheckoutApiClient/createCheckoutApiClient.ts","../src/modules/checkout/utils/clearCheckoutSessionToken/clearCheckoutSessionToken.ts","../src/modules/checkout/utils/withCheckoutSessionTokenCleanupOn401/withCheckoutSessionTokenCleanupOn401.ts","../src/modules/checkout/attachCheckoutTransactionSource/attachCheckoutTransactionSource.ts","../src/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.ts","../src/modules/checkout/cancelCheckoutTransaction/cancelCheckoutTransaction.ts","../src/modules/checkout/getCheckouts/getCheckouts.ts","../src/modules/checkout/createCheckoutTransaction/createCheckoutTransaction.ts","../src/modules/checkout/getCheckoutTransaction/getCheckoutTransaction.ts","../src/modules/checkout/getCheckoutTransactionQuote/getCheckoutTransactionQuote.ts","../src/modules/checkout/prepareCheckoutTransaction/prepareCheckoutTransaction.ts","../src/modules/wallets/utils/assertWalletProviderMethodDefined/assertWalletProviderMethodDefined.ts","../src/modules/swap/constants.ts","../src/modules/swap/utils/ensureCorrectActiveNetwork/ensureCorrectActiveNetwork.ts","../src/modules/swap/executeSwapTransaction/executeSwapTransaction.ts","../src/modules/checkout/submitCheckoutTransaction/submitCheckoutTransaction.ts","../src/modules/checkout/trackCheckoutTransaction/trackCheckoutTransaction.ts","../src/modules/checkout/utils/requiresConversion/requiresConversion.ts","../src/modules/deviceRegistration/completeDeviceRegistration/completeDeviceRegistration.ts","../src/modules/deviceRegistration/getDeviceRegistrationTokenFromUrl/getDeviceRegistrationTokenFromUrl.ts","../src/modules/deviceRegistration/detectDeviceRegistrationRedirect/detectDeviceRegistrationRedirect.ts","../src/modules/deviceRegistration/getRegisteredDevices/getRegisteredDevices.ts","../src/modules/deviceRegistration/isDeviceRegistrationRequired/isDeviceRegistrationRequired.ts","../src/modules/deviceRegistration/revokeAllRegisteredDevices/revokeAllRegisteredDevices.ts","../src/modules/deviceRegistration/revokeRegisteredDevice/revokeRegisteredDevice.ts","../src/modules/funding/coinbase/addCoinbaseOnrampOrderEventListener/addCoinbaseOnrampOrderEventListener.ts","../src/modules/funding/coinbase/getMissingVerificationForCoinbaseOnrampOrder/getMissingVerificationForCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/utils/validateUserCredentialsForCoinbaseOnrampOrder/validateUserCredentialsForCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/createCoinbaseOnrampOrder/createCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/getCoinbaseBuyUrl/getCoinbaseBuyUrl.ts","../src/modules/funding/cryptoDotCom/createCryptoDotComPayment/createCryptoDotComPayment.ts","../src/modules/funding/moonpay/getMoonPayCurrencies/getMoonPayCurrencies.ts","../src/modules/funding/moonpay/errors/MoonPayInvalidUrlError.ts","../src/modules/funding/moonpay/errors/MoonPayProviderNotAvailableError.ts","../src/modules/funding/moonpay/getMoonPayUrl/getMoonPayUrl.ts","../src/modules/funding/kraken/createKrakenExchangeTransfer/createKrakenExchangeTransfer.ts","../src/modules/funding/kraken/getKrakenAccounts/getKrakenAccounts.ts","../src/modules/funding/kraken/getKrakenWhitelistedAddresses/getKrakenWhitelistedAddresses.ts","../src/modules/initializeClient/waitForClientInitialized/waitForClientInitialized.ts","../src/modules/instrumentation/setInstrumentationEnabled/setInstrumentationEnabled.ts","../src/modules/legacyWalletBook/getWalletBookCdnUrl/getWalletBookCdnUrl.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/fetchWithTimeout/fetchWithTimeout.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/walletBookCacheStorageKeySchema.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/fetchLegacyWalletBook.ts","../src/modules/legacyWalletBook/shouldFilterWallet/shouldFilterWallet.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect.ts","../src/modules/legacyWalletBook/getSpriteUrl/getSpriteUrl.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformGroup/transformGroup.ts","../src/utils/getChainFromWalletBookIdentifier/getChainFromWalletBookIdentifier.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getChainFromWalletSchema/getChainFromWalletSchema.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformWallet/transformWallet.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformWalletBook/transformWalletBook.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getWalletConnectCatalog.ts","../src/modules/legacyWalletBook/matchWalletProvidersToCatalogGroup/matchWalletProvidersToCatalogGroup.ts","../src/modules/legacyWalletBook/excludeInstalledFromCatalog/collectInstalledGroupIds/collectInstalledGroupIds.ts","../src/modules/legacyWalletBook/excludeInstalledFromCatalog/excludeInstalledFromCatalog.ts","../src/modules/wallets/walletProvider/extractChainFromNormalizedName/extractChainFromNormalizedName.ts","../src/modules/legacyWalletBook/getWalletConnectCatalogWalletByWalletProviderKey/getWalletConnectCatalogWalletByWalletProviderKey.ts","../src/utils/isMobile/isMobile.ts","../src/modules/walletOptionsCatalogue/getInstallationLinkForCurrentPlatform/getInstallationLinkForCurrentPlatform.ts","../src/modules/walletOptionsCatalogue/resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey.ts","../src/modules/walletOptionsCatalogue/buildInAppBrowserOptions/getInAppBrowserUrl/getInAppBrowserUrl.ts","../src/modules/walletOptionsCatalogue/buildInAppBrowserOptions/buildInAppBrowserOptions.ts","../src/modules/walletOptionsCatalogue/buildInstallationUrls/buildInstallationUrls.ts","../src/modules/walletOptionsCatalogue/buildInstallationUrlsByWalletOptionKey/buildInstallationUrlsByWalletOptionKey.ts","../src/modules/legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink.ts","../src/modules/walletOptionsCatalogue/buildMetaMaskSdkUriOptions/buildMetaMaskSdkUriOptions.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getChainsFromWalletSchema/getChainsFromWalletSchema.ts","../src/modules/walletOptionsCatalogue/buildWalletConnectOptions/buildWalletConnectOptions.ts","../src/modules/walletOptionsCatalogue/buildWalletOption/buildWalletOption.ts","../src/modules/wallets/hasWalletProviderConnectMethod/hasWalletProviderConnectMethod.ts","../src/modules/walletOptionsCatalogue/classifyWithWalletProviderSource/classifyWithWalletProviderSource.ts","../src/modules/wallets/utils/stripChainSuffix/stripChainSuffix.ts","../src/modules/walletOptionsCatalogue/normalizeWalletDisplayName/normalizeWalletDisplayName.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/findByNameMatch/findByNameMatch.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/resolveWalletOptionKey/resolveWalletOptionKey.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/findWalletOptionKeyForProviderKey.ts","../src/modules/walletOptionsCatalogue/buildWithWalletProviderOptions/buildWithWalletProviderOptions.ts","../src/modules/walletOptionsCatalogue/excludedWalletOptionKeys/excludedWalletOptionKeys.ts","../src/modules/walletOptionsCatalogue/groupOptionsByWalletOption/groupOptionsByWalletOption.ts","../src/modules/walletOptionsCatalogue/getConnectionOptionPriority/getConnectionOptionPriority.ts","../src/modules/walletOptionsCatalogue/sortConnectionOptions/sortConnectionOptions.ts","../src/modules/legacyWalletBook/priorityWalletKeys/priorityWalletKeys.ts","../src/modules/walletOptionsCatalogue/getPriorityIndex/getPriorityIndex.ts","../src/modules/walletOptionsCatalogue/compareByRelevance/compareByRelevance.ts","../src/modules/walletOptionsCatalogue/hasAnyConnectionOption/hasAnyConnectionOption.ts","../src/modules/walletOptionsCatalogue/hasInstalledProvider/hasInstalledProvider.ts","../src/modules/walletOptionsCatalogue/sortWalletOptions/sortWalletOptions.ts","../src/modules/walletOptionsCatalogue/getWalletOptionsCatalogue/getWalletOptionsCatalogue.ts","../src/modules/user/updateUser/updateUser.ts","../src/modules/mfa/acknowledgeRecoveryCodes/acknowledgeRecoveryCodes.ts","../src/modules/mfa/authenticateMfaRecoveryCode/authenticateMfaRecoveryCode.ts","../src/modules/auth/passkeys/getPasskeyAuthenticationOptions/getPasskeyAuthenticationOptions.ts","../src/modules/auth/passkeys/serverAuthenticatePasskey/serverAuthenticatePasskey.ts","../src/modules/mfa/authenticatePasskeyMFA/authenticatePasskeyMFA.ts","../src/modules/mfa/authenticateTotpMfaDevice/authenticateTotpMfaDevice.ts","../src/modules/mfa/createNewMfaRecoveryCodes/createNewMfaRecoveryCodes.ts","../src/modules/mfa/deleteMfaDevice/deleteMfaDevice.ts","../src/modules/mfa/getMfaDevices/getMfaDevices.ts","../src/modules/mfa/getMfaRecoveryCodes/getMfaRecoveryCodes.ts","../src/modules/mfa/isPendingRecoveryCodesAcknowledgment/isPendingRecoveryCodesAcknowledgment.ts","../src/modules/mfa/registerTotpMfaDevice/registerTotpMfaDevice.ts","../src/modules/mfa/setDefaultMfaDevice/setDefaultMfaDevice.ts","../src/modules/otp/sendEmailOTP/sendEmailOTP.ts","../src/modules/otp/sendSmsOTP/supportedCountries.ts","../src/modules/otp/sendSmsOTP/sendSmsOTP.ts","../src/modules/otp/verifyOTP/verifyOTPForUserSignIn/verifyOTPForUserSignIn.ts","../src/modules/otp/verifyOTP/verifyOTPForUserUpdate/verifyOTPForUserUpdate.ts","../src/modules/otp/verifyOTP/verifyOTP.ts","../src/modules/swap/getSwapQuote/getSwapQuote.ts","../src/modules/swap/getSwapStatus/getSwapStatus.ts","../src/modules/user/deleteUser/deleteUser.ts","../src/modules/user/isUserOnboardingComplete/isUserOnboardingComplete.ts","../src/modules/walletBackup/googleDrive/constants.ts","../src/modules/walletBackup/googleDrive/findMissingGoogleDriveBackupScopes/findMissingGoogleDriveBackupScopes.ts","../src/modules/walletBackup/googleDrive/utils/fetchGoogleDriveOauthAccess/fetchGoogleDriveOauthAccess.ts","../src/modules/walletBackup/googleDrive/utils/findGoogleOauthAccountId/findGoogleOauthAccountId.ts","../src/modules/walletBackup/googleDrive/getGoogleDriveBackupReadiness/getGoogleDriveBackupReadiness.ts","../src/modules/walletBackup/googleDrive/hasAllGoogleDriveBackupScopes/hasAllGoogleDriveBackupScopes.ts","../src/modules/walletBackup/googleDrive/isInsufficientGoogleDriveScopesError/isInsufficientGoogleDriveScopesError.ts","../src/modules/wallets/assertWalletAccountSigningAvailability/assertWalletAccountSigningAvailability.ts","../src/modules/wallets/confirmTransaction/confirmTransaction.ts","../src/modules/wallets/utils/getAddressesWithTypesFromConnectionResult/getAddressesWithTypesFromConnectionResult.ts","../src/modules/wallets/connectWithWalletProvider/connectWithWalletProvider.ts","../src/modules/wallets/hardwareWallet/formatSignatureForHardwareWallet/formatSignatureForHardwareWallet.ts","../src/modules/wallets/utils/getChainIdForAccountVerification/getChainIdForAccountVerification.ts","../src/modules/wallets/utils/getSignInMessage/getSignInMessage.ts","../src/modules/wallets/proveWalletAccountOwnership/proveWalletAccountOwnership.ts","../src/modules/wallets/utils/isSameAddress/isSameAddress.ts","../src/modules/wallets/verifyWalletAccountForSignInOrTransfer/verifyWalletAccountForSignInOrTransfer.ts","../src/modules/wallets/verifyWalletAccount/verifyWalletAccount.ts","../src/modules/wallets/walletProvider/isDeeplinkWalletProvider/isDeeplinkWalletProvider.ts","../src/modules/wallets/connectAndVerifyWithWalletProvider/connectAndVerifyWithWalletProvider.ts","../src/modules/wallets/getAvailableWalletProvidersData/getAvailableWalletProvidersData.ts","../src/modules/wallets/getConnectedAddresses/getConnectedAddresses.ts","../src/modules/wallets/getOwnerWalletAccountForSmartWalletAccount/getOwnerWalletAccountForSmartWalletAccount.ts","../src/modules/wallets/getWalletAccountAddressByType/getWalletAccountAddressByType.ts","../src/modules/wallets/getWalletProviderDataByKey/getWalletProviderDataByKey.ts","../src/modules/wallets/isAnyWalletAccountConnected/isAnyWalletAccountConnected.ts","../src/modules/wallets/hardwareWallet/canConnectWithHardwareWallet/canConnectWithHardwareWallet.ts","../src/modules/wallets/hardwareWallet/isHardwareWalletAccount/isHardwareWalletAccount.ts","../src/modules/wallets/isWalletAccountVerified/isWalletAccountVerified.ts","../src/modules/wallets/networks/addNetwork/addNetwork.ts","../src/modules/wallets/networks/getActiveNetworkData/getActiveNetworkData.ts","../src/modules/wallets/networks/getActiveNetworkId/getActiveNetworkId.ts","../src/modules/wallets/networks/getNativeBalance/getNativeBalance.ts","../src/modules/wallets/networks/getBalanceForAddress/getBalanceForAddress.ts","../src/modules/wallets/networks/getTransactionHistory/getTransactionHistory.ts","../src/modules/wallets/networks/isProgrammaticNetworkSwitchAvailable/isProgrammaticNetworkSwitchAvailable.ts","../src/modules/wallets/networks/switchActiveNetwork/switchActiveNetwork.ts","../src/modules/wallets/primaryWalletAccount/selectPrimaryWalletAccount/selectPrimaryWalletAccount.ts","../src/modules/wallets/disconnectWalletAccount/disconnectWalletAccount.ts","../src/modules/wallets/removeWalletAccount/removeWalletAccount.ts","../src/modules/wallets/signMessage/signMessage.ts","../src/modules/wallets/transferAmount/transferAmount.ts","../src/modules/wallets/transferWalletAccount/transferWalletAccount.ts","../src/modules/wallets/utils/getWalletAccountFromAddress/getWalletAccountFromAddress.ts","../src/modules/wallets/walletProvider/events/offWalletProviderEvent/offWalletProviderEvent.ts","../src/modules/wallets/walletProvider/events/onWalletProviderEvent/onWalletProviderEvent.ts","../src/utils/parseUserAgent/parseUserAgent.ts","../src/exports/index.ts"],"sourcesContent":["import type { DynamicClient } from '../../../client/types';\n\n/**\n * Maps the state keys to the event names.\n *\n * This is mainly to ensure that whenever a new state key is added, the developer\n * will have to come to this file and remember to add it here and in the interface.\n */\nexport const stateChangeEvents = {\n initStatus: 'initStatusChanged',\n mfaToken: 'mfaTokenChanged',\n projectSettings: 'projectSettingsChanged',\n sessionExpiresAt: 'sessionExpiresAtChanged',\n token: 'tokenChanged',\n user: 'userChanged',\n} satisfies {\n [K in keyof DynamicClient]: `${K}Changed`;\n};\n\n// Add the state change events to the global events interface.\ndeclare global {\n interface DynamicEvents {\n initStatusChanged: (args: {\n initStatus: DynamicClient['initStatus'];\n }) => void;\n\n mfaTokenChanged: (args: { mfaToken: DynamicClient['mfaToken'] }) => void;\n\n projectSettingsChanged: (args: {\n projectSettings: DynamicClient['projectSettings'];\n }) => void;\n\n sessionExpiresAtChanged: (args: {\n sessionExpiresAt: DynamicClient['sessionExpiresAt'];\n }) => void;\n\n tokenChanged: (args: { token: DynamicClient['token'] }) => void;\n\n userChanged: (args: { user: DynamicClient['user'] }) => void;\n }\n}\n\nexport type DynamicStateChangeEvents =\n DynamicEvents[(typeof stateChangeEvents)[keyof typeof stateChangeEvents]];\n","type AppendConnectionUriToDeeplinkParams = {\n connectionUri: string;\n deeplinkUrl: string;\n};\n\n/**\n * Appends a wallet connection URI to a deeplink URL.\n *\n * Generic across URI-deeplink connection options — works for both\n * WalletConnect pairing URIs and MetaMask SDK URIs. Determines the\n * appropriate query parameter separator based on whether the deeplink\n * already contains query parameters.\n *\n * @param params.deeplinkUrl - The base deeplink URL (e.g., `walletapp://wc` or `walletapp://wc?param=value`).\n * @param params.connectionUri - The connection URI to append.\n * @returns The deeplink URL with the connection URI appended as a query parameter.\n *\n * @example\n * ```ts\n * appendConnectionUriToDeeplink({ deeplinkUrl: 'walletapp://wc', connectionUri: 'wc:123-456' })\n * // Returns: 'walletapp://wc?uri=wc%3A123-456'\n *\n * appendConnectionUriToDeeplink({ deeplinkUrl: 'walletapp://wc?param=value', connectionUri: 'wc:123-456' })\n * // Returns: 'walletapp://wc?param=value&uri=wc%3A123-456'\n * ```\n * @not-instrumented\n */\nexport const appendConnectionUriToDeeplink = ({\n connectionUri,\n deeplinkUrl,\n}: AppendConnectionUriToDeeplinkParams): string => {\n const url = new URL(deeplinkUrl);\n\n url.searchParams.set('uri', connectionUri);\n\n return url.href;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { NONCE_POOL_SIZE } from '../constants';\nimport { fetchAndStoreNonces } from '../fetchAndStoreNonces/fetchAndStoreNonces';\n\n/** @not-instrumented */\nexport const prefetchNoncesIfNeeded = async (\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n if (core.state.get().prefetchedNonces.length >= NONCE_POOL_SIZE) {\n return;\n }\n\n await fetchAndStoreNonces(client);\n};\n","import type { RuntimeServices } from '../runtimeServices.types';\n\n/**\n * Creates a new runtime services instance that manages service registration and retrieval.\n *\n * @returns A RuntimeServices object with methods to get, register, and unregister services\n * @not-instrumented\n */\nexport const createRuntimeServices = (): RuntimeServices => {\n const registry = new Map<string, unknown>();\n\n return {\n getByKey: <T>(key: string) => registry.get(key) as T | null,\n // eslint-disable-next-line custom-rules/require-single-object-param\n register: (key: string, service: unknown) => registry.set(key, service),\n unregister: (key: string) => registry.delete(key),\n };\n};\n","export type SetLongTimeoutOptions = {\n /** The function to invoke after the delay elapses. */\n callback: () => void;\n\n /** The delay in milliseconds before invoking the callback. */\n delay: number;\n};\n\n/**\n * A replacement for setTimeout that supports delays longer than 2147483647ms (~24.8 days).\n * @not-instrumented\n */\nexport const setLongTimeout = ({\n callback,\n delay,\n}: SetLongTimeoutOptions): VoidFunction => {\n const MAX_DELAY = 2147483647; // Maximum delay for setTimeout (2^31 - 1)\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let remaining = delay;\n\n const run = () => {\n if (remaining <= MAX_DELAY) {\n timeoutId = setTimeout(callback, remaining);\n } else {\n timeoutId = setTimeout(() => {\n remaining -= MAX_DELAY;\n run();\n }, MAX_DELAY);\n }\n };\n\n run();\n\n // Return a cancel function\n return () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n };\n};\n","import type { DynamicClient } from '../../../client/types';\nimport { getCore } from '../../../client/core/getCore';\nimport { subscribeWithSelector } from '../../../utils/observable/subscribeWithSelector';\nimport { logoutWithReason } from '../logoutWithReason';\nimport { setLongTimeout } from './setLongTimeout';\n\n/**\n * Sets up a timeout to log out the user when their token expires.\n * @not-instrumented\n */\nexport const initializeAuth = (client: DynamicClient) => {\n const core = getCore(client);\n\n let clearExpirationTimeout: VoidFunction | null = null;\n\n const onChangeExpiration = subscribeWithSelector(\n core.state,\n (state) => state.sessionExpiresAt\n );\n\n const checkExpiration = () => {\n const expiration = core.state.get().sessionExpiresAt;\n\n clearExpirationTimeout?.();\n\n if (!expiration) {\n return;\n }\n\n const now = new Date();\n\n const timeUntilExpiration = expiration.getTime() - now.getTime();\n\n if (timeUntilExpiration <= 0) {\n void logoutWithReason({ reason: 'token-expired' }, client);\n return;\n }\n\n // Wait for token expiration\n clearExpirationTimeout = setLongTimeout({\n callback: checkExpiration,\n delay: timeUntilExpiration,\n });\n };\n\n onChangeExpiration(checkExpiration);\n\n checkExpiration();\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { emitEvent } from '../../clientEvents';\n\n/**\n * Sets up bidirectional event synchronization between the core event emitter\n * and the CrossTabBroadcast service.\n *\n * This enables events fired in one tab to be received in other tabs.\n *\n * **Local → Cross-Tab (Forwarding)**\n * - Listens to specific events on core.eventEmitter\n * - Forwards them to other tabs via core.crossTabBroadcast.send()\n *\n * **Cross-Tab → Local (Receiving)**\n * - Listens to cross-tab events via core.crossTabBroadcast.on()\n * - Emits corresponding \"*InAnotherTab\" events on core.eventEmitter\n *\n * @param client - The Dynamic client instance\n * @not-instrumented\n */\nexport const setupCrossTabEventSync = (client: DynamicClient) => {\n const core = getCore(client);\n\n // === FORWARDING: Local events → Cross-Tab ===\n // Listen to deviceRegistrationCompleted and forward to other tabs\n const handleDeviceRegistrationCompleted = () => {\n core.crossTabBroadcast.send({ event: 'deviceRegistrationCompleted' });\n };\n\n core.eventEmitter.on(\n 'deviceRegistrationCompleted',\n handleDeviceRegistrationCompleted\n );\n\n // === RECEIVING: Cross-Tab → Local events ===\n // Listen to cross-tab deviceRegistrationCompleted and emit local variant\n const handleCrossTabDeviceRegistrationCompleted = () => {\n emitEvent({ event: 'deviceRegistrationCompletedInAnotherTab' }, client);\n };\n\n core.crossTabBroadcast.on(\n 'deviceRegistrationCompleted',\n handleCrossTabDeviceRegistrationCompleted\n );\n};\n","import * as z from 'zod/mini';\n\nimport type { Chain } from '../../chain';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport type { WalletAddressType } from '../walletAccount';\n\nexport const unverifiedWalletAccountSchema = z.object({\n address: z.string(),\n addressesWithTypes: z.optional(\n z.array(\n z.object({\n address: z.string(),\n publicKey: z.optional(z.string()),\n type: z.custom<WalletAddressType>((val) => typeof val === 'string'),\n })\n )\n ),\n chain: z.custom<Chain>((val) => typeof val === 'string'),\n hardwareWalletVendor: z.optional(\n z.custom<HardwareWalletVendor>((val) => typeof val === 'string')\n ),\n id: z.string(),\n lastSelectedAt: z.nullable(z.date()),\n walletProviderKey: z.string(),\n});\n","import * as z from 'zod/mini';\n\nexport const walletProviderKeyMapSchema = z.record(z.string(), z.string());\n","import type { ProjectSettings, SdkUser } from '@dynamic-labs/sdk-api-core';\nimport * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../services/storage';\nimport { unverifiedWalletAccountSchema } from '../wallets/unverifiedWalletAccounts';\nimport { walletProviderKeyMapSchema } from '../wallets/walletProvider/walletProviderKeyMap/schema';\n\nexport const stateStorageKeySchema = createStorageKeySchema({\n key: 'state',\n schema: z.object({\n apiVersion: z.string(),\n prefetchedNonces: z.array(z.string()),\n prefetchedNoncesExpiration: z.nullable(z.number()),\n projectSettings: z.custom<ProjectSettings | null>(),\n unverifiedWalletAccounts: z.array(unverifiedWalletAccountSchema),\n user: z.custom<SdkUser | null>(),\n walletProviderKeyMap: walletProviderKeyMapSchema,\n }),\n});\n\nexport const sessionStorageKeySchema = createStorageKeySchema({\n config: { storageTier: 'secure' },\n key: 'session',\n schema: z.object({\n /**\n * The current available captcha token.\n */\n captchaToken: z.nullable(z.string()),\n\n /**\n * The current available elevated access tokens.\n */\n elevatedAccessTokens: z.array(\n z.object({\n /**\n * Milliseconds since epoch of token expiration.\n */\n expiresAt: z.number(),\n /**\n * The scopes of the token.\n */\n scopes: z.array(z.string()),\n /**\n * Whether the token is single use.\n */\n singleUse: z.nullable(z.boolean()),\n /**\n * The token string.\n */\n token: z.string(),\n })\n ),\n\n /**\n * Legacy token will be undefined in environments with cookie based sessions.\n *\n * @deprecated Use `token` instead.\n */\n legacyToken: z.nullable(z.string()),\n\n /**\n * The current available MFA token.\n */\n mfaToken: z.nullable(z.string()),\n\n /**\n * Milliseconds since epoch of session expiration.\n */\n sessionExpiration: z.number(),\n\n /**\n * The current session keys.\n */\n sessionKeys: z.nullable(z.string()),\n\n /**\n * Token will be undefined in environments with cookie based sessions.\n */\n token: z.nullable(z.string()),\n }),\n});\n","import { BaseError } from '../../../errors/base';\n\nexport class KeyMigrationError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(expectedPublicKey: string, importedPublicKey: string) {\n super({\n cause: null,\n code: 'key_migration_public_key_mismatch',\n docsUrl: null,\n name: 'KeyMigrationError',\n shortMessage: `Public key mismatch after import: expected \"${expectedPublicKey}\", got \"${importedPublicKey}\"`,\n });\n }\n}\n","import type { DynamicCoreState } from '../../../client/core/types';\nimport type { KeychainService } from '../../../services/keychain';\nimport type { Logger } from '../../../services/logger';\nimport type { Storage } from '../../../services/storage/storage.types';\nimport { getBuffer } from '../../../utils/getBuffer';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { ObservableState } from '../../../utils/observable/observable.types';\nimport { sessionStorageKeySchema } from '../../storageSync/schema';\nimport { KeyMigrationError } from './KeyMigrationError';\n\ntype LegacySessionKeysBlob = {\n privateKeyJwk?: JsonWebKey;\n publicKey?: string;\n};\n\ntype MigrateSessionKeyToKeychainParams = {\n keychain: KeychainService;\n logger: Logger;\n state: ObservableState<DynamicCoreState>;\n storage: Storage;\n};\n\n/**\n * Migrates legacy session keys from the hydrated state into the IndexedDB keychain\n * as non-extractable CryptoKey objects.\n *\n * Must run after hydrateStateWithStorage so that state.sessionKeys already holds\n * the legacy base64 blob (or the new public key hex if already migrated).\n *\n * Idempotent: skips if the keychain already has a `session` key.\n * Throws on failure — callers should handle errors (e.g. .catch(() => logout(client))).\n * @not-instrumented\n */\nexport const migrateSessionKeyToKeychain = async ({\n keychain,\n logger,\n state,\n storage,\n}: MigrateSessionKeyToKeychainParams): Promise<void> => {\n if (isServerSideRendering()) {\n return;\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Checking for existing session key in keychain');\n\n if (await keychain.hasKey('session')) {\n logger.debug('[migrateSessionKeyToKeychain] Session key already exists in keychain, skipping migration');\n return;\n }\n\n const encodedSessionKeys = state.get().sessionKeys;\n\n if (!encodedSessionKeys) {\n logger.debug('[migrateSessionKeyToKeychain] No session keys in state, nothing to migrate');\n return;\n }\n\n let blob: LegacySessionKeysBlob;\n\n try {\n blob = JSON.parse(\n getBuffer().from(encodedSessionKeys, 'base64').toString()\n ) as LegacySessionKeysBlob;\n } catch {\n // Not a legacy base64 blob — already a public key hex string or invalid\n logger.debug('[migrateSessionKeyToKeychain] Session keys are not a legacy blob, skipping migration');\n return;\n }\n\n const { privateKeyJwk, publicKey } = blob;\n\n if (!privateKeyJwk || !publicKey) {\n logger.debug('[migrateSessionKeyToKeychain] Legacy blob missing privateKeyJwk or publicKey, skipping migration');\n return;\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Found legacy session key, importing into keychain', {\n expectedPublicKey: publicKey,\n });\n\n const importedPublicKey = await keychain.importKey('session', privateKeyJwk);\n\n logger.debug('[migrateSessionKeyToKeychain] Key imported', {\n expectedPublicKey: publicKey,\n importedPublicKey,\n });\n\n if (importedPublicKey !== publicKey) {\n throw new KeyMigrationError(publicKey, importedPublicKey);\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Public key validated, updating state and storage');\n\n state.set({ sessionKeys: importedPublicKey });\n\n const currentSession = await storage.getItem(sessionStorageKeySchema);\n\n if (currentSession) {\n await storage.setItem(sessionStorageKeySchema, {\n ...currentSession,\n sessionKeys: importedPublicKey,\n });\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Migration complete');\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicCoreState } from '../../../client/core/types';\nimport type { DynamicClient } from '../../../client/types';\nimport { isEqualShallow } from '../../../utils/isEqualShallow';\nimport { emitEvent } from '../../clientEvents';\nimport { stateChangeEvents } from './events';\n\n/** @not-instrumented */\nexport const raiseStateEvents = (client: DynamicClient) => {\n const core = getCore(client);\n\n core.state.subscribe((value, previous) => {\n const eventEntries = Object.entries(stateChangeEvents) as Array<\n [keyof DynamicCoreState, keyof DynamicEvents]\n >;\n\n eventEntries.forEach(([key, event]) => {\n // Check if this key had a change\n if (isEqualShallow(value[key], previous[key])) return;\n\n emitEvent(\n {\n args: { [key]: value[key] },\n event,\n },\n client\n );\n });\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicCoreState } from '../../../client/core/types';\nimport type { DynamicClient } from '../../../client/types';\nimport { SDK_API_CORE_VERSION } from '../../../constants';\nimport { checkAndRaiseWalletAccountsChangedEvent } from '../../auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent';\nimport { sessionStorageKeySchema, stateStorageKeySchema } from '../schema';\n\n/** @not-instrumented */\nexport const hydrateStateWithStorage = async (\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n const previousState = core.state.get();\n\n const stateChanges: Partial<DynamicCoreState> = {};\n\n // ================ TOKEN =================\n\n const session = await core.storage.getItem(sessionStorageKeySchema);\n\n const isSessionValid =\n session?.sessionExpiration && session.sessionExpiration > Date.now();\n\n if (isSessionValid) {\n stateChanges.token = session.token;\n stateChanges.legacyToken = session.legacyToken;\n stateChanges.sessionExpiresAt = new Date(session.sessionExpiration);\n stateChanges.mfaToken = session.mfaToken;\n stateChanges.elevatedAccessTokens = session.elevatedAccessTokens.map((token) => ({\n expiresAt: new Date(token.expiresAt),\n scopes: token.scopes,\n singleUse: token.singleUse ?? false,\n token: token.token,\n }));\n stateChanges.captchaToken = session.captchaToken;\n stateChanges.sessionKeys = session.sessionKeys;\n }\n\n // ================ STATE =================\n\n const storedState = await core.storage.getItem(stateStorageKeySchema);\n\n // Only hydrate state if it came from an API with the same version as the current SDK\n if (storedState?.apiVersion === SDK_API_CORE_VERSION) {\n stateChanges.unverifiedWalletAccounts =\n storedState.unverifiedWalletAccounts;\n\n stateChanges.walletProviderKeyMap = storedState.walletProviderKeyMap;\n\n if (storedState.prefetchedNoncesExpiration && storedState.prefetchedNoncesExpiration > Date.now()) {\n stateChanges.prefetchedNonces = storedState.prefetchedNonces;\n stateChanges.prefetchedNoncesExpiration = storedState.prefetchedNoncesExpiration;\n }\n\n // Variables that should only be hydrated if the session is valid\n if (isSessionValid) {\n stateChanges.user = storedState.user;\n }\n\n // if there's a session/user or connected unverified wallets, we should hydrate project settings\n // so we don't refetch it on initial load\n if (\n isSessionValid ||\n (storedState.unverifiedWalletAccounts ?? []).length > 0\n ) {\n stateChanges.projectSettings = storedState.projectSettings;\n }\n }\n\n if (Object.keys(stateChanges).length > 0) {\n core.state.set(stateChanges);\n }\n\n checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { SDK_API_CORE_VERSION } from '../../../constants';\nimport { sessionStorageKeySchema, stateStorageKeySchema } from '../schema';\n\n/** @not-instrumented */\nexport const syncStateWithStorage = (client: DynamicClient) => {\n const core = getCore(client);\n\n core.state.subscribe((state) => {\n if (state.sessionExpiresAt === null) {\n void core.storage.removeItem(sessionStorageKeySchema);\n } else {\n void core.storage.setItem(sessionStorageKeySchema, {\n captchaToken: state.captchaToken,\n elevatedAccessTokens: (state.elevatedAccessTokens || []).map(\n (token) => ({\n expiresAt: token.expiresAt.getTime(),\n scopes: token.scopes,\n singleUse: token.singleUse ?? null,\n token: token.token,\n })\n ),\n legacyToken: state.legacyToken,\n mfaToken: state.mfaToken,\n sessionExpiration: state.sessionExpiresAt.getTime(),\n sessionKeys: state.sessionKeys,\n token: state.token,\n });\n }\n\n void core.storage.setItem(stateStorageKeySchema, {\n apiVersion: SDK_API_CORE_VERSION,\n prefetchedNonces: state.prefetchedNonces,\n prefetchedNoncesExpiration: state.prefetchedNoncesExpiration,\n projectSettings: state.projectSettings,\n unverifiedWalletAccounts: state.unverifiedWalletAccounts,\n user: state.user,\n walletProviderKeyMap: state.walletProviderKeyMap,\n });\n });\n};\n","import type { DynamicClient } from '../../client/types';\nimport { hydrateStateWithStorage } from './hydrateStateWithStorage';\nimport { syncStateWithStorage } from './syncStateWithStorage';\n\n/** @not-instrumented */\nexport const initializeStorageSync = async (client: DynamicClient) => {\n // Initialize the state value with what's stored in the storage\n await hydrateStateWithStorage(client);\n\n // Keep the storage up to date with the state\n syncStateWithStorage(client);\n};\n","import type { SdkUser } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { checkAndRaiseWalletAccountsChangedEvent } from '../../auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent';\n\n/**\n * Refreshes the current user's data from the server.\n *\n * This function fetches the latest authenticated user information from the backend\n * and updates the local user state.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authenticated user.\n * @instrumented\n */\nexport const refreshUser = async (\n client = getDefaultClient()\n): Promise<SdkUser> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const previousState = { ...core.state.get() };\n\n const user = await apiClient.getAuthenticatedUser({\n environmentId: core.environmentId,\n });\n\n core.state.set({ user });\n\n checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);\n\n return user;\n};\n","import { BaseError } from './base';\n\nexport class ClientAlreadyInitializedError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'client_already_initialized_error',\n docsUrl: null,\n name: 'ClientAlreadyInitializedError',\n shortMessage: 'Client must not be initialized more than once',\n });\n }\n}\n","import { getCore } from '../../client/core/getCore';\nimport { getDefaultClient } from '../../client/defaultClient';\nimport { prefetchNoncesIfNeeded } from '../../utils/getNonce/prefetchNoncesIfNeeded/prefetchNoncesIfNeeded';\nimport { initializeAuth } from '../auth/initializeAuth';\nimport { logoutWithReason } from '../auth/logoutWithReason';\nimport { setupCrossTabEventSync } from '../crossTabEventSync';\nimport { migrateSessionKeyToKeychain } from '../keychainMigration/migrateSessionKeyToKeychain/migrateSessionKeyToKeychain';\nimport { fetchProjectSettings } from '../projectSettings/fetchProjectSettings';\nimport { isCookieEnabled } from '../projectSettings/isCookieEnabled';\nimport { generateSessionKeys } from '../sessionKeys/generateSessionKeys';\nimport { raiseStateEvents } from '../state/raiseStateEvents';\nimport { initializeStorageSync } from '../storageSync';\nimport { refreshAuth } from '../user/refreshAuth';\nimport { refreshUser } from '../user/refreshUser';\nimport { restoreUserSharesForAllWalletAccounts } from '../waas/restoreUserSharesForAllWalletAccounts';\nimport { ClientAlreadyInitializedError } from './../../errors/ClientAlreadyInitializedError';\nimport {\n FETCH_PROJECT_SETTINGS_TRACKER_KEY,\n GENERATE_SESSION_KEYS_TRACKER_KEY,\n INITIALIZE_STORAGE_SYNC_TRACKER_KEY,\n REFRESH_USER_STATE_FROM_COOKIE_TRACKER_KEY,\n REFRESH_USER_STATE_FROM_VALID_TOKEN_TRACKER_KEY,\n} from './consts';\n\n/**\n * Initializes the Dynamic client and all its modules and services.\n *\n * This function orchestrates the initialization of authentication, project settings,\n * session keys, and storage sync. It manages the initialization status and handles\n * any errors that occur during the process.\n *\n * You only need to call this function if you are not using `autoInitialize: true` in createDynamicClient.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when initialization is complete.\n * @throws ClientAlreadyInitializedError If the client is already initialized.\n * @instrumented\n */\nexport const initializeClient = async (client = getDefaultClient()) => {\n const core = getCore(client);\n\n core.logger.debug(\n '[initializeClient] Initializing client. Current init status',\n core.state.get().initStatus\n );\n\n if (core.state.get().initStatus !== 'uninitialized') {\n throw new ClientAlreadyInitializedError();\n }\n\n core.state.set({ initStatus: 'in-progress' });\n\n initializeAuth(client);\n\n raiseStateEvents(client);\n\n setupCrossTabEventSync(client);\n\n const initializeStorageSyncPromise = initializeStorageSync(client);\n\n const migrationPromise: Promise<void> = initializeStorageSyncPromise.then(\n async () => {\n await migrateSessionKeyToKeychain({\n keychain: core.keychain,\n logger: core.logger,\n state: core.state,\n storage: core.storage,\n }).catch(() =>\n logoutWithReason({ reason: 'keychain-migration-failed' }, client)\n );\n\n // If session keys exist in state but the keychain key is absent (e.g. IndexedDB\n // was cleared after a new-format session was written), sign the user out.\n if (\n core.state.get().sessionKeys &&\n !(await core.keychain.hasKey('session'))\n ) {\n await logoutWithReason({ reason: 'keychain-key-missing' }, client);\n }\n }\n );\n\n const fetchProjectSettingsPromise: Promise<void> = migrationPromise.then(\n async () => {\n if (!core.state.get().projectSettings) {\n await fetchProjectSettings(client);\n }\n }\n );\n\n // Prefetch nonces in the background so they are ready when a wallet\n // signing operation starts. Not tracked — failures are non-blocking.\n void fetchProjectSettingsPromise\n .then(() => prefetchNoncesIfNeeded(client))\n .catch((error) => {\n core.logger.error('Failed to prefetch nonces:', error);\n });\n\n /**\n * Generate session keys if they don't exist\n */\n const generateSessionKeysPromise: Promise<void> =\n fetchProjectSettingsPromise.then(async () => {\n if (!core.state.get().sessionKeys) {\n await generateSessionKeys(client);\n }\n });\n\n /**\n * Refresh user state on initialization when cookie is enabled.\n * This is necessary for supporting multiple subdomain domains.\n *\n * When a user logs in on sub1.example.com, they will have a cookie set. However, when they access\n * sub2.example.com, the cookie will be present but the user state will not be present.\n * We need to fetch the user to access the expiration date of the cookie on the new subdomain.\n *\n * This is also needed in case a user logs in with a new user on sub1.example.com and then accesses\n * sub2.example.com that had the original logged-in user. We need to fetch the user to refresh\n * the user state with the correct logged-in user.\n */\n const refreshUserStateFromCookiePromise: Promise<void> =\n fetchProjectSettingsPromise.then(async () => {\n /**\n * When cookies are enabled, we need to refresh the user as part of the initialization process\n * to ensure the user is logged in and sync the auth state with the server.\n *\n * This call can fail with a 401 error if the user is not logged in and the SDK should finish its initialization process\n * without throwing an error because that is an expected behavior.\n */\n if (isCookieEnabled(client)) {\n await refreshAuth(client).catch(async (error) => {\n if (error.status === 401) {\n core.logger.error('Session expired during initialization', error);\n\n if (client.user) {\n await logoutWithReason(\n { reason: 'session-refresh-unauthorized' },\n client\n );\n }\n } else {\n throw error;\n }\n });\n }\n });\n\n /**\n * When a token is persisted but the user state was lost (e.g. storage cleared\n * partially), re-fetch the user from the server. This path is skipped when\n * cookies are enabled because the token is not stored in SDK state.\n */\n const refreshUserStateFromValidTokenPromise: Promise<void> =\n refreshUserStateFromCookiePromise.then(async () => {\n if (core.state.get().token && !core.state.get().user) {\n await refreshUser(client).catch(async () => {\n await logoutWithReason({ reason: 'user-refresh-failed' }, client);\n });\n }\n });\n\n core.initTrack.track({\n name: INITIALIZE_STORAGE_SYNC_TRACKER_KEY,\n promise: initializeStorageSyncPromise,\n });\n\n core.initTrack.track({\n name: FETCH_PROJECT_SETTINGS_TRACKER_KEY,\n promise: fetchProjectSettingsPromise,\n });\n\n core.initTrack.track({\n name: GENERATE_SESSION_KEYS_TRACKER_KEY,\n promise: generateSessionKeysPromise,\n });\n\n core.initTrack.track({\n name: REFRESH_USER_STATE_FROM_COOKIE_TRACKER_KEY,\n promise: refreshUserStateFromCookiePromise,\n });\n\n core.initTrack.track({\n name: REFRESH_USER_STATE_FROM_VALID_TOKEN_TRACKER_KEY,\n promise: refreshUserStateFromValidTokenPromise,\n });\n\n try {\n await core.initTrack.waitForAll();\n\n core.state.set({ initStatus: 'finished' });\n } catch (error) {\n core.logger.error('Client initialization failed', error);\n core.state.set({ initStatus: 'failed' });\n\n throw error;\n }\n\n if (client.user) {\n void restoreUserSharesForAllWalletAccounts(client);\n }\n};\n","import { EventEmitter } from 'eventemitter3';\n\nimport { createDeferredPromise } from '../../utils/deferredPromise';\nimport { CannotTrackError } from './../../errors/CannotTrackError';\nimport type {\n AsyncProcessEntry,\n AsyncTrack,\n AsyncTrackEmitter,\n} from './asyncTrack.types';\n\n/**\n * Creates a tracker that associates names with promises and raises as promises resolve.\n * @not-instrumented\n */\nexport const createAsyncTrack = (): AsyncTrack => {\n /**\n * Whether tracking is enabled.\n * All processes must be tracked on the same node tick.\n *\n * This ensures no process is missed (as it would throw when tracked on a different node tick).\n */\n let isTrackEnabled = true;\n\n const eventEmitter: AsyncTrackEmitter = new EventEmitter();\n\n const allSettledPromise = createDeferredPromise<void>();\n\n const tracker = new Map<string, AsyncProcessEntry>();\n\n /**\n * Checks if all processes are initialized and resolves the main promise if they are.\n */\n const checkIfAllSettled = () => {\n const allSettled = Array.from(tracker.values()).every(\n ({ status }) => status === 'resolved'\n );\n\n if (!allSettled) return;\n\n allSettledPromise.resolve();\n };\n\n const track: AsyncTrack['track'] = ({ name, promise }) => {\n if (!isTrackEnabled) {\n throw new CannotTrackError();\n }\n\n // Disable tracking in the next node tick\n void Promise.resolve().then(() => (isTrackEnabled = false));\n\n tracker.set(name, { promise, status: 'pending' });\n\n promise\n .then(() => {\n tracker.set(name, { promise, status: 'resolved' });\n\n eventEmitter.emit('resolved', name);\n\n checkIfAllSettled();\n })\n .catch((error) => {\n tracker.set(name, { promise, status: 'failed' });\n\n eventEmitter.emit('failed', name, error);\n\n allSettledPromise.reject(error);\n });\n };\n\n const waitForAll: AsyncTrack['waitForAll'] = () => allSettledPromise.promise;\n\n const getTracker: AsyncTrack['getTracker'] = <T>(trackerKey: string) =>\n tracker.get(trackerKey) as AsyncProcessEntry<T>;\n\n return {\n getTracker,\n off: eventEmitter.off.bind(eventEmitter),\n on: eventEmitter.on.bind(eventEmitter),\n track,\n waitForAll,\n };\n};\n","import EventEmitter from 'eventemitter3';\n\n/** @not-instrumented */\nexport const createEventEmitter = () => new EventEmitter();\n","import { BaseError } from './base';\n\nexport class UnavailableInServerSideError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(unavailableFeature: string) {\n super({\n cause: null,\n code: 'unavailable_in_server_side_error',\n docsUrl: null,\n name: 'UnavailableInServerSideError',\n shortMessage: `This function is not available in server-side rendering: ${unavailableFeature}`,\n });\n }\n}\n","import { UnavailableInServerSideError } from '../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../utils/isServerSideRendering';\nimport type { Fetch } from './fetch.types';\n\n/**\n * Creates a fetch instance that uses the native window.fetch API.\n * @not-instrumented\n */\nexport const createWebFetch = (): Fetch => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(new UnavailableInServerSideError('createWebFetch'));\n }\n\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for fetch\n return window.fetch.bind(window);\n};\n","import type { Logger } from '../../logger/logger.types';\nimport { getUserAgent } from '../../../utils/getUserAgent/getUserAgent';\nimport type { ObservableState } from '../../../utils/observable/observable.types';\nimport { extractSessionId } from '../../../modules/auth/extractSessionId/extractSessionId';\nimport type { Instrumentation } from '../instrumentation.types';\nimport { scrubParameters } from '../scrubParameters';\n\ntype ConnectLoggerToInstrumentationParams = {\n environmentId: string;\n extensions: Set<string>;\n instrumentation: Instrumentation;\n logger: Logger;\n sdkSessionId: string;\n sdkVersion: string;\n state: ObservableState<DynamicCoreState>;\n};\n\n/**\n * Subscribes to the logger's 'log' event and forwards every entry to the\n * instrumentation service as an InstrumentationEvent.\n *\n * Bridges the logger and instrumentation subsystems without coupling them\n * at construction time — either can exist without the other.\n * Only error-level log entries are forwarded.\n * @not-instrumented\n */\nexport const connectLoggerToInstrumentation = ({\n environmentId,\n extensions,\n instrumentation,\n logger,\n sdkSessionId,\n sdkVersion,\n state,\n}: ConnectLoggerToInstrumentationParams) => {\n logger.on('log', (level, message, ...args) => {\n if (level !== 'error') {\n return;\n }\n\n const { token, user } = state.get();\n\n instrumentation.log({\n environmentId,\n // Callers occasionally pass plain objects (or serialized Errors) to\n // `logger.error` that include credentials or PII. Route them through\n // `scrubParameters` so the same redaction rules used by the @instrumented\n // function wrappers apply here too — otherwise this path silently\n // bypasses key-based PII scrubbing.\n parameters: scrubParameters({\n piiFields: instrumentation.config.piiFields,\n value: { args, message },\n }),\n registeredExtensionKeys: Array.from(extensions),\n sdkSessionId,\n sdkVersion,\n // Logger bridge only forwards error-level entries, so status is always 'error'.\n status: 'error',\n timestamp: new Date().toISOString(),\n tokenSessionId: token ? extractSessionId(token) : null,\n userAgent: getUserAgent(),\n userId: user?.id ?? null,\n });\n });\n};\n","import { DEFAULT_PII_FIELDS } from '../constants';\nimport type {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationEvent,\n InstrumentationTransport,\n} from '../instrumentation.types';\n\ntype CreateInstrumentationParams = {\n config?: Partial<InstrumentationConfig>;\n};\n\n// eslint-disable-next-line custom-rules/require-single-object-param\nconst buildPiiFields = (customFields: string[] = []): string[] => {\n const merged = [...DEFAULT_PII_FIELDS, ...customFields];\n const deduplicated = new Set(merged);\n return [...deduplicated];\n};\n\n/**\n * Creates the instrumentation service that gates event emission behind an\n * enabled flag and delegates to a pluggable transport.\n *\n * The transport is intentionally optional at creation time — it is wired in\n * later via setTransport so the SDK can initialise without one. Events logged\n * before a transport is set are simply dropped.\n *\n * Custom piiFields are merged with and deduplicated against the defaults so\n * callers only need to list additional fields, not replicate the baseline.\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const createInstrumentation = ({\n config: inputConfig,\n}: CreateInstrumentationParams = {}): Instrumentation => {\n let transport: InstrumentationTransport | undefined;\n\n const config: InstrumentationConfig = {\n enabled: inputConfig?.enabled ?? true,\n piiFields: buildPiiFields(inputConfig?.piiFields),\n };\n\n const emit = (event: InstrumentationEvent) => {\n if (!config.enabled || !transport) {\n return;\n }\n transport.log(event);\n };\n\n return {\n config,\n log: emit,\n logFunction: emit,\n setEnabled: (value) => {\n config.enabled = value;\n },\n setTransport: (t) => {\n transport = t;\n },\n };\n};\n","import type { Fetch } from '../../../fetch';\nimport type {\n InstrumentationEvent,\n InstrumentationTransport,\n} from '../../instrumentation.types';\n\nconst LOGS_BASE_URL = 'https://logs.dynamicauth.com/api/v1';\n\ntype CreateDynamicTransportParams = {\n environmentId: string;\n fetch: Fetch;\n};\n\n/**\n * Creates a batched transport that ships instrumentation events to Dynamic's\n * log ingestion endpoint.\n *\n * Events are queued synchronously and flushed as a single HTTP batch in the\n * next microtask (via queueMicrotask). Multiple log() calls within the same\n * synchronous tick are coalesced into one request, avoiding a round-trip per\n * event.\n *\n * Fetch errors are swallowed to prevent an instrumentation failure from\n * triggering another instrumentation event and causing an infinite loop.\n *\n * Works in both browser and SSR environments — fetch is injected and\n * queueMicrotask is available in Node.js >= 11.\n * @not-instrumented\n */\nexport const createDynamicTransport = (\n params: CreateDynamicTransportParams\n): InstrumentationTransport => {\n const queue: InstrumentationEvent[] = [];\n let flushScheduled = false;\n\n const flush = () => {\n flushScheduled = false;\n // splice(0) atomically drains the queue and returns all accumulated events.\n // Using splice rather than reassigning the array reference ensures events\n // logged between flush scheduling and flush execution are not silently dropped.\n const events = queue.splice(0);\n\n if (events.length === 0) return;\n\n const url = `${LOGS_BASE_URL}/${params.environmentId}`;\n\n void params\n .fetch(url, {\n body: JSON.stringify(events),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n .catch(() => {\n // Swallow fetch errors to prevent instrumentation failure from causing\n // an infinite loop of instrumentation events.\n });\n };\n\n return {\n log: (event) => {\n queue.push(event);\n\n if (!flushScheduled) {\n flushScheduled = true;\n queueMicrotask(flush);\n }\n },\n };\n};\n","import { UnavailableInServerSideError } from '../../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { NavigationHandler } from '../navigate.types';\n\n/**\n * Creates a navigation handler that uses the native window.location API.\n * @not-instrumented\n */\nexport const createNavigationHandler = (): NavigationHandler => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(\n new UnavailableInServerSideError('createNavigationHandler')\n );\n }\n\n return async (url) => {\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for navigation\n window.location.href = url;\n };\n};\n","import { UnavailableInServerSideError } from '../../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { OpenDeeplink } from '../openDeeplink.types';\n\n/**\n * Creates a deeplink opener that navigates the current tab to the deeplink URL.\n *\n * Uses `window.location.assign` instead of `window.open` deliberately.\n * This matters for Phantom redirect specifically, which is the only deep link\n * provider that redirects back to the app in a new tab. With `window.open`,\n * the browser first opens an `about:blank` tab before the native wallet app\n * handles the deep link. When Phantom redirects back, it opens yet another\n * tab. The user ends up with three tabs (original, about:blank, redirect) and\n * the browser focuses the lingering about:blank after the redirect tab closes.\n * `window.location.assign` reuses the current tab, avoiding the extra tab\n * entirely.\n * @not-instrumented\n */\nexport const createWebDeeplinkOpener = (): OpenDeeplink => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(\n new UnavailableInServerSideError('createWebDeeplinkOpener')\n );\n }\n\n return async (url) => {\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for opening a deeplink\n window.location.assign(url);\n };\n};\n","/**\n * Because this is the web implementation of the passkey service, we need to\n * import the browser's WebAuthn API directly.\n * @not-instrumented\n */\nimport {\n // eslint-disable-next-line no-restricted-syntax\n browserSupportsWebAuthn,\n // eslint-disable-next-line no-restricted-syntax\n startAuthentication,\n // eslint-disable-next-line no-restricted-syntax\n startRegistration,\n} from '@simplewebauthn/browser';\n\nimport type {\n CreatePasskeyServiceParams,\n PasskeyService,\n} from '../passkey.types';\n\n/**\n * Create a passkey service that uses the browser's WebAuthn API.\n *\n * Metadata is accepted for parity with the native implementation (which uses\n * `universalLink` to validate the associated domain) but is unused on web —\n * the browser derives the relying party from `window.location.origin`.\n * @not-instrumented\n */\nexport const createPasskeyService = (\n _params?: CreatePasskeyServiceParams\n): PasskeyService => ({\n authenticate: (options) => startAuthentication(options),\n isSupported: () => browserSupportsWebAuthn(),\n register: (options) => startRegistration(options),\n});\n","import { assertDefined } from '../../assertDefined';\nimport type { DeferredPromise } from '../../deferredPromise';\nimport { createDeferredPromise } from '../../deferredPromise';\nimport type { DebouncedMutex } from '../debouncedMutex.types';\n\n/**\n * State for a debounced mutex.\n */\ntype DebouncedMutexState = {\n /**\n * Next callback to run.\n */\n nextCallback: (() => Promise<void>) | null;\n /**\n * Promise that resolves when the debounced mutex is released.\n */\n queuePromise: Promise<void>;\n /**\n * Promises that allow callers to await the completion of the next callback execution.\n * Each invocation adds a promise to this array, which gets resolved when the callback finishes.\n */\n resolutionPromises: DeferredPromise<void>[];\n /**\n * Timer for the debounced mutex.\n *\n * Uses `ReturnType<typeof setTimeout>` because the project's lib includes both\n * \"dom\" and \"@types/node\" — DOM's setTimeout returns `number`, Node's returns\n * `Timeout`. This makes the type portable between web and native builds.\n */\n timer: ReturnType<typeof setTimeout> | null;\n};\n\n/** @not-instrumented */\nexport const createDebouncedMutex = (): DebouncedMutex => {\n const mutexState = new Map<string, DebouncedMutexState>();\n\n return async ({ lockKey, callback, debounceTime = 0 }) => {\n const resolutionPromise = createDeferredPromise<void>();\n\n // Prefill the state for this key if it doesn't exist to avoid needing to check for existence later.\n if (!mutexState.has(lockKey)) {\n mutexState.set(lockKey, {\n nextCallback: null,\n queuePromise: Promise.resolve(),\n resolutionPromises: [],\n timer: null,\n });\n }\n\n const currentState = mutexState.get(lockKey);\n\n // This should never happen, but we'll assert it for TS safety.\n assertDefined(currentState, `Mutex state for key ${lockKey} not found`);\n\n currentState.resolutionPromises.push(resolutionPromise);\n\n if (currentState.timer) {\n clearTimeout(currentState.timer);\n }\n\n // The last invocation wins. Always.\n currentState.nextCallback = callback;\n\n const addCallbackToQueue = async () => {\n currentState.queuePromise = currentState.queuePromise.then(async () => {\n if (!currentState.nextCallback) {\n return;\n }\n\n // We can't just use the callback param directly because later invocations\n // should override previous ones.\n // Scenario to illustrate this (none of these will use the timer param for simplicity):\n // 1. Very long running promise callback A runs\n // 2. While it's running, we invoke callback B, which queues itself with \"then\" and overrides nextCallback with B.\n // 3. While A is still running, we invoke callback C, same thing happens, now nextCallback is C.\n // 4. A resolves, nextCallback is invoked with C.\n // 5. After C resolves, nextCallback is invoked with null, so it doesn't run.\n // Conclusion: B was never executed and only the last invocation runs.\n const { nextCallback } = currentState;\n\n currentState.nextCallback = null;\n\n const promisesToResolve = currentState.resolutionPromises;\n\n currentState.resolutionPromises = [];\n\n try {\n await nextCallback();\n\n promisesToResolve.forEach((resolutionPromise) =>\n resolutionPromise.resolve()\n );\n } catch (error) {\n promisesToResolve.forEach((resolutionPromise) =>\n resolutionPromise.reject(error)\n );\n }\n });\n };\n\n if (debounceTime > 0) {\n currentState.timer = setTimeout(addCallbackToQueue, debounceTime);\n } else {\n await addCallbackToQueue();\n }\n\n return resolutionPromise.promise;\n };\n};\n","import { BaseError } from './base';\n\nexport class InvalidStorageValue extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(key: string, value: unknown) {\n super({\n cause: null,\n code: 'invalid_storage_value',\n docsUrl: null,\n name: 'InvalidStorageValue',\n shortMessage: `Tried to store state with a forbidden value. Key: ${key}, Value: ${value}`,\n });\n }\n}\n","import { InvalidStorageValue } from '../../../errors/InvalidStorageValue';\nimport type { ObservableState } from '../observable.types';\n\n/**\n * Creates an observable state object that allows subscribing to immutable state changes.\n *\n * This function creates a state management system with the following capabilities:\n * - Get the current state\n * - Update state partially\n * - Subscribe to state changes\n * - Unsubscribe from state changes\n *\n * @param getInitialState - A function that returns the initial state object\n * @returns An ObservableState object with methods to manage and observe state changes\n * @example\n * ```typescript\n * const state = createObservableState(() => ({\n * count: 0,\n * name: 'John'\n * }));\n *\n * // Subscribe to changes\n * const unsubscribe = state.subscribe((current, previous) => {\n * console.log('State changed:', current, 'Previous:', previous);\n * });\n *\n * // Update state\n * state.set({ count: 1 });\n *\n * // Get current state\n * const currentState = state.get();\n *\n * // Unsubscribe when done\n * unsubscribe();\n * ```\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const createObservableState = <T extends Record<string, unknown>>(\n getInitialState: () => T\n): ObservableState<T> => {\n // ===============\n // NOTIFICATIONS\n // ===============\n const subscribers = new Set<(value: T, previous: T) => void>();\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const notifySubscribers = (value: T, previous: T) => {\n subscribers.forEach((callback) => callback(value, previous));\n };\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const subscribe = (\n callback: (value: Readonly<T>, previous: Readonly<T>) => void\n ) => {\n subscribers.add(callback);\n\n return () => unsubscribe(callback);\n };\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const unsubscribe = (\n callback: (value: Readonly<T>, previous: Readonly<T>) => void\n ) => {\n subscribers.delete(callback);\n };\n\n // ===============\n // STATE\n // ===============\n\n let currentState = getInitialState();\n\n const get = () => currentState;\n\n const set = (partial: Partial<T>) => {\n const previous = currentState;\n\n Object.entries(partial).forEach(([key, value]) => {\n if (value === undefined) {\n throw new InvalidStorageValue(key, value);\n }\n });\n\n currentState = Object.assign({}, currentState, partial);\n\n notifySubscribers(currentState, previous);\n };\n\n return {\n get,\n getInitialState,\n set,\n subscribe,\n unsubscribe,\n };\n};\n","/**\n * The default API base URL for Dynamic apps in production.\n */\nexport const DEFAULT_API_BASE_URL = 'https://app.dynamicauth.com/api/v0';\n","import type { DynamicCoreState } from '../types';\n\n/**\n * The initial values for the state of the client.\n * @not-instrumented\n */\nexport const getInitialState = (): DynamicCoreState => ({\n captchaToken: null,\n elevatedAccessTokens: [],\n initStatus: 'uninitialized',\n legacyToken: null,\n mfaToken: null,\n prefetchedNonces: [],\n prefetchedNoncesExpiration: null,\n projectSettings: null,\n sessionExpiresAt: null,\n sessionKeys: null,\n token: null,\n unverifiedWalletAccounts: [],\n user: null,\n walletProviderKeyMap: {},\n});\n","import { version } from '../../../../package.json';\nimport { createAsyncTrack } from '../../../services/asyncTrack';\nimport { createCrossTabBroadcast } from '../../../services/crossTabBroadcast/createCrossTabBroadcast';\nimport { createEventEmitter } from '../../../services/eventEmitter';\nimport { createWebFetch } from '../../../services/fetch/createWebFetch';\nimport { connectLoggerToInstrumentation } from '../../../services/instrumentation/connectLoggerToInstrumentation';\nimport { createInstrumentation } from '../../../services/instrumentation/createInstrumentation';\nimport { createDynamicTransport } from '../../../services/instrumentation/transports/createDynamicTransport';\nimport { createLogger } from '../../../services/logger/createLogger';\nimport { createNavigationHandler } from '../../../services/navigate/createNavigationHandler';\nimport { createKeychainService } from '../../../services/keychain';\nimport { createWebDeeplinkOpener } from '../../../services/openDeeplink/createWebDeeplinkOpener';\nimport { createPasskeyService } from '../../../services/passkey';\nimport { createRealtimeService } from '../../../services/realtime/createRealtimeService';\nimport { createRuntimeServices } from '../../../services/runtimeServices';\nimport {\n createLocalStorageAdapter,\n createStorage,\n} from '../../../services/storage';\nimport { createDebouncedMutex } from '../../../utils/debouncedMutex/createDebouncedMutex';\nimport { getKeychainIndexedDBName } from '../../../utils/getKeychainIndexedDBName';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering/isServerSideRendering';\nimport { createObservableState } from '../../../utils/observable/createObservableState';\nimport { randomString } from '../../../utils/randomString/randomString';\nimport { DEFAULT_API_BASE_URL } from '../../consts';\nimport type { DynamicClientConfig } from '../../types';\nimport type { DynamicCore, DynamicCoreState } from '../types';\nimport { getInitialState } from './getInitialState';\n\n/**\n * Creates a core instance that contains all the services and state of the Dynamic SDK client.\n * @not-instrumented\n */\nexport const createCore = (config: DynamicClientConfig): DynamicCore => {\n const apiBaseUrl = config.coreConfig?.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n const logger =\n config.coreConfig?.logger ?? createLogger({ level: config.logLevel });\n\n const storage = createStorage({\n prefix: `dynamic_${config.environmentId}`,\n storageAdapter:\n config.coreConfig?.storageAdapter ?? createLocalStorageAdapter(),\n });\n\n const fetch = config.coreConfig?.fetch ?? createWebFetch();\n\n const openDeeplink =\n config.coreConfig?.openDeeplink ?? createWebDeeplinkOpener();\n\n const openAuthSession = config.coreConfig?.openAuthSession;\n\n const navigate = config.coreConfig?.navigate ?? createNavigationHandler();\n\n const state = createObservableState<DynamicCoreState>(getInitialState);\n\n const debouncedMutex = createDebouncedMutex();\n\n const eventEmitter = createEventEmitter();\n\n const initTrack = createAsyncTrack();\n\n const sdkSessionId = randomString({ length: 32 });\n\n const instrumentation = createInstrumentation({\n config: config.instrumentation,\n });\n\n const extensions = new Set<string>();\n\n connectLoggerToInstrumentation({\n environmentId: config.environmentId,\n extensions,\n instrumentation,\n logger,\n sdkSessionId,\n sdkVersion: version,\n state,\n });\n\n if (!isServerSideRendering()) {\n instrumentation.setTransport(\n createDynamicTransport({\n environmentId: config.environmentId,\n fetch,\n })\n );\n }\n\n const runtimeServices = createRuntimeServices();\n\n const metadata = {\n ...config.metadata,\n universalLink:\n config.metadata?.universalLink ??\n // eslint-disable-next-line no-restricted-globals\n (isServerSideRendering() ? undefined : window.location.origin),\n };\n\n const passkey =\n config.coreConfig?.passkey ?? createPasskeyService({ metadata });\n\n const realtime = config.coreConfig?.realtime ?? createRealtimeService();\n\n const deviceSigner = config.coreConfig?.deviceSigner;\n\n const keychain =\n config.coreConfig?.keychain ??\n createKeychainService({\n dbName: getKeychainIndexedDBName({\n environmentId: config.environmentId,\n }),\n });\n\n const crossTabBroadcast =\n config.coreConfig?.crossTabBroadcast ??\n createCrossTabBroadcast({\n channelName: `dynamic_${config.environmentId}_broadcast`,\n });\n\n return {\n apiBaseUrl,\n crossTabBroadcast,\n debouncedMutex,\n deviceSigner,\n environmentId: config.environmentId,\n eventEmitter,\n extensions,\n fetch,\n getApiHeaders: config.coreConfig?.getApiHeaders ?? (() => ({})),\n initTrack,\n instrumentation,\n keychain,\n logger,\n metadata,\n navigate,\n openAuthSession,\n openDeeplink,\n passkey,\n realtime,\n runtimeServices,\n sdkSessionId,\n state,\n storage,\n transformers: config.transformers,\n version,\n waas: config.waas,\n };\n};\n","import { initializeClient } from '../../modules/initializeClient';\nimport { isServerSideRendering } from '../../utils/isServerSideRendering';\nimport { createCore } from '../core/createCore';\nimport { setDefaultClient } from '../defaultClient';\nimport type { DynamicClient, DynamicClientConfig } from '../types';\n\n/**\n * Creates a new DynamicClient instance.\n *\n * Notice the `autoInitialize` flag is true by default (unless you're running\n * in SSR), so the client will be automatically initialized when created — if\n * you want to manually initialize the client, you can set the `autoInitialize`\n * flag to false and then later call the `initializeClient` function.\n *\n * Manually calling `initializeClient` also allows you to catch any potential\n * errors that may occur during initialization.\n *\n * @param config - The configuration for the Dynamic client, like the environment ID, app url, etc.\n * @returns The Dynamic client instance.\n * @instrumented\n */\nexport const createDynamicClient = (\n config: DynamicClientConfig\n): DynamicClient => {\n const core = createCore(config);\n\n const client = {\n get __core() {\n return core;\n },\n get initStatus() {\n return core.state.get().initStatus;\n },\n get mfaToken() {\n return core.state.get().mfaToken;\n },\n get projectSettings() {\n return core.state.get().projectSettings;\n },\n get sessionExpiresAt() {\n return core.state.get().sessionExpiresAt;\n },\n get token() {\n return core.state.get().token;\n },\n get user() {\n return core.state.get().user;\n },\n };\n\n // Define if SDK should auto initialize, default to true\n const autoInitialize = config.autoInitialize ?? true;\n\n // Prevent the auto initialization in SSR\n const shouldAutoInitialize = isServerSideRendering() ? false : autoInitialize;\n\n core.logger.debug('[createDynamicClient] Creating client...');\n\n if (shouldAutoInitialize) {\n core.logger.debug('[createDynamicClient] Initializing client...');\n void initializeClient(client);\n }\n\n setDefaultClient(client);\n\n return client;\n};\n","import { BaseError } from './base';\n\nexport class CheckoutSessionTokenMissingError extends BaseError {\n constructor({ transactionId }: { transactionId: string }) {\n super({\n cause: null,\n code: 'checkout_session_token_missing',\n docsUrl: null,\n name: 'CheckoutSessionTokenMissingError',\n shortMessage: `No session token found for transaction ${transactionId}. Session tokens are issued once at transaction creation and cannot be recovered.`,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype DeeplinkConnectAndVerifyUnsupportedErrorParams = {\n walletProviderKey: string;\n};\n\nexport class DeeplinkConnectAndVerifyUnsupportedError extends BaseError {\n constructor({\n walletProviderKey,\n }: DeeplinkConnectAndVerifyUnsupportedErrorParams) {\n super({\n cause: null,\n code: 'deeplink_connect_and_verify_unsupported',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n 'On mobile, deep link wallet providers (e.g. Phantom redirect) cannot connect and verify in a single step.',\n 'iOS does not allow two sequential deep links — the second one is silently ignored because it is no longer tied to a user gesture.',\n 'Android may handle sequential deep links differently, but this guard applies to all mobile platforms to ensure a stable experience and prevent production-only errors.',\n 'Use connectWithWalletProvider() first, then call verifyWalletAccount() from a separate user action (e.g. a \"Verify Ownership\" button).',\n ],\n name: 'DeeplinkConnectAndVerifyUnsupportedError',\n shortMessage:\n 'connectAndVerifyWithWalletProvider is not supported for deep link wallet providers on mobile. Use connectWithWalletProvider and verifyWalletAccount separately.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class FeeEstimationFailedError extends BaseError {\n constructor(params: { cause?: Error; message: string }) {\n super({\n cause: params.cause || null,\n code: 'fee_estimation_failed_error',\n docsUrl: null,\n name: 'FeeEstimationFailedError',\n shortMessage: params.message,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class InvalidDeviceRegistrationRedirectError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'invalid_device_registration_redirect_error',\n docsUrl: null,\n metaMessages: [\n 'To check if a URL is a valid device registration redirect before extracting the token, use detectDeviceRegistrationRedirect from the @dynamic-labs-sdk/client package.',\n ],\n name: 'InvalidDeviceRegistrationRedirectError',\n shortMessage:\n 'The provided URL is not a valid device registration redirect.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class InvalidRedirectStorageStateError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'invalid_redirect_storage_state_error',\n docsUrl: null,\n name: 'InvalidRedirectStorageStateError',\n shortMessage:\n 'The social redirect data found in local storage does not match the expected state. Try connecting again.',\n });\n }\n}\n","import { BaseError } from './base';\n\ntype InvalidSocialCallbackOriginErrorParams = {\n actualOrigin: string;\n expectedOrigin: string;\n};\n\nexport class InvalidSocialCallbackOriginError extends BaseError {\n constructor({\n actualOrigin,\n expectedOrigin,\n }: InvalidSocialCallbackOriginErrorParams) {\n super({\n cause: null,\n code: 'invalid_social_callback_origin_error',\n docsUrl: null,\n name: 'InvalidSocialCallbackOriginError',\n shortMessage: `OAuth callback URL origin mismatch. Expected ${expectedOrigin}, got ${actualOrigin}. This may indicate a compromised auth session or misconfigured redirect URL.`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class UserCancelledSocialPopUpError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'user_cancelled_social_popup_error',\n docsUrl: null,\n name: 'UserCancelledSocialPopUpError',\n shortMessage:\n 'The user cancelled (or dismissed) the social authentication pop-up.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class MissingRedirectStorageStateError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'missing_redirect_storage_state_error',\n docsUrl: null,\n name: 'MissingRedirectStorageStateError',\n shortMessage:\n 'The social redirect data was not found in local storage. Try connecting again.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class MissingSocialUrlParamError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(param: string) {\n super({\n cause: null,\n code: 'missing_social_url_param_error',\n docsUrl: null,\n name: 'MissingSocialParamError',\n shortMessage: `To complete social sign in, the following URL query parameter is required to be set but was not found: ${param}`,\n });\n }\n}\n","import type { UserFields } from '@dynamic-labs/sdk-api-core';\n\nimport { BaseError } from './base';\n\ntype MissingUserVerificationErrorParams = {\n informationToVerify: Extract<keyof UserFields, 'email' | 'phoneNumber'>;\n message?: string;\n};\n\nexport class MissingUserVerificationError extends BaseError {\n public readonly informationToVerify: MissingUserVerificationErrorParams['informationToVerify'];\n\n constructor({\n informationToVerify,\n message,\n }: MissingUserVerificationErrorParams) {\n super({\n cause: null,\n code: 'missing_user_verification_error',\n docsUrl: null,\n name: 'MissingUserVerificationError',\n shortMessage:\n message ??\n `The user is missing verification for ${informationToVerify}. Please verify the user's ${informationToVerify}`,\n });\n\n this.informationToVerify = informationToVerify;\n }\n}\n","import { BaseError } from './base';\n\ntype NetworkAddingUnavailableErrorParams = {\n extraMessages?: string[];\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkAddingUnavailableError extends BaseError {\n constructor({\n walletProviderKey,\n originalError,\n extraMessages,\n }: NetworkAddingUnavailableErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_adding_unavailable',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n ...(extraMessages ?? []),\n ],\n name: 'NetworkAddingUnavailableError',\n shortMessage: `Network adding is not available for this wallet provider. The user should manually add the network in their wallet`,\n });\n }\n}\n","import type { NetworkData } from '../modules/wallets/networks/networkProvider/networkProvider.types';\nimport { BaseError } from './base';\n\ntype NetworkNotAddedErrorParams = {\n networkData: NetworkData;\n networkId: string;\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkNotAddedError extends BaseError {\n readonly networkData: NetworkData;\n\n constructor({\n networkData,\n networkId,\n originalError,\n walletProviderKey,\n }: NetworkNotAddedErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_not_added',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n `Network ID: ${networkId}`,\n 'The network is not added to the wallet. If the wallet provider supports adding networks, call the `addNetwork` method before switching.',\n 'The network data is available in the error payload as `error.networkData` and can be passed directly to `addNetwork`.',\n ],\n name: 'NetworkNotAddedError',\n shortMessage: `Cannot switch to network ${networkId} because it is not added to the wallet. If the wallet provider supports it, call \\`addNetwork\\` with the network data from \\`error.networkData\\` first.`,\n });\n\n this.networkData = networkData;\n }\n}\n","import { BaseError } from './base';\n\ntype NetworkSwitchingUnavailableErrorParams = {\n extraMessages?: string[];\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkSwitchingUnavailableError extends BaseError {\n constructor({\n walletProviderKey,\n originalError,\n extraMessages,\n }: NetworkSwitchingUnavailableErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_switching_unavailable',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n ...(extraMessages ?? []),\n ],\n name: 'NetworkSwitchingUnavailableError',\n shortMessage: `Network switching is not available at this time. The user should manually switch networks in their wallet`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoAddressFoundError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_address_found_error',\n docsUrl: null,\n name: 'NoAddressFoundError',\n shortMessage: 'No address is connected to the wallet',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoPasskeyCredentialsFoundError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_passkey_credentials_found_error',\n docsUrl: null,\n name: 'NoPasskeyCredentialsFoundError',\n shortMessage: 'No passkey credentials found',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoSmartWalletAccountSignerFoundError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(smartWalletAddress: string) {\n super({\n cause: null,\n code: 'no_smart_wallet_account_signer_found_error',\n docsUrl: null,\n name: 'NoSmartWalletAccountSignerFoundError',\n shortMessage: `No signer wallet account found for smart wallet account ${smartWalletAddress}`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoWebAuthNSupportError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_webauthn_support_error',\n docsUrl: null,\n name: 'NoWebAuthNSupportError',\n shortMessage: 'Browser does not support WebAuthn',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class SimulationFailedError extends BaseError {\n constructor(params: { cause?: Error; message: string }) {\n super({\n cause: params.cause || null,\n code: 'simulation_failed_error',\n docsUrl: null,\n name: 'SimulationFailedError',\n shortMessage: params.message,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype TokenSwapErrorParams = {\n message: string;\n originalError?: unknown;\n};\n\nexport class TokenSwapError extends BaseError {\n constructor({ message, originalError }: TokenSwapErrorParams) {\n const cause =\n originalError && originalError instanceof Error ? originalError : null;\n super({\n cause,\n code: 'token_swap_error',\n docsUrl: null,\n name: 'TokenSwapError',\n shortMessage: message,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype UnrecognizedNetworkErrorParams = {\n networkId: string;\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class UnrecognizedNetworkError extends BaseError {\n constructor({\n networkId,\n originalError,\n walletProviderKey,\n }: UnrecognizedNetworkErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'unrecognized_network',\n docsUrl: null,\n metaMessages: [`Wallet provider key: ${walletProviderKey}`],\n name: 'UnrecognizedNetworkError',\n shortMessage: `Attempt to switch to unrecognized network of ID ${networkId}. Please enable this network in your dashboard configuration first.`,\n });\n }\n}\n","import { BaseError, type BaseErrorParameters } from './base';\n\nexport class UserNotAuthenticatedError extends BaseError {\n constructor({\n shortMessage,\n }: Partial<Pick<BaseErrorParameters, 'shortMessage'>> = {}) {\n super({\n cause: null,\n code: 'user_not_authenticated_error',\n docsUrl: null,\n name: 'UserNotAuthenticatedError',\n shortMessage: shortMessage ?? 'User not authenticated',\n });\n }\n}\n","import { BaseError } from './base';\n\ntype UserRejectedErrorParams = {\n action: string;\n};\n\nexport class UserRejectedError extends BaseError {\n constructor({ action }: UserRejectedErrorParams) {\n super({\n cause: null,\n code: 'user_rejected',\n docsUrl: null,\n name: 'UserRejectedError',\n shortMessage: `User rejected action \"${action}\"`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class WalletAccountAlreadyVerifiedError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(address: string) {\n super({\n cause: null,\n code: 'wallet_account_already_verified_error',\n docsUrl: null,\n name: 'WalletAccountAlreadyVerifiedError',\n shortMessage: `Wallet account ${address} is already verified`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class WalletAccountNotSelectedError extends BaseError {\n public readonly expectedAddress: string;\n public readonly selectedAddress: string;\n\n constructor(params: { expectedAddress: string; selectedAddress: string }) {\n const currentAccountInfo = params.selectedAddress\n ? ` (currently ${params.selectedAddress})`\n : '';\n super({\n cause: null,\n code: 'wallet_account_not_selected_error',\n docsUrl: null,\n name: 'WalletAccountNotSelected',\n shortMessage: `This wallet only supports signing with its selected account${currentAccountInfo}. Please select account ${params.expectedAddress} in your wallet app and try again`,\n });\n\n this.expectedAddress = params.expectedAddress;\n this.selectedAddress = params.selectedAddress;\n }\n}\n","import { BaseError } from './base';\n\ntype WalletProviderMethodUnavailableErrorParams = {\n methodName: string;\n walletProviderKey: string;\n};\n\nexport class WalletProviderMethodUnavailableError extends BaseError {\n constructor({\n methodName,\n walletProviderKey,\n }: WalletProviderMethodUnavailableErrorParams) {\n super({\n cause: null,\n code: 'wallet_provider_method_unavailable_error',\n docsUrl: null,\n name: 'WalletProviderMethodUnavailableError',\n shortMessage: `Wallet provider ${walletProviderKey} does not have ${methodName} available`,\n });\n }\n}\n","import { type StepUpCheckResponse, type TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createApiClient } from '../../apiClient/createApiClient';\nimport { getElevatedAccessToken } from '../getElevatedAccessToken';\n\nconst STEP_UP_REQUIRED_DEFAULT: StepUpCheckResponse = {\n credentials: [],\n isRequired: true,\n};\n\n/**\n * Checks whether step-up authentication is required for a given scope\n * and returns the available credentials to satisfy it.\n *\n * First performs a fast local check — if a valid elevated access token already\n * exists for the scope, returns `{ isRequired: false }` immediately without\n * an API call.\n *\n * Otherwise, calls the backend `stepUp/check` endpoint which evaluates\n * feature flags, SDK version, MFA settings, and action-based requirements\n * to determine if step-up is needed. The response includes the available\n * credentials and a recommended default credential.\n *\n * If the request fails for any reason, defaults to `{ isRequired: true }`\n * as a safety measure.\n *\n * @param params.scope - The scope to check (e.g., 'wallet:export').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The step-up check result with `isRequired`, `credentials`, and `defaultCredentialId`.\n *\n * @example\n * ```typescript\n * const result = await checkStepUpAuth({ scope: TokenScope.Walletexport });\n * if (result.isRequired) {\n * // Show step-up auth UI using result.credentials\n * }\n * ```\n * @instrumented\n */\nexport const checkStepUpAuth = async (\n { scope }: { scope: TokenScope },\n client: DynamicClient = getDefaultClient()\n): Promise<StepUpCheckResponse> => {\n // Fast local check: if we already have a valid elevated token, no step-up needed\n const existingToken = getElevatedAccessToken(\n { consume: false, scope },\n client\n );\n\n if (existingToken) {\n return { credentials: [], isRequired: false };\n }\n\n try {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.stepUpCheck({\n environmentId: core.environmentId,\n stepUpCheckRequest: { scope },\n });\n\n return {\n credentials: response.credentials ?? [],\n defaultCredentialId: response.defaultCredentialId,\n isRequired: response.isRequired,\n };\n } catch {\n // Default to requiring step-up on any failure for safety\n return STEP_UP_REQUIRED_DEFAULT;\n }\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { parseElevatedAccessToken } from '../../updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken';\nimport { upsertElevatedAccessToken } from '../../updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken';\n\ntype RequestExternalAuthElevatedTokenParams = {\n externalJwt: string;\n};\n\n/**\n * Requests an elevated access token using an external auth assertion JWT.\n *\n * The assertion JWT must be signed by the customer's backend using the same key\n * registered in the environment's external auth JWKS URL. It must include\n * `sub`, `scope`, `jti`, and `exp` claims.\n *\n * The returned elevated access token is automatically parsed and stored in state,\n * and can be retrieved via `getElevatedAccessToken`.\n *\n * @param params.externalJwt - The assertion JWT signed by the customer's backend.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the assertion response containing the elevated access token.\n * @instrumented\n * @redact-params\n */\nexport const requestExternalAuthElevatedToken = async (\n { externalJwt }: RequestExternalAuthElevatedTokenParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.externalAuthVerify({\n environmentId: core.environmentId,\n externalAuthSigninRequest: {\n jwt: externalJwt,\n },\n });\n\n const parsedToken = parseElevatedAccessToken({\n token: response.elevatedAccessToken,\n });\n if (parsedToken) {\n const currentTokens = core.state.get().elevatedAccessTokens || [];\n core.state.set({\n elevatedAccessTokens: upsertElevatedAccessToken({\n currentTokens,\n newToken: parsedToken,\n }),\n });\n }\n\n return response;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\n\ntype SignInWithExternalJwtParams = {\n externalJwt?: string;\n sessionPublicKey?: string;\n};\n\n/**\n * Signs in a user using an external JWT token.\n *\n * This function allows authentication using JWT tokens from external providers,\n * enabling integration with custom authentication systems.\n *\n * @param [params.externalJwt] - Optional external JWT token to authenticate with. Not required when using cookie based auth.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authentication response from the server.\n * @instrumented\n * @redact-params\n */\nexport const signInWithExternalJwt = async (\n { externalJwt, sessionPublicKey }: SignInWithExternalJwtParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.externalAuthSignin({\n environmentId: core.environmentId,\n externalAuthSigninRequest: {\n jwt: externalJwt,\n sessionPublicKey,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { logoutWithReason } from '../logoutWithReason';\n\n/**\n * Logs out the current user and clears all authentication data.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the logout process is complete.\n * @not-instrumented\n */\nexport const logout = async (client = getDefaultClient()) => {\n /**\n * Delegates to `logoutWithReason` with `'user-intent'` so telemetry correctly\n * attributes the logout to an explicit user action. Instrumentation lives on\n * `logoutWithReason` — this wrapper is intentionally not instrumented so that\n * Datadog sees a single function name per logout regardless of entry point.\n */\n return logoutWithReason({ reason: 'user-intent' }, client);\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\n\n/**\n * Deletes a passkey for the current user.\n *\n * @param params.passkeyId - The unique identifier of the passkey to delete.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the passkey is successfully deleted.\n * @instrumented\n */\nexport const deletePasskey = async (\n { passkeyId }: { passkeyId: string },\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient(\n {\n elevatedAccessTokenScope: TokenScope.Credentialunlink,\n includeMfaToken: true,\n },\n client\n );\n\n await apiClient.deletePasskey({\n deleteUserPasskeyRequest: {\n passkeyId,\n },\n environmentId: core.environmentId,\n });\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\n\n/**\n * Retrieves all passkeys associated with the current user.\n *\n * This function fetches the list of registered passkeys (WebAuthn credentials)\n * that the user can use for multi-factor authentication.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of the user's registered passkeys.\n * @not-instrumented\n */\nexport const getPasskeys = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.getUserPasskeys({\n environmentId: core.environmentId,\n });\n\n return response.passkeys;\n};\n","import type { GetPasskeyRegistrationOptionsResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\n/** @not-instrumented */\nexport const getPasskeyRegistrationOptions = async (\n client: DynamicClient\n): Promise<PublicKeyCredentialCreationOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyRegistrationOptionsResponse =\n await apiClient.getPasskeyRegistrationOptions({\n environmentId: core.environmentId,\n });\n\n return options as PublicKeyCredentialCreationOptionsJSON;\n};\n","import type { CreateMfaToken } from '@dynamic-labs/sdk-api-core';\nimport { TokenScope } from '@dynamic-labs/sdk-api-core';\nimport { type RegistrationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerRegisterPasskeyParams = {\n createMfaToken?: CreateMfaToken;\n registration: RegistrationResponseJSON;\n};\n\n/** @not-instrumented */\nexport const serverRegisterPasskey = async (\n { registration, createMfaToken }: ServerRegisterPasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentiallink },\n client\n );\n\n const response = await apiClient.registerPasskey({\n environmentId: core.environmentId,\n passkeyRegisterRequest: {\n ...registration,\n createMfaToken,\n response: {\n ...registration.response,\n clientDataJson: registration.response.clientDataJSON,\n },\n } as Parameters<\n typeof apiClient.registerPasskey\n >[0]['passkeyRegisterRequest'],\n });\n\n return response;\n};\n","import type { CreateMfaToken } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { NoWebAuthNSupportError } from '../../../../errors/NoWebAuthNSupportError';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\nimport { getPasskeyRegistrationOptions } from '../getPasskeyRegistrationOptions';\nimport { serverRegisterPasskey } from '../serverRegisterPasskey';\n\ntype RegisterPasskeyParams = {\n createMfaToken?: CreateMfaToken;\n};\n\n/**\n * Registers a new passkey for the current user.\n *\n * This function creates a new WebAuthn credential that can be used for\n * passwordless authentication. The user will be prompted to create a passkey\n * using their device's biometric authentication or security key.\n *\n * @param [params.createMfaToken] - Optional configuration for MFA token creation.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the registration response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @instrumented\n * @redact-params\n */\nexport const registerPasskey = async (\n { createMfaToken }: RegisterPasskeyParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyRegistrationOptions(client);\n\n const registration = await core.passkey.register({\n optionsJSON: options as PublicKeyCredentialCreationOptionsJSON,\n });\n\n const response = await serverRegisterPasskey(\n { createMfaToken, registration },\n client\n );\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type { GetPasskeyAuthenticationOptionsResponse } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\nexport type GetPasskeyAuthenticationSignInOptionsParams = {\n relatedOriginRpId?: string;\n};\n\n/** @not-instrumented */\nexport const getPasskeyAuthenticationSignInOptions = async (\n { relatedOriginRpId }: GetPasskeyAuthenticationSignInOptionsParams = {},\n client: DynamicClient\n): Promise<PublicKeyCredentialRequestOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyAuthenticationOptionsResponse =\n await apiClient.getPasskeyAuthenticationSigninOptions({\n environmentId: core.environmentId,\n relatedOriginRpId: relatedOriginRpId,\n });\n\n return options as PublicKeyCredentialRequestOptionsJSON;\n};\n","import type {\n CreateMfaToken,\n PasskeyAuthRequest,\n} from '@dynamic-labs/sdk-api-core';\nimport type { AuthenticationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerSigninPasskeyParams = {\n authentication: AuthenticationResponseJSON;\n createMfaToken?: CreateMfaToken;\n};\n\n/** @not-instrumented */\nexport const serverSigninPasskey = async (\n { authentication, createMfaToken }: ServerSigninPasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.signinWithPasskey({\n environmentId: core.environmentId,\n passkeyAuthRequest: {\n ...authentication,\n createMfaToken,\n response: {\n ...authentication.response,\n clientDataJson: authentication.response.clientDataJSON,\n },\n } as PasskeyAuthRequest,\n });\n\n return response;\n};\n","import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { NoWebAuthNSupportError } from '../../../../errors/NoWebAuthNSupportError';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\nimport { getPasskeyAuthenticationSignInOptions } from '../getPasskeyAuthenticationSignInOptions';\nimport { serverSigninPasskey } from '../serverSigninPasskey';\n\nexport type SignInWithPasskeyParams = {\n relatedOriginRpId?: string;\n};\n\n/**\n * Signs in the user using a registered passkey.\n *\n * This function authenticates the user with a previously registered WebAuthn\n * credential, providing passwordless authentication using biometrics or\n * security keys.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authentication response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @instrumented\n * @redact-params\n */\nexport const signInWithPasskey = async (\n { relatedOriginRpId }: SignInWithPasskeyParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyAuthenticationSignInOptions(\n { relatedOriginRpId },\n client\n );\n\n const formattedOptions: PublicKeyCredentialRequestOptionsJSON = {\n ...options,\n };\n\n const authentication = await core.passkey.authenticate({\n optionsJSON: formattedOptions,\n });\n\n const response = await serverSigninPasskey({ authentication }, client);\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { SocialAccount, SocialProvider } from '../social.types';\n\n/**\n * Retrieves all social accounts associated with the current user.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of `SocialAccount` objects associated with the user.\n * @not-instrumented\n */\nexport const getUserSocialAccounts = (\n client = getDefaultClient()\n): SocialAccount[] => {\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const socialCredentials =\n user.verifiedCredentials.filter(\n (credential) =>\n credential.format === JwtVerifiedCredentialFormatEnum.Oauth\n ) ?? [];\n\n return socialCredentials.map((credential) => ({\n accountId: credential.oauthAccountId ?? undefined,\n displayName: credential.oauthDisplayName ?? undefined,\n emails: credential.oauthEmails ?? [],\n photos: credential.oauthAccountPhotos ?? [],\n provider: credential.oauthProvider as SocialProvider,\n username: credential.oauthUsername ?? undefined,\n verifiedCredentialId: credential.id,\n }));\n};\n","/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const removeDynamicOauthParamsFromUrl = (url: string) => {\n const urlObject = new URL(url);\n\n urlObject.searchParams.delete('dynamicOauthState');\n urlObject.searchParams.delete('dynamicOauthCode');\n\n return urlObject.toString();\n};\n","import { ProviderEnum } from '@dynamic-labs/sdk-api-core';\nimport * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../../../services/storage';\n\n/** The schema to track the state of the OAuth flow. */\nexport const redirectStateStorageKeySchema = createStorageKeySchema({\n key: 'redirectState',\n schema: z.object({\n codeVerifier: z.optional(z.string()),\n provider: z.enum(ProviderEnum),\n state: z.string(),\n }),\n});\n","/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const digestSHA256 = (str: string) => {\n const encoder = new TextEncoder();\n const data = encoder.encode(str);\n return crypto.subtle.digest('SHA-256', data);\n};\n","/**\n * Encodes a string to base64url.\n *\n * @param str - The string to encode as an ArrayBuffer.\n * @returns The base64url encoded string.\n * @not-instrumented\n */\nexport const encodeBase64Url = (str: ArrayBuffer) => {\n const numberArray: number[] = [];\n new Uint8Array(str).forEach((item) => numberArray.push(item));\n\n // Deprecated btoa used for web compatibility\n return btoa(String.fromCharCode.apply(null, numberArray))\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n};\n","import { type Provider, ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { assertDefined } from '../../../../../../../utils/assertDefined';\n\nconst APPLE_RESPONSE_MODE = 'form_post' as const;\nconst APPLE_RESPONSE_TYPE = 'code id_token' as const;\n\nexport type AddOAuthUrlParamsOptions = {\n /** The base URL to add OAuth parameters to. */\n baseUrl: URL;\n\n /** When true, adds prompt=consent to force Google to return a fresh refresh token. * @not-instrumented\n */\n isGoogleDriveBackupEnabled?: boolean;\n\n /** The provider configuration to build the URL for. */\n provider: Provider;\n};\n\n/** Helper function to add OAuth URL parameters to a given base URL. * @not-instrumented\n */\nexport const addOAuthUrlParams = ({\n baseUrl,\n isGoogleDriveBackupEnabled,\n provider,\n}: AddOAuthUrlParamsOptions): URL => {\n assertDefined(provider.clientId, 'Client ID not found');\n assertDefined(provider.provider, 'Provider type not found');\n assertDefined(provider.redirectUrl, 'Redirect URL not found');\n\n const providerType = provider.provider;\n\n baseUrl.searchParams.set('client_id', provider.clientId);\n baseUrl.searchParams.set('response_type', 'code');\n baseUrl.searchParams.set('redirect_uri', provider.redirectUrl);\n\n if (providerType === ProviderEnum.Tiktok) {\n baseUrl.searchParams.delete('client_id');\n baseUrl.searchParams.set('client_key', provider.clientId);\n }\n\n if (providerType === ProviderEnum.Google) {\n baseUrl.searchParams.set('access_type', 'offline');\n\n if (isGoogleDriveBackupEnabled) {\n baseUrl.searchParams.set('prompt', 'consent');\n }\n }\n\n // Add logic for providers that require additional parameters\n if (providerType === ProviderEnum.Apple) {\n baseUrl.searchParams.set('response_mode', APPLE_RESPONSE_MODE);\n baseUrl.searchParams.set('response_type', APPLE_RESPONSE_TYPE);\n }\n\n if (provider.scopes) {\n baseUrl.searchParams.set('scope', provider.scopes);\n }\n\n return baseUrl;\n};\n","import { type Provider, ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { assertDefined } from '../../../../../../../utils/assertDefined';\n\n/** Helper function to build the OAuth base URL for a given provider. * @not-instrumented\n */\nexport const getOAuthBaseUrl = (provider: Provider): URL => {\n assertDefined(provider.provider, 'Provider type not found');\n\n const providerType = provider.provider;\n\n if (providerType === ProviderEnum.Telegram) {\n assertDefined(\n provider.authorizationUrl,\n 'Telegram authorization URL not found'\n );\n return new URL(provider.authorizationUrl);\n }\n\n assertDefined(provider.baseAuthUrl, 'Base auth URL not found');\n\n if (providerType === ProviderEnum.Shopify) {\n assertDefined(\n provider.shopifyStore,\n 'Shopify store value not found in provider'\n );\n const loginBaseUrl = provider.baseAuthUrl.replace(\n '{{shopifyStore}}',\n provider.shopifyStore\n );\n return new URL(loginBaseUrl);\n }\n\n return new URL(provider.baseAuthUrl);\n};\n","import {\n type ProviderEnum,\n WaasBackupOptionsEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicCore } from '../../../../../../client/core/types';\nimport { assertDefined } from '../../../../../../utils/assertDefined';\nimport { digestSHA256 } from '../../../../../../utils/digestSHA256';\nimport { encodeBase64Url } from '../../../../../../utils/encodeBase64Url';\nimport { randomString } from '../../../../../../utils/randomString';\nimport { addOAuthUrlParams } from './addOAuthUrlParams';\nimport { getOAuthBaseUrl } from './getOAuthBaseUrl';\n\nconst providersRequiringPkce = ['twitter', 'github'];\n\ntype OAuthUrl = {\n /** A randomly generated string for PKCE flows. * @not-instrumented\n */\n codeVerifier?: string;\n\n /** A randomly generated string for the OAuth flow. */\n state: string;\n\n /** The OAuth URL for the given provider. */\n url: URL;\n};\n\n/** Helper function to build the OAuth URL for a given provider. * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const buildOAuthUrl = async (\n /** The core instance. */\n core: DynamicCore,\n\n /** The provider to build the OAuth URL for. */\n provider: ProviderEnum\n): Promise<OAuthUrl> => {\n const { projectSettings } = core.state.get();\n\n // Check if the provider is supported\n assertDefined(projectSettings, 'Project settings not found');\n assertDefined(projectSettings.providers, 'Project providers not found');\n\n const socialProvider = projectSettings.providers.find(\n (p) => p.provider === provider\n );\n\n assertDefined(socialProvider, `Social provider ${provider} not supported`);\n\n // Check if Google Drive backup is enabled for WaaS\n const isGoogleDriveBackupEnabled =\n projectSettings.sdk.waas?.backupOptions?.includes(\n WaasBackupOptionsEnum.GoogleDrive\n );\n\n // Build the OAuth URL\n const loginBaseUrl = getOAuthBaseUrl(socialProvider);\n const socialProviderUrl = addOAuthUrlParams({\n baseUrl: loginBaseUrl,\n isGoogleDriveBackupEnabled,\n provider: socialProvider,\n });\n\n // Add PKCE and state parameters\n const usingPkce = providersRequiringPkce.includes(provider);\n const state = randomString({ length: 32 });\n const codeVerifier = randomString({ length: 43 });\n\n socialProviderUrl.searchParams.set('state', state);\n socialProviderUrl.searchParams.set('response_type', 'code');\n\n if (usingPkce) {\n const digest = await digestSHA256(codeVerifier);\n\n socialProviderUrl.searchParams.set(\n 'code_challenge',\n encodeBase64Url(digest)\n );\n socialProviderUrl.searchParams.set('code_challenge_method', 'S256');\n }\n\n return {\n codeVerifier: usingPkce ? codeVerifier : undefined,\n state,\n url: socialProviderUrl,\n };\n};\n","import type { ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { createApiClient } from '../../../../apiClient';\nimport { removeDynamicOauthParamsFromUrl } from '../../removeDynamicOauthParamsFromUrl';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\nimport { buildOAuthUrl } from './buildOAuthUrl';\nimport type { SignInWithSocialRedirectParams } from './signInWithSocialRedirect.types';\n\nexport type { SignInWithSocialRedirectParams } from './signInWithSocialRedirect.types';\n\n/**\n * Initiates social authentication by redirecting to the OAuth provider.\n *\n * This function redirects the user to the specified social provider's\n * authorization page to complete the OAuth authentication flow.\n * After the flow is complete, the user is redirected back to your app.\n * Call `detectSocialRedirectUrl` to check whether the user was redirected\n * back because of this flow, then call `completeSocialRedirect` to finish\n * the social authentication.\n *\n * @param params.provider - The social provider to authenticate with (e.g., 'google', 'github').\n * @param params.redirectUrl - The URL to redirect back to after authentication.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @instrumented\n */\nexport const signInWithSocialRedirect = async (\n { provider, redirectUrl }: SignInWithSocialRedirectParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await core.initTrack.waitForAll();\n\n const providerType = provider as ProviderEnum;\n\n const { url, state, codeVerifier } = await buildOAuthUrl(core, providerType);\n\n await apiClient.initAuth({\n environmentId: core.environmentId,\n oauthInitAuthRequest: {\n redirectUrl: removeDynamicOauthParamsFromUrl(redirectUrl),\n state,\n },\n providerType,\n });\n\n await core.storage.setItem(redirectStateStorageKeySchema, {\n codeVerifier,\n provider: providerType,\n state,\n });\n\n await core.navigate(url.toString());\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { MethodNotImplementedError } from '../../../../../errors/MethodNotImplementedError';\nimport type { User } from '../../../../user/user.types';\nimport type { SignInWithSocialPopUpParams } from './signInWithSocialPopUp.types';\n\nexport type { SignInWithSocialPopUpParams } from './signInWithSocialPopUp.types';\n\n/**\n * Sign in with a social provider via an in-app popup (ASWebAuthenticationSession\n * on iOS, Chrome Custom Tabs on Android).\n *\n * This method is **only available on React Native**. On web, use\n * {@link signInWithSocialRedirect} + {@link completeSocialRedirect} instead —\n * the browser already owns the tab so there is no popup to open.\n *\n * @throws MethodNotImplementedError Always on web.\n * @instrumented\n */\nexport const signInWithSocialPopUp = async (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- params required to match standard signature in check-platform-types; destructure pattern cannot be renamed\n { provider }: SignInWithSocialPopUpParams,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- client default required by check-dynamic-client-param-in-external-functions\n client = getDefaultClient()\n): Promise<User | null> => {\n throw new MethodNotImplementedError(\n 'signInWithSocialPopUp (only available on React Native — use signInWithSocialRedirect on web)'\n );\n};\n","import { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\nimport type { DetectSocialRedirectUrlParams } from './detectSocialRedirectUrl.types';\n\nexport type { DetectSocialRedirectUrlParams } from './detectSocialRedirectUrl.types';\n\n/**\n * Detects whether the given URL is an OAuth redirect from a social provider.\n *\n * Examines the URL parameters to determine whether it carries OAuth callback\n * data that originated from a social authentication flow started by\n * `signInWithSocialRedirect`.\n *\n * @param params.url - The URL to check for OAuth redirect parameters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to true if the URL is an OAuth redirect, false otherwise.\n * @not-instrumented\n */\nexport const detectSocialRedirectUrl = async (\n { url }: DetectSocialRedirectUrlParams,\n client = getDefaultClient()\n): Promise<boolean> => {\n const core = getCore(client);\n\n const dynamicOauthState = url.searchParams.get('dynamicOauthState');\n const dynamicOauthCode = url.searchParams.get('dynamicOauthCode');\n\n if (!dynamicOauthState || !dynamicOauthCode) {\n return false;\n }\n\n // Wait for SDK to load\n await core.initTrack.waitForAll();\n\n const storedSocialRedirectState = await core.storage.getItem(\n redirectStateStorageKeySchema\n );\n\n return storedSocialRedirectState?.state === dynamicOauthState;\n};\n","import type { TokenScope, VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../../client/types';\nimport { InvalidRedirectStorageStateError } from '../../../../../errors/InvalidRedirectStorageStateError';\nimport { MissingRedirectStorageStateError } from '../../../../../errors/MissingRedirectStorageStateError';\nimport { MissingSocialUrlParamError } from '../../../../../errors/MissingSocialUrlParamError';\nimport { createApiClient } from '../../../../apiClient';\nimport { consumeCaptchaToken } from '../../../../captcha/consumeCaptchaToken';\nimport type { User } from '../../../../user/user.types';\nimport { updateAuthFromVerifyResponse } from '../../../updateAuthFromVerifyResponse';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\n\ntype ProcessSocialCallbackParams = {\n requestedScopes?: TokenScope[];\n url: URL;\n};\n\n/**\n * Platform-agnostic OAuth callback processor used by both the web redirect\n * flow (`completeSocialRedirect`) and the native pop-up flow\n * (`signInWithSocialPopUp`). Intentionally has no `.native.ts` variant — the\n * logic (parse URL, validate state, call oauthSignIn/oauthVerify, update auth)\n * works identically on every platform.\n *\n * Not exported from the public SDK surface; public callers go through\n * `completeSocialRedirect` or `signInWithSocialPopUp` instead.\n *\n * @param params.url - The callback URL containing OAuth response parameters.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token when verifying (linking) a social account.\n * @param client - The Dynamic client instance.\n * @returns The authenticated user, or null if the verify response had none.\n * @throws MissingSocialUrlParamError If required OAuth parameters are missing.\n * @throws MissingRedirectStorageStateError If no stored redirect state exists.\n * @throws InvalidRedirectStorageStateError If the stored state doesn't match the URL state.\n * @instrumented\n */\nexport const processSocialCallback = async (\n { url, requestedScopes }: ProcessSocialCallbackParams,\n client: DynamicClient\n): Promise<User | null> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await core.initTrack.waitForAll();\n\n const dynamicOauthState = url.searchParams.get('dynamicOauthState');\n const dynamicOauthCode = url.searchParams.get('dynamicOauthCode');\n\n if (!dynamicOauthState) {\n throw new MissingSocialUrlParamError('dynamicOauthState');\n }\n\n if (!dynamicOauthCode) {\n throw new MissingSocialUrlParamError('dynamicOauthCode');\n }\n\n const storedSocialRedirectState = await core.storage.getItem(\n redirectStateStorageKeySchema\n );\n\n if (!storedSocialRedirectState) {\n throw new MissingRedirectStorageStateError();\n }\n\n if (storedSocialRedirectState.state !== dynamicOauthState) {\n throw new InvalidRedirectStorageStateError();\n }\n\n const { provider, codeVerifier } = storedSocialRedirectState;\n\n await core.storage.removeItem(redirectStateStorageKeySchema);\n\n let response: VerifyResponse;\n\n // If the user is already authenticated, we're verifying the social auth to link it to the user\n if (client.user) {\n response = await apiClient.oauthVerify({\n environmentId: core.environmentId,\n oauthRequest: {\n code: dynamicOauthCode,\n codeVerifier,\n requestedScopes,\n state: dynamicOauthState,\n },\n providerType: provider,\n });\n } else {\n // Otherwise we're signing in with the social auth\n response = await apiClient.oauthSignIn({\n environmentId: core.environmentId,\n oauthRequest: {\n captchaToken: consumeCaptchaToken(client),\n code: dynamicOauthCode,\n codeVerifier,\n state: dynamicOauthState,\n },\n providerType: provider,\n });\n }\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response.user;\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { User } from '../../../../user/user.types';\nimport { processSocialCallback } from '../processSocialCallback';\nimport type { CompleteSocialRedirectParams } from './completeSocialRedirect.types';\n\nexport type { CompleteSocialRedirectParams } from './completeSocialRedirect.types';\n\n/**\n * Completes the social authentication flow after the OAuth redirect.\n *\n * Processes the OAuth callback URL with the authorization code and finishes\n * authenticating (or linking) the user with the social provider. This is the\n * final step after `signInWithSocialRedirect` + `detectSocialRedirectUrl`.\n *\n * @param params.url - The callback URL containing OAuth response parameters.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token when verifying (linking) a social account.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authenticated user or null.\n * @throws MissingSocialUrlParamError If required OAuth parameters are missing.\n * @throws InvalidRedirectStorageStateError If the stored state doesn't match.\n * @instrumented\n */\nexport const completeSocialRedirect = (\n { url, requestedScopes }: CompleteSocialRedirectParams,\n client = getDefaultClient()\n): Promise<User | null> =>\n processSocialCallback({ requestedScopes, url }, client);\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { SocialProvider } from '../../social.types';\nimport { signInWithSocialRedirect } from '../signInWithSocialRedirect';\n\ntype AuthenticateWithSocialParams = {\n provider: SocialProvider;\n redirectUrl: string;\n};\n\n/**\n * @deprecated Renamed to {@link signInWithSocialRedirect}. This alias will be\n * removed in a future major version.\n *\n * @instrumented\n */\nexport const authenticateWithSocial = (\n params: AuthenticateWithSocialParams,\n client = getDefaultClient()\n) => signInWithSocialRedirect(params, client);\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { User } from '../../../../user/user.types';\nimport { completeSocialRedirect } from '../completeSocialRedirect';\n\ntype CompleteSocialAuthenticationParams = {\n requestedScopes?: TokenScope[];\n url: URL;\n};\n\n/**\n * @deprecated Renamed to {@link completeSocialRedirect}. This alias will be\n * removed in a future major version.\n *\n * @instrumented\n */\nexport const completeSocialAuthentication = (\n params: CompleteSocialAuthenticationParams,\n client = getDefaultClient()\n): Promise<User | null> => completeSocialRedirect(params, client);\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { detectSocialRedirectUrl } from '../detectSocialRedirectUrl';\n\ntype DetectOAuthRedirectParams = {\n url: URL;\n};\n\n/**\n * @deprecated Renamed to {@link detectSocialRedirectUrl}. This alias will be\n * removed in a future major version.\n *\n * @not-instrumented\n */\nexport const detectOAuthRedirect = (\n params: DetectOAuthRedirectParams,\n client = getDefaultClient()\n): Promise<boolean> => detectSocialRedirectUrl(params, client);\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletAccounts } from '../../getWalletAccounts';\nimport type { WalletAccount } from '../../walletAccount';\n\n/**\n * Get the primary wallet account.\n * The primary wallet account is the one that was last selected by the user.\n * This information is stored in both unverified and verified wallet accounts.\n * This function consolidates this information to determine which wallet was most recently selected.\n * @not-instrumented\n */\nexport const getPrimaryWalletAccount = (\n client = getDefaultClient()\n): WalletAccount | null => {\n const walletAccounts = getWalletAccounts(client);\n\n const sortedLastSelectedWalletAccounts = walletAccounts\n .filter(\n (\n walletAccount\n ): walletAccount is WalletAccount & { lastSelectedAt: Date } =>\n Boolean(walletAccount.lastSelectedAt)\n )\n .sort((a, b) => b.lastSelectedAt.getTime() - a.lastSelectedAt.getTime());\n\n if (sortedLastSelectedWalletAccounts.length === 0) {\n return null;\n }\n\n const [primaryWalletAccount] = sortedLastSelectedWalletAccounts;\n\n return primaryWalletAccount;\n};\n","import type { VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { createApiClient } from '../../../../apiClient';\nimport { getPrimaryWalletAccount } from '../../../../wallets/primaryWalletAccount/getPrimaryWalletAccount';\nimport { updateAuthFromVerifyResponse } from '../../../updateAuthFromVerifyResponse';\n\ntype UnlinkSocialAccountParams = {\n verifiedCredentialId: string;\n};\n\n/**\n * Unlinks a social account from the user's account.\n *\n * @param params.verifiedCredentialId - The verified credential ID of the social account to unlink.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verify response.\n * @instrumented\n * @redact-params\n */\nexport const unlinkSocialAccount = async (\n { verifiedCredentialId }: UnlinkSocialAccountParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n // the api seems to require us to pass the primary wallet id when\n // unlinking a social account if the user has wallets\n const primaryWalletAccount = getPrimaryWalletAccount(client);\n const walletId = primaryWalletAccount?.verifiedCredentialId?.replace(\n '-zerodev',\n ''\n );\n\n const response = await apiClient.verifyUnlink({\n environmentId: core.environmentId,\n verifyUnlinkRequest: {\n verifiedCredentialId,\n walletId: walletId ?? undefined,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type { ChainEnum, TokenBalance } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { getWalletProviderFromWalletAccount } from '../../wallets/utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../wallets/walletAccount';\n\ntype GetTokenBalancesBaseParams = {\n /**\n * Whether to filter out spam tokens.\n * Defaults to true.\n * @not-instrumented\n */\n filterSpamTokens?: boolean;\n /** Whether to force a refresh of the balances instead of using the api cached value. */\n forceRefresh?: boolean;\n /** Whether to include the native token balance. */\n includeNative?: boolean;\n /** Whether to include the prices of the tokens. */\n includePrices?: boolean;\n /** The wallet account to get the balances for. */\n walletAccount: WalletAccount;\n /** If provided, only return balances for the specified contracts. */\n whitelistedContracts?: Array<string>;\n};\n\nexport type GetTokenBalancesParams = GetTokenBalancesBaseParams &\n (\n | {\n /**\n * The network ID to get the balances for.\n * If neither `networkId` nor `networkIds` is provided, the active network ID will be used.\n * Mutually exclusive with `networkIds`.\n */\n networkId?: number;\n networkIds?: never;\n }\n | {\n networkId?: never;\n /**\n * The network IDs to get the balances for.\n * Mutually exclusive with `networkId`.\n */\n networkIds?: string[];\n }\n );\n\n/**\n * Retrieves the token balances for a wallet account on one chain. Fetched\n * from the Dynamic API.\n *\n * Use this for ERC-20-style token balances scoped to a single wallet\n * account. Supports optional spam filtering, price inclusion, native-token\n * inclusion, and one-or-many networks within the wallet's chain.\n *\n * For native-only balance, use {@link getNativeBalance}. For a\n * multi-chain portfolio across many addresses, use\n * {@link getMultichainTokenBalances}.\n *\n * @param params.walletAccount - The wallet account to get the balances for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of token balances.\n * @not-instrumented\n */\nexport const getTokenBalances = async (\n {\n walletAccount,\n networkId,\n networkIds,\n includePrices,\n includeNative,\n filterSpamTokens,\n whitelistedContracts,\n forceRefresh,\n }: GetTokenBalancesParams,\n client = getDefaultClient()\n): Promise<TokenBalance[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n if (!networkId && !networkIds) {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n const activeNetworkId = await walletProvider.getActiveNetworkId();\n networkId = Number(activeNetworkId.networkId);\n }\n\n const balances = await apiClient.getAccountBalances({\n accountAddress: walletAccount.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: walletAccount.chain as ChainEnum,\n environmentId: core.environmentId,\n filterSpamTokens,\n forceRefresh,\n includeNative,\n includePrices,\n networkId,\n networkIds,\n whitelistedContracts,\n });\n\n return balances;\n};\n","import type {\n MultichainAccountBalanceResponse,\n MultichainAccountBalancesRequest,\n MultichainAccountBalancesRequestBalanceRequests,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain/chain.types';\n\nexport type GetMultichainTokenBalancesBalanceRequest =\n Omit<MultichainAccountBalancesRequest, 'balanceRequests'> & {\n balanceRequests: Array<\n Omit<MultichainAccountBalancesRequestBalanceRequests, 'chain'> & {\n chain: Chain;\n }\n >;\n };\n\nexport type GetMultichainTokenBalancesParams = {\n balanceRequest: GetMultichainTokenBalancesBalanceRequest;\n};\n\n/**\n * Retrieves token balances across multiple chains, networks, and addresses\n * in a single batched API request.\n *\n * Use this for portfolio-style views that need to render a user's holdings\n * across their entire multi-chain wallet set. For a single account on one\n * chain, use {@link getTokenBalances}; for native-only balance, use\n * {@link getNativeBalance}.\n *\n * @param params.balanceRequest - The balance request configuration specifying which chains, networks and addresses to query.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the chain balances across multiple networks.\n * @not-instrumented\n */\nexport const getMultichainTokenBalances = async (\n { balanceRequest }: GetMultichainTokenBalancesParams,\n client = getDefaultClient()\n): Promise<MultichainAccountBalanceResponse['chainBalances']> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.postMultichainAccountBalances({\n environmentId: core.environmentId,\n multichainAccountBalancesRequest:\n balanceRequest as MultichainAccountBalancesRequest,\n });\n\n return response.chainBalances;\n};\n","import * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../../services/storage';\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const createCheckoutSessionTokenStorageKey = (transactionId: string) => {\n return createStorageKeySchema({\n key: `checkoutSessionToken:${transactionId}`,\n schema: z.string(),\n });\n};\n","import type { SDKApi } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { CheckoutSessionTokenMissingError } from '../../../../errors/CheckoutSessionTokenMissingError';\nimport { createApiClient } from '../../../apiClient';\nimport { createCheckoutSessionTokenStorageKey } from '../createCheckoutSessionTokenStorageKey';\n\ntype CreateCheckoutApiClientParams = {\n transactionId: string;\n};\n\ntype CheckoutApiClientResult = {\n apiClient: SDKApi;\n environmentId: string;\n sessionToken: string;\n};\n\n/** @not-instrumented */\nexport const createCheckoutApiClient = async (\n { transactionId }: CreateCheckoutApiClientParams,\n client: DynamicClient\n): Promise<CheckoutApiClientResult> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const sessionToken = await core.storage.getItem(\n createCheckoutSessionTokenStorageKey(transactionId)\n );\n\n if (!sessionToken) {\n throw new CheckoutSessionTokenMissingError({ transactionId });\n }\n\n return {\n apiClient,\n environmentId: core.environmentId,\n sessionToken,\n };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createCheckoutSessionTokenStorageKey } from '../createCheckoutSessionTokenStorageKey';\n\nexport type ClearCheckoutSessionTokenParams = {\n transactionId: string;\n};\n\n/**\n * Removes the locally stored checkout session token for the given transaction.\n *\n * The checkout session token is the anonymous credential that authorizes\n * mutations to a single in-flight checkout transaction. Once the transaction\n * has reached a terminal state (cancelled, expired, failed, completed) it can\n * no longer be advanced, and the token is dead weight that should not be\n * persisted in browser storage — leaving it around lets a later XSS payload\n * exfiltrate a credential with no further use, and it can also confuse the\n * SDK on subsequent loads into believing an active session exists.\n *\n * The server-side revocation lives in dashboard-api; this is the SDK-side\n * defense-in-depth.\n *\n * @not-instrumented\n */\nexport const clearCheckoutSessionToken = async (\n { transactionId }: ClearCheckoutSessionTokenParams,\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n await core.storage.removeItem(\n createCheckoutSessionTokenStorageKey(transactionId)\n );\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { APIError } from '../../../../errors/APIError';\nimport type { DynamicClient } from '../../../../client/types';\nimport { clearCheckoutSessionToken } from '../clearCheckoutSessionToken';\n\nexport type WithCheckoutSessionTokenCleanupOn401Params<T> = {\n call: () => Promise<T>;\n transactionId: string;\n};\n\n/**\n * Checkout mutation routes are guarded server-side only by session-token\n * validation, so a 401 means the token is dead (revoked, expired, deleted,\n * or invalid). Leaving a dead token in `localStorage` widens the XSS\n * exfiltration surface for no benefit and makes the next SDK load attempt\n * requests that are guaranteed to fail.\n *\n * @not-instrumented\n */\nexport const withCheckoutSessionTokenCleanupOn401 = async <T>(\n { call, transactionId }: WithCheckoutSessionTokenCleanupOn401Params<T>,\n client: DynamicClient\n): Promise<T> => {\n try {\n return await call();\n } catch (error) {\n if (error instanceof APIError && error.status === 401) {\n try {\n await clearCheckoutSessionToken({ transactionId }, client);\n } catch (cleanupError) {\n getCore(client).logger.error(\n 'Failed to clear checkout session token after 401',\n cleanupError\n );\n }\n }\n throw error;\n }\n};\n","import type {\n AttachSourceRequest,\n ChainEnum,\n CheckoutSourceTypeEnum,\n ExchangeKeyEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { Chain } from '../../chain';\nimport type {\n CheckoutSupportedExchangeProvider,\n CheckoutTransaction,\n} from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\ntype AttachCheckoutTransactionSourceWalletParams = {\n /** The address of the user's wallet. */\n fromAddress: string;\n /** The network id for the token that the user is paying with. */\n fromChainId: string;\n /** The chain name of the user's wallet. */\n fromChainName: Chain;\n /** @defaultValue `'wallet'` */\n sourceType?: 'wallet';\n transactionId: string;\n};\n\ntype AttachCheckoutTransactionSourceExchangeParams = {\n /**\n * The exchange provider key (e.g. `'coinbase'`).\n * The backend uses this to look up the exchange configuration,\n * generate a buy URL, and create the exchange source record.\n */\n exchangeProvider: CheckoutSupportedExchangeProvider;\n sourceType: 'exchange';\n transactionId: string;\n};\n\n/**\n * Parameters for {@link attachCheckoutTransactionSource}.\n *\n * This is a discriminated union on `sourceType`:\n * - `'wallet'` (default) — requires `fromAddress`, `fromChainId`, `fromChainName`\n * - `'exchange'` — requires `exchangeProvider`\n */\nexport type AttachCheckoutTransactionSourceParams =\n | AttachCheckoutTransactionSourceWalletParams\n | AttachCheckoutTransactionSourceExchangeParams;\n\n/**\n * Attaches a payment source to a checkout transaction.\n *\n * For exchange sources, the backend generates the buy URL and creates the\n * exchange source record. The response includes `exchangeSource.metadata.url`\n * which can be embedded in an iframe for the user to complete payment.\n *\n * @param params AttachCheckoutTransactionSourceParams - The source details to attach.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction (with exchangeSource if sourceType is 'exchange')\n * @instrumented\n */\nexport const attachCheckoutTransactionSource = async (\n params: AttachCheckoutTransactionSourceParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { transactionId, sourceType = 'wallet' } = params;\n\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n const attachSourceRequest: AttachSourceRequest = {\n sourceType: sourceType as CheckoutSourceTypeEnum,\n };\n\n if (params.sourceType === 'exchange') {\n attachSourceRequest.exchangeProvider =\n params.exchangeProvider as ExchangeKeyEnum;\n } else {\n attachSourceRequest.fromAddress = params.fromAddress;\n attachSourceRequest.fromChainId = params.fromChainId;\n // eslint-disable-next-line custom-rules/ban-chain-enum\n attachSourceRequest.fromChainName = params.fromChainName as ChainEnum;\n }\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.attachSource({\n attachSourceRequest,\n environmentId,\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import type { CheckoutTransaction } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type BroadcastCheckoutTransactionParams = {\n transactionId: string;\n /**\n * The on-chain transaction hash. Required for wallet sources, optional\n * for exchange sources (the user may not have it).\n */\n txHash?: string;\n};\n\n/**\n * Records that a checkout transaction has been broadcasted.\n *\n * For wallet sources, pass the `txHash` from the on-chain transaction.\n * For exchange sources, `txHash` can be omitted — the user confirms\n * they completed the payment and the transaction moves to `broadcasted`.\n *\n * @param params BroadcastCheckoutTransactionParams - The transaction ID and optional tx hash.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction\n * @instrumented\n */\nexport const broadcastCheckoutTransaction = async (\n { transactionId, txHash }: BroadcastCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.recordCheckoutBroadcast({\n environmentId,\n recordBroadcastRequest: { txHash },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { clearCheckoutSessionToken } from '../utils/clearCheckoutSessionToken';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type CancelCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Cancels a checkout transaction before it has been broadcasted\n *\n * @param params CancelCheckoutTransactionParams - The transaction to cancel.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The cancelled checkout transaction\n * @instrumented\n */\nexport const cancelCheckoutTransaction = async (\n { transactionId }: CancelCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n const result = await withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.cancelCheckoutTransaction({\n environmentId,\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n\n await clearCheckoutSessionToken({ transactionId }, client);\n\n return result;\n};\n","import type { Checkout } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\n\n/** @not-instrumented */\nexport const getCheckouts = async (\n client: DynamicClient\n): Promise<Checkout[]> => {\n const projectSettings = client.projectSettings;\n\n assertDefined(projectSettings, 'Project settings are not available');\n\n return projectSettings.checkouts ?? [];\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { CheckoutTransactionCreateResponse } from '../checkout.types';\nimport { getCheckouts } from '../getCheckouts';\nimport { createCheckoutSessionTokenStorageKey } from '../utils/createCheckoutSessionTokenStorageKey';\n// TODO(realtime): Re-enable the realtime auto-subscribe once the Ably API key\n// is provisioned in the dashboard-api environment. The `realtime/auth`\n// endpoint currently returns \"Realtime service is not configured\" for\n// environments without Ably wiring, so we are temporarily disabling the\n// auto-subscribe to avoid surfacing connection errors to customers. See\n// https://dynamiclabsgroup.slack.com/archives/C03DWBF0LE8/p1778590548698209\n// import { subscribeToCheckoutTransaction } from '../utils/subscribeToCheckoutTransaction';\n\nexport type DestinationAddress = {\n address: string;\n chain: Chain;\n};\n\nexport type CreateCheckoutTransactionParams = {\n amount: string;\n checkoutId?: string;\n currency: string;\n /**\n * The destination addresses for each settlement token destination.\n * Must be provided for each settlement token chain, unless the\n * addresses have already been provided on the checkout creation.\n */\n destinationAddresses?: DestinationAddress[];\n expiresIn?: number;\n memo?: object;\n};\n\n/**\n * Creates a new checkout transaction and stores the session token for subsequent calls\n *\n * @param params CreateCheckoutTransactionParams - The parameters for the checkout transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created transaction with session token\n * @instrumented\n */\nexport const createCheckoutTransaction = async (\n params: CreateCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransactionCreateResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const checkouts = await getCheckouts(client);\n\n // If no checkout ID is provided, try to fallback to the first checkout in the list\n const checkoutId = params.checkoutId || checkouts?.[0]?.id;\n\n assertDefined(\n checkoutId,\n 'No checkout found. Please make sure you have a Checkout setup in the Dashboard.'\n );\n\n const result = await apiClient.createCheckoutTransaction({\n checkoutId,\n checkoutTransactionCreateRequest: {\n amount: params.amount,\n currency: params.currency,\n destinationAddresses: params.destinationAddresses?.map((address) => ({\n address: address.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: address.chain as ChainEnum,\n })),\n expiresIn: params.expiresIn,\n memo: params.memo,\n },\n environmentId: core.environmentId,\n });\n\n await core.storage.setItem(\n createCheckoutSessionTokenStorageKey(result.transaction.id),\n result.sessionToken\n );\n\n // TODO(realtime): Re-enable the realtime auto-subscribe once the Ably API\n // key is provisioned in the dashboard-api environment. See the import\n // block above for context.\n // subscribeToCheckoutTransaction(\n // { transactionId: result.transaction.id },\n // client\n // ).catch((error) => {\n // core.logger.error(\n // 'Failed to subscribe to checkout transaction realtime channel',\n // error\n // );\n // });\n\n return result;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createApiClient } from '../../apiClient';\nimport type { CheckoutTransaction } from '../checkout.types';\n\nexport type GetCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Fetches the current state of a checkout transaction\n *\n * @param params GetCheckoutTransactionParams - The parameters for fetching the transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The checkout transaction\n * @not-instrumented\n */\nexport const getCheckoutTransaction = async (\n { transactionId }: GetCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getCheckoutTransaction({\n environmentId: core.environmentId,\n transactionId,\n });\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type GetCheckoutTransactionQuoteParams = {\n /**\n * Optional chain identifier the source funds will originate from for this\n * quote. When provided, this overrides the fromChainId recorded at\n * attachSource time. The chain family (fromChainName) and source address\n * (fromAddress) are locked at attachSource time — to switch chain families\n * or wallets, call attachSource again.\n */\n fromChainId?: string;\n /**\n * When omitted, defaults to native token for the chain specified in\n * fromChainName in the attach source step.\n */\n fromTokenAddress?: string;\n slippage?: number;\n transactionId: string;\n};\n\n/**\n * Fetches a quote for a checkout transaction\n *\n * @param params GetCheckoutTransactionQuoteParams - The quote parameters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction with quote data\n * @not-instrumented\n */\nexport const getCheckoutTransactionQuote = async (\n {\n fromChainId,\n fromTokenAddress,\n slippage,\n transactionId,\n }: GetCheckoutTransactionQuoteParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.quoteCheckoutTransaction({\n environmentId,\n quoteRequest: {\n fromChainId,\n fromTokenAddress,\n slippage,\n },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type PrepareCheckoutTransactionParams = {\n /**\n * Whether to assert the balance for the gas cost of the transaction.\n * If true, the prepare signing request will fail if the balance is not sufficient for the gas cost.\n * @default false\n */\n assertBalanceForGasCost?: boolean;\n /**\n * Whether to assert the balance for the transfer amount of the transaction.\n * If true, the prepare signing request will fail if the balance is not sufficient for the transfer amount.\n * @default false\n */\n assertBalanceForTransferAmount?: boolean;\n transactionId: string;\n};\n\n/**\n * Prepares a checkout transaction for signing\n * This should be called immediately before triggering the transaction signing.\n * It will confirm the quote is still valid, the risk state is cleared, and the transaction is ready to be signed.\n *\n * @param params PrepareCheckoutTransactionParams - The transaction to prepare.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction\n * @instrumented\n */\nexport const prepareCheckoutTransaction = async (\n {\n assertBalanceForGasCost,\n assertBalanceForTransferAmount,\n transactionId,\n }: PrepareCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.prepareCheckoutTransaction({\n environmentId,\n prepareSigningRequest: {\n assertBalanceForGasCost: assertBalanceForGasCost ?? false,\n assertBalanceForTransferAmount:\n assertBalanceForTransferAmount ?? false,\n },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","/* eslint-disable func-style -- javascript requires this to be a function */\n\nimport { WalletProviderMethodUnavailableError } from '../../../../errors/WalletProviderMethodUnavailableError';\nimport type { WalletProvider } from '../../walletProvider/walletProvider.types';\n\n/**\n * Asserts that a specific wallet provider method is defined, throwing an error if it's not.\n * This function acts as a type guard, narrowing the type to ensure the method exists.\n *\n * @template T - The specific wallet provider method key being checked\n * @param walletProvider - The wallet provider object to check\n * @param methodName - The name of the method to check for availability\n * @throws Throws WalletProviderMethodUnavailableError if the method is not defined\n * @example\n * ```typescript\n * const walletProvider: WalletProvider = getWalletProvider();\n * assertWalletProviderMethodDefined(walletProvider, 'connect');\n * // walletProvider.connect is now guaranteed to be defined\n * await walletProvider.connect();\n * ```\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport function assertWalletProviderMethodDefined<\n T extends keyof WalletProvider\n>(\n walletProvider: WalletProvider,\n methodName: T\n): asserts walletProvider is WalletProvider &\n Required<Pick<WalletProvider, T>> {\n if (walletProvider[methodName] === undefined) {\n throw new WalletProviderMethodUnavailableError({\n methodName: methodName as string,\n walletProviderKey: walletProvider.key,\n });\n }\n}\n","export const SWAP_SUPPORTED_CHAINS = ['BTC', 'EVM', 'SOL', 'SUI', 'TRON'];\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport type { WalletProvider } from '../../../wallets/walletProvider';\n\nexport type EnsureCorrectActiveNetworkParams = {\n requiredNetworkId: string;\n walletProvider: WalletProvider;\n};\n\n/**\n * Ensures the wallet provider is on the correct active network if possible.\n * If the wallet provider is not on the correct active network, it will try to switch to the correct active network.\n * It's not a blocker, so it will just log the error and skip the step if it fails.\n *\n * @not-instrumented\n */\nexport const ensureCorrectActiveNetwork = async (\n { requiredNetworkId, walletProvider }: EnsureCorrectActiveNetworkParams,\n client: DynamicClient\n) => {\n const { logger } = getCore(client);\n\n // Skip if no network id to switch to or the wallet provider doesn't support network switching\n if (!requiredNetworkId || !walletProvider.switchActiveNetwork) {\n return;\n }\n\n logger.debug(\n '[ensureCorrectActiveNetwork] Required network id',\n requiredNetworkId\n );\n\n try {\n const { networkId: activeNetworkId } =\n await walletProvider.getActiveNetworkId();\n\n logger.debug(\n '[ensureCorrectActiveNetwork] Check if should switch network',\n {\n activeNetworkId,\n requiredNetworkId,\n }\n );\n\n if (!activeNetworkId || activeNetworkId === requiredNetworkId) {\n logger.debug(\n '[ensureCorrectActiveNetwork] No active network id found or active network id is the same as the required network id - skipping this step'\n );\n return;\n }\n\n await walletProvider.switchActiveNetwork({\n networkId: requiredNetworkId,\n });\n } catch (error) {\n // intentionally swallowed: network switching is best-effort and the swap\n // should proceed even if we can't verify or change the active network\n logger.debug(\n '[ensureCorrectActiveNetwork] Error getting active network id or switching network - skipping this step',\n error\n );\n }\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { assertWalletProviderMethodDefined } from '../../wallets/utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../../wallets/utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { SWAP_SUPPORTED_CHAINS } from '../constants';\nimport type { SwapTransactionSigningPayload } from '../swap.types';\nimport { ensureCorrectActiveNetwork } from '../utils/ensureCorrectActiveNetwork';\n\nexport type ExecuteSwapTransactionParams = {\n /**\n * The callback to invoke when the transaction execution step changes.\n *\n * 'approval' - The approval step begins. (only happens for ERC-20 tokens when the allowance is insufficient)\n * 'transaction' - The transaction step begins.\n */\n onStepChange?: (step: 'approval' | 'transaction') => void;\n /**\n * The signing payload for the swap transaction.\n * Usually obtained from a `getSwapQuote` call.\n */\n signingPayload: SwapTransactionSigningPayload;\n /**\n * Controls whether the swap is routed through Dynamic's gas sponsorship.\n *\n * - `'auto'` (default): the swap is sponsored when gas sponsorship is enabled\n * for the chain AND the wallet is a Dynamic embedded wallet. Otherwise the\n * user pays gas.\n * - `'off'`: the swap is never sponsored, regardless of project settings or\n * wallet capabilities. The user pays gas.\n *\n * @default 'auto'\n */\n sponsorshipMode?: 'auto' | 'off';\n /**\n * The wallet account to execute the swap transaction on.\n */\n walletAccount: WalletAccount;\n};\n\n/**\n * Executes a swap transaction\n *\n * @param params ExecuteSwapTransactionParams - The parameters for the swap transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The transaction hash.\n * @instrumented\n */\nexport const executeSwapTransaction = async (\n {\n walletAccount,\n signingPayload,\n onStepChange,\n sponsorshipMode,\n }: ExecuteSwapTransactionParams,\n client = getDefaultClient()\n): Promise<{ transactionHash: string }> => {\n if (!SWAP_SUPPORTED_CHAINS.includes(walletAccount.chain)) {\n throw new InvalidParamError(\n `Chain ${walletAccount.chain} is not supported for swap transactions`\n );\n }\n\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'executeSwapTransaction');\n\n await ensureCorrectActiveNetwork(\n {\n requiredNetworkId: signingPayload.chainId,\n walletProvider,\n },\n client\n );\n\n const { transactionHash } = await walletProvider.executeSwapTransaction({\n onStepChange,\n signingPayload,\n sponsorshipMode,\n walletAccount,\n });\n\n return { transactionHash };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { executeSwapTransaction } from '../../swap/executeSwapTransaction';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { broadcastCheckoutTransaction } from '../broadcastCheckoutTransaction';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport type { PrepareCheckoutTransactionParams } from '../prepareCheckoutTransaction';\nimport { prepareCheckoutTransaction } from '../prepareCheckoutTransaction';\n\nexport type SubmitCheckoutTransactionParams = {\n onStepChange?: (step: 'approval' | 'transaction') => void;\n transactionId: string;\n walletAccount: WalletAccount;\n} & PrepareCheckoutTransactionParams;\n\n/**\n * Prepares, signs, and broadcasts a checkout transaction in one call.\n *\n * Orchestrates the full submission flow:\n * 1. Calls prepareCheckoutTransaction to advance to signing state and lock the quote\n * 2. Ensures the wallet is on the correct network for the transaction\n * 3. Delegates on-chain signing to the wallet provider's executeSwapTransaction method\n * 4. Calls broadcastCheckoutTransaction with the resulting txHash\n *\n * @param params SubmitCheckoutTransactionParams - The transaction ID, wallet account, and optional step callback.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The broadcasted checkout transaction\n * @instrumented\n */\nexport const submitCheckoutTransaction = async (\n {\n onStepChange,\n transactionId,\n walletAccount,\n assertBalanceForGasCost,\n assertBalanceForTransferAmount,\n }: SubmitCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const prepared = await prepareCheckoutTransaction(\n { assertBalanceForGasCost, assertBalanceForTransferAmount, transactionId },\n client\n );\n\n const signingPayload = prepared.quote?.signingPayload;\n\n assertDefined(\n signingPayload,\n 'No signing payload returned from prepare — quote may be missing transaction data'\n );\n\n const { transactionHash } = await executeSwapTransaction(\n {\n onStepChange,\n signingPayload,\n walletAccount,\n },\n client\n );\n\n return broadcastCheckoutTransaction(\n { transactionId, txHash: transactionHash },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\n// TODO(realtime): Re-enable the realtime subscribe call once the Ably API key\n// is provisioned in the dashboard-api environment. The `realtime/auth`\n// endpoint currently returns \"Realtime service is not configured\" for\n// environments without Ably wiring, so we are temporarily turning this into\n// a no-op to avoid surfacing connection errors to customers. See\n// https://dynamiclabsgroup.slack.com/archives/C03DWBF0LE8/p1778590548698209\n// import { subscribeToCheckoutTransaction } from '../utils/subscribeToCheckoutTransaction';\n\nexport type TrackCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Subscribes to realtime `checkoutTransactionExecutionStateChanged` and\n * `checkoutTransactionSettlementStateChanged` events for an existing\n * checkout transaction.\n *\n * This is only needed after a page refresh to re-establish the subscription.\n * Transactions created with {@link createCheckoutTransaction} are automatically\n * subscribed — calling this again for those is unnecessary unless the page\n * has been reloaded.\n *\n * NOTE: Temporarily a no-op while the Ably API key is being provisioned for\n * the realtime checkout transaction channel. Will be re-enabled once the\n * dashboard-api environment has the Ably wiring in place.\n *\n * @param params.transactionId - The ID of the checkout transaction to track.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @not-instrumented\n */\nexport const trackCheckoutTransaction = (\n _params: TrackCheckoutTransactionParams,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n client: DynamicClient = getDefaultClient()\n): Promise<void> => {\n // TODO(realtime): Re-enable once the Ably API key is configured. See the\n // import block above for context.\n // return subscribeToCheckoutTransaction({ transactionId }, client);\n return Promise.resolve();\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { InvalidParamError } from '../../../../errors/InvalidParamError';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { CheckoutTransaction } from '../../checkout.types';\nimport { getCheckouts } from '../../getCheckouts';\n\nexport type RequiresConversionParams = {\n transaction: CheckoutTransaction;\n};\n\n/**\n * Determines whether a token conversion (swap/bridge) is required for a checkout transaction.\n *\n * Returns `true` when the from token does not match any settlement token defined in\n * the checkout's settlement config for the given chain — meaning the asset must be\n * converted before it can settle.\n * Returns `false` when the from token already matches a settlement token, so no\n * conversion is needed.\n *\n * @param params - The from token details and the checkout's settlement config.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Whether a token conversion is required\n * @not-instrumented\n */\nexport const requiresConversion = async (\n { transaction }: RequiresConversionParams,\n client = getDefaultClient()\n): Promise<boolean> => {\n if (\n !transaction.fromChainId ||\n !transaction.fromChainName ||\n !transaction.fromToken\n ) {\n throw new InvalidParamError(\n 'Transaction is missing source information. Make sure that attachCheckoutTransactionSource has been called before calling this function.'\n );\n }\n\n const allCheckouts = await getCheckouts(client);\n\n const checkout = allCheckouts.find(\n (checkout) => checkout.id === transaction.checkoutId\n );\n\n assertDefined(\n checkout,\n 'Could not find checkout associated with transaction.'\n );\n\n return !checkout.settlementConfig.settlements.some(\n (settlement) =>\n settlement.chainName === transaction.fromChainName &&\n settlement.chainId === transaction.fromChainId &&\n settlement.tokenAddress === transaction.fromToken\n );\n};\n","import type { VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\nconst DEVICE_REGISTRATION_TOKEN_HEADER = 'x-dynamic-device-registration-token';\n\ntype CompleteDeviceRegistrationParams = {\n deviceToken: string;\n};\n\n/** @instrumented */\nexport const completeDeviceRegistration = async (\n { deviceToken }: CompleteDeviceRegistrationParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n assertDefined(deviceToken, 'deviceToken is required');\n\n const core = getCore(client);\n const apiClient = createApiClient(\n {\n headers: {\n [DEVICE_REGISTRATION_TOKEN_HEADER]: deviceToken,\n },\n },\n client\n );\n\n const response = await apiClient.deviceRegistration({\n environmentId: core.environmentId,\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n // Emit event after successful registration\n emitEvent({ event: 'deviceRegistrationCompleted' }, client);\n\n return response;\n};\n","import { InvalidDeviceRegistrationRedirectError } from '../../../errors/InvalidDeviceRegistrationRedirectError';\n\ntype GetDeviceRegistrationTokenFromUrlParams = {\n url: string;\n};\n\n/**\n * Safely extracts the device token from a device registration redirect URL.\n *\n * This function validates that the URL is a valid device registration redirect\n * then extracts and returns the deviceToken.\n *\n * @returns The device token as a string if valid.\n * @throws InvalidDeviceRegistrationRedirectError If the URL is not a valid device registration redirect.\n * @not-instrumented\n */\nexport const getDeviceRegistrationTokenFromUrl = ({\n url,\n}: GetDeviceRegistrationTokenFromUrlParams): string => {\n let urlObject: URL;\n\n try {\n urlObject = new URL(url);\n } catch {\n throw new InvalidDeviceRegistrationRedirectError();\n }\n\n const deviceRegistrationToken = urlObject.searchParams.get(\n 'deviceRegistrationToken'\n );\n\n if (!deviceRegistrationToken || deviceRegistrationToken.trim() === '') {\n throw new InvalidDeviceRegistrationRedirectError();\n }\n\n return deviceRegistrationToken;\n};\n","import { getDeviceRegistrationTokenFromUrl } from '../getDeviceRegistrationTokenFromUrl';\n\ntype DetectDeviceRegistrationRedirectParams = {\n url: string;\n};\n\n/**\n * Detects if the current URL is a device registration redirect.\n *\n * This function uses getDeviceRegistrationTokenFromUrl to validate the URL and determine\n * if it contains device registration redirect data from a device authentication flow.\n *\n * @returns True if the URL is a device registration redirect, false otherwise.\n * @not-instrumented\n */\nexport const detectDeviceRegistrationRedirect = ({\n url,\n}: DetectDeviceRegistrationRedirectParams): boolean => {\n try {\n getDeviceRegistrationTokenFromUrl({ url });\n return true;\n } catch {\n return false;\n }\n};\n","import type { DeviceRegistrationResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { UnauthorizedError } from '../../../errors/UnauthorizedError';\nimport { createApiClient } from '../../apiClient';\n\n/** @not-instrumented */\nexport const getRegisteredDevices = async (\n client = getDefaultClient()\n): Promise<DeviceRegistrationResponse[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.listDeviceRegistrations({\n environmentId: core.environmentId,\n });\n\n return response.deviceRegistrations;\n } catch (error) {\n /**\n * The API will return 401 when no devices are registered when there are no\n * devices registered. We need to handle this case gracefully.\n */\n if (error instanceof UnauthorizedError) {\n return [];\n }\n\n throw error;\n }\n};\n","import type { User } from '../../user/user.types';\n\n/**\n * Checks if device registration is required for the given user.\n *\n * This function determines if the user has the deviceRegistration\n * scope, indicating that device registration is required.\n *\n * @param user - The user to check.\n * @returns True if device registration is required, false otherwise.\n * @not-instrumented\n */\nexport const isDeviceRegistrationRequired = (user: User) =>\n Boolean(user.scope?.includes('device:register'));\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\n/** @instrumented */\nexport const revokeAllRegisteredDevices = async (\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await apiClient.deleteAllDeviceRegistrations({\n environmentId: core.environmentId,\n });\n\n await logoutWithReason({ reason: 'all-devices-revoked' }, client);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\ntype RevokeRegisteredDeviceParams = {\n deviceRegistrationId: string;\n};\n\n/** @instrumented */\nexport const revokeRegisteredDevice = async (\n { deviceRegistrationId }: RevokeRegisteredDeviceParams,\n client = getDefaultClient()\n): Promise<void> => {\n assertDefined(deviceRegistrationId, 'deviceRegistrationId is required');\n\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.deleteDeviceRegistration({\n deviceRegistrationId,\n environmentId: core.environmentId,\n });\n\n if (response.currentDeviceRevoked) {\n await logoutWithReason({ reason: 'device-revoked' }, client);\n }\n};\n","/* eslint-disable no-restricted-globals */\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { ValueMustBeDefinedError } from '../../../../errors/ValueMustBeDefinedError';\n\ntype AddCoinbaseOnrampOrderEventListenerParams = {\n listener: (event: {\n data: Record<string, unknown>;\n eventName: string;\n }) => void;\n};\n\n/**\n * Adds a listener for Coinbase onramp order events.\n *\n * @param params.listener - The listener function to call when an event is received.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A function to remove the listener.\n * @throws {ValueMustBeDefinedError} If the window is not available.\n * @docs https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api#events-names\n * @not-instrumented\n */\nexport const addCoinbaseOnrampOrderEventListener = (\n { listener }: AddCoinbaseOnrampOrderEventListenerParams,\n client = getDefaultClient()\n): VoidFunction => {\n const core = getCore(client);\n\n if (typeof window === 'undefined') {\n throw new ValueMustBeDefinedError(\n 'Window is not available to listen for Coinbase onramp order events'\n );\n }\n\n const handleMessageEvent = (event: MessageEvent) => {\n if (event.origin !== 'https://pay.coinbase.com') {\n return;\n }\n\n core.logger.debug(\n '[addCoinbaseOnrampOrderEventListener] pay.coinbase.com event received',\n { event }\n );\n\n try {\n const coinbaseOnrampOrderEventData = JSON.parse(event.data);\n\n if (!coinbaseOnrampOrderEventData.eventName?.startsWith('onramp_api.')) {\n return;\n }\n\n listener({\n data: coinbaseOnrampOrderEventData.data,\n eventName: coinbaseOnrampOrderEventData.eventName,\n });\n } catch (error) {\n core.logger.debug(\n '[addCoinbaseOnrampOrderEventListener] Failed to parse Coinbase onramp order event data',\n {\n error,\n }\n );\n }\n };\n\n window.addEventListener('message', handleMessageEvent);\n\n return () => {\n window.removeEventListener('message', handleMessageEvent);\n };\n};\n","import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { InvalidParamError } from '../../../../errors/InvalidParamError';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type {\n CoinbaseOnrampOrderPaymentMethod,\n FieldMissingVerificationForCoinbaseOnramp,\n} from '../coinbase.types';\n\ntype GetMissingVerificationForCoinbaseOnrampOrderResponse =\n FieldMissingVerificationForCoinbaseOnramp[];\n\ntype GetMissingVerificationForCoinbaseOnrampOrderParams = {\n paymentMethod: CoinbaseOnrampOrderPaymentMethod;\n};\n\n/**\n * This function is used to get a list of fields that are missing verification for a Coinbase onramp order\n *\n * - If the user is missing information for an email or phone number, the field will be returned with the error code MISSING_INFORMATION\n * - If the user is missing verification for an email or phone number, the field will be returned with the error code MISSING_VERIFICATION\n * and the existing unverified email or phone number will be included in the data field.\n * - If the user's phone number has not been verified in the last 60 days, the field will be returned with the error code VERIFICATION_EXPIRED\n * and the existing phone number will be included in the data field.\n *\n * @param params.paymentMethod - The payment method that will be used to create the onramp order\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns FieldMissingVerificationForCoinbaseOnramp[] - An array of fields that are missing verification for a Coinbase onramp order\n * @throws {InvalidParamError} - If the payment method is not valid\n * @throws {ValueMustBeDefinedError} - If the user is not authenticated\n * @not-instrumented\n */\nexport const getMissingVerificationForCoinbaseOnrampOrder = (\n { paymentMethod }: GetMissingVerificationForCoinbaseOnrampOrderParams,\n client = getDefaultClient()\n): GetMissingVerificationForCoinbaseOnrampOrderResponse => {\n // adding the payment method as a param for now just so a user has to pass an object as the first param\n // that way, when we add more payment methods, we can easily add them to the param object\n // and not have to change the function signature\n if (paymentMethod !== 'GUEST_CHECKOUT_APPLE_PAY') {\n throw new InvalidParamError(`Invalid payment method: ${paymentMethod}`);\n }\n\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const fieldsMissingVerification: FieldMissingVerificationForCoinbaseOnramp[] =\n [];\n\n const emailVerifiedCredential = user.verifiedCredentials.find(\n (credential) => credential.format === JwtVerifiedCredentialFormatEnum.Email\n );\n\n if (!user.email) {\n // when user has no email at all (verified or not)\n fieldsMissingVerification.push({\n errorCode: 'MISSING_INFORMATION',\n field: 'email',\n });\n } else if (!emailVerifiedCredential) {\n // when user has an email but it is not verified\n fieldsMissingVerification.push({\n data: user.email,\n errorCode: 'MISSING_VERIFICATION',\n field: 'email',\n });\n }\n\n const phoneVerifiedCredential = user.verifiedCredentials.find(\n (credential) =>\n credential.format === JwtVerifiedCredentialFormatEnum.PhoneNumber\n );\n\n const phoneNumberVerifiedInPast60Days =\n phoneVerifiedCredential?.verifiedAt &&\n phoneVerifiedCredential.verifiedAt >=\n new Date(Date.now() - 60 * 24 * 60 * 60 * 1000);\n\n if (!user.phoneNumber) {\n // when user has no phone number at all (verified or not)\n fieldsMissingVerification.push({\n errorCode: 'MISSING_INFORMATION',\n field: 'phoneNumber',\n });\n } else if (!phoneVerifiedCredential) {\n // when user has a phone number but it is not verified\n fieldsMissingVerification.push({\n data: user.phoneNumber,\n errorCode: 'MISSING_VERIFICATION',\n field: 'phoneNumber',\n });\n } else if (!phoneNumberVerifiedInPast60Days) {\n // when user has a verified phone number but it is not verified in the last 60 days\n fieldsMissingVerification.push({\n data: user.phoneNumber,\n errorCode: 'VERIFICATION_EXPIRED',\n field: 'phoneNumber',\n });\n }\n\n return fieldsMissingVerification;\n};\n","import { type SdkUser } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../../../client/types/DynamicClient';\nimport { MissingUserVerificationError } from '../../../../../errors/MissingUserVerificationError';\nimport { assertDefined } from '../../../../../utils/assertDefined';\nimport { getMissingVerificationForCoinbaseOnrampOrder } from '../../getMissingVerificationForCoinbaseOnrampOrder';\n\n/** @not-instrumented */\nexport const validateUserCredentialsForCoinbaseOnrampOrder = (\n client: DynamicClient\n): SdkUser => {\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const fieldsMissingVerification =\n getMissingVerificationForCoinbaseOnrampOrder(\n { paymentMethod: 'GUEST_CHECKOUT_APPLE_PAY' },\n client\n );\n\n const missingEmailVerification = fieldsMissingVerification.find(\n (field) => field.field === 'email'\n );\n\n if (missingEmailVerification) {\n throw new MissingUserVerificationError({\n informationToVerify: 'email',\n message:\n 'User must have a verified email to create a Coinbase onramp order',\n });\n }\n\n const missingPhoneNumberVerification = fieldsMissingVerification.find(\n (field) => field.field === 'phoneNumber'\n );\n\n if (\n missingPhoneNumberVerification &&\n missingPhoneNumberVerification.errorCode !== 'VERIFICATION_EXPIRED'\n ) {\n throw new MissingUserVerificationError({\n informationToVerify: 'phoneNumber',\n message:\n 'User must have a verified phone number to create a Coinbase onramp order',\n });\n }\n\n // this is a requirement for Coinbase Onramp\n // https://docs.cdp.coinbase.com/api-reference/v2/rest-api/onramp/create-an-onramp-order#body-phone-number-verified-at\n if (\n missingPhoneNumberVerification &&\n missingPhoneNumberVerification.errorCode === 'VERIFICATION_EXPIRED'\n ) {\n throw new MissingUserVerificationError({\n informationToVerify: 'phoneNumber',\n message:\n \"The user's phone number has not been verified in the last 60 days. Please re-verify the user's phone number\",\n });\n }\n\n return user;\n};\n","import type { CoinbaseOnrampOrderPaymentMethod } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CoinbaseCreateOnrampOrderRequest,\n CoinbaseOnrampOrderResponse,\n} from '../coinbase.types';\nimport { validateUserCredentialsForCoinbaseOnrampOrder } from '../utils/validateUserCredentialsForCoinbaseOnrampOrder';\n\n/**\n * Creates a Coinbase onramp order\n *\n * @param orderParams CoinbaseCreateOnrampOrderRequest - The parameters for the onramp order.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created order\n * @throws {MissingUserVerificationError} If the user is missing verification for email or phone\n * @instrumented\n */\nexport const createCoinbaseOnrampOrder = async (\n orderParams: CoinbaseCreateOnrampOrderRequest,\n client = getDefaultClient()\n): Promise<CoinbaseOnrampOrderResponse> => {\n const user = validateUserCredentialsForCoinbaseOnrampOrder(client);\n\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const { isSandbox, ...restOrderParams } = orderParams;\n\n const orderResponse = await apiClient.createCoinbaseOnrampOrder({\n coinbaseOnrampOrderCreateRequest: {\n ...restOrderParams,\n // to create a sandbox order, we need to prefix the partner user ref with 'sandbox-'\n // https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api#testing\n partnerUserRef:\n orderParams.partnerUserRef ??\n (isSandbox ? `sandbox-${user.id}` : user.id),\n paymentMethod:\n orderParams.paymentMethod as CoinbaseOnrampOrderPaymentMethod,\n },\n environmentId: core.environmentId,\n });\n\n if (!isSandbox || !orderResponse.paymentLink) {\n return orderResponse;\n }\n\n return {\n ...orderResponse,\n paymentLink: {\n ...orderResponse.paymentLink,\n url: `${orderResponse.paymentLink.url}&useApplePaySandbox=true`,\n },\n };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CoinbaseOnrampGetBuyUrlRequest,\n CoinbaseOnrampGetBuyUrlResponse,\n} from '../coinbase.types';\n\n/**\n * Gets a Coinbase buy URL\n *\n * @param buyUrlParams CoinbaseOnrampGetBuyUrlRequest - The parameters for the buy URL.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns an object containing the buy URL\n * @not-instrumented\n */\nexport const getCoinbaseBuyUrl = async (\n buyUrlParams: CoinbaseOnrampGetBuyUrlRequest,\n client = getDefaultClient()\n): Promise<CoinbaseOnrampGetBuyUrlResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.generateCoinbaseOnrampBuyUrl({\n coinbaseOnrampGetBuyUrlRequest: buyUrlParams,\n environmentId: core.environmentId,\n });\n\n return response;\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CryptoDotComPaymentCreateRequest,\n CryptoDotComPaymentResponse,\n} from '../cryptoDotCom.types';\n\n/**\n * Creates a crypto.com payment\n *\n * @param paymentParams CryptoDotComPaymentCreateRequest - The parameters for the payment.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created payment\n * @instrumented\n */\nexport const createCryptoDotComPayment = async (\n paymentParams: CryptoDotComPaymentCreateRequest,\n client = getDefaultClient()\n): Promise<CryptoDotComPaymentResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.createCryptoDotComPayment({\n cryptoDotComPaymentCreateRequest: {\n ...paymentParams,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chain: paymentParams.chain as ChainEnum,\n },\n environmentId: core.environmentId,\n });\n\n return response;\n};\n","/* eslint-disable custom-rules/ban-chain-enum */\nimport type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { GetMoonPayCurrenciesParams, MoonPayCurrency } from '../moonpay.types';\n\n/**\n * Fetches the list of crypto currencies supported by MoonPay for the given chain\n * and network, filtered to active currencies only. Requires a MoonPay publishable\n * API key to be configured for the environment.\n *\n * @param params - The chain and optional network ID to filter currencies by.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of supported MoonPay currencies.\n * @instrumented\n */\nexport const getMoonPayCurrencies = async (\n params: GetMoonPayCurrenciesParams,\n client: DynamicClient = getDefaultClient()\n): Promise<MoonPayCurrency[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getMoonPayCurrencies({\n // Chain is typed as ChainEnum in the generated API client; our public type\n // is Chain (string literal union). The values are identical at runtime.\n chain: params.chain as unknown as ChainEnum,\n environmentId: core.environmentId,\n ...(params.networkId ? { networkId: params.networkId } : {}),\n });\n\n return response.currencies ?? [];\n};\n","import { BaseError } from '../../../../errors/base';\n\nexport class MoonPayInvalidUrlError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'moonpay_invalid_url_error',\n docsUrl: null,\n name: 'MoonPayInvalidUrlError',\n shortMessage:\n 'MoonPay is configured but returned an invalid or untrusted URL. This may indicate a misconfiguration — please contact support if the issue persists.',\n });\n }\n}\n","import { BaseError } from '../../../../errors/base';\n\nexport class MoonPayProviderNotAvailableError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'moonpay_provider_not_available_error',\n docsUrl: null,\n name: 'MoonPayProviderNotAvailableError',\n shortMessage:\n 'MoonPay provider not available. Ensure MoonPay is enabled and a publishable API key is configured in the Dynamic dashboard.',\n });\n }\n}\n","import { ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport { MoonPayInvalidUrlError } from '../errors/MoonPayInvalidUrlError';\nimport { MoonPayProviderNotAvailableError } from '../errors/MoonPayProviderNotAvailableError';\nimport type { GetMoonPayUrlParams } from '../moonpay.types';\n\n/**\n * Returns the signed MoonPay URL for the given wallet and token.\n *\n * Uses the Dynamic onramp API to retrieve the pre-signed URL that can be\n * opened in a browser tab to allow the user to purchase crypto via MoonPay.\n *\n * @param params - Parameters including chain, wallet address, and optional token/currency filters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The signed MoonPay URL.\n * @instrumented\n */\nexport const getMoonPayUrl = async (\n params: GetMoonPayUrlParams,\n client: DynamicClient = getDefaultClient()\n): Promise<string> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getSupportedOnramps({\n chain: params.chain,\n currency: params.currency,\n environmentId: core.environmentId,\n includeDisabled: true,\n merchantName: params.merchantName,\n networkId: params.networkId,\n token: params.token,\n tokenAmount: params.tokenAmount,\n walletAddress: params.walletAddress,\n });\n\n const moonPayProvider = response.onramps?.find(\n (provider) => provider.provider === ProviderEnum.MoonPay\n );\n\n if (!moonPayProvider?.url) {\n throw new MoonPayProviderNotAvailableError();\n }\n\n // Validate scheme and host before returning — the URL is opened in a browser tab\n // and a compromised API response could inject a javascript: URI or phishing URL.\n // Use exact match or dot-prefixed subdomain check to block lookalikes like evilmoonpay.com.\n const parsedUrl = new URL(moonPayProvider.url);\n const isValidHost =\n parsedUrl.hostname === 'moonpay.com' || parsedUrl.hostname.endsWith('.moonpay.com');\n if (parsedUrl.protocol !== 'https:' || !isValidHost) {\n core.logger.error('[getMoonPayUrl] Invalid URL returned by onramp API', {\n url: moonPayProvider.url,\n });\n throw new MoonPayInvalidUrlError();\n }\n\n return moonPayProvider.url;\n};\n","import type { CreateExchangeTransferRequest } from '@dynamic-labs/sdk-api-core';\nimport { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { ExchangeTransferResponse } from '../kraken.types';\n\n// Kraken transfer request includes accountId + transfer parameters\nexport type KrakenTransferRequest = CreateExchangeTransferRequest & {\n /**\n * The Kraken account ID to transfer from (get from getKrakenAccounts)\n * @instrumented\n */\n accountId: string;\n};\n\n/**\n * Creates a Kraken exchange transfer to send crypto from a Kraken account to a whitelisted address\n *\n * @param transferParams - The parameters for the transfer including accountId\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created transfer\n * @not-instrumented\n */\nexport const createKrakenExchangeTransfer = async (\n transferParams: KrakenTransferRequest,\n client = getDefaultClient()\n): Promise<ExchangeTransferResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const { accountId, ...createExchangeTransferRequest } = transferParams;\n\n const response = await apiClient.postExchangeAccountTransfer({\n accountId,\n createExchangeTransferRequest,\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n });\n\n return response;\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\nimport { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { Chain } from '../../../chain';\nimport type { KrakenAccount } from '../kraken.types';\n\nexport type GetKrakenAccountsParams = {\n /**\n * Optional chain filter\n * @not-instrumented\n */\n chainName?: Chain;\n /**\n * Optional network ID filter\n */\n networkId?: number;\n};\n\n/**\n * Gets the Kraken accounts (balances) for the authenticated user\n *\n * @param [params] GetKrakenAccountsParams - Optional filters for the accounts.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Array of Kraken accounts with balances\n * @not-instrumented\n */\nexport const getKrakenAccounts = async (\n params?: GetKrakenAccountsParams,\n client = getDefaultClient()\n): Promise<KrakenAccount[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getUserAccounts({\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params?.chainName as ChainEnum,\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n networkId: params?.networkId,\n });\n\n return response;\n};\n","import { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { TransferDestinationResponse } from '../kraken.types';\n\n/**\n * Gets the whitelisted addresses for Kraken transfers\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Transfer destinations response with whitelisted addresses\n * @not-instrumented\n */\nexport const getKrakenWhitelistedAddresses = async (\n client = getDefaultClient()\n): Promise<TransferDestinationResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getExchangeTransferDestinations({\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n });\n\n return response;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\n\n/**\n * Allows waiting until all modules of the client have been properly initialized\n * and are ready for use.\n *\n * @returns a promise that resolves once the client is fully initialized.\n * @not-instrumented\n */\nexport const waitForClientInitialized = async (client = getDefaultClient()) => {\n const core = getCore(client);\n\n await core.initTrack.waitForAll();\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\n\nexport type SetInstrumentationEnabledOptions = {\n /** Whether event collection should be active. */\n enabled: boolean;\n};\n\n/**\n * Enables or disables event collection for the client's instrumentation service.\n *\n * When enabled, events are forwarded to the configured transport on every\n * instrumented function call. When disabled, instrumented functions run\n * normally but emit no telemetry.\n * @instrumented\n */\nexport const setInstrumentationEnabled = (\n { enabled }: SetInstrumentationEnabledOptions,\n client: DynamicClient = getDefaultClient()\n) => {\n getCore(client).instrumentation.setEnabled(enabled);\n};\n","/**\n * Default CDN URL for the wallet book.\n * @not-instrumented\n */\nconst DEFAULT_WALLET_BOOK_CDN_URL =\n 'https://dynamic-static-assets.com/wallet-book/v1/stable/wallet-book.json';\n\n/**\n * Gets the wallet book CDN URL from environment variables with fallback to default.\n *\n * Checks for environment variables in the following order:\n * 1. WALLET_BOOK_CDN_URL\n * 2. NEXT_PUBLIC_WALLET_BOOK_CDN_URL\n * 4. Default CDN URL\n *\n * @returns The wallet book CDN URL to use.\n * @not-instrumented\n */\nexport const getWalletBookCdnUrl = (): string => {\n if (typeof process !== 'undefined' && process.env) {\n const envVar =\n process.env.WALLET_BOOK_CDN_URL ||\n process.env.NEXT_PUBLIC_WALLET_BOOK_CDN_URL;\n\n if (envVar) {\n return envVar;\n }\n }\n\n return DEFAULT_WALLET_BOOK_CDN_URL;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { APIError } from '../../../../errors/APIError';\nimport { getWalletBookCdnUrl } from '../../getWalletBookCdnUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\n\n/**\n * The timeout for each fetch attempt in milliseconds.\n * @not-instrumented\n */\nconst FETCH_TIMEOUT_MS = 30000; // 30 seconds\n\n/**\n * Fetches the wallet book from the CDN endpoint with timeout handling.\n *\n * @param client - The Dynamic client instance.\n * @returns A promise that resolves to the wallet book data.\n * @not-instrumented\n */\nexport const fetchWithTimeout = async (\n client: DynamicClient\n): Promise<WalletBookSchema> => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n const core = getCore(client);\n\n try {\n const response = await core.fetch(getWalletBookCdnUrl(), {\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new APIError(\n `Failed to fetch wallet book: ${response.status} ${response.statusText}`,\n 'wallet_book_fetch_error',\n response.status\n );\n }\n\n const data = (await response.json()) as WalletBookSchema;\n\n return data;\n } finally {\n clearTimeout(timeoutId);\n }\n};\n","import * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../services/storage';\nimport type { WalletBookSchema } from '../legacyWalletBook.types';\n\n/**\n * The schema to store the cached wallet book data.\n */\nexport const walletBookCacheStorageKeySchema = createStorageKeySchema({\n key: 'legacyWalletBookCache',\n schema: z.object({\n groups: z.record(z.string(), z.any()),\n wallets: z.record(z.string(), z.any()),\n }) as z.ZodMiniType<WalletBookSchema>,\n});\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { retryOnFail } from '../../../utils/retryOnFail';\nimport type { WalletBookSchema } from '../legacyWalletBook.types';\nimport { fetchWithTimeout } from './fetchWithTimeout';\nimport { walletBookCacheStorageKeySchema } from './walletBookCacheStorageKeySchema';\n\n/**\n * The maximum number of retry attempts.\n * @not-instrumented\n */\nconst MAX_RETRIES = 3;\n\n/**\n * The delay between retries in milliseconds.\n */\nconst RETRY_DELAY_MS = 100;\n\n/**\n * Fetches the legacy wallet book from Dynamic's CDN endpoint.\n *\n * This function implements a two-tier fallback strategy:\n * 1. Primary: Fetch from CDN endpoint (with retries)\n * 2. Secondary: Use cached version from localStorage if available\n *\n * @param client - The Dynamic client instance.\n * @returns A promise that resolves to the wallet book data.\n * @throws If both CDN fetch and cache retrieval fail.\n * @not-instrumented\n */\nexport const fetchLegacyWalletBook = async (\n client: DynamicClient\n): Promise<WalletBookSchema> => {\n const core = getCore(client);\n\n core.logger.debug('[fetchLegacyWalletBook] Fetching wallet book...');\n\n // Try to fetch from CDN with retry logic\n try {\n const walletBook = await retryOnFail({\n delay: RETRY_DELAY_MS,\n fn: async () => fetchWithTimeout(client),\n maxRetries: MAX_RETRIES,\n });\n\n await core.storage.setItem(walletBookCacheStorageKeySchema, walletBook);\n\n core.logger.debug(\n '[fetchLegacyWalletBook] Successfully fetched wallet book from CDN'\n );\n\n return walletBook;\n } catch (error) {\n core.logger.debug(\n '[fetchLegacyWalletBook] Failed to fetch from CDN, trying cache...',\n error\n );\n\n // Try to get from cache\n const cachedWalletBook = await core.storage.getItem(\n walletBookCacheStorageKeySchema\n );\n\n if (cachedWalletBook) {\n core.logger.debug('[fetchLegacyWalletBook] Using cached wallet book');\n\n return cachedWalletBook as WalletBookSchema;\n }\n\n // If both CDN and cache fail, throw the original error\n core.logger.debug(\n '[fetchLegacyWalletBook] Failed to fetch from CDN and no cache available'\n );\n\n throw error;\n }\n};\n","import type { WalletSchema } from '../legacyWalletBook.types';\n\n/**\n * Embedded wallet keys that should be filtered out from any external-wallet\n * catalogue. These wallets are not products the user \"connects\" to from the\n * wallet selection list — they are embedded sign-in methods that live behind\n * different SDK entry points.\n * @not-instrumented\n */\nexport const EMBEDDED_WALLET_KEYS = [\n 'magicemailotp',\n 'magiclink',\n 'magicsocial',\n 'turnkey',\n 'turnkeyhd',\n 'zerodev',\n 'dynamicwaas',\n 'coinbasempc',\n 'mpcvault',\n 'mpcwallet',\n];\n\nexport type ShouldFilterWalletParams = {\n /** The wallet schema to check. */\n wallet: WalletSchema;\n\n /** The wallet key identifier. */\n walletKey: string;\n};\n\n/**\n * Generic \"is this wallet eligible for an external-wallet catalogue\" check.\n * Filters out:\n *\n * 1. Embedded sign-in methods (see {@link EMBEDDED_WALLET_KEYS}).\n * 2. Wallets that only ship a browser-extension injection (`injectedConfig`)\n * with no mobile or desktop links — these have no surface a customer\n * catalogue UI can drive to.\n *\n * Channel-specific eligibility (WalletConnect support, in-app browser URL,\n * installation links, …) is the caller's responsibility — wrap this helper\n * with an additional check, e.g.\n * {@link shouldFilterWalletForWalletConnect}.\n *\n * @returns True if the wallet should be filtered out, false otherwise.\n * @not-instrumented\n */\nexport const shouldFilterWallet = ({\n wallet,\n walletKey,\n}: ShouldFilterWalletParams): boolean => {\n if (EMBEDDED_WALLET_KEYS.includes(walletKey)) {\n return true;\n }\n\n const hasInjectedConfig =\n wallet.injectedConfig && wallet.injectedConfig.length > 0;\n const hasMobileLinks = Boolean(\n wallet.mobile?.androidId ||\n wallet.mobile?.iosId ||\n wallet.mobile?.native ||\n wallet.mobile?.universal\n );\n const hasDesktopLinks = Boolean(\n wallet.desktop?.chromeId ||\n wallet.desktop?.edgeId ||\n wallet.desktop?.firefoxId ||\n wallet.desktop?.operaId ||\n wallet.desktop?.safariId ||\n wallet.desktop?.universal\n );\n\n return Boolean(hasInjectedConfig && !hasMobileLinks && !hasDesktopLinks);\n};\n","import { shouldFilterWallet } from '../../shouldFilterWallet/shouldFilterWallet';\nimport type { ShouldFilterWalletParams } from '../../shouldFilterWallet/shouldFilterWallet';\n\n/**\n * WalletConnect-specific filter. Applies the generic\n * {@link shouldFilterWallet} eligibility rules and additionally drops\n * wallets that do not advertise WalletConnect `sign_v2` support — the\n * protocol version Dynamic pairs against.\n *\n * @returns True if the wallet should be excluded from the WalletConnect\n * catalog, false otherwise.\n * @not-instrumented\n */\nexport const shouldFilterWalletForWalletConnect = ({\n wallet,\n walletKey,\n}: ShouldFilterWalletParams): boolean => {\n if (shouldFilterWallet({ wallet, walletKey })) {\n return true;\n }\n\n return !wallet.walletConnect?.sdks.includes('sign_v2');\n};\n","import { DYNAMIC_ICONIC_SPRITE_URL } from '../../../constants';\n\ntype GetSpriteUrlParams = {\n spriteId: string;\n};\n\n/**\n * Gets the sprite URL for a given sprite ID.\n *\n * @param params.spriteId - The sprite identifier from the wallet book.\n * @returns The full URL to the sprite icon\n * @not-instrumented\n */\nexport const getSpriteUrl = ({ spriteId }: GetSpriteUrlParams): string =>\n `${DYNAMIC_ICONIC_SPRITE_URL}#${spriteId}`;\n","import { getSpriteUrl } from '../../getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport type { WalletConnectCatalogGroup } from '../getWalletConnectCatalog.types';\n\ntype TransformGroupParams = {\n group: WalletBookSchema['groups'][string];\n};\n\n/**\n * Transforms a wallet group schema into a WalletConnect catalog group.\n * @not-instrumented\n */\nexport const transformGroup = ({\n group,\n}: TransformGroupParams): WalletConnectCatalogGroup => {\n const spriteId = group.brand?.spriteId ?? '';\n\n return {\n key: group.key,\n name: group.name,\n primaryColor: group.brand?.primaryColor,\n spriteUrl: spriteId ? getSpriteUrl({ spriteId }) : '',\n };\n};\n","import type { Chain } from '../../modules/chain';\nimport { CHAINS_INFO_MAP } from '../../modules/wallets/constants';\n\ntype GetChainFromWalletBookIdentifierParams = {\n identifier: string;\n};\n\n/**\n * Resolves a wallet-book chain identifier (as found in\n * `injectedConfig[].chain` or as an alias embedded in a wallet key) to a\n * {@link Chain}. Looks up by `apiChainName` first, then by any\n * `legacyWalletBookAliases` declared on the corresponding `CHAINS_INFO_MAP`\n * entry.\n *\n * Returns `undefined` when the identifier doesn't match any known chain,\n * letting the caller pick its own fallback (e.g. defaulting to EVM, or\n * trying a different lookup strategy).\n *\n * Centralised here rather than in `legacyWalletBook` so all chain naming\n * knowledge stays alongside `CHAINS_INFO_MAP`.\n * @not-instrumented\n */\nexport const getChainFromWalletBookIdentifier = ({\n identifier,\n}: GetChainFromWalletBookIdentifierParams): Chain | undefined => {\n const normalised = identifier.toLowerCase();\n const chains = Object.keys(CHAINS_INFO_MAP) as Chain[];\n\n return chains.find((chain) => {\n const info = CHAINS_INFO_MAP[chain];\n\n return (\n info.apiChainName === normalised ||\n info.legacyWalletBookAliases?.includes(normalised) === true\n );\n });\n};\n","import type { Chain } from '../../../chain';\nimport { getChainFromVerifiedCredentialChain } from '../../../../utils/getChainFromVerifiedCredentialChain';\nimport { getChainFromWalletBookIdentifier } from '../../../../utils/getChainFromWalletBookIdentifier';\nimport { CHAINS_INFO_MAP } from '../../../wallets/constants';\nimport type { WalletSchema } from '../../legacyWalletBook.types';\n\ntype ExtractChainPrefixParams = {\n chainIdentifier: string;\n};\n\n/**\n * Extracts the chain prefix from a chain identifier string.\n * For example, \"eip155:1\" -> \"eip155\", \"solana:...\" -> \"solana\"\n *\n * Exported so {@link getChainsFromWalletSchema} can apply the same\n * parsing to its multi-chain pass without duplicating the logic.\n * @not-instrumented\n */\nexport const extractChainPrefix = ({\n chainIdentifier,\n}: ExtractChainPrefixParams): string => {\n const colonIndex = chainIdentifier.indexOf(':');\n\n if (colonIndex === -1) {\n return chainIdentifier;\n }\n\n return chainIdentifier.substring(0, colonIndex);\n};\n\ntype GetChainFromWalletKeyParams = {\n walletKey: string;\n};\n\n/**\n * Attempts to extract the chain from a wallet key by looking for embedded\n * chain identifiers (apiChainName + legacyWalletBookAliases from CHAINS_INFO_MAP).\n *\n * Derives patterns dynamically so adding a chain in `CHAINS_INFO_MAP`\n * picks it up here — no parallel hardcoded list.\n *\n * @param params.walletKey - The wallet key identifier.\n * @returns The chain type if found, undefined otherwise.\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nconst getChainFromWalletKey = ({\n walletKey,\n}: GetChainFromWalletKeyParams): Chain | undefined => {\n const lowerKey = walletKey.toLowerCase();\n const chains = Object.keys(CHAINS_INFO_MAP) as Chain[];\n\n for (const chain of chains) {\n const info = CHAINS_INFO_MAP[chain];\n const patterns = [info.apiChainName, ...(info.legacyWalletBookAliases ?? [])];\n\n if (patterns.some((pattern) => lowerKey.includes(pattern))) {\n return chain;\n }\n }\n\n return undefined;\n};\n\ntype GetChainFromWalletSchemaParams = {\n wallet: WalletSchema;\n walletKey?: string;\n};\n\n/**\n * Gets the chain from a wallet book entry.\n * Checks injectedConfig first, then falls back to the chains array, then the wallet key.\n * If no chain can be determined, defaults to EVM.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @param params.walletKey - The wallet key identifier (optional, used as last resort fallback).\n * @returns The chain type, defaults to EVM if no chain can be determined.\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const getChainFromWalletSchema = ({\n wallet,\n walletKey,\n}: GetChainFromWalletSchemaParams): Chain => {\n // First, check injectedConfig for the chain field\n if (wallet.injectedConfig && wallet.injectedConfig.length > 0) {\n const injectedChain = wallet.injectedConfig[0].chain;\n\n if (injectedChain) {\n const chain = getChainFromWalletBookIdentifier({\n identifier: injectedChain,\n });\n\n if (chain) {\n return chain;\n }\n }\n }\n\n // Fall back to checking the chains array\n if (wallet.chains && wallet.chains.length > 0) {\n const firstChain = wallet.chains[0];\n const chainPrefix = extractChainPrefix({ chainIdentifier: firstChain });\n\n try {\n return getChainFromVerifiedCredentialChain(chainPrefix);\n } catch {\n // If the chain prefix is not recognized, fall back to wallet key check\n }\n }\n\n // Last resort: try to extract chain from wallet key\n if (walletKey) {\n const chainFromKey = getChainFromWalletKey({ walletKey });\n\n if (chainFromKey) {\n return chainFromKey;\n }\n }\n\n // Default to EVM if no chain can be determined\n return 'EVM';\n};\n","import { getSpriteUrl } from '../../getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport { getChainFromWalletSchema } from '../getChainFromWalletSchema';\nimport type { WalletConnectCatalogWallet } from '../getWalletConnectCatalog.types';\n\ntype TransformWalletParams = {\n wallet: WalletBookSchema['wallets'][string];\n walletKey: string;\n};\n\n/**\n * Transforms a wallet schema into a WalletConnect catalog wallet entry.\n * @not-instrumented\n */\nexport const transformWallet = ({\n wallet,\n walletKey,\n}: TransformWalletParams): WalletConnectCatalogWallet => {\n const spriteId = wallet.brand?.spriteId ?? '';\n\n const androidId = wallet.mobile?.androidId;\n const iosId = wallet.mobile?.iosId;\n\n return {\n chain: getChainFromWalletSchema({ wallet, walletKey }),\n deeplinks: {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n },\n downloadLinks: {\n androidUrl: androidId\n ? `https://play.google.com/store/apps/details?id=${androidId}`\n : undefined,\n iosUrl: iosId ? `https://apps.apple.com/app/${iosId}` : undefined,\n },\n groupId: wallet.group,\n name: wallet.name,\n primaryColor: wallet.brand?.primaryColor,\n spriteUrl: spriteId ? getSpriteUrl({ spriteId }) : '',\n };\n};\n","import type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport type {\n WalletConnectCatalog,\n WalletConnectCatalogGroup,\n WalletConnectCatalogWallet,\n} from '../getWalletConnectCatalog.types';\nimport { shouldFilterWalletForWalletConnect } from '../shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect';\nimport { transformGroup } from '../transformGroup';\nimport { transformWallet } from '../transformWallet';\n\ntype TransformWalletBookParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Transforms the legacy wallet book into a WalletConnect catalog structure.\n * Filters out embedded wallets and injected-only wallets.\n * @not-instrumented\n */\nexport const transformWalletBook = ({\n walletBook,\n}: TransformWalletBookParams): WalletConnectCatalog => {\n const groups: Record<string, WalletConnectCatalogGroup> = {};\n\n for (const [groupKey, group] of Object.entries(walletBook.groups)) {\n groups[groupKey] = transformGroup({ group });\n }\n\n const wallets: Record<string, WalletConnectCatalogWallet> = {};\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWalletForWalletConnect({ wallet, walletKey })) {\n continue;\n }\n\n wallets[walletKey] = transformWallet({ wallet, walletKey });\n }\n\n return { groups, wallets };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { fetchLegacyWalletBook } from '../fetchLegacyWalletBook';\nimport type { WalletConnectCatalog } from './getWalletConnectCatalog.types';\nimport { transformWalletBook } from './transformWalletBook';\n\n/**\n * Retrieves the WalletConnect catalog from Dynamic's wallet book.\n *\n * This function fetches the wallet book and returns a WalletConnect catalog structure\n * that can be used for displaying wallet information and performing deep links for mobile wallet connections.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the WalletConnect catalog containing groups and wallets.\n * @throws If unable to fetch the wallet book from the API (when both CDN fetch and cache retrieval fail).\n * @not-instrumented\n */\nexport const getWalletConnectCatalog = async (\n client = getDefaultClient()\n): Promise<WalletConnectCatalog> => {\n const walletBook = await fetchLegacyWalletBook(client);\n\n return transformWalletBook({ walletBook });\n};\n","import type { WalletProviderData } from '../../wallets/walletProvider/walletProvider.types';\n\ntype MatchWalletProvidersToCatalogGroupParams = {\n catalogGroupKey: string;\n catalogGroupName?: string;\n walletProviders: WalletProviderData[];\n};\n\nconst normalize = (value: string): string =>\n value.toLowerCase().replace(/\\s+/g, '').replace(/wallet/g, '');\n\n/**\n * Returns the wallet providers that belong to the same wallet group as the\n * given WalletConnect catalog entry. Useful for de-duplicating \"installed\"\n * vs \"available via WalletConnect\" wallets when rendering a combined list.\n *\n * Matching is done on normalized identifiers — lowercased, whitespace removed,\n * and the literal substring \"wallet\" stripped — so that variations like:\n * - catalog key `\"trust\"` + catalog name `\"Trust Wallet\"`\n * - provider `groupKey: \"trustwallet\"` + `displayName: \"Trust Wallet\"`\n * collapse into a single match.\n *\n * @param params.catalogGroupKey - Key of the catalog group (e.g. `\"metamask\"`).\n * @param [params.catalogGroupName] - Optional display name (e.g. `\"Trust Wallet\"`); matched as a fallback when the key is opaque.\n * @param params.walletProviders - Currently available wallet providers (from `getAvailableWalletProvidersData`).\n * @returns The subset of `walletProviders` that match the catalog group.\n * @not-instrumented\n */\nexport const matchWalletProvidersToCatalogGroup = ({\n catalogGroupKey,\n catalogGroupName,\n walletProviders,\n}: MatchWalletProvidersToCatalogGroupParams): WalletProviderData[] => {\n const targets = new Set<string>([normalize(catalogGroupKey)]);\n if (catalogGroupName) targets.add(normalize(catalogGroupName));\n\n return walletProviders.filter((provider) => {\n const candidates = [\n normalize(provider.groupKey),\n normalize(provider.metadata.displayName),\n ];\n return candidates.some((candidate) => targets.has(candidate));\n });\n};\n","import type { WalletProviderData } from '../../../wallets/walletProvider/walletProvider.types';\nimport type { WalletConnectCatalog } from '../../getWalletConnectCatalog/getWalletConnectCatalog.types';\nimport { matchWalletProvidersToCatalogGroup } from '../../matchWalletProvidersToCatalogGroup';\n\ntype CollectInstalledGroupIdsParams = {\n catalog: WalletConnectCatalog;\n walletProviders: WalletProviderData[];\n};\n\n/**\n * Scans the catalog and returns the set of group identifiers for which at\n * least one installed wallet provider matches.\n *\n * Walks the catalog twice on purpose:\n * - First through `wallets`, to cover wallets that point to a `groupId`\n * with no matching entry in `groups` (we fall back to the wallet's own\n * name for matching in that case).\n * - Then through `groups`, to catch orphan group entries that have no\n * wallet referencing them.\n *\n * The check is skipped for any group already known to be installed, so a\n * multi-chain wallet (same `groupId` across EVM + SOL entries) only runs\n * the match once.\n *\n * @not-instrumented\n */\nexport const collectInstalledGroupIds = ({\n catalog,\n walletProviders,\n}: CollectInstalledGroupIdsParams): Set<string> => {\n const installedGroupIds = new Set<string>();\n\n // First pass: iterate wallets so we can use each wallet's own `name` as a\n // fallback when its group has no metadata entry in `catalog.groups`.\n for (const [walletKey, wallet] of Object.entries(catalog.wallets)) {\n const groupId = wallet.groupId || walletKey;\n if (installedGroupIds.has(groupId)) continue;\n\n const groupName = catalog.groups[groupId]?.name || wallet.name;\n\n const matches = matchWalletProvidersToCatalogGroup({\n catalogGroupKey: groupId,\n catalogGroupName: groupName,\n walletProviders,\n });\n\n if (matches.length > 0) installedGroupIds.add(groupId);\n }\n\n // Second pass: pick up groups that exist in `catalog.groups` but are not\n // referenced by any wallet (e.g. brand-only entries).\n for (const [groupKey, group] of Object.entries(catalog.groups)) {\n if (installedGroupIds.has(groupKey)) continue;\n\n const matches = matchWalletProvidersToCatalogGroup({\n catalogGroupKey: groupKey,\n catalogGroupName: group.name,\n walletProviders,\n });\n\n if (matches.length > 0) installedGroupIds.add(groupKey);\n }\n\n return installedGroupIds;\n};\n","import type { WalletProviderData } from '../../wallets/walletProvider/walletProvider.types';\nimport type { WalletConnectCatalog } from '../getWalletConnectCatalog/getWalletConnectCatalog.types';\nimport { collectInstalledGroupIds } from './collectInstalledGroupIds';\n\ntype ExcludeInstalledFromCatalogParams = {\n catalog: WalletConnectCatalog;\n walletProviders: WalletProviderData[];\n};\n\n/**\n * Returns a new WalletConnect catalog with the wallets and groups that the\n * user already has installed removed.\n *\n * Useful when rendering a combined wallet list (installed + WalletConnect\n * catalog) where each wallet should appear exactly once: installed wallets\n * win and the corresponding catalog entries get hidden.\n *\n * Matching is delegated to {@link collectInstalledGroupIds}, so a single\n * installed provider removes every wallet that shares its group — e.g. an\n * installed MetaMask hides both the EVM and SOL catalog entries.\n *\n * The original catalog object is not mutated.\n *\n * @param params.catalog - The full WalletConnect catalog (typically from `getWalletConnectCatalog`).\n * @param params.walletProviders - Currently available wallet providers.\n * @returns A new catalog with only the wallets and groups the user does not have installed.\n * @not-instrumented\n */\nexport const excludeInstalledFromCatalog = ({\n catalog,\n walletProviders,\n}: ExcludeInstalledFromCatalogParams): WalletConnectCatalog => {\n // Step 1: figure out which catalog groups the user already has installed.\n // We compute this up front so filtering wallets and groups below is a\n // simple set lookup per entry.\n const installedGroupIds = collectInstalledGroupIds({\n catalog,\n walletProviders,\n });\n\n // Step 2: keep only wallets whose effective group id is not installed.\n // Wallets without an explicit `groupId` are treated as their own group,\n // which mirrors how the catalog itself associates wallets to groups.\n const wallets: WalletConnectCatalog['wallets'] = {};\n for (const [walletKey, wallet] of Object.entries(catalog.wallets)) {\n const groupId = wallet.groupId || walletKey;\n if (installedGroupIds.has(groupId)) continue;\n wallets[walletKey] = wallet;\n }\n\n // Step 3: keep only group metadata entries that are not installed. This\n // prevents the caller from rendering an empty/orphan group with no\n // wallets behind it.\n const groups: WalletConnectCatalog['groups'] = {};\n for (const [groupKey, group] of Object.entries(catalog.groups)) {\n if (installedGroupIds.has(groupKey)) continue;\n groups[groupKey] = group;\n }\n\n return { groups, wallets };\n};\n","import type { Chain } from '../../../chain';\nimport { CHAINS_INFO_MAP } from '../../constants';\n\ntype ExtractChainFromNormalizedNameParams = {\n normalizedWalletNameWithChain: string;\n};\n\n/**\n * Extracts the chain from a normalized wallet name with chain suffix.\n * The chain is appended in lowercase at the end (e.g., \"metamaskevm\" -> \"EVM\").\n *\n * @param params.normalizedWalletNameWithChain - The normalized wallet name with chain suffix.\n * @returns The chain if found, undefined otherwise.\n * @not-instrumented\n */\nexport const extractChainFromNormalizedName = ({\n normalizedWalletNameWithChain,\n}: ExtractChainFromNormalizedNameParams): Chain | undefined => {\n const lowerName = normalizedWalletNameWithChain.toLowerCase();\n\n // Get all chain names in lowercase, sorted by length (longest first) to match longest suffix first\n const chainSuffixes = (Object.keys(CHAINS_INFO_MAP) as Chain[])\n .map((chain) => chain.toLowerCase())\n .sort((a, b) => b.length - a.length);\n\n for (const suffix of chainSuffixes) {\n if (lowerName.endsWith(suffix)) {\n return suffix.toUpperCase() as Chain;\n }\n }\n\n return undefined;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { extractChainFromNormalizedName } from '../../wallets/walletProvider/extractChainFromNormalizedName';\nimport { splitWalletProviderKey } from '../../wallets/walletProvider/splitWalletProviderKey';\nimport { getWalletConnectCatalog } from '../getWalletConnectCatalog';\nimport type { WalletConnectCatalogWallet } from '../getWalletConnectCatalog/getWalletConnectCatalog.types';\n\ntype GetWalletConnectCatalogWalletByWalletProviderKeyParams = {\n walletProviderKey: string;\n};\n\n/**\n * Gets the WalletConnect catalog wallet entry for a given wallet provider key.\n *\n * This function extracts the wallet name and chain from the wallet provider key and matches it\n * against the WalletConnect catalog to find the corresponding wallet entry, which includes\n * deep link information for mobile wallet connections.\n *\n * @param params.walletProviderKey - The wallet provider key to get the catalog wallet entry for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the WalletConnect catalog wallet entry, or undefined if not found.\n * @not-instrumented\n */\nexport const getWalletConnectCatalogWalletByWalletProviderKey = async (\n { walletProviderKey }: GetWalletConnectCatalogWalletByWalletProviderKeyParams,\n client = getDefaultClient()\n): Promise<WalletConnectCatalogWallet | undefined> => {\n const { normalizedWalletNameWithChain } =\n splitWalletProviderKey(walletProviderKey);\n\n const chain = extractChainFromNormalizedName({\n normalizedWalletNameWithChain,\n });\n\n if (!chain) {\n return undefined;\n }\n\n // Remove chain suffix from wallet name (e.g., \"metamaskevm\" -> \"metamask\")\n let walletProviderName = normalizedWalletNameWithChain.toLowerCase();\n\n if (walletProviderName.endsWith(chain.toLowerCase())) {\n walletProviderName = walletProviderName.slice(0, -chain.length);\n }\n\n // Remove \"wallet\" substring (e.g., \"trustwallet\" -> \"trust\", \"okxwallet\" -> \"okx\")\n walletProviderName = walletProviderName.replace(/wallet/g, '');\n\n const walletConnectCatalog = await getWalletConnectCatalog(client);\n\n for (const [walletKey, wallet] of Object.entries(\n walletConnectCatalog.wallets\n )) {\n if (wallet.chain !== chain) {\n continue;\n }\n\n const walletKeyLower = walletKey.toLowerCase();\n const walletNameLower = wallet.name.toLowerCase().replace(/\\s+/g, '');\n\n if (\n walletKeyLower.includes(walletProviderName) ||\n walletNameLower.includes(walletProviderName)\n ) {\n return wallet;\n }\n }\n\n return undefined;\n};\n","/* eslint-disable no-useless-escape */\n/* eslint-disable no-restricted-globals */\n/**\n * Sourced from http://detectmobilebrowsers.com/\n * @not-instrumented\n */\n\nconst userAgentRegex1 =\n /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ios|ipad|playbook|silk/i;\n\nconst userAgentRegex2 =\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i;\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const isMobile = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return (\n userAgentRegex1.test(navigator.userAgent) ||\n userAgentRegex2.test(navigator.userAgent.substring(0, 4)) ||\n isIPad(maxTouchPointsOverride) ||\n isIPhone()\n );\n};\n\n/** @not-instrumented */\n \nexport const isIPhone = () =>\n typeof window === 'undefined' || typeof navigator === 'undefined'\n ? false\n : /iPhone|ios/.test(navigator.userAgent);\n\n/** @not-instrumented */\n \nexport const isIPhone8OrEarlier = () =>\n typeof window === 'undefined' || typeof navigator === 'undefined'\n ? false\n : iPhoneLegacyRegex.some(({ regex }) => regex.test(navigator.userAgent));\n\n/**\n * @param [optional] maxTouchPointsOverride - this is used for testing since\n * it seems that JSDOM doesn't support maxTouchPoints, so it was impossible\n * to mock it\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file, custom-rules/require-single-object-param\nexport const isIPad = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n const maxTouchPoints = maxTouchPointsOverride || navigator.maxTouchPoints;\n\n return (\n /iPad/.test(navigator.userAgent) ||\n (/Mac/.test(navigator.userAgent) && maxTouchPoints === 5)\n );\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file, custom-rules/require-single-object-param\nexport const isIOS = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return isIPhone() || isIPad(maxTouchPointsOverride);\n};\n\n/** @not-instrumented */\n \nexport const isAndroid = () => isMobile() && !isIOS();\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isLegacySafari = () => {\n // We need to check if window.CSS exists and if it has supports function.\n // We can use it only in browsers. This prevents customer tests from failing because of that.\n if (\n typeof window === 'undefined' ||\n !window.CSS ||\n typeof window.CSS.supports !== 'function'\n ) {\n return false;\n }\n\n // Older versions of Safari <15 are not supporting aspect-ratio css property.\n // We can use that to check if user is on older browser.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio\n const cssValue = 'aspect-ratio: 1 / 1';\n\n return !CSS.supports(cssValue);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isSamsungBrowser = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return navigator.userAgent.includes('SamsungBrowser');\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isSafariBrowser = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n const { userAgent } = navigator;\n\n const isSafari =\n userAgent.includes('Safari') &&\n !userAgent.includes('Chrome') &&\n !userAgent.includes('Chromium');\n\n return isSafari;\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isEdgeBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\bEdg\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isOperaBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\b(OPR|Opera)\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isFirefoxBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\bFirefox\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isChromeBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n // Chromium-based browsers (Edge, Opera, Brave, ...) all carry \"Chrome\"\n // in their UA, so the more specific brands must be excluded here.\n return (\n /\\bChrome\\//.test(navigator.userAgent) &&\n !isEdgeBrowser() &&\n !isOperaBrowser()\n );\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isWindows = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return navigator.userAgent.indexOf('Windows') !== -1;\n};\n\n// regex from: https://github.com/matomo-org/device-detector/blob/master/regexes/device/mobiles.yml\nconst iPhoneLegacyRegex = [\n {\n model: 'iPhone 5',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?5[C,_]12|5)$/,\n },\n {\n model: 'iPhone 5C',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?5[C,_]34)$/,\n },\n {\n model: 'iPhone 5S',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?6[C,_]12|5S)$/,\n },\n {\n model: 'iPhone 6 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?7[C,_]1|1C2%257enohPi|6PLUS)$/,\n },\n {\n model: 'iPhone 6',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?7[C,_]2|6)$/,\n },\n {\n model: 'iPhone 6s Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]2|6SPLUS)$/,\n },\n {\n model: 'iPhone 6s',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]1|iPhone[ /]6s|6S)$/,\n },\n {\n model: 'iPhone SE',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]4|SE)$/,\n },\n {\n model: 'iPhone 7',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?9[C,_]13|iphone7|7)$/,\n },\n {\n model: 'iPhone 7 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?9[C,_]24|7PLUS)$/,\n },\n {\n model: 'iPhone 8',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?10[C,_]14|8)$/,\n },\n {\n model: 'iPhone 8 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?10[C,_]25|8PLUS)$/,\n },\n];\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const getAndroidVersion = () => {\n if (typeof navigator === 'undefined') {\n return;\n }\n\n const androidVersionMatch = navigator.userAgent.match(\n /Android (\\d+(\\.\\d+)?)/\n );\n\n if (!androidVersionMatch) {\n return;\n }\n\n const androidVersion = parseFloat(androidVersionMatch[1]);\n\n return androidVersion;\n};\n","import {\n isAndroid,\n isChromeBrowser,\n isEdgeBrowser,\n isFirefoxBrowser,\n isIOS,\n isOperaBrowser,\n isSafariBrowser,\n} from '../../../utils/isMobile/isMobile';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\ntype GetInstallationLinkForCurrentPlatformParams = {\n installationUrls: InstallationUrls;\n};\n\n/**\n * Resolves the {@link InstallationUrls} field that matches the platform\n * the SDK is currently running on:\n *\n * - iOS → `ios`\n * - Android → `android`\n * - Edge → `edge`\n * - Opera → `opera`\n * - Firefox → `firefox`\n * - Safari → `safari`\n * - Chrome (or other Chromium-based browsers) → `chrome`\n *\n * Returns `undefined` when no entry exists for the detected platform —\n * callers typically render a \"not available on this device\" affordance\n * in that case rather than offering a download targeted at a different\n * browser/OS.\n *\n * Each branch returns exactly the field for the detected platform — no\n * fallback to a different browser's URL. If you'd rather surface every\n * link a wallet's manifest publishes so the user can pick where to\n * install, read `installationUrls` directly instead of going through\n * this helper.\n *\n * @param params.installationUrls - The wallet option's `installationUrls`\n * record (from `getWalletOptionsCatalogue`).\n * @returns The install URL for the detected platform, or `undefined`.\n * @not-instrumented\n */\nexport const getInstallationLinkForCurrentPlatform = ({\n installationUrls,\n}: GetInstallationLinkForCurrentPlatformParams): string | undefined => {\n if (isIOS()) return installationUrls.ios;\n if (isAndroid()) return installationUrls.android;\n if (isEdgeBrowser()) return installationUrls.edge;\n if (isOperaBrowser()) return installationUrls.opera;\n if (isFirefoxBrowser()) return installationUrls.firefox;\n if (isSafariBrowser()) return installationUrls.safari;\n if (isChromeBrowser()) return installationUrls.chrome;\n return undefined;\n};\n","import type { WalletSchema } from '../../legacyWalletBook/legacyWalletBook.types';\n\ntype ResolveWalletBookWalletOptionKeyParams = {\n wallet: WalletSchema;\n walletKey: string;\n};\n\n/**\n * Resolves which wallet option (group) a wallet book entry belongs to. Used\n * by the catalogue's wallet-book-driven transformers (URI deeplink,\n * `inAppBrowser`, `installation`) to bucket their emitted options.\n *\n * Wallet book entries inconsistently use `group` / `chainGroup` /\n * `walletGroup` for the same idea. The wallet key itself acts as the wallet\n * option key when no group field is set.\n *\n * @param params.wallet - The wallet entry.\n * @param params.walletKey - The wallet's key in `walletBook.wallets`.\n * @returns The wallet option key.\n * @not-instrumented\n */\nexport const resolveWalletBookWalletOptionKey = ({\n wallet,\n walletKey,\n}: ResolveWalletBookWalletOptionKeyParams): string =>\n wallet.group ?? wallet.chainGroup ?? wallet.walletGroup ?? walletKey;\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype GetInAppBrowserUrlParams = {\n wallet: WalletBookSchema['wallets'][string];\n};\n\n/**\n * Returns the wallet's in-app browser URL template, preferring the v2\n * field. `inAppBrowser` is deprecated but some wallet book entries\n * still carry only the v1 value, so it acts as a fallback. Trailing\n * `?? undefined` collapses the schema's `string | null` typing down to\n * the `string | undefined` return contract.\n *\n * @param params.wallet - The wallet book wallet entry.\n * @returns The in-app browser URL, or `undefined` if neither field is set.\n * @not-instrumented\n */\nexport const getInAppBrowserUrl = ({\n wallet,\n}: GetInAppBrowserUrlParams): string | undefined =>\n wallet.mobile?.inAppBrowserV2 ?? wallet.mobile?.inAppBrowser ?? undefined; // NOSONAR\n","import { getChainFromWalletSchema } from '../../legacyWalletBook/getWalletConnectCatalog/getChainFromWalletSchema/getChainFromWalletSchema';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\nimport { getInAppBrowserUrl } from './getInAppBrowserUrl/getInAppBrowserUrl';\n\ntype BuildInAppBrowserOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `inAppBrowser` catalogue options from the wallet book. A wallet\n * qualifies when it exposes a mobile in-app-browser URL — typically a\n * `cb_url={{encodedDappURI}}`-style template the customer fills in with the\n * current page URL before opening.\n *\n * Reuses the generic `shouldFilterWallet` rules — embedded sign-in methods\n * and injected-only wallets are dropped — so the catalogue's notion of\n * \"external wallet\" stays consistent across option types.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `inAppBrowser` options paired with their wallet option keys.\n * @not-instrumented\n */\nexport const buildInAppBrowserOptions = ({\n walletBook,\n}: BuildInAppBrowserOptionsParams): ConnectionOptionForWalletOption[] => {\n const result: ConnectionOptionForWalletOption[] = [];\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n const url = getInAppBrowserUrl({ wallet });\n\n if (!url) {\n continue;\n }\n\n result.push({\n option: {\n chain: getChainFromWalletSchema({ wallet, walletKey }),\n type: 'inAppBrowser',\n url,\n },\n walletOptionKey: resolveWalletBookWalletOptionKey({ wallet, walletKey }),\n });\n }\n\n return result;\n};\n","import type { WalletSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\nconst PLAY_STORE_URL_TEMPLATE =\n 'https://play.google.com/store/apps/details?id=';\nconst APP_STORE_URL_TEMPLATE = 'https://apps.apple.com/app/';\nconst CHROME_WEB_STORE_URL_TEMPLATE =\n 'https://chrome.google.com/webstore/detail/';\nconst FIREFOX_ADDONS_URL_TEMPLATE =\n 'https://addons.mozilla.org/firefox/addon/';\nconst EDGE_ADDONS_URL_TEMPLATE =\n 'https://microsoftedge.microsoft.com/addons/detail/';\n\ntype BuildInstallationUrlsParams = {\n wallet: WalletSchema;\n};\n\n/**\n * Builds the install/download URL bag for a wallet book entry. Returns the\n * concrete URLs assembled from each store's ID field — Play Store, App\n * Store, Chrome Web Store, Firefox Add-ons, Edge Add-ons — plus the wallet's\n * own `desktop.universal` / `desktop.native` URLs when set.\n *\n * Fields the wallet book does not carry are left undefined; callers should\n * skip emitting an installation option for a wallet whose URL bag is empty.\n *\n * @param params.wallet - The wallet book entry.\n * @returns The URL bag, omitting fields the wallet does not provide.\n * @not-instrumented\n */\nexport const buildInstallationUrls = ({\n wallet,\n}: BuildInstallationUrlsParams): InstallationUrls => {\n const androidId = wallet.mobile?.androidId;\n const iosId = wallet.mobile?.iosId;\n const chromeId = wallet.desktop?.chromeId;\n const firefoxId = wallet.desktop?.firefoxId;\n const edgeId = wallet.desktop?.edgeId;\n const native = wallet.desktop?.universal ?? wallet.desktop?.native;\n\n return {\n android: androidId ? `${PLAY_STORE_URL_TEMPLATE}${androidId}` : undefined,\n chrome: chromeId\n ? `${CHROME_WEB_STORE_URL_TEMPLATE}${chromeId}`\n : undefined,\n edge: edgeId ? `${EDGE_ADDONS_URL_TEMPLATE}${edgeId}` : undefined,\n firefox: firefoxId\n ? `${FIREFOX_ADDONS_URL_TEMPLATE}${firefoxId}`\n : undefined,\n ios: iosId ? `${APP_STORE_URL_TEMPLATE}${iosId}` : undefined,\n native: native || undefined,\n };\n};\n","import type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport { buildInstallationUrls } from '../buildInstallationUrls/buildInstallationUrls';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\ntype HasAnyInstallationUrlParams = {\n urls: InstallationUrls;\n};\n\n/**\n * `buildInstallationUrls` always returns an object, but it can be fully\n * `undefined`-valued when the wallet book entry has no installable surface.\n * Skip those wallets — emitting an empty URL bag helps nobody.\n */\nconst hasAnyInstallationUrl = ({ urls }: HasAnyInstallationUrlParams): boolean =>\n Object.values(urls).some(Boolean);\n\ntype BuildInstallationUrlsByWalletOptionKeyParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Collects install / download URLs for every wallet book entry that has\n * at least one installable surface, keyed by the wallet option key the\n * wallet groups under. The catalogue assembly step merges this map into\n * the per-key wallet option shell so `WalletOption.installationUrls` is\n * populated alongside (or instead of) `connectionOptions`.\n *\n * First-seen URLs win when multiple wallet book entries resolve to the\n * same wallet option key — wallet book authors put the most accurate\n * install links on the canonical entry, so the first-seen one is the\n * right pick.\n *\n * Reuses the generic `shouldFilterWallet` rules so embedded wallets do\n * not appear here either — they're not user-installable products.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns A map from wallet option key to its install URL bag.\n * @not-instrumented\n */\nexport const buildInstallationUrlsByWalletOptionKey = ({\n walletBook,\n}: BuildInstallationUrlsByWalletOptionKeyParams): Map<\n string,\n InstallationUrls\n> => {\n const map = new Map<string, InstallationUrls>();\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n const urls = buildInstallationUrls({ wallet });\n\n if (!hasAnyInstallationUrl({ urls })) {\n continue;\n }\n\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n if (!map.has(walletOptionKey)) {\n map.set(walletOptionKey, urls);\n }\n }\n\n return map;\n};\n","import type { WalletSchema } from '../legacyWalletBook.types';\n\ntype HasUsableDeeplinkParams = {\n wallet: WalletSchema;\n};\n\n/**\n * Whether a wallet book entry exposes at least one mobile deeplink the\n * catalogue can drive — either a native scheme (`metamask://`) or a\n * universal link (`https://metamask.app.link`). Used by the URI-deeplink\n * builders (`buildWalletConnectOptions`, `buildMetaMaskSdkUriOptions`)\n * to skip wallets that have no app to launch.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @returns True when the wallet has a native or universal mobile link.\n * @not-instrumented\n */\nexport const hasUsableDeeplink = ({\n wallet,\n}: HasUsableDeeplinkParams): boolean =>\n Boolean(wallet.mobile?.native || wallet.mobile?.universal);\n","import type { Chain } from '../../chain';\nimport { hasUsableDeeplink } from '../../legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\n\n/**\n * Wallet option key the MetaMask SDK URI extension targets.\n */\nconst METAMASK_WALLET_OPTION_KEY = 'metamask';\n\n/**\n * Chains the MetaMask SDK URI pairing supports.\n *\n * Unlike WalletConnect — whose per-wallet chain support is read from the\n * wallet book — the MetaMask SDK URI is a single Dynamic integration whose\n * chain coverage is defined by which `connectWithMetaMaskUri<Chain>`\n * primitives the SDK ships (EVM + SOL). The MetaMask wallet-book entry only\n * advertises its EVM (`eip155`) chains, so deriving the chain from the book\n * would never surface the Solana pairing; the SDK's own capabilities are\n * listed explicitly instead.\n */\nconst METAMASK_SDK_URI_SUPPORTED_CHAINS: readonly Chain[] = ['EVM', 'SOL'];\n\ntype BuildMetaMaskSdkUriOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `metamaskSdkUri`-discriminator catalogue options from a\n * fetched wallet book. The MetaMask SDK URI extension only targets the\n * MetaMask wallet, so the builder iterates the book looking for the\n * entry whose resolved wallet option key is `'metamask'`.\n *\n * Applies the generic `shouldFilterWallet` rules (drops embedded keys +\n * injected-only-without-links entries). Crucially does NOT require WC\n * `sign_v2` support — MetaMask SDK URI is a different protocol from\n * WalletConnect, so the WC-specific filter does not apply here.\n *\n * Emits one `metamaskSdkUri` option per chain the MetaMask SDK URI pairing\n * supports (see {@link METAMASK_SDK_URI_SUPPORTED_CHAINS}) so the picker can\n * offer both the EVM and Solana pairings for the single MetaMask entry.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `metamaskSdkUri` options for MetaMask if eligible, otherwise an empty array.\n * @not-instrumented\n */\nexport const buildMetaMaskSdkUriOptions = ({\n walletBook,\n}: BuildMetaMaskSdkUriOptionsParams): ConnectionOptionForWalletOption[] => {\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n if (walletOptionKey !== METAMASK_WALLET_OPTION_KEY) {\n continue;\n }\n\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n if (!hasUsableDeeplink({ wallet })) {\n continue;\n }\n\n const deeplinks = {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n };\n\n // One option per supported chain so the wallet picker can offer (and\n // chain-switch between) MetaMask's EVM and Solana URI pairings.\n return METAMASK_SDK_URI_SUPPORTED_CHAINS.map((chain) => ({\n option: {\n chain,\n deeplinks,\n type: 'metamaskSdkUri',\n },\n walletOptionKey,\n }));\n }\n\n return [];\n};\n","import { getChainFromVerifiedCredentialChain } from '../../../../utils/getChainFromVerifiedCredentialChain';\nimport { getChainFromWalletBookIdentifier } from '../../../../utils/getChainFromWalletBookIdentifier';\nimport type { Chain } from '../../../chain';\nimport type { WalletSchema } from '../../legacyWalletBook.types';\nimport {\n extractChainPrefix,\n getChainFromWalletSchema,\n} from '../getChainFromWalletSchema/getChainFromWalletSchema';\n\ntype GetChainsFromWalletSchemaParams = {\n wallet: WalletSchema;\n walletKey?: string;\n};\n\n/**\n * Returns every chain a wallet book entry advertises support for —\n * deduped, in `injectedConfig` order, then `chains` order. Used by the\n * catalogue's WalletConnect builder so a multi-chain wallet (e.g. Trust\n * supports EVM + SOL) gets one option per chain rather than one option\n * for whichever chain `getChainFromWalletSchema` happened to pick first.\n *\n * Falls back to {@link getChainFromWalletSchema}'s single-result behavior\n * (`['EVM']` default) when neither field is populated, so the helper\n * never returns an empty array — every eligible wallet emits at least\n * one option.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @param [params.walletKey] - The wallet key identifier (used as last-resort fallback).\n * @returns Ordered, deduped array of Chains.\n * @not-instrumented\n */\nexport const getChainsFromWalletSchema = ({\n wallet,\n walletKey,\n}: GetChainsFromWalletSchemaParams): Chain[] => {\n // Set keeps insertion order, so collect → toArray preserves the\n // injectedConfig-first, chains-second emission order without a parallel\n // dedupe array.\n const chains = new Set<Chain>();\n\n for (const entry of wallet.injectedConfig ?? []) {\n if (!entry.chain) continue;\n\n const chain = getChainFromWalletBookIdentifier({ identifier: entry.chain });\n\n if (chain) chains.add(chain);\n }\n\n for (const identifier of wallet.chains ?? []) {\n const prefix = extractChainPrefix({ chainIdentifier: identifier });\n\n try {\n const chain = getChainFromVerifiedCredentialChain(prefix);\n chains.add(chain);\n } catch {\n // Unknown prefix — skip.\n }\n }\n\n if (chains.size === 0) {\n const chain = getChainFromWalletSchema({ wallet, walletKey });\n chains.add(chain);\n }\n\n return Array.from(chains);\n};\n","import type { Chain } from '../../chain';\nimport { getChainsFromWalletSchema } from '../../legacyWalletBook/getWalletConnectCatalog/getChainsFromWalletSchema/getChainsFromWalletSchema';\nimport { shouldFilterWalletForWalletConnect } from '../../legacyWalletBook/getWalletConnectCatalog/shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect';\nimport { hasUsableDeeplink } from '../../legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\n\n/**\n * Chains Dynamic ships a WalletConnect extension for. Anything else a\n * wallet book entry advertises (Cosmos, BTC, …) gets filtered out — the\n * catalogue should not surface a chain the SDK has no `connectWithWalletConnect<Chain>`\n * primitive for.\n */\nconst WALLETCONNECT_SUPPORTED_CHAINS: ReadonlySet<Chain> = new Set([\n 'EVM',\n 'SOL',\n]);\n\ntype BuildWalletConnectOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `walletConnect`-discriminator catalogue options from a fetched\n * wallet book. Applies the WalletConnect-specific eligibility filter\n * (`shouldFilterWalletForWalletConnect`) so embedded wallets and entries\n * without `sign_v2` support are excluded — same surface as\n * `getWalletConnectCatalog`.\n *\n * Skips the MetaMask wallet entry: MetaMask is steered to its own URI\n * connection extension via `buildMetaMaskSdkUriOptions`. Keeping the two\n * builders separate means each protocol owns its own eligibility rules\n * (WC needs `sign_v2`; MM SDK URI does not), so excluding one\n * discriminator via `excludedConnectionOptionTypes` doesn't accidentally\n * gate the other.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `walletConnect` options paired with their wallet option keys.\n * @not-instrumented\n */\nexport const buildWalletConnectOptions = ({\n walletBook,\n}: BuildWalletConnectOptionsParams): ConnectionOptionForWalletOption[] => {\n const result: ConnectionOptionForWalletOption[] = [];\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWalletForWalletConnect({ wallet, walletKey })) {\n continue;\n }\n\n if (!hasUsableDeeplink({ wallet })) {\n continue;\n }\n\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n // MetaMask is steered to the MetaMask SDK URI builder.\n if (walletOptionKey === 'metamask') {\n continue;\n }\n\n const chains = getChainsFromWalletSchema({ wallet, walletKey }).filter(\n (chain) => WALLETCONNECT_SUPPORTED_CHAINS.has(chain)\n );\n\n for (const chain of chains) {\n result.push({\n option: {\n chain,\n deeplinks: {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n },\n type: 'walletConnect',\n },\n walletOptionKey,\n });\n }\n }\n\n return result;\n};\n","import { getSpriteUrl } from '../../legacyWalletBook/getSpriteUrl/getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { WithWalletProviderDisplayOverride } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport type {\n InstallationUrls,\n WalletConnectionOption,\n WalletOption,\n} from '../walletOptionsCatalogue.types';\n\ntype BuildWalletOptionParams = {\n connectionOptions: WalletConnectionOption[];\n displayOverride?: WithWalletProviderDisplayOverride;\n installationUrls?: InstallationUrls;\n walletBook: WalletBookSchema;\n walletOptionKey: string;\n};\n\n/**\n * Assembles a `WalletOption` for a resolved wallet option key, populated\n * with the connection options the transformers produced for it plus an\n * optional install / download URL bag.\n *\n * Display merge rules (provider self-announced metadata wins where set):\n *\n * - `name`: `displayOverride.name` ?? wallet book group name ?? wallet\n * book wallet name ?? bare key.\n * - `iconUrl`: `displayOverride.iconUrl` ?? wallet book group sprite URL\n * ?? wallet book wallet sprite URL ?? `''`.\n * - `primaryColor`: wallet book group brand color ?? wallet book wallet\n * brand color (providers do not ship a primary color in their\n * announcement metadata).\n * - `installationUrls`: copied through if present.\n *\n * The per-wallet fallback handles wallets that exist as individual entries\n * in the book (e.g. Rainbow) rather than as members of a multi-wallet group\n * — those don't get a `walletBook.groups[…]` shell.\n *\n * Why provider precedence: a registered wallet provider knows its own\n * brand best (EIP-6963 / Wallet Standard / vendor SDK announcement is the\n * wallet authoring its own identity). The wallet book fills in fields the\n * announcement does not carry — currently only `primaryColor`.\n *\n * @param params.connectionOptions - The connections to attach to this wallet option.\n * @param [params.displayOverride] - Provider-announced display info that overrides the wallet book's name and iconUrl.\n * @param [params.installationUrls] - Install/download URL bag for this wallet.\n * @param params.walletBook - The fetched wallet book.\n * @param params.walletOptionKey - The wallet option key.\n * @returns The constructed wallet option.\n * @not-instrumented\n */\nexport const buildWalletOption = ({\n connectionOptions,\n displayOverride,\n installationUrls,\n walletBook,\n walletOptionKey,\n}: BuildWalletOptionParams): WalletOption => {\n const group = walletBook.groups[walletOptionKey];\n const groupSpriteId = group?.brand?.spriteId;\n const groupIconUrl = groupSpriteId\n ? getSpriteUrl({ spriteId: groupSpriteId })\n : undefined;\n\n // Fall back to the wallet entry's own brand when the wallet option key\n // matches an individual wallet (e.g. Rainbow) rather than a multi-wallet\n // group — those entries don't get a `walletBook.groups[…]` shell, so\n // `group.brand` is undefined and we'd otherwise emit an empty iconUrl.\n const walletEntry = walletBook.wallets[walletOptionKey];\n const walletSpriteId = walletEntry?.brand?.spriteId;\n const walletIconUrl = walletSpriteId\n ? getSpriteUrl({ spriteId: walletSpriteId })\n : undefined;\n\n return {\n connectionOptions,\n iconUrl:\n displayOverride?.iconUrl ?? groupIconUrl ?? walletIconUrl ?? '',\n installationUrls,\n key: walletOptionKey,\n name:\n displayOverride?.name ?? group?.name ?? walletEntry?.name ?? walletOptionKey,\n primaryColor:\n group?.brand?.primaryColor ?? walletEntry?.brand?.primaryColor,\n };\n};\n","import type { WalletProvider } from '../walletProvider';\n\ntype HasWalletProviderConnectMethodParams = {\n walletProvider: WalletProvider;\n};\n\n/**\n * Returns true when the given wallet provider exposes a `connect` method,\n * which is the signal we use to decide whether it belongs in the external\n * wallet picker as an `available provider`.\n *\n * Providers that don't expose `connect` (embedded wallets,\n * account-abstraction wrappers, MetaMask SDK / WalletConnect-backed\n * providers) are still sign-in capable, but via different SDK entry\n * points — they should not appear in the external picker as a\n * `withWalletProvider`-style option.\n *\n * Centralizing the predicate means future tweaks (e.g. a registry of\n * provider keys to exclude) land in one place and every consumer stays\n * in lockstep.\n *\n * @param params.walletProvider - The wallet provider to test.\n * @returns True when the provider exposes a `connect` method.\n * @not-instrumented\n */\nexport const hasWalletProviderConnectMethod = ({\n walletProvider,\n}: HasWalletProviderConnectMethodParams): boolean =>\n Boolean(walletProvider.connect);\n","import { WalletProviderPriority } from '../../wallets/walletProviderRegistry';\nimport type { WalletProviderRegistryEntry } from '../../wallets/walletProviderRegistry';\nimport type { WithWalletProviderSource } from '../walletOptionsCatalogue.types';\n\ntype ClassifyWithWalletProviderSourceParams = {\n entry: WalletProviderRegistryEntry;\n};\n\n\n/**\n * Maps a registered wallet provider's registration priority to the\n * `WithWalletProviderSource` value that should appear on its catalogue option.\n *\n * Priority mapping (set by each chain extension when it calls\n * `registry.register`):\n *\n * - `WALLET_SDK` → `'sdk'` — branded SDKs wrapped by chain extensions\n * (Base Account via `@base-org/account`, MetaMask Connect, …).\n * - `WALLET_SELF_ANNOUNCEMENT_STANDARD` → `'selfAnnounced'` — in-page\n * self-announcement standards (EIP-6963 on EVM, Wallet Standard on\n * Solana / Sui / …).\n * - `WINDOW_INJECT` → `'windowInjected'` — legacy `window.*` injection.\n *\n * Returns `undefined` for providers whose registration priority does not\n * correspond to a connectable external-wallet source — callers filter these\n * out before emitting catalogue options.\n *\n * @param params.entry - The registry entry to classify.\n * @returns The matching source, or `undefined` if this entry should not\n * surface a `withWalletProvider` option.\n * @not-instrumented\n */\nexport const classifyWithWalletProviderSource = ({\n entry,\n}: ClassifyWithWalletProviderSourceParams):\n | WithWalletProviderSource\n | undefined => {\n const { priority } = entry;\n\n if (priority === WalletProviderPriority.WALLET_SDK) {\n return 'sdk';\n }\n\n if (priority === WalletProviderPriority.WALLET_SELF_ANNOUNCEMENT_STANDARD) {\n return 'selfAnnounced';\n }\n\n if (priority === WalletProviderPriority.WINDOW_INJECT) {\n return 'windowInjected';\n }\n\n return undefined;\n};\n","import type { Chain } from '../../../chain';\n\ntype StripChainSuffixParams = {\n chain: Chain;\n normalizedName: string;\n};\n\n/**\n * Removes the lowercased chain suffix that `normalizeWalletNameWithChain`\n * appends. Used by `findWalletOptionKeyForProviderKey` to recover the wallet\n * book wallet key candidate from a `walletProviderKey`. If the suffix is\n * not present (some chain extensions already bake the chain into the\n * display name), the input is returned unchanged.\n *\n * @param params.chain - The chain whose suffix should be stripped.\n * @param params.normalizedName - The normalized wallet-name-with-chain string.\n * @returns The name with the chain suffix removed, or the input unchanged.\n * @not-instrumented\n */\nexport const stripChainSuffix = ({\n chain,\n normalizedName,\n}: StripChainSuffixParams): string => {\n const suffix = chain.toLowerCase();\n\n if (normalizedName.endsWith(suffix)) {\n return normalizedName.slice(0, -suffix.length);\n }\n\n return normalizedName;\n};\n","/**\n * Normalizes a wallet's self-announced `displayName` into a stable wallet\n * option key. Used by `findWalletOptionKeyForProviderKey` as the off-book\n * fallback — registered providers whose `walletProviderKey` does not\n * resolve to any wallet book entry still surface in the catalogue under a\n * key derived from the name they ship in their metadata.\n *\n * The normalization (lowercase + whitespace-strip) intentionally matches\n * how the legacy wallet book composes its `wallets.<key>` keys, so a\n * self-described provider's option will merge cleanly with its book entry\n * if one ever lands later.\n *\n * Multi-chain registrations of the same wallet (e.g. Phantom announced via\n * EIP-6963 on EVM and via Wallet Standard on Solana) collapse onto the\n * same wallet option through this normalization, since each registration\n * announces the same `displayName`.\n *\n * @param displayName - The provider's `metadata.displayName`.\n * @returns The normalized wallet option key (lowercased, no whitespace).\n * @not-instrumented\n */\nexport const normalizeWalletDisplayName = (displayName: string): string =>\n displayName.toLowerCase().replace(/\\s+/g, '');\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype FindByNameMatchParams = {\n candidate: string;\n walletBook: WalletBookSchema;\n};\n\nconst normalize = (value: string | undefined): string | undefined =>\n value === undefined ? undefined : value.toLowerCase().replace(/\\s+/g, '');\n\n/**\n * Looks for a wallet book entry whose `name` or `shortName` normalizes to\n * the same string as `candidate`. Used as a fallback by\n * `findWalletOptionKeyForProviderKey` for providers whose\n * `walletProviderKey` strips down to a value that does not match any\n * `walletBook.wallets` key directly (e.g. an extension whose display name\n * happens to match the wallet's `shortName` instead of its book key).\n *\n * @param params.candidate - The lowercased, chain-suffix-stripped candidate.\n * @param params.walletBook - The fetched wallet book.\n * @returns The matching wallet book wallet key, or `undefined`.\n * @not-instrumented\n */\nexport const findByNameMatch = ({\n candidate,\n walletBook,\n}: FindByNameMatchParams): string | undefined => {\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (\n normalize(wallet.name) === candidate ||\n normalize(wallet.shortName) === candidate\n ) {\n return walletKey;\n }\n }\n\n return undefined;\n};\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype ResolveWalletOptionKeyParams = {\n fallback: string;\n wallet: WalletBookSchema['wallets'][string];\n};\n\n/**\n * Picks the wallet option (group) key for a wallet book wallet. The wallet\n * book carries the group association under a few different field names\n * (`group`, `chainGroup`, `walletGroup`) depending on the wallet's\n * provenance — this helper centralises the lookup. When none of those\n * fields are set, the wallet key itself acts as its own wallet option key.\n *\n * @param params.fallback - Wallet key to return if no group field is set.\n * @param params.wallet - The wallet book wallet entry.\n * @returns The resolved wallet option key.\n * @not-instrumented\n */\nexport const resolveWalletOptionKey = ({\n fallback,\n wallet,\n}: ResolveWalletOptionKeyParams): string =>\n wallet.group ?? wallet.chainGroup ?? wallet.walletGroup ?? fallback;\n","import type { Chain } from '../../chain';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { splitWalletProviderKey } from '../../wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey';\nimport { stripChainSuffix } from '../../wallets/utils/stripChainSuffix/stripChainSuffix';\nimport type { WalletProvider } from '../../wallets/walletProvider/walletProvider.types';\nimport { normalizeWalletDisplayName } from '../normalizeWalletDisplayName/normalizeWalletDisplayName';\nimport { findByNameMatch } from './findByNameMatch/findByNameMatch';\nimport { resolveWalletOptionKey } from './resolveWalletOptionKey/resolveWalletOptionKey';\n\ntype FindWalletOptionKeyForProviderKeyParams = {\n chain: Chain;\n walletBook: WalletBookSchema;\n walletProvider: WalletProvider;\n};\n\n/**\n * Resolves a registered wallet provider to the wallet option key it should\n * be bucketed under. Always returns a key — providers with no wallet book\n * match fall back to their self-announced `metadata.displayName`, so the\n * catalogue surfaces them as self-described tiles instead of silently\n * dropping them.\n *\n * Resolution order (each step short-circuits on first hit):\n *\n * 1. **Direct wallet book lookup with chain suffix** — try\n * `walletBook.wallets[normalizedWalletNameWithChain]` as-is. Wallet\n * book entries are inconsistent about whether they keep the chain\n * suffix (e.g. `metamaskevm`) or strip it (e.g. `metamask`), so try\n * the suffixed form first.\n * 2. **Direct wallet book lookup without chain suffix** — strip the\n * suffix and retry.\n * 3. **Name match heuristic with chain suffix** — scan\n * `walletBook.wallets` for an entry whose normalized `name` or\n * `shortName` equals the suffixed candidate.\n * 4. **Name match heuristic without chain suffix** — same scan on the\n * stripped candidate.\n * 5. **Display-name fallback** — derive a stable key from\n * `walletProvider.metadata.displayName` via\n * {@link normalizeWalletDisplayName}. Multi-chain registrations of the\n * same self-described wallet (e.g. Phantom on EVM and Solana) collapse\n * onto the same tile because each announces the same display name.\n *\n * @param params.chain - The provider's chain (used to strip the suffix).\n * @param params.walletBook - The fetched wallet book.\n * @param params.walletProvider - The registered wallet provider.\n * @returns The wallet option key for this provider.\n * @not-instrumented\n */\nexport const findWalletOptionKeyForProviderKey = ({\n chain,\n walletBook,\n walletProvider,\n}: FindWalletOptionKeyForProviderKeyParams): string => {\n const { normalizedWalletNameWithChain } = splitWalletProviderKey(\n walletProvider.key\n );\n const strippedCandidate = stripChainSuffix({\n chain,\n normalizedName: normalizedWalletNameWithChain,\n });\n const candidates = [normalizedWalletNameWithChain, strippedCandidate];\n\n for (const candidate of candidates) {\n const directHit = walletBook.wallets[candidate];\n\n if (directHit) {\n return resolveWalletOptionKey({\n fallback: candidate,\n wallet: directHit,\n });\n }\n }\n\n for (const candidate of candidates) {\n const nameMatchKey = findByNameMatch({\n candidate,\n walletBook,\n });\n\n if (nameMatchKey) {\n return resolveWalletOptionKey({\n fallback: nameMatchKey,\n wallet: walletBook.wallets[nameMatchKey],\n });\n }\n }\n\n return normalizeWalletDisplayName(walletProvider.metadata.displayName);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { hasWalletProviderConnectMethod } from '../../wallets/hasWalletProviderConnectMethod';\nimport type { WalletProviderRegistryEntry } from '../../wallets/walletProviderRegistry';\nimport { classifyWithWalletProviderSource } from '../classifyWithWalletProviderSource/classifyWithWalletProviderSource';\nimport { findWalletOptionKeyForProviderKey } from '../findWalletOptionKeyForProviderKey/findWalletOptionKeyForProviderKey';\nimport type { WithWalletProviderConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * Display override sourced from a registered wallet provider's announced\n * metadata (EIP-6963 / Wallet Standard / vendor SDK). The outer\n * transformer applies these on top of any wallet book group entry — the\n * provider knows its own brand best, so `name` + `iconUrl` here win\n * over the wallet book's values when both exist.\n */\nexport type WithWalletProviderDisplayOverride = {\n iconUrl: string;\n name: string;\n};\n\n/**\n * One `WithWalletProviderConnectionOption` paired with the wallet option\n * key it should be bucketed under, plus the provider's self-announced\n * display metadata. The outer transformer groups by `walletOptionKey` and\n * uses `displayOverride` to build the wallet option shell, with provider\n * precedence over the wallet book's display fields.\n */\nexport type WithWalletProviderOptionForWalletOption = {\n displayOverride: WithWalletProviderDisplayOverride;\n option: WithWalletProviderConnectionOption;\n walletOptionKey: string;\n};\n\ntype BuildWithWalletProviderOptionsParams = {\n entries: WalletProviderRegistryEntry[];\n walletBook: WalletBookSchema;\n};\n\n/**\n * Converts each registered wallet provider entry into a\n * `WithWalletProviderConnectionOption` paired with its target wallet\n * option key and the provider's display override. Every classifiable\n * entry surfaces in the catalogue; the outer transformer uses the\n * carried `displayOverride` to override any wallet book branding for\n * that key (provider self-announcement wins over book).\n *\n * Entries whose registration priority is not recognised by\n * `classifyWithWalletProviderSource` are dropped from the catalogue and\n * an error is logged so Datadog surfaces the unknown registration path —\n * in production this should never happen, every chain extension is\n * expected to register with one of the documented priorities.\n *\n * @param params.entries - Snapshot of the registry's entries.\n * @param params.walletBook - The fetched wallet book.\n * @param client - The Dynamic client (used for logging unclassifiable entries).\n * @returns An array of tagged options, in input order.\n * @not-instrumented\n */\nexport const buildWithWalletProviderOptions = (\n { entries, walletBook }: BuildWithWalletProviderOptionsParams,\n client: DynamicClient\n): WithWalletProviderOptionForWalletOption[] => {\n const result: WithWalletProviderOptionForWalletOption[] = [];\n\n for (const entry of entries) {\n if (!hasWalletProviderConnectMethod({ walletProvider: entry.walletProvider })) {\n continue;\n }\n\n const source = classifyWithWalletProviderSource({ entry });\n\n if (!source) {\n getCore(client).logger.error(\n 'buildWithWalletProviderOptions: registered wallet provider has an unrecognised priority — unable to identify how this wallet was registered',\n {\n chain: entry.walletProvider.chain,\n displayName: entry.walletProvider.metadata.displayName,\n priority: entry.priority,\n walletProviderKey: entry.walletProvider.key,\n walletProviderType: entry.walletProvider.walletProviderType,\n }\n );\n continue;\n }\n\n const walletOptionKey = findWalletOptionKeyForProviderKey({\n chain: entry.walletProvider.chain,\n walletBook,\n walletProvider: entry.walletProvider,\n });\n\n result.push({\n displayOverride: {\n iconUrl: entry.walletProvider.metadata.icon,\n name: entry.walletProvider.metadata.displayName,\n },\n option: {\n chain: entry.walletProvider.chain,\n source,\n type: 'withWalletProvider',\n walletProviderKey: entry.walletProvider.key,\n },\n walletOptionKey,\n });\n }\n\n return result;\n};\n","/**\n * Wallet option keys `getWalletOptionsCatalogue` drops before returning.\n * Curated, product-level suppression.\n *\n * Example: Base Account SDK is the recommended entry point for\n * Coinbase-managed users, so the legacy Coinbase Wallet entries are\n * suppressed in favor of the SDK-backed `baseaccount` tile. Both the\n * wallet book group key (`coinbase`) and the normalized display-name\n * key (`coinbasewallet`) are listed so suppression holds regardless of\n * how the resolver lands on a key.\n *\n * Used in: `getWalletOptionsCatalogue`.\n */\nexport const EXCLUDED_WALLET_OPTION_KEYS: ReadonlySet<string> = new Set([\n 'coinbase',\n 'coinbasewallet',\n]);\n","import type { WithWalletProviderDisplayOverride } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * A `connectionOption` tagged with the wallet option key it belongs under.\n * Transformer outputs produce these; the catalogue groups them by\n * `walletOptionKey` before building wallet option shells.\n *\n * `displayOverride` is set only by the `withWalletProvider` transformer,\n * carrying the provider's self-announced `name` + `iconUrl`. The shell\n * builder applies it on top of any wallet book entry — provider\n * metadata wins over book branding.\n */\nexport type ConnectionOptionForWalletOption = {\n displayOverride?: WithWalletProviderDisplayOverride;\n option: WalletConnectionOption;\n walletOptionKey: string;\n};\n\n/**\n * Bucket of grouped options for a single wallet option key, plus the\n * first-seen display override (if any). Returned by\n * `groupOptionsByWalletOption` for the catalogue to feed into the shell\n * builder.\n */\nexport type GroupedWalletOption = {\n connectionOptions: WalletConnectionOption[];\n displayOverride?: WithWalletProviderDisplayOverride;\n};\n\ntype GroupOptionsByWalletOptionParams = {\n options: ConnectionOptionForWalletOption[];\n};\n\n/**\n * Buckets tagged connection options by their wallet option key. Preserves\n * first-seen order so that the caller's choice of\n * `walletOptionOrdering: 'relevance'` naturally inherits the upstream input\n * order (wallet book order for walletConnect/inAppBrowser/installation,\n * registry order for withWalletProvider).\n *\n * Carries through the first-seen `displayOverride` per wallet option\n * key, so the shell builder can apply provider-announced metadata on\n * top of any wallet book entry.\n *\n * @param params.options - The tagged options to group.\n * @returns A map from wallet option key to its grouped option bucket,\n * iterable in first-seen order.\n * @not-instrumented\n */\nexport const groupOptionsByWalletOption = ({\n options,\n}: GroupOptionsByWalletOptionParams): Map<string, GroupedWalletOption> => {\n const map = new Map<string, GroupedWalletOption>();\n\n for (const { displayOverride, option, walletOptionKey } of options) {\n const existing = map.get(walletOptionKey);\n\n if (existing) {\n existing.connectionOptions.push(option);\n if (!existing.displayOverride && displayOverride) {\n existing.displayOverride = displayOverride;\n }\n } else {\n map.set(walletOptionKey, {\n connectionOptions: [option],\n displayOverride,\n });\n }\n }\n\n return map;\n};\n","import type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * Numeric priority for each `WalletConnectionOption` type. Lower values rank\n * first. Used to sort each wallet option's `connectionOptions` array so the\n * best connection path lands at index 0. Has no bearing on how the outer\n * wallet-option list is ordered — that's controlled by\n * `WalletOptionOrdering`.\n *\n * `withWalletProvider > walletConnect / metamaskSdkUri > inAppBrowser`\n */\nconst CONNECTION_OPTION_PRIORITY: Record<WalletConnectionOption['type'], number> = {\n inAppBrowser: 2,\n metamaskSdkUri: 1,\n walletConnect: 1,\n withWalletProvider: 0,\n};\n\ntype GetConnectionOptionPriorityParams = {\n option: WalletConnectionOption;\n};\n\n/**\n * Returns the numeric priority of a `WalletConnectionOption` for sorting.\n * Lower numbers rank first.\n *\n * @param params.option - The connection option to inspect.\n * @returns The numeric priority — lower is better.\n * @not-instrumented\n */\nexport const getConnectionOptionPriority = ({\n option,\n}: GetConnectionOptionPriorityParams): number =>\n CONNECTION_OPTION_PRIORITY[option.type];\n","import { getConnectionOptionPriority } from '../getConnectionOptionPriority/getConnectionOptionPriority';\nimport type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\ntype SortConnectionOptionsParams = {\n options: WalletConnectionOption[];\n};\n\n/**\n * Sorts a wallet option's `connectionOptions` so the most preferred option lands at\n * index 0. Primary sort is by option-type priority\n * (`withWalletProvider` > URI deeplink > `inAppBrowser`);\n * within a type, ties break alphabetically by `chain` for deterministic\n * output across calls.\n *\n * Returns a new array — the input is not mutated.\n *\n * @param params.options - The options to sort.\n * @returns A new array in priority order.\n * @not-instrumented\n */\nexport const sortConnectionOptions = ({\n options,\n}: SortConnectionOptionsParams): WalletConnectionOption[] =>\n [...options].sort((a, b) => {\n const priorityDelta =\n getConnectionOptionPriority({ option: a }) -\n getConnectionOptionPriority({ option: b });\n\n if (priorityDelta !== 0) {\n return priorityDelta;\n }\n\n return a.chain.localeCompare(b.chain);\n });\n","/**\n * Hand-curated list of wallet book group keys that should surface at the top\n * of catalogue listings. Lower index = higher priority. Anything not in this\n * list falls through to the secondary sort (alphabetical by name).\n *\n * Used by `sortWalletOptions` (relevance mode) and by the react-demo's\n * WalletConnect picker. Keep both in sync when adding entries.\n */\nexport const PRIORITY_WALLET_KEYS: readonly string[] = [\n 'metamask',\n 'coinbase',\n 'baseaccount',\n 'phantom',\n 'magiceden',\n 'trust',\n 'okxwallet',\n 'rainbow',\n 'argentx',\n 'backpack',\n 'xverse',\n 'onekey',\n 'solflare',\n 'braavos',\n 'brave',\n 'unisat',\n 'bitgetwallet',\n 'coin98',\n];\n","import { PRIORITY_WALLET_KEYS } from '../../legacyWalletBook/priorityWalletKeys/priorityWalletKeys';\nimport type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype GetPriorityIndexParams = {\n walletOption: WalletOption;\n};\n\n/**\n * Returns the index of a wallet option in `PRIORITY_WALLET_KEYS`, or\n * `Number.POSITIVE_INFINITY` when the wallet is not in the hand-curated\n * priority list. Lower index = higher priority.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns Numeric priority index — lower is better.\n * @not-instrumented\n */\nexport const getPriorityIndex = ({\n walletOption,\n}: GetPriorityIndexParams): number => {\n const index = PRIORITY_WALLET_KEYS.indexOf(walletOption.key);\n\n return index === -1 ? Number.POSITIVE_INFINITY : index;\n};\n","import { getPriorityIndex } from '../getPriorityIndex/getPriorityIndex';\nimport type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype CompareByRelevanceParams = {\n a: WalletOption;\n b: WalletOption;\n};\n\n/**\n * Compares two wallet options for relevance ordering: priority-list index\n * first, then alphabetical-by-name as the tie-break. Suitable for passing\n * straight to `Array.prototype.sort`.\n *\n * @param params.a - First wallet option.\n * @param params.b - Second wallet option.\n * @returns Negative when `a` ranks first, positive when `b` ranks first.\n * @not-instrumented\n */\nexport const compareByRelevance = ({\n a,\n b,\n}: CompareByRelevanceParams): number => {\n const aIndex = getPriorityIndex({ walletOption: a });\n const bIndex = getPriorityIndex({ walletOption: b });\n\n if (aIndex !== bIndex) {\n return aIndex - bIndex;\n }\n\n return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });\n};\n","import type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype HasAnyConnectionOptionParams = {\n walletOption: WalletOption;\n};\n\n/**\n * True when the wallet option has at least one connection — i.e. the user\n * can sign in right now. Install-only wallet options surface in the\n * catalogue too (they carry `installationUrls`) but have an empty\n * `connectionOptions` array; this predicate distinguishes them from\n * actually connectable wallets in the relevance sort.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns True when `connectionOptions` is non-empty.\n * @not-instrumented\n */\nexport const hasAnyConnectionOption = ({\n walletOption,\n}: HasAnyConnectionOptionParams): boolean =>\n walletOption.connectionOptions.length > 0;\n","import type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype HasInstalledProviderParams = {\n walletOption: WalletOption;\n};\n\n/**\n * True when the wallet option has a `withWalletProvider` connection — i.e.\n * the user already has the wallet available in the page (browser extension,\n * Wallet Standard announcement, window injection, or an SDK-backed provider\n * one of our chain extensions registered). `connectionOptions` is\n * pre-sorted, so a registered provider always sits at index 0 when present.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns True when an installed provider is available.\n * @not-instrumented\n */\nexport const hasInstalledProvider = ({\n walletOption,\n}: HasInstalledProviderParams): boolean =>\n walletOption.connectionOptions[0]?.type === 'withWalletProvider';\n","import { compareByRelevance } from '../compareByRelevance/compareByRelevance';\nimport { hasAnyConnectionOption } from '../hasAnyConnectionOption/hasAnyConnectionOption';\nimport { hasInstalledProvider } from '../hasInstalledProvider/hasInstalledProvider';\nimport type {\n WalletOption,\n WalletOptionOrdering,\n} from '../walletOptionsCatalogue.types';\n\ntype SortWalletOptionsParams = {\n ordering: WalletOptionOrdering;\n walletOptions: WalletOption[];\n};\n\n/**\n * Sorts the outer wallet-option list. This is the only ordering controlled\n * by the customer; the inner `connectionOptions` array of each wallet\n * option is ordered separately by `sortConnectionOptions` using a fixed\n * option-type priority.\n *\n * - `'relevance'` (default): bucket wallet options into three tiers, in\n * this order:\n * 1. **Installed provider** — user already has the wallet available\n * (`withWalletProvider` at index 0).\n * 2. **Connectable** — has at least one connection (URI deeplink\n * or `inAppBrowser`) but no installed provider.\n * 3. **Install-only** — no connection at all; only `installationUrls`.\n * Within each tier, rank by the hand-curated {@link PRIORITY_WALLET_KEYS}\n * list (MetaMask, Coinbase, Phantom, …); unknown wallets fall through to\n * alphabetical-by-name order at the tail of their tier.\n * - `'alphabetical'`: case-insensitive sort by wallet option `name`,\n * without bucketing.\n *\n * Returns a new array — the input is not mutated.\n *\n * @param params.walletOptions - The wallet options to sort.\n * @param params.ordering - The requested ordering.\n * @returns A new array in the requested order.\n * @not-instrumented\n */\nexport const sortWalletOptions = ({\n walletOptions,\n ordering,\n}: SortWalletOptionsParams): WalletOption[] => {\n if (ordering === 'alphabetical') {\n return [...walletOptions].sort((a, b) =>\n a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })\n );\n }\n\n const installed: WalletOption[] = [];\n const connectable: WalletOption[] = [];\n const installOnly: WalletOption[] = [];\n\n for (const walletOption of walletOptions) {\n if (hasInstalledProvider({ walletOption })) {\n installed.push(walletOption);\n } else if (hasAnyConnectionOption({ walletOption })) {\n connectable.push(walletOption);\n } else {\n installOnly.push(walletOption);\n }\n }\n\n installed.sort((a, b) => compareByRelevance({ a, b }));\n connectable.sort((a, b) => compareByRelevance({ a, b }));\n installOnly.sort((a, b) => compareByRelevance({ a, b }));\n\n return [...installed, ...connectable, ...installOnly];\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { fetchLegacyWalletBook } from '../../legacyWalletBook/fetchLegacyWalletBook';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { getWalletProviderRegistry } from '../../wallets/walletProviderRegistry';\nimport { buildInAppBrowserOptions } from '../buildInAppBrowserOptions/buildInAppBrowserOptions';\nimport { buildInstallationUrlsByWalletOptionKey } from '../buildInstallationUrlsByWalletOptionKey/buildInstallationUrlsByWalletOptionKey';\nimport { buildMetaMaskSdkUriOptions } from '../buildMetaMaskSdkUriOptions/buildMetaMaskSdkUriOptions';\nimport { buildWalletConnectOptions } from '../buildWalletConnectOptions/buildWalletConnectOptions';\nimport { buildWalletOption } from '../buildWalletOption/buildWalletOption';\nimport { buildWithWalletProviderOptions } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport { EXCLUDED_WALLET_OPTION_KEYS } from '../excludedWalletOptionKeys/excludedWalletOptionKeys';\nimport { groupOptionsByWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { sortConnectionOptions } from '../sortConnectionOptions/sortConnectionOptions';\nimport { sortWalletOptions } from '../sortWalletOptions/sortWalletOptions';\nimport type {\n GetWalletOptionsCatalogueParams,\n InstallationUrls,\n WalletOption,\n WalletOptionsCatalogue,\n} from '../walletOptionsCatalogue.types';\n\nconst EMPTY_WALLET_BOOK: WalletBookSchema = { groups: {}, wallets: {} };\n\n/**\n * Returns the catalogue of external wallet options a user can sign in\n * with through this client. Always includes installed wallet providers;\n * pass `includeMobileOptions: true` to additionally surface\n * WalletConnect, in-app-browser, and install links.\n *\n * Pass `excludedConnectionOptionTypes` to drop specific connection types\n * from the catalogue (e.g. `['inAppBrowser']` on desktop). Wallets whose\n * only connection was an excluded type fall through to the install-only\n * tier of the relevance ordering.\n *\n * @param [params] - Inclusion flag + ordering preference + exclusions.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the wallet options catalogue.\n * @not-instrumented\n */\nexport const getWalletOptionsCatalogue = async (\n params: GetWalletOptionsCatalogueParams = {},\n client = getDefaultClient()\n): Promise<WalletOptionsCatalogue> => {\n const includeMobileOptions = params.includeMobileOptions ?? false;\n const walletOptionOrdering = params.walletOptionOrdering ?? 'relevance';\n const excludedConnectionOptionTypes = new Set(\n params.excludedConnectionOptionTypes ?? []\n );\n\n const walletBook = includeMobileOptions\n ? await fetchLegacyWalletBook(client)\n : EMPTY_WALLET_BOOK;\n\n const allConnectionOptions: ConnectionOptionForWalletOption[] = [];\n\n if (!excludedConnectionOptionTypes.has('withWalletProvider')) {\n const entries = getWalletProviderRegistry(client).listProviderEntries();\n allConnectionOptions.push(\n ...buildWithWalletProviderOptions({ entries, walletBook }, client)\n );\n }\n\n if (includeMobileOptions) {\n // Each URI-deeplink discriminator has its own builder with its own\n // eligibility filter (WC requires `sign_v2`; MM SDK URI does not).\n // Keeping them separate means excluding one discriminator never\n // accidentally gates the other.\n if (!excludedConnectionOptionTypes.has('walletConnect')) {\n allConnectionOptions.push(...buildWalletConnectOptions({ walletBook }));\n }\n if (!excludedConnectionOptionTypes.has('metamaskSdkUri')) {\n allConnectionOptions.push(...buildMetaMaskSdkUriOptions({ walletBook }));\n }\n if (!excludedConnectionOptionTypes.has('inAppBrowser')) {\n allConnectionOptions.push(...buildInAppBrowserOptions({ walletBook }));\n }\n }\n\n const installationUrlsByKey: Map<string, InstallationUrls> =\n includeMobileOptions\n ? buildInstallationUrlsByWalletOptionKey({ walletBook })\n : new Map();\n\n const grouped = groupOptionsByWalletOption({\n options: allConnectionOptions,\n });\n // Union keeps connection-bearing entries first (in their first-seen order)\n // and appends install-only entries — wallets the user can install but\n // cannot connect to yet via any other channel.\n const allWalletOptionKeys = new Set([\n ...grouped.keys(),\n ...installationUrlsByKey.keys(),\n ]);\n const walletOptions: WalletOption[] = [];\n\n for (const walletOptionKey of allWalletOptionKeys) {\n if (EXCLUDED_WALLET_OPTION_KEYS.has(walletOptionKey)) {\n continue;\n }\n\n const groupedEntry = grouped.get(walletOptionKey);\n const connectionOptions = groupedEntry\n ? sortConnectionOptions({ options: groupedEntry.connectionOptions })\n : [];\n\n walletOptions.push(\n buildWalletOption({\n connectionOptions,\n displayOverride: groupedEntry?.displayOverride,\n installationUrls: installationUrlsByKey.get(walletOptionKey),\n walletBook,\n walletOptionKey,\n })\n );\n }\n\n return sortWalletOptions({ ordering: walletOptionOrdering, walletOptions });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport type { OTPVerification } from '../../otp/otp.types';\nimport type { UpdateUserFields } from '../user.types';\n\ntype UpdateUserParams = {\n userFields: UpdateUserFields;\n};\n\n/**\n * Updates the current user's profile information.\n *\n * This function allows updating various user fields such as email, name,\n * and other profile information. Some updates may require OTP verification,\n * like email and phone number.\n *\n * @param params.userFields - The user fields to update.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to OTP verification details if verification is required, or undefined.\n * @instrumented\n * @redact-params\n */\nexport const updateUser = async (\n { userFields }: UpdateUserParams,\n client = getDefaultClient()\n): Promise<OTPVerification | undefined> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.updateSelf({\n environmentId: core.environmentId,\n userFields,\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n if (response.emailVerification) {\n return {\n email: response.emailVerification.email,\n verificationUUID: response.emailVerification.verificationUUID,\n };\n }\n\n if (response.smsVerification) {\n return {\n isoCountryCode: response.smsVerification.isoCountryCode,\n phoneCountryCode: response.smsVerification.phoneCountryCode,\n phoneNumber: response.smsVerification.phoneNumber,\n verificationUUID: response.smsVerification.verificationUUID,\n };\n }\n\n return undefined;\n};\n","import { MfaBackupCodeAcknowledgement } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { updateUser } from '../../user/updateUser';\n\n/**\n * Acknowledges that the user has viewed and saved their MFA recovery codes.\n *\n * This function marks the recovery codes as acknowledged, indicating that\n * the user has properly backed up their MFA recovery codes for account recovery.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the acknowledgment is complete.\n * @instrumented\n */\nexport const acknowledgeRecoveryCodes = async (client = getDefaultClient()) => {\n return updateUser(\n {\n userFields: {\n mfaBackupCodeAcknowledgement: MfaBackupCodeAcknowledgement.Complete,\n },\n },\n client\n );\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticateMfaRecoveryCodeParams = {\n code: string;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaTokenOptions?: CreateMfaToken;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using an MFA recovery code.\n *\n * This function allows users to bypass normal MFA requirements by using\n * one of their backup recovery codes when none of the registered MFA methods are available.\n *\n * @param params.code - The recovery code to authenticate with.\n * @param [params.createMfaTokenOptions] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @not-instrumented\n */\nexport const authenticateMfaRecoveryCode = async (\n { code, createMfaTokenOptions, requestedScopes }: AuthenticateMfaRecoveryCodeParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.authMfaRecovery({\n environmentId: core.environmentId,\n mFAAuthRecoveryDevicePostRequest: {\n code,\n createMfaToken: createMfaTokenOptions,\n requestedScopes,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import type { GetPasskeyAuthenticationOptionsResponse } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\nexport type GetPasskeyAuthenticationOptionsParams = {\n relatedOriginRpId?: string;\n};\n\n/** @not-instrumented */\nexport const getPasskeyAuthenticationOptions = async (\n { relatedOriginRpId }: GetPasskeyAuthenticationOptionsParams = {},\n client: DynamicClient\n): Promise<PublicKeyCredentialRequestOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyAuthenticationOptionsResponse =\n await apiClient.getPasskeyAuthenticationOptions({\n environmentId: core.environmentId,\n relatedOriginRpId,\n });\n\n return options as PublicKeyCredentialRequestOptionsJSON;\n};\n","import type {\n CreateMfaToken,\n PasskeyAuthRequest,\n TokenScope,\n} from '@dynamic-labs/sdk-api-core';\nimport type { AuthenticationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerAuthenticatePasskeyParams = {\n authentication: AuthenticationResponseJSON;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaToken?: CreateMfaToken;\n requestedScopes?: TokenScope[];\n};\n\n/** @not-instrumented */\nexport const serverAuthenticatePasskey = async (\n { authentication, createMfaToken, requestedScopes }: ServerAuthenticatePasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.authenticateMfaPasskeyDevice({\n environmentId: core.environmentId,\n passkeyAuthRequest: {\n ...authentication,\n createMfaToken,\n requestedScopes,\n response: {\n ...authentication.response,\n clientDataJson: authentication.response.clientDataJSON,\n },\n } as PasskeyAuthRequest,\n });\n\n return response;\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { NoPasskeyCredentialsFoundError } from '../../../errors/NoPasskeyCredentialsFoundError';\nimport { NoWebAuthNSupportError } from '../../../errors/NoWebAuthNSupportError';\nimport { getPasskeyAuthenticationOptions } from '../../auth/passkeys/getPasskeyAuthenticationOptions';\nimport { serverAuthenticatePasskey } from '../../auth/passkeys/serverAuthenticatePasskey';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticatePasskeyMFAParams = {\n /** @deprecated Use `requestedScopes` instead. */\n createMfaToken?: CreateMfaToken;\n relatedOriginRpId?: string;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using a passkey for multi-factor authentication.\n *\n * This function prompts the user to authenticate with their registered\n * passkey to complete an MFA challenge and obtain an MFA token.\n *\n * @param [params.createMfaToken] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @throws NoPasskeyCredentialsFoundError If no passkey credentials are found.\n * @not-instrumented\n */\nexport const authenticatePasskeyMFA = async (\n {\n createMfaToken,\n relatedOriginRpId,\n requestedScopes,\n }: AuthenticatePasskeyMFAParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n try {\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyAuthenticationOptions(\n { relatedOriginRpId },\n client\n );\n const allowCredentials = options.allowCredentials?.map((credential) => ({\n ...credential,\n type: 'public-key' as const,\n }));\n\n if (!allowCredentials?.length) {\n throw new NoPasskeyCredentialsFoundError();\n }\n\n // Ensure allowCredentials has the required type property\n const formattedOptions: PublicKeyCredentialRequestOptionsJSON = {\n ...options,\n allowCredentials,\n };\n\n const authentication = await core.passkey.authenticate({\n optionsJSON: formattedOptions,\n });\n\n const response = await serverAuthenticatePasskey(\n { authentication, createMfaToken, requestedScopes },\n client\n );\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticateTotpMfaDeviceParams = {\n code: string;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaTokenOptions?: CreateMfaToken;\n deviceId?: string;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using a TOTP (Time-based One-Time Password) MFA device.\n *\n * This function validates a TOTP code from an authenticator app and returns\n * an MFA token upon successful authentication.\n *\n * @param params.code - The 6-digit TOTP code from the authenticator app.\n * @param [params.deviceId] - The ID of the specific TOTP device to authenticate with.\n * @param [params.createMfaTokenOptions] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @not-instrumented\n */\nexport const authenticateTotpMfaDevice = async (\n { deviceId, code, createMfaTokenOptions, requestedScopes }: AuthenticateTotpMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.authMfaTotpDevice({\n environmentId: core.environmentId,\n mFAAuthTotpDevicePostRequest: {\n code,\n createMfaToken: createMfaTokenOptions,\n id: deviceId,\n requestedScopes,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { deviceId, mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { deviceId, error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Generates new MFA recovery codes for the current user.\n *\n * This function creates a fresh set of backup codes that can be used\n * to bypass MFA requirements if none of the registered MFA methods are available.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the newly generated recovery codes.\n * @instrumented\n * @redact-params\n */\nexport const createNewMfaRecoveryCodes = async (\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.createNewRecoveryCodes({\n environmentId: core.environmentId,\n });\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { getElevatedAccessToken } from '../../auth/getElevatedAccessToken';\nimport { createApiClient } from '../../apiClient';\n\ntype DeleteMfaDeviceParams = {\n deviceId: string;\n mfaAuthToken?: string;\n};\n\n/**\n * Deletes a specific MFA device from the user's account.\n *\n * When an elevated access token for `credential:unlink` is available,\n * it is sent via the `x-dyn-elevated-access-token` header and the\n * MFA auth token is not required. Otherwise, `mfaAuthToken` must be\n * provided for backward compatibility with the legacy MFA flow.\n *\n * @param params.deviceId - The unique identifier of the MFA device to delete.\n * @param params.mfaAuthToken - The MFA authentication token. Optional when using elevated access tokens.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the MFA device is successfully deleted.\n * @instrumented\n */\nexport const deleteMfaDevice = async (\n { deviceId, mfaAuthToken }: DeleteMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n assertDefined(deviceId, 'deviceId is required');\n\n // Check without consuming — createApiClient handles actual retrieval.\n const hasElevatedToken = getElevatedAccessToken(\n { consume: false, scope: TokenScope.Credentialunlink },\n client\n );\n\n if (!hasElevatedToken) {\n assertDefined(mfaAuthToken, 'mfaAuthToken is required');\n }\n\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentialunlink },\n client\n );\n\n return apiClient.deleteMfaDevice({\n environmentId: core.environmentId,\n mfaDeviceId: deviceId,\n // The generated SDK types xMfaAuthToken as required (string, not string?).\n // When using elevated tokens the backend skips this header entirely, but\n // we still need to satisfy the type. Once the OpenAPI spec marks it optional\n // this fallback can be removed.\n xMfaAuthToken: mfaAuthToken ?? '',\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Retrieves all MFA devices registered for the current user.\n *\n * This function fetches the list of multi-factor authentication devices\n * associated with the user's account, such as TOTP authenticators.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of the user's registered MFA devices.\n * @not-instrumented\n */\nexport const getMfaDevices = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const { devices } = await apiClient.getUserMfaDevices({\n environmentId: core.environmentId,\n });\n\n return devices;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Retrieves the current MFA recovery codes for the user.\n *\n * This function fetches the backup codes that can be used to bypass\n * MFA requirements if none of the registered MFA methods are available.\n * If user doesn't have any recovery codes, it will create them,\n * otherwise it will return the existing ones.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the user's MFA recovery codes.\n * @not-instrumented\n */\nexport const getMfaRecoveryCodes = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getRecoveryCodes({\n environmentId: core.environmentId,\n });\n};\n","import { MfaBackupCodeAcknowledgement } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\n\n/**\n * Checks if the user is still pending acknowledgment of their MFA recovery codes.\n *\n * This function determines whether the user has been presented with recovery\n * codes that they have not yet acknowledged as saved or backed up.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if recovery codes are pending acknowledgment, false otherwise.\n * @not-instrumented\n */\nexport const isPendingRecoveryCodesAcknowledgment = (\n client = getDefaultClient()\n) => {\n const user = client.user;\n\n assertDefined(user, 'User not logged in');\n\n return (\n user.mfaBackupCodeAcknowledgement === MfaBackupCodeAcknowledgement.Pending\n );\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Registers a new TOTP (Time-based One-Time Password) MFA device.\n *\n * This function initiates the registration of a TOTP authenticator app\n * (like Google Authenticator or Authy) for multi-factor authentication.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the TOTP registration response containing setup information,\n * like the secret key and the OTP Auth URI.\n * @instrumented\n */\nexport const registerTotpMfaDevice = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentiallink },\n client\n );\n\n return apiClient.registerTotpMfaDevice({\n environmentId: core.environmentId,\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\n\ntype SetDefaultMfaDeviceParams = {\n deviceId: string;\n};\n\n/**\n * Sets the default MFA device for the current user.\n *\n * This function designates a specific MFA TOTP device as the primary method\n * for multi-factor authentication challenges.\n *\n * @param params.deviceId - The unique identifier of the MFA device to set as default.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the default MFA device is successfully set.\n * @instrumented\n */\nexport const setDefaultMfaDevice = async (\n { deviceId }: SetDefaultMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n assertDefined(deviceId, 'deviceId is required');\n\n // All that this endpoint does is set the default device to the one provided.\n return apiClient.updateUserMfaDevice({\n environmentId: core.environmentId,\n mfaDeviceId: deviceId,\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { consumeCaptchaToken } from '../../captcha/consumeCaptchaToken';\nimport type { OTPVerification } from '../otp.types';\n\nexport type SendEmailOTPParams = {\n email: string;\n};\n\n/**\n * Sends a one-time password (OTP) to the specified email address.\n *\n * Once you have the OTP code, you should then use `verifyOTP` to verify it and complete the authentication process.\n *\n * @param params.email - The email address to send the OTP to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an OTPVerification object containing the email and verification UUID.\n * @instrumented\n * @redact-params\n */\nexport const sendEmailOTP = async (\n { email }: SendEmailOTPParams,\n client = getDefaultClient()\n): Promise<OTPVerification> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const { verificationUUID } = await apiClient.createEmailVerification({\n emailVerificationCreateRequest: {\n captchaToken: consumeCaptchaToken(client),\n email,\n },\n environmentId: core.environmentId,\n });\n\n return { email, verificationUUID };\n};\n","// Source:\n// https://github.com/dynamic-labs/redcoast/blob/main/apps/dashboard/src/app/routes/Configurations/Providers/components/SmsProviderSection/utils/countries.ts\n\n// these are the countries was populated based on the wikipedia page\n// referenced in twilio's docs: https://www.twilio.com/docs/voice/api/dialingpermissions-country-resource\n// and this doc for country codes: https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.pdf\nexport type CountryCode =\n | 'AC'\n | 'AD'\n | 'AE'\n | 'AF'\n | 'AG'\n | 'AI'\n | 'AL'\n | 'AM'\n | 'AO'\n | 'AR'\n | 'AS'\n | 'AT'\n | 'AU'\n | 'AW'\n | 'AZ'\n | 'BA'\n | 'BB'\n | 'BD'\n | 'BE'\n | 'BF'\n | 'BG'\n | 'BH'\n | 'BI'\n | 'BJ'\n | 'BM'\n | 'BN'\n | 'BO'\n | 'BR'\n | 'BS'\n | 'BT'\n | 'BW'\n | 'BY'\n | 'BZ'\n | 'CA'\n | 'CD'\n | 'CF'\n | 'CG'\n | 'CH'\n | 'CI'\n | 'CK'\n | 'CL'\n | 'CM'\n | 'CN'\n | 'CO'\n | 'CR'\n | 'CU'\n | 'CV'\n | 'CW'\n | 'CY'\n | 'CZ'\n | 'DE'\n | 'DJ'\n | 'DK'\n | 'DM'\n | 'DO'\n | 'DZ'\n | 'EC'\n | 'EE'\n | 'EG'\n | 'ER'\n | 'ES'\n | 'ET'\n | 'FI'\n | 'FJ'\n | 'FK'\n | 'FM'\n | 'FO'\n | 'FR'\n | 'GA'\n | 'GB'\n | 'GD'\n | 'GE'\n | 'GF'\n | 'GG'\n | 'GH'\n | 'GI'\n | 'GL'\n | 'GM'\n | 'GN'\n | 'GP'\n | 'GQ'\n | 'GR'\n | 'GT'\n | 'GU'\n | 'GW'\n | 'GY'\n | 'HK'\n | 'HN'\n | 'HR'\n | 'HT'\n | 'HU'\n | 'IC'\n | 'ID'\n | 'IE'\n | 'IL'\n | 'IM'\n | 'IN'\n | 'IQ'\n | 'IR'\n | 'IS'\n | 'IT'\n | 'JM'\n | 'JO'\n | 'JP'\n | 'KE'\n | 'KG'\n | 'KH'\n | 'KI'\n | 'KM'\n | 'KN'\n | 'KP'\n | 'KR'\n | 'KW'\n | 'KY'\n | 'LA'\n | 'LB'\n | 'LC'\n | 'LI'\n | 'LK'\n | 'LR'\n | 'LS'\n | 'LT'\n | 'LU'\n | 'LV'\n | 'LY'\n | 'MA'\n | 'MC'\n | 'MD'\n | 'ME'\n | 'MG'\n | 'MH'\n | 'MK'\n | 'ML'\n | 'MM'\n | 'MN'\n | 'MO'\n | 'MP'\n | 'MQ'\n | 'MR'\n | 'MS'\n | 'MT'\n | 'MU'\n | 'MV'\n | 'MW'\n | 'MX'\n | 'MY'\n | 'MZ'\n | 'NA'\n | 'NC'\n | 'NE'\n | 'NF'\n | 'NG'\n | 'NI'\n | 'NL'\n | 'NO'\n | 'NP'\n | 'NU'\n | 'NZ'\n | 'OM'\n | 'PA'\n | 'PE'\n | 'PF'\n | 'PG'\n | 'PH'\n | 'PK'\n | 'PL'\n | 'PM'\n | 'PR'\n | 'PS'\n | 'PT'\n | 'PW'\n | 'PY'\n | 'QA'\n | 'RE'\n | 'RO'\n | 'RS'\n | 'RU'\n | 'RW'\n | 'SA'\n | 'SB'\n | 'SC'\n | 'SD'\n | 'SE'\n | 'SG'\n | 'SI'\n | 'SK'\n | 'SL'\n | 'SM'\n | 'SN'\n | 'SO'\n | 'SR'\n | 'SS'\n | 'ST'\n | 'SV'\n | 'SY'\n | 'SZ'\n | 'TC'\n | 'TD'\n | 'TG'\n | 'TH'\n | 'TJ'\n | 'TL'\n | 'TM'\n | 'TN'\n | 'TO'\n | 'TR'\n | 'TT'\n | 'TV'\n | 'TW'\n | 'TZ'\n | 'UA'\n | 'UG'\n | 'US'\n | 'UY'\n | 'UZ'\n | 'VA'\n | 'VC'\n | 'VE'\n | 'VG'\n | 'VI'\n | 'VN'\n | 'VU'\n | 'WF'\n | 'WS'\n | 'XK'\n | 'YE'\n | 'ZA'\n | 'ZM'\n | 'ZW';\n\nexport type CountryData = {\n code: string;\n name: string;\n};\n\nexport type CountryPhoneData = Record<CountryCode, CountryData>;\n\nexport const supportedCountries: CountryPhoneData = {\n AC: {\n code: '247',\n name: 'Ascension',\n },\n AD: {\n code: '376',\n name: 'Andorra',\n },\n AE: {\n code: '971',\n name: 'United Arab Emirates',\n },\n AF: {\n code: '93',\n name: 'Afghanistan',\n },\n AG: {\n code: '1268',\n name: 'Antigua and Barbuda',\n },\n AI: {\n code: '1264',\n name: 'Anguilla',\n },\n AL: {\n code: '355',\n name: 'Albania',\n },\n AM: {\n code: '374',\n name: 'Armenia',\n },\n AO: {\n code: '244',\n name: 'Angola',\n },\n AR: {\n code: '54',\n name: 'Argentina',\n },\n AS: {\n code: '1684',\n name: 'American Samoa',\n },\n AT: {\n code: '43',\n name: 'Austria',\n },\n AU: {\n code: '61',\n name: 'Australia/Cocos/Christmas Island',\n },\n AW: {\n code: '297',\n name: 'Aruba',\n },\n AZ: {\n code: '994',\n name: 'Azerbaijan',\n },\n BA: {\n code: '387',\n name: 'Bosnia and Herzegovina',\n },\n BB: {\n code: '1246',\n name: 'Barbados',\n },\n BD: {\n code: '880',\n name: 'Bangladesh',\n },\n BE: {\n code: '32',\n name: 'Belgium',\n },\n BF: {\n code: '226',\n name: 'Burkina Faso',\n },\n BG: {\n code: '359',\n name: 'Bulgaria',\n },\n BH: {\n code: '973',\n name: 'Bahrain',\n },\n BI: {\n code: '257',\n name: 'Burundi',\n },\n BJ: {\n code: '229',\n name: 'Benin',\n },\n BM: {\n code: '1441',\n name: 'Bermuda',\n },\n BN: {\n code: '673',\n name: 'Brunei',\n },\n BO: {\n code: '591',\n name: 'Bolivia',\n },\n BR: {\n code: '55',\n name: 'Brazil',\n },\n BS: {\n code: '1242',\n name: 'Bahamas',\n },\n BT: {\n code: '975',\n name: 'Bhutan',\n },\n BW: {\n code: '267',\n name: 'Botswana',\n },\n BY: {\n code: '375',\n name: 'Belarus',\n },\n BZ: {\n code: '501',\n name: 'Belize',\n },\n CA: {\n code: '1',\n name: 'Canada',\n },\n CD: {\n code: '243',\n name: 'Congo, Dem Rep',\n },\n CF: {\n code: '236',\n name: 'Central Africa',\n },\n CG: {\n code: '242',\n name: 'Congo',\n },\n CH: {\n code: '41',\n name: 'Switzerland',\n },\n CI: {\n code: '225',\n name: 'Ivory Coast',\n },\n CK: {\n code: '682',\n name: 'Cook Islands',\n },\n CL: {\n code: '56',\n name: 'Chile',\n },\n CM: {\n code: '237',\n name: 'Cameroon',\n },\n CN: {\n code: '86',\n name: 'China',\n },\n CO: {\n code: '57',\n name: 'Colombia',\n },\n CR: {\n code: '506',\n name: 'Costa Rica',\n },\n CU: {\n code: '53',\n name: 'Cuba',\n },\n CV: {\n code: '238',\n name: 'Cape Verde',\n },\n CW: {\n code: '599',\n name: 'Curaçao and Caribbean Netherlands (Bonaire, Sint Eustatius, Sint Maarten, Saba)',\n },\n CY: {\n code: '357',\n name: 'Cyprus',\n },\n CZ: {\n code: '420',\n name: 'Czech Republic',\n },\n DE: {\n code: '49',\n name: 'Germany',\n },\n DJ: {\n code: '253',\n name: 'Djibouti',\n },\n DK: {\n code: '45',\n name: 'Denmark',\n },\n DM: {\n code: '1767',\n name: 'Dominica',\n },\n DO: {\n code: '1829',\n name: 'Dominican Republic',\n },\n DZ: {\n code: '213',\n name: 'Algeria',\n },\n EC: {\n code: '593',\n name: 'Ecuador',\n },\n EE: {\n code: '372',\n name: 'Estonia',\n },\n EG: {\n code: '20',\n name: 'Egypt',\n },\n ER: {\n code: '291',\n name: 'Eritrea',\n },\n ES: {\n code: '34',\n name: 'Spain',\n },\n ET: {\n code: '251',\n name: 'Ethiopia',\n },\n FI: {\n code: '358',\n name: 'Finland/Aland Islands',\n },\n FJ: {\n code: '679',\n name: 'Fiji',\n },\n FK: {\n code: '500',\n name: 'Falkland Islands',\n },\n FM: {\n code: '691',\n name: 'Micronesia',\n },\n FO: {\n code: '298',\n name: 'Faroe Islands',\n },\n FR: {\n code: '33',\n name: 'France',\n },\n GA: {\n code: '241',\n name: 'Gabon',\n },\n GB: {\n code: '44',\n name: 'United Kingdom',\n },\n GD: {\n code: '1473',\n name: 'Grenada',\n },\n GE: {\n code: '995',\n name: 'Georgia',\n },\n GF: {\n code: '594',\n name: 'French Guiana',\n },\n GG: {\n code: '44',\n name: 'Guernsey/Jersey',\n },\n GH: {\n code: '233',\n name: 'Ghana',\n },\n GI: {\n code: '350',\n name: 'Gibraltar',\n },\n GL: {\n code: '299',\n name: 'Greenland',\n },\n GM: {\n code: '220',\n name: 'Gambia',\n },\n GN: {\n code: '224',\n name: 'Guinea',\n },\n GP: {\n code: '590',\n name: 'Guadeloupe',\n },\n GQ: {\n code: '240',\n name: 'Equatorial Guinea',\n },\n GR: {\n code: '30',\n name: 'Greece',\n },\n GT: {\n code: '502',\n name: 'Guatemala',\n },\n GU: {\n code: '1671',\n name: 'Guam',\n },\n GW: {\n code: '245',\n name: 'Guinea-Bissau',\n },\n GY: {\n code: '592',\n name: 'Guyana',\n },\n HK: {\n code: '852',\n name: 'Hong Kong',\n },\n HN: {\n code: '504',\n name: 'Honduras',\n },\n HR: {\n code: '385',\n name: 'Croatia',\n },\n HT: {\n code: '509',\n name: 'Haiti',\n },\n HU: {\n code: '36',\n name: 'Hungary',\n },\n IC: {\n code: '3491',\n name: 'Canary Islands',\n },\n ID: {\n code: '62',\n name: 'Indonesia',\n },\n IE: {\n code: '353',\n name: 'Ireland',\n },\n IL: {\n code: '972',\n name: 'Israel',\n },\n IM: {\n code: '44',\n name: 'Isle of Man',\n },\n IN: {\n code: '91',\n name: 'India',\n },\n IQ: {\n code: '964',\n name: 'Iraq',\n },\n IR: {\n code: '98',\n name: 'Iran',\n },\n IS: {\n code: '354',\n name: 'Iceland',\n },\n IT: {\n code: '39',\n name: 'Italy',\n },\n JM: {\n code: '1876',\n name: 'Jamaica',\n },\n JO: {\n code: '962',\n name: 'Jordan',\n },\n JP: {\n code: '81',\n name: 'Japan',\n },\n KE: {\n code: '254',\n name: 'Kenya',\n },\n KG: {\n code: '996',\n name: 'Kyrgyzstan',\n },\n KH: {\n code: '855',\n name: 'Cambodia',\n },\n KI: {\n code: '686',\n name: 'Kiribati',\n },\n KM: {\n code: '269',\n name: 'Comoros',\n },\n KN: {\n code: '1869',\n name: 'St Kitts and Nevis',\n },\n KP: {\n code: '850',\n name: \"Korea Dem People's Rep\",\n },\n KR: {\n code: '82',\n name: 'Korea Republic of',\n },\n KW: {\n code: '965',\n name: 'Kuwait',\n },\n KY: {\n code: '1345',\n name: 'Cayman Islands',\n },\n LA: {\n code: '856',\n name: 'Laos PDR',\n },\n LB: {\n code: '961',\n name: 'Lebanon',\n },\n LC: {\n code: '1758',\n name: 'St Lucia',\n },\n LI: {\n code: '423',\n name: 'Liechtenstein',\n },\n LK: {\n code: '94',\n name: 'Sri Lanka',\n },\n LR: {\n code: '231',\n name: 'Liberia',\n },\n LS: {\n code: '266',\n name: 'Lesotho',\n },\n LT: {\n code: '370',\n name: 'Lithuania',\n },\n LU: {\n code: '352',\n name: 'Luxembourg',\n },\n LV: {\n code: '371',\n name: 'Latvia',\n },\n LY: {\n code: '218',\n name: 'Libya',\n },\n MA: {\n code: '212',\n name: 'Morocco/Western Sahara',\n },\n MC: {\n code: '377',\n name: 'Monaco',\n },\n MD: {\n code: '373',\n name: 'Moldova',\n },\n ME: {\n code: '382',\n name: 'Montenegro',\n },\n MG: {\n code: '261',\n name: 'Madagascar',\n },\n MH: {\n code: '692',\n name: 'Marshall Islands',\n },\n MK: {\n code: '389',\n name: 'Republic of North Macedonia',\n },\n ML: {\n code: '223',\n name: 'Mali',\n },\n MM: {\n code: '95',\n name: 'Myanmar (Burma)',\n },\n MN: {\n code: '976',\n name: 'Mongolia',\n },\n MO: {\n code: '853',\n name: 'Macau',\n },\n MP: {\n code: '1670',\n name: 'Northern Mariana Islands',\n },\n MQ: {\n code: '596',\n name: 'Martinique',\n },\n MR: {\n code: '222',\n name: 'Mauritania',\n },\n MS: {\n code: '1664',\n name: 'Montserrat',\n },\n MT: {\n code: '356',\n name: 'Malta',\n },\n MU: {\n code: '230',\n name: 'Mauritius',\n },\n MV: {\n code: '960',\n name: 'Maldives',\n },\n MW: {\n code: '265',\n name: 'Malawi',\n },\n MX: {\n code: '52',\n name: 'Mexico',\n },\n MY: {\n code: '60',\n name: 'Malaysia',\n },\n MZ: {\n code: '258',\n name: 'Mozambique',\n },\n NA: {\n code: '264',\n name: 'Namibia',\n },\n NC: {\n code: '687',\n name: 'New Caledonia',\n },\n NE: {\n code: '227',\n name: 'Niger',\n },\n NF: {\n code: '672',\n name: 'Norfolk Island',\n },\n NG: {\n code: '234',\n name: 'Nigeria',\n },\n NI: {\n code: '505',\n name: 'Nicaragua',\n },\n NL: {\n code: '31',\n name: 'Netherlands',\n },\n NO: {\n code: '47',\n name: 'Norway',\n },\n NP: {\n code: '977',\n name: 'Nepal',\n },\n NU: {\n code: '683',\n name: 'Niue',\n },\n NZ: {\n code: '64',\n name: 'New Zealand',\n },\n OM: {\n code: '968',\n name: 'Oman',\n },\n PA: {\n code: '507',\n name: 'Panama',\n },\n PE: {\n code: '51',\n name: 'Peru',\n },\n PF: {\n code: '689',\n name: 'French Polynesia',\n },\n PG: {\n code: '675',\n name: 'Papua New Guinea',\n },\n PH: {\n code: '63',\n name: 'Philippines',\n },\n PK: {\n code: '92',\n name: 'Pakistan',\n },\n PL: {\n code: '48',\n name: 'Poland',\n },\n PM: {\n code: '508',\n name: 'St Pierre and Miquelon',\n },\n PR: {\n code: '1787',\n name: 'Puerto Rico',\n },\n PS: {\n code: '970, 972',\n name: 'Palestinian Territory',\n },\n PT: {\n code: '351',\n name: 'Portugal',\n },\n PW: {\n code: '680',\n name: 'Palau',\n },\n PY: {\n code: '595',\n name: 'Paraguay',\n },\n QA: {\n code: '974',\n name: 'Qatar',\n },\n RE: {\n code: '262',\n name: 'Reunion/Mayotte',\n },\n RO: {\n code: '40',\n name: 'Romania',\n },\n RS: {\n code: '381',\n name: 'Serbia',\n },\n RU: {\n code: '7',\n name: 'Russia/Kazakhstan',\n },\n RW: {\n code: '250',\n name: 'Rwanda',\n },\n SA: {\n code: '966',\n name: 'Saudi Arabia',\n },\n SB: {\n code: '677',\n name: 'Solomon Islands',\n },\n SC: {\n code: '248',\n name: 'Seychelles',\n },\n SD: {\n code: '249',\n name: 'Sudan',\n },\n SE: {\n code: '46',\n name: 'Sweden',\n },\n SG: {\n code: '65',\n name: 'Singapore',\n },\n SI: {\n code: '386',\n name: 'Slovenia',\n },\n SK: {\n code: '421',\n name: 'Slovakia',\n },\n SL: {\n code: '232',\n name: 'Sierra Leone',\n },\n SM: {\n code: '378',\n name: 'San Marino',\n },\n SN: {\n code: '221',\n name: 'Senegal',\n },\n SO: {\n code: '252',\n name: 'Somalia',\n },\n SR: {\n code: '597',\n name: 'Suriname',\n },\n SS: {\n code: '211',\n name: 'South Sudan',\n },\n ST: {\n code: '239',\n name: 'Sao Tome and Principe',\n },\n SV: {\n code: '503',\n name: 'El Salvador',\n },\n SY: {\n code: '963',\n name: 'Syria',\n },\n SZ: {\n code: '268',\n name: 'Swaziland',\n },\n TC: {\n code: '1649',\n name: 'Turks and Caicos Islands',\n },\n TD: {\n code: '235',\n name: 'Chad',\n },\n TG: {\n code: '228',\n name: 'Togo',\n },\n TH: {\n code: '66',\n name: 'Thailand',\n },\n TJ: {\n code: '992',\n name: 'Tajikistan',\n },\n TL: {\n code: '670',\n name: 'East Timor',\n },\n TM: {\n code: '993',\n name: 'Turkmenistan',\n },\n TN: {\n code: '216',\n name: 'Tunisia',\n },\n TO: {\n code: '676',\n name: 'Tonga',\n },\n TR: {\n code: '90',\n name: 'Turkiye',\n },\n TT: {\n code: '1868',\n name: 'Trinidad and Tobago',\n },\n TV: {\n code: '688',\n name: 'Tuvalu',\n },\n TW: {\n code: '886',\n name: 'Taiwan',\n },\n TZ: {\n code: '255',\n name: 'Tanzania',\n },\n UA: {\n code: '380',\n name: 'Ukraine',\n },\n UG: {\n code: '256',\n name: 'Uganda',\n },\n US: {\n code: '1',\n name: 'United States',\n },\n UY: {\n code: '598',\n name: 'Uruguay',\n },\n UZ: {\n code: '998',\n name: 'Uzbekistan',\n },\n VA: {\n code: '379',\n name: 'Vatican City',\n },\n VC: {\n code: '1784',\n name: 'St Vincent Grenadines',\n },\n VE: {\n code: '58',\n name: 'Venezuela',\n },\n VG: {\n code: '1284',\n name: 'Virgin Islands, British',\n },\n VI: {\n code: '1340',\n name: 'Virgin Islands, U.S.',\n },\n VN: {\n code: '84',\n name: 'Vietnam',\n },\n VU: {\n code: '678',\n name: 'Vanuatu',\n },\n WF: {\n code: '681',\n name: 'Wallis and Futuna',\n },\n WS: {\n code: '685',\n name: 'Samoa',\n },\n XK: {\n code: '383',\n name: 'Kosovo',\n },\n YE: {\n code: '967',\n name: 'Yemen',\n },\n ZA: {\n code: '27',\n name: 'South Africa',\n },\n ZM: {\n code: '260',\n name: 'Zambia',\n },\n ZW: {\n code: '263',\n name: 'Zimbabwe',\n },\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { consumeCaptchaToken } from '../../captcha/consumeCaptchaToken';\nimport type { OTPVerification } from '../otp.types';\nimport type { CountryCode } from './supportedCountries';\nimport { supportedCountries } from './supportedCountries';\n\nexport type SendSmsOTPParams = {\n isoCountryCode: CountryCode;\n phoneNumber: string;\n};\n\n/**\n * Sends a one-time password (OTP) via SMS to the specified phone number.\n *\n * @param params.isoCountryCode - The ISO country code for the phone number (e.g., 'US', 'CA', 'GB').\n * @param params.phoneNumber - The phone number to send the OTP to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an OTPVerification object containing the phone details and verification UUID.\n * @instrumented\n * @redact-params\n */\nexport const sendSmsOTP = async (\n { isoCountryCode, phoneNumber }: SendSmsOTPParams,\n client = getDefaultClient()\n): Promise<OTPVerification> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const phoneCountryCode = supportedCountries[isoCountryCode].code;\n\n const { verificationUUID } = await apiClient.createSmsVerification({\n environmentId: core.environmentId,\n smsVerificationCreateRequest: {\n captchaToken: consumeCaptchaToken(client),\n isoCountryCode,\n phoneCountryCode,\n phoneNumber,\n },\n });\n\n return { isoCountryCode, phoneCountryCode, phoneNumber, verificationUUID };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { VerifyOTPParams } from '../verifyOTP';\n\n/** @not-instrumented */\nexport const verifyOTPForUserSignIn = async (\n { otpVerification, verificationToken }: VerifyOTPParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const verifyRequest = {\n verificationToken,\n verificationUUID: otpVerification.verificationUUID,\n };\n\n if (otpVerification.email) {\n return apiClient.signInWithEmailVerification({\n emailVerificationVerifyRequest: verifyRequest,\n environmentId: core.environmentId,\n });\n }\n\n return apiClient.signInWithSmsVerification({\n environmentId: core.environmentId,\n smsVerificationVerifyRequest: verifyRequest,\n });\n};\n","import type {\n EmailVerificationVerifyRequest,\n SmsVerificationVerifyRequest,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { VerifyOTPParams } from '../verifyOTP';\n\n/** @not-instrumented */\nexport const verifyOTPForUserUpdate = async (\n { otpVerification, verificationToken, requestedScopes }: VerifyOTPParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const verifyRequest:\n | EmailVerificationVerifyRequest\n | SmsVerificationVerifyRequest = {\n verificationToken,\n verificationUUID: otpVerification.verificationUUID,\n };\n if (requestedScopes) verifyRequest.requestedScopes = requestedScopes;\n\n if (otpVerification.email) {\n return apiClient.verifyEmailVerification({\n emailVerificationVerifyRequest: verifyRequest,\n environmentId: core.environmentId,\n });\n }\n\n return apiClient.verifySmsVerification({\n environmentId: core.environmentId,\n smsVerificationVerifyRequest: verifyRequest,\n });\n};\n","import type { TokenScope, VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport type { OTPVerification } from '../otp.types';\nimport { verifyOTPForUserSignIn } from './verifyOTPForUserSignIn';\nimport { verifyOTPForUserUpdate } from './verifyOTPForUserUpdate';\n\nexport type VerifyOTPParams = {\n otpVerification: OTPVerification;\n requestedScopes?: TokenScope[];\n verificationToken: string;\n};\n\n/**\n * Verifies a one-time password (OTP) for user authentication or updates.\n *\n * This function validates the OTP code provided by the user and completes\n * the verification process for either sign-in or account updates.\n *\n * @param params.otpVerification - The OTP verification object containing verification details.\n * @param params.verificationToken - The token received from the OTP verification process.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verify response object upon successful verification.\n * @instrumented\n * @redact-params\n */\nexport const verifyOTP = async (\n { otpVerification, verificationToken, requestedScopes }: VerifyOTPParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n let response: VerifyResponse;\n if (client.user) {\n response = await verifyOTPForUserUpdate(\n {\n otpVerification,\n requestedScopes,\n verificationToken,\n },\n client\n );\n } else {\n response = await verifyOTPForUserSignIn(\n { otpVerification, verificationToken },\n client\n );\n }\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type {\n ChainEnum,\n SwapQuoteRequestOrderEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { SwapQuoteOrder, SwapQuoteResponse } from '../swap.types';\n\nexport type GetSwapQuoteParams = {\n from: {\n /* Source wallet address */\n address: string;\n /**\n * Source token amount, including all decimals (e.g. 1000000 for 1 USDC (6 decimals))\n * Mutually exclusive with `to.amount`\n */\n amount?: string;\n /* Source chain (e.g. 'EVM', 'SOL', 'SUI') */\n chain: Chain;\n /* Source network id (e.g. 1 for Ethereum, 137 for Polygon) */\n networkId: string;\n /* Source token address. Use zero address for EVM and SOL native tokens. */\n tokenAddress: string;\n };\n /**\n * The price impact threshold above which routes are hidden.\n * As an example, one should specify 0.15 (15%) to hide routes with more than 15% price impact.\n */\n maxPriceImpact?: number;\n /**\n * Which kind of route should be preferred\n *\n * FASTEST: This sorting criterion prioritizes routes with the shortest estimated execution time.\n * Users who value speed and want their transactions to be completed as quickly as possible should choose the fastest routes.\n *\n * CHEAPEST: This criterion focuses on minimizing the cost of the transaction, whether in token amount or USD amount (USD amount minus gas cost).\n * Users looking for the most economical option should choose the cheapest routes.\n *\n */\n order?: SwapQuoteOrder;\n /* The maximum allowed slippage for the transaction as a decimal value. 0.005 represents 0.5%. */\n slippage?: number;\n to: {\n /* Destination wallet address */\n address: string;\n /**\n * Destination token amount, including all decimals (e.g. 1000000 for 1 USDC (6 decimals))\n * Mutually exclusive with `from.amount`\n */\n amount?: string;\n /* Destination chain (e.g. 'EVM', 'SOL', 'SUI') */\n chain: Chain;\n /* Destination network id (e.g. 1 for Ethereum, 137 for Polygon) */\n networkId: string;\n /* Destination token address. Use zero address for EVM and SOL native tokens. */\n tokenAddress: string;\n };\n};\n\n/**\n * Gets a swap quote\n *\n * @param params GetSwapQuoteParams - The parameters for the swap quote.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The swap quote details. Use the `signingPayload` field to get the transaction data for the wallet to sign.\n * @not-instrumented\n */\nexport const getSwapQuote = async (\n params: GetSwapQuoteParams,\n client = getDefaultClient()\n): Promise<SwapQuoteResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n if (!params.from.amount && !params.to.amount) {\n throw new InvalidParamError('Either from.amount or to.amount is required');\n }\n\n if (params.from.amount && params.to.amount) {\n throw new InvalidParamError(\n 'Only one of from.amount or to.amount is allowed'\n );\n }\n\n const response = await apiClient.swapQuote({\n environmentId: core.environmentId,\n swapQuoteRequest: {\n from: {\n ...params.from,\n chainId: params.from.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.from.chain as ChainEnum,\n },\n maxPriceImpact: params.maxPriceImpact,\n order: params.order as SwapQuoteRequestOrderEnum,\n slippage: params.slippage,\n to: {\n ...params.to,\n chainId: params.to.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.to.chain as ChainEnum,\n },\n },\n });\n return response;\n};\n","import type {\n ChainEnum,\n SwapStatusRequestChain,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { TokenSwapError } from '../../../errors/TokenSwapError';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { SwapStatusResponse } from '../swap.types';\n\nexport type GetSwapStatusParams = {\n from?: {\n chain: Chain;\n networkId: string;\n };\n to?: {\n chain: Chain;\n networkId: string;\n };\n txHash: string;\n};\n\n/**\n * Gets the status of a swap\n *\n * @param params GetSwapStatusParams - The parameters for the swap status.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The swap status.\n * @not-instrumented\n */\nexport const getSwapStatus = async (\n params: GetSwapStatusParams,\n client = getDefaultClient()\n): Promise<SwapStatusResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n let from: SwapStatusRequestChain | undefined;\n\n if (params.from) {\n from = {\n chainId: params.from.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.from.chain as ChainEnum,\n };\n }\n\n let to: SwapStatusRequestChain | undefined;\n if (params.to) {\n to = {\n chainId: params.to.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.to.chain as ChainEnum,\n };\n }\n try {\n const response = await apiClient.swapStatus({\n environmentId: core.environmentId,\n swapStatusRequest: {\n from,\n to,\n txHash: params.txHash,\n },\n });\n\n return {\n status: response.status,\n substatus: response.substatus,\n };\n } catch (error) {\n throw new TokenSwapError({\n message: 'Failed to get swap status',\n originalError: error,\n });\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\n/**\n * Deletes the current user's account permanently.\n *\n * This function performs a hard delete of the user account. Upon successful deletion,\n * the user will be automatically logged out and all authentication data will be cleared.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the user account is successfully deleted.\n * @instrumented\n */\nexport const deleteUser = async (\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n await apiClient.hardDeleteUser({\n environmentId: core.environmentId,\n });\n\n await logoutWithReason({ reason: 'user-deleted' }, client);\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { isPendingRecoveryCodesAcknowledgment } from '../../mfa/isPendingRecoveryCodesAcknowledgment';\nimport { isUserMissingMfaAuth } from '../../mfa/isUserMissingMfaAuth';\n\n/**\n * Checks if the user has completed all onboarding requirements.\n *\n * This function verifies whether a user has fulfilled all necessary requirements\n * including KYC fields (Know Your Customer information) and MFA setup\n * (Multi-Factor Authentication including recovery codes acknowledgment).\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if onboarding is complete (no pending requirements), false if there are pending requirements.\n * @not-instrumented\n */\nexport const isUserOnboardingComplete = (client = getDefaultClient()) => {\n const user = client.user;\n\n assertDefined(user, 'User not logged in');\n\n const hasMissingKycFields = Boolean(user.missingFields?.length);\n const hasPendingMfaAuth = isUserMissingMfaAuth(client);\n const hasPendingRecoveryCodes = isPendingRecoveryCodesAcknowledgment(client);\n\n const userOnboardingComplete = !hasMissingKycFields && !hasPendingMfaAuth && !hasPendingRecoveryCodes;\n\n return userOnboardingComplete;\n};\n","/**\n * OAuth scopes that must be granted on the user's Google account in order\n * for the keyshare backup upload to Google Drive to succeed.\n *\n * Exported so host apps can pre-flight check or display these in their own\n * UX. Kept as a `readonly` tuple to discourage mutation.\n */\nexport const GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES = [\n 'https://www.googleapis.com/auth/drive.appdata',\n 'https://www.googleapis.com/auth/drive.file',\n] as const;\n\n/**\n * Stable phrase the WaaS layer includes in Google Drive 401 / scope-insufficient\n * upload failure messages. Match by `.includes(...)` rather than equality\n * because the iframe message-handler fallback path rewraps the original error\n * as `new Error(String(response.error))`, which prefixes the message with\n * \"Error: \". The phrase remains unique to the auth/scope case across all the\n * Drive failure reasons (rate-limit, storage-full, 5xx, network all use\n * distinct prefixes), so message-only matching is sufficient to discriminate.\n */\nexport const ACCESS_DENIED_PHRASE = 'Google Drive access denied';\n","import { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../constants';\n\n/**\n * Returns the Google OAuth scopes from `GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES`\n * that are NOT present in `grantedScopes`. An empty array means all required\n * scopes have been granted.\n *\n * @param grantedScopes - Scopes the user has granted to their Google account.\n * @returns The subset of required scopes that are still missing.\n * @not-instrumented\n */\nexport const findMissingGoogleDriveBackupScopes = (\n grantedScopes: readonly string[]\n): string[] =>\n GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES.filter(\n (required) => !grantedScopes.includes(required)\n );\n","import type { UserOauthAccessTokenResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../../client/types';\nimport { createApiClient } from '../../../../apiClient';\n\nexport type FetchGoogleDriveOauthAccessParams = {\n oauthAccountId: string;\n};\n\n/**\n * Fetches the user's stored Google OAuth access token together with the\n * scopes that were granted when the token was issued.\n *\n * Internal to the Google Drive backup readiness check — not exported as a\n * public API. The returned `scopes` array can be empty for legacy tokens\n * captured before the API began tracking granted scopes.\n *\n * @param params.oauthAccountId - The verified-credential id of the linked\n * Google account (see `findGoogleOauthAccountId`).\n * @param client - The Dynamic client instance.\n * @returns The OAuth access token and granted scopes.\n * @not-instrumented\n */\nexport const fetchGoogleDriveOauthAccess = async (\n { oauthAccountId }: FetchGoogleDriveOauthAccessParams,\n client: DynamicClient\n): Promise<UserOauthAccessTokenResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getEndUserOauthAccessToken({\n environmentId: core.environmentId,\n oauthAccountId,\n });\n};\n","import {\n type JwtVerifiedCredential,\n JwtVerifiedCredentialFormatEnum,\n ProviderEnum,\n} from '@dynamic-labs/sdk-api-core';\n\n/**\n * Returns the verified-credential `id` (UUID of the user_oauth_accounts row)\n * for the user's linked Google account, or `undefined` if no Google account\n * is linked.\n *\n * The `getEndUserOauthAccessToken` API path parameter expects this UUID, NOT\n * the third-party `oauthAccountId` (Google's numeric profile ID) — those are\n * stored in the same credential under different fields.\n *\n * @param credentials - The user's verified credentials, typically from\n * `client.user?.verifiedCredentials`.\n * @returns The credential id of the linked Google oauth account, or\n * `undefined`.\n * @not-instrumented\n */\nexport const findGoogleOauthAccountId = (\n credentials: readonly JwtVerifiedCredential[] | undefined\n): string | undefined =>\n credentials?.find(\n (cred) =>\n cred.format === JwtVerifiedCredentialFormatEnum.Oauth &&\n cred.oauthProvider === ProviderEnum.Google\n )?.id;\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../constants';\nimport { findMissingGoogleDriveBackupScopes } from '../findMissingGoogleDriveBackupScopes';\nimport type { GoogleDriveBackupReadiness } from '../googleDrive.types';\nimport { fetchGoogleDriveOauthAccess } from '../utils/fetchGoogleDriveOauthAccess';\nimport { findGoogleOauthAccountId } from '../utils/findGoogleOauthAccountId';\n\n/**\n * Pre-flight readiness check for backing up MPC keyshares to Google Drive.\n *\n * Call this before initiating the keyshare backup ceremony. When the result\n * is `'needs-access'`, have the user re-link their Google account so the\n * required Drive scopes are granted, then call this again before retrying\n * the backup. This avoids spending an MPC reshare ceremony on a backup that\n * will predictably fail.\n *\n * Status values:\n * - `'ready'`: stored scopes include both required Drive scopes; backup\n * should succeed (barring transient errors).\n * - `'needs-access'`: backup likely won't succeed without user intervention.\n * Three sub-cases, distinguished by `missingScopes`:\n * - No Google account linked → `missingScopes` is the full required set.\n * - Some scopes granted but not all → `missingScopes` lists the gap.\n * - Legacy token captured before scope tracking shipped (`scopes: []` from\n * the API) → `missingScopes` is empty. Forcing a fresh consent will\n * populate the scopes column for subsequent calls.\n *\n * Failures of the underlying access-token fetch propagate as Promise\n * rejections — the caller is expected to surface or retry them.\n *\n * Pair with `isInsufficientGoogleDriveScopesError` to detect post-flight\n * scope failures (e.g. for the legacy \"unknown scopes\" case where pre-flight\n * cannot prove failure).\n *\n * @param [client] - The Dynamic client instance. Only required when using\n * multiple Dynamic clients.\n * @returns The readiness result.\n * @instrumented\n */\nexport const getGoogleDriveBackupReadiness = async (\n client = getDefaultClient()\n): Promise<GoogleDriveBackupReadiness> => {\n const { user } = client;\n\n const oauthAccountId = findGoogleOauthAccountId(user?.verifiedCredentials);\n\n if (!oauthAccountId) {\n // No Google credential linked — every required scope is effectively\n // missing, so populate the full set so callers can render their\n // \"we need access to ...\" UX without checking the empty case.\n return {\n missingScopes: GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES,\n status: 'needs-access',\n };\n }\n\n const { accessToken, scopes } = await fetchGoogleDriveOauthAccess(\n { oauthAccountId },\n client\n );\n\n if (scopes.length === 0) {\n // Legacy token captured before scope tracking shipped — we can't\n // confirm the upload will work, so surface as needs-access (with empty\n // missingScopes to differentiate from the explicit-missing case).\n // Forcing a fresh consent populates the scopes column for next time.\n return {\n accessToken,\n missingScopes: [],\n status: 'needs-access',\n };\n }\n\n const missing = findMissingGoogleDriveBackupScopes(scopes);\n\n if (missing.length === 0) {\n return {\n accessToken,\n missingScopes: [],\n status: 'ready',\n };\n }\n\n return {\n accessToken,\n missingScopes: missing,\n status: 'needs-access',\n };\n};\n","import { findMissingGoogleDriveBackupScopes } from '../findMissingGoogleDriveBackupScopes';\n\n/**\n * Returns whether `grantedScopes` covers every Google OAuth scope required\n * to upload a keyshare backup to Google Drive.\n *\n * @param grantedScopes - Scopes the user has granted to their Google account.\n * @returns `true` when every required scope is granted, otherwise `false`.\n * @not-instrumented\n */\nexport const hasAllGoogleDriveBackupScopes = (\n grantedScopes: readonly string[]\n): boolean => findMissingGoogleDriveBackupScopes(grantedScopes).length === 0;\n","import { ACCESS_DENIED_PHRASE } from '../constants';\n\n/**\n * Type-guard for Google Drive backup failures caused by missing or\n * insufficient OAuth scopes (or otherwise denied access).\n *\n * Recover by having the user re-link their Google account and retrying the\n * backup once the granted scopes include\n * `GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES`.\n *\n * @param err - The unknown value to check.\n * @returns `true` when `err` is an `Error` whose message indicates Google\n * Drive access was denied.\n * @not-instrumented\n */\nexport const isInsufficientGoogleDriveScopesError = (\n err: unknown\n): err is Error =>\n err instanceof Error && err.message.includes(ACCESS_DENIED_PHRASE);\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\nimport { WalletAccountNotSelectedError } from './../../../errors/WalletAccountNotSelectedError';\n\ntype AssertWalletAccountSigningAvailabilityParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Asserts that a wallet account is available and ready for signing operations.\n *\n * This function verifies that the specified wallet account is currently\n * connected and selected in the wallet app, ensuring it can perform signing operations.\n *\n * If the wallet account is not available, the user might need to reconnect it or\n * change the account in their wallet app to make it active.\n *\n * @param params.walletAccount - The wallet account to verify signing availability for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves if the wallet is available for signing.\n * @throws WalletAccountNotSelectedError If the wallet account is not currently selected.\n * @not-instrumented\n */\nexport const assertWalletAccountSigningAvailability = async (\n { walletAccount }: AssertWalletAccountSigningAvailabilityParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { addresses } = await walletProvider.getConnectedAddresses();\n\n if (addresses.length > 0 && !addresses.includes(walletAccount.address)) {\n throw new WalletAccountNotSelectedError({\n expectedAddress: walletAccount.address,\n selectedAddress: addresses[0],\n });\n }\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { ConfirmTransactionParams } from '../walletProvider/walletProvider.types';\n\n/**\n * Waits for a transaction to be confirmed on-chain.\n *\n * Delegates to the wallet provider's `confirmTransaction` implementation,\n * which polls the appropriate chain API until the transaction is included\n * in a block or the maximum wait time is exceeded.\n *\n * @param params.walletAccount - The wallet account that submitted the transaction.\n * @param params.transactionHash - The transaction hash to wait for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the transaction is confirmed.\n * @throws If the wallet provider does not support the confirmTransaction method.\n * @instrumented\n */\nexport const confirmTransaction = async (\n { walletAccount, transactionHash }: ConfirmTransactionParams,\n client = getDefaultClient()\n): Promise<void> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'confirmTransaction');\n\n await walletProvider.confirmTransaction({ transactionHash, walletAccount });\n};\n","import type { WalletAddressWithType } from '../../walletAccount/walletAccount.types';\nimport type { WalletProviderConnectResult } from '../../walletProvider/walletProvider.types';\n\n/** @not-instrumented */\nexport const getAddressesWithTypesFromConnectionResult = (\n connectionResult: WalletProviderConnectResult\n): WalletAddressWithType[] => {\n return connectionResult.addresses.filter(\n (address): address is WalletAddressWithType =>\n !!address.address && !!address.type\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport { reconcileWalletAccountsAgainstClient } from '../reconcileWalletAccountsAgainstClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { formatWalletAccountId } from '../utils/formatWalletAccountId';\nimport { getAddressesWithTypesFromConnectionResult } from '../utils/getAddressesWithTypesFromConnectionResult';\nimport type { WalletAccount } from '../walletAccount';\nimport { NoAddressFoundError } from './../../../errors/NoAddressFoundError';\n\ntype ConnectWithWalletProviderParams = {\n addToDynamicWalletAccounts?: boolean;\n hardwareWalletVendor?: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Connects to a wallet provider and returns the connected wallet account.\n *\n * Note: This function will not verify the wallet account, use the verifyWalletAccount function to do that\n * or connectAndVerifyWithWalletProvider to do that in a single step.\n * @see verifyWalletAccount\n * @see connectAndVerifyWithWalletProvider\n *\n * @param params.walletProviderKey - The unique key identifying the wallet provider to connect to (e.g. 'metamaskevm', 'phantomsol').\n * @param [params.addToDynamicWalletAccounts] - Whether to add the connected wallet account to the user's wallet accounts. Defaults to true.\n * @param [params.hardwareWalletVendor] - The hardware wallet vendor, if connecting via a hardware wallet (e.g. 'ledger').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the connected wallet account.\n * @throws NoAddressFoundError If the request to connect was successful but no address is connected to your app.\n * @instrumented\n */\nexport const connectWithWalletProvider = async (\n {\n walletProviderKey,\n addToDynamicWalletAccounts = true,\n hardwareWalletVendor,\n }: ConnectWithWalletProviderParams,\n client = getDefaultClient()\n): Promise<WalletAccount> => {\n const walletProvider = getWalletProviderByKey(\n {\n walletProviderKey,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'connect');\n\n const { addresses } = await walletProvider.connect();\n\n // We only materialize the first connected address to stay consistent with\n // the dynamic-auth pattern — simpler, and there's no real demand for\n // multi-address-per-provider connections at the moment.\n const mainAddress = addresses?.length ? addresses[0].address : null;\n\n /**\n * This error is thrown in case the wallet has no addresses connected\n * to the dapp. Then the error is thrown so the consumer can instruct the\n * user on the next steps.\n */\n if (!mainAddress) {\n throw new NoAddressFoundError();\n }\n\n const walletAccount: WalletAccount = {\n address: mainAddress,\n addressesWithTypes: getAddressesWithTypesFromConnectionResult({\n addresses,\n }),\n chain: walletProvider.chain,\n hardwareWalletVendor,\n id: formatWalletAccountId({\n address: mainAddress,\n chain: walletProvider.chain,\n walletProviderKey,\n }),\n lastSelectedAt: null,\n verifiedCredentialId: null,\n walletProviderKey,\n };\n\n const [reconciledWalletAccount] = reconcileWalletAccountsAgainstClient(\n {\n addToDynamicWalletAccounts,\n walletAccounts: [walletAccount],\n walletProviderKey,\n },\n client\n );\n\n return reconciledWalletAccount;\n};\n","import type { HardwareWalletVendor } from '../hardwareWallet.types';\n\ntype FormatSignatureForHardwareWalletParams = {\n hardwareWalletVendor: HardwareWalletVendor;\n signature: string;\n};\n\n/**\n * Wraps a raw signature in the JSON format expected by the backend for hardware wallet verification.\n *\n * @param params.hardwareWalletVendor - The hardware wallet vendor that produced the signature.\n * @param params.signature - The raw signature string to wrap.\n * @returns The signature wrapped in `{ signedTransaction: { data } }` JSON format.\n * @not-instrumented\n */\nexport const formatSignatureForHardwareWallet = ({\n signature,\n hardwareWalletVendor: _,\n}: FormatSignatureForHardwareWalletParams): string =>\n JSON.stringify({\n signedTransaction: {\n data: signature,\n },\n });\n","import type { Chain } from '../../../chain';\nimport type { WalletProvider } from '../../../wallets/walletProvider/walletProvider.types';\n\n/** @not-instrumented */\nexport const getChainIdForAccountVerification = async ({\n walletProvider,\n}: {\n walletProvider: WalletProvider;\n}) => {\n // for some chains, we don't need to specify a chain id for account verification because it's\n // not required and it might break the message signature in some wallets (e.g. Trust Wallet SOL)\n const chainsThatDontNeedChainId: Chain[] = ['BTC', 'SOL', 'SUI'];\n\n if (chainsThatDontNeedChainId.includes(walletProvider.chain)) {\n return undefined;\n }\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n if (networkId) {\n return networkId;\n }\n\n // default to ethereum mainnet\n if (walletProvider.chain === 'EVM') {\n return '1';\n }\n\n return undefined;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport { getAppMetadata } from '../../../../utils/getAppMetadata';\nimport { getNonce } from '../../../../utils/getNonce';\nimport { CHAINS_INFO_MAP } from '../../constants';\nimport type { WalletAccount } from '../../walletAccount';\nimport { formatSignInMessage } from '../formatSignInMessage';\nimport { getChainIdForAccountVerification } from '../getChainIdForAccountVerification';\nimport { getWalletProviderFromWalletAccount } from '../getWalletProviderFromWalletAccount';\nimport { createSignInMessageStatement } from './createSignInMessageStatement';\n\ntype GetSignInMessageParams = {\n nonce?: string;\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getSignInMessage = async (\n { nonce: nonceOverride, walletAccount }: GetSignInMessageParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const { appUniversalLink } = getAppMetadata(client);\n\n assertDefined(appUniversalLink, 'Universal link is not set');\n\n const url = new URL(appUniversalLink);\n const domain = url.host;\n\n const nonce = nonceOverride ?? (await getNonce(client));\n\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n // for starknet, the message to sign needs to be a JSON object with the domain and nonce\n if (walletProvider.chain === 'STARK') {\n /**\n * Starknet requires the strings to be 31 chars long\n * Nonce - we need to keep full size for nonce verification on the backend (the backend shortens it to 31 chars)\n * Domain - we need to shorten the domain to 31 chars\n */\n return JSON.stringify({\n domain: domain.substring(0, 31),\n nonce,\n });\n }\n\n const statement = createSignInMessageStatement(client);\n\n const messageToSign = await formatSignInMessage({\n address: walletAccount.address,\n blockchainName: CHAINS_INFO_MAP[walletProvider.chain].blockchainName,\n chainId: await getChainIdForAccountVerification({ walletProvider }),\n domain,\n issuedAt: new Date().toISOString(),\n nonce,\n requestId: core.environmentId,\n statement,\n uri: url.toString(),\n });\n\n return messageToSign;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getSignInMessage } from '../utils/getSignInMessage';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype ProveWalletAccountOwnershipParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Proves ownership of a wallet account by signing a verification message.\n *\n * This function generates a sign-in message and requires the user to sign it\n * with their wallet's private key, proving they control the wallet address.\n *\n * @param params.walletAccount - The wallet account to prove ownership of.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the message and signature.\n * @instrumented\n */\nexport const proveWalletAccountOwnership = async (\n { walletAccount }: ProveWalletAccountOwnershipParams,\n client = getDefaultClient()\n): Promise<{\n messageToSign: string;\n signature: string;\n}> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'signMessage');\n\n const messageToSign = await getSignInMessage(\n { nonce: walletProvider.getConnectProofNonce?.(), walletAccount },\n client\n );\n\n const { signature } = await walletProvider.signMessage({\n message: messageToSign,\n walletAccount,\n });\n\n return { messageToSign, signature };\n};\n","import type { Chain } from '../../../chain';\nimport { normalizeAddress } from '../normalizeAddress';\n\nexport type IsSameAddressOptions = {\n /** The chain used to normalize both addresses before comparison. */\n chain: Chain;\n\n /** The first address to compare. */\n left: string;\n\n /** The second address to compare. */\n right: string;\n};\n\n/** @not-instrumented */\nexport const isSameAddress = ({ chain, left, right }: IsSameAddressOptions) =>\n normalizeAddress({ address: left, chain }) ===\n normalizeAddress({ address: right, chain });\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { getWalletAccounts } from '../getWalletAccounts';\nimport { formatSignatureForHardwareWallet } from '../hardwareWallet/formatSignatureForHardwareWallet';\nimport { proveWalletAccountOwnership } from '../proveWalletAccountOwnership';\nimport { removeUnverifiedWalletAccount } from '../unverifiedWalletAccounts/removeUnverifiedWalletAccount';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport { isSameAddress } from '../utils/isSameAddress';\nimport { verifyMessageSignatureOwnership } from '../verifyMessageSignatureOwnership';\nimport type { WalletAccount } from '../walletAccount';\nimport { updateWalletProviderKeysForVerifiedCredentials } from '../walletProvider/walletProviderKeyMap/updateWalletProviderKeysForVerifiedCredentials';\nimport { WalletAccountAlreadyVerifiedError } from './../../../errors/WalletAccountAlreadyVerifiedError';\n\ntype VerifyWalletAccountForSignInOrTransferParams = {\n isTransfer: boolean;\n requestedScopes?: TokenScope[];\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const verifyWalletAccountForSignInOrTransfer = async (\n {\n walletAccount,\n isTransfer,\n requestedScopes,\n }: VerifyWalletAccountForSignInOrTransferParams,\n client: DynamicClient\n): Promise<WalletAccount> => {\n if (walletAccount.verifiedCredentialId) {\n throw new WalletAccountAlreadyVerifiedError(walletAccount.address);\n }\n\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { messageToSign, signature } = await proveWalletAccountOwnership(\n {\n walletAccount,\n },\n client\n );\n\n const formattedSignature = walletAccount.hardwareWalletVendor\n ? formatSignatureForHardwareWallet({\n hardwareWalletVendor: walletAccount.hardwareWalletVendor,\n signature,\n })\n : signature;\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const response = await verifyMessageSignatureOwnership(\n {\n addressesWithTypes: walletAccount.addressesWithTypes,\n chain: walletAccount.chain,\n isTransfer,\n messageToSign,\n networkId,\n requestedScopes,\n signature: formattedSignature,\n walletAddress: walletAccount.address,\n walletDisplayName: walletProvider.metadata.displayName,\n walletProviderType: walletProvider.walletProviderType,\n },\n client\n );\n\n const walletVerifiedCredential = response.user?.verifiedCredentials.find(\n (verifiedCredential) =>\n isSameAddress({\n chain: walletAccount.chain,\n left: verifiedCredential.address ?? '',\n right: walletAccount.address,\n })\n );\n\n assertDefined(\n walletVerifiedCredential,\n `After verifying, still unable to find verified wallet credential for wallet account ${walletAccount.address} on chain ${walletAccount.chain}`\n );\n\n updateWalletProviderKeysForVerifiedCredentials(\n {\n keysToUpdate: {\n [walletVerifiedCredential.id]: walletProvider.key,\n },\n },\n client\n );\n\n /**\n * Adds the user with the new wallet verified credential\n * This will add the new verified wallet account to the client`s state\n */\n updateAuthFromVerifyResponse({ response }, client);\n\n /**\n * Remove the now verified wallet account from the unverified wallet accounts\n */\n removeUnverifiedWalletAccount(\n { unverifiedWalletAccount: walletAccount },\n client\n );\n\n const verifiedWalletAccount = getWalletAccounts(client).find(({ address }) =>\n isSameAddress({\n chain: walletAccount.chain,\n left: address,\n right: walletAccount.address,\n })\n );\n\n assertDefined(\n verifiedWalletAccount,\n `Unable to find wallet account ${walletAccount.address} on chain ${walletAccount.chain} for verified credential ${walletVerifiedCredential.id}`\n );\n\n return verifiedWalletAccount;\n};\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { verifyWalletAccountForSignInOrTransfer } from '../verifyWalletAccountForSignInOrTransfer';\nimport type { WalletAccount } from '../walletAccount';\n\ntype VerifyWalletAccountParams = {\n requestedScopes?: TokenScope[];\n walletAccount: WalletAccount;\n};\n\n/**\n * Verifies ownership of a wallet account and adds it to the user's profile.\n *\n * This function requires the user to sign a message to prove wallet ownership,\n * then sets the wallet account as verified.\n *\n * @param params.walletAccount - The wallet account to verify ownership of.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verified wallet account.\n * @throws WalletAccountAlreadyVerifiedError If the wallet is already verified.\n * @throws WalletAlreadyLinkedToAnotherUserError If the wallet is linked to another user.\n * @instrumented\n */\nexport const verifyWalletAccount = async (\n { walletAccount, requestedScopes }: VerifyWalletAccountParams,\n client = getDefaultClient()\n): Promise<WalletAccount> => {\n return verifyWalletAccountForSignInOrTransfer(\n {\n isTransfer: false,\n requestedScopes,\n walletAccount,\n },\n client\n );\n};\n","import { WalletProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport type { WalletProviderData } from '../walletProvider.types';\n\ntype IsDeeplinkWalletProviderParams = {\n walletProvider: WalletProviderData;\n};\n\n/**\n * Returns true if the wallet provider uses the deep link protocol (e.g. Phantom redirect on mobile).\n * @not-instrumented\n */\nexport const isDeeplinkWalletProvider = ({\n walletProvider,\n}: IsDeeplinkWalletProviderParams): boolean =>\n walletProvider.walletProviderType === WalletProviderEnum.DeepLink;\n","import { AuthModeEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { DeeplinkConnectAndVerifyUnsupportedError } from '../../../errors/DeeplinkConnectAndVerifyUnsupportedError';\nimport { isMobile } from '../../../utils/isMobile';\nimport { createVisit } from '../../auth/createVisit';\nimport { connectWithWalletProvider } from '../connectWithWalletProvider';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport { verifyWalletAccount } from '../verifyWalletAccount';\nimport { isDeeplinkWalletProvider } from '../walletProvider/isDeeplinkWalletProvider';\n\ntype ConnectAndVerifyWithWalletProviderParams = {\n hardwareWalletVendor?: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Connects to a wallet provider and verifies ownership through message signing.\n *\n * This function combines wallet connection and verification in a single step,\n * requiring the user to sign a message to prove wallet ownership before\n * the wallet account is added to their profile.\n *\n * @throws {DeeplinkConnectAndVerifyUnsupportedError} On mobile with deep link\n * wallet providers (e.g. Phantom redirect). This function triggers two sequential\n * deeplinks — one to connect and another to sign for verification. iOS will not\n * honor the second deeplink because it is no longer tied to a user gesture.\n * Android may handle sequential deeplinks differently, but this guard applies to\n * all mobile platforms to ensure a stable experience and prevent production-only\n * errors. Use `connectWithWalletProvider` first and then invoke\n * `verifyWalletAccount` separately from a new user gesture (e.g. a \"Verify\n * Ownership\" button).\n *\n * @param params.walletProviderKey - The unique key identifying the wallet provider to connect to.\n * @param [params.hardwareWalletVendor] - The hardware wallet vendor, if connecting via a hardware wallet (e.g. 'ledger').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the connected and verified wallet account.\n * @instrumented\n */\nexport const connectAndVerifyWithWalletProvider = async (\n { walletProviderKey, hardwareWalletVendor }: ConnectAndVerifyWithWalletProviderParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n if (isMobile() && isDeeplinkWalletProvider({ walletProvider })) {\n throw new DeeplinkConnectAndVerifyUnsupportedError({ walletProviderKey });\n }\n\n const walletAccount = await connectWithWalletProvider(\n { addToDynamicWalletAccounts: false, hardwareWalletVendor, walletProviderKey },\n client\n );\n\n await verifyWalletAccount({ walletAccount }, client);\n\n /*\n * send information to backend to kick off background jobs\n * this is an async work, but does not need to be awaited\n */\n void createVisit({ authMode: AuthModeEnum.AndSign, walletAccount }, client);\n\n return walletAccount;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { hasWalletProviderConnectMethod } from '../hasWalletProviderConnectMethod';\nimport { getWalletProviders } from '../getWalletProviders';\nimport type { WalletProviderData } from '../walletProvider';\n\n/**\n * Retrieves data for all available wallet providers that can be used for connection.\n *\n * This function returns metadata about wallet providers that users can\n * connect to, like MetaMask, Phantom, etc.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of wallet provider data including chain, keys, and metadata.\n * @not-instrumented\n */\nexport const getAvailableWalletProvidersData = (\n client = getDefaultClient()\n): WalletProviderData[] => {\n const allWalletProviders = getWalletProviders(client);\n\n const filteredWalletProviders = allWalletProviders.filter((walletProvider) =>\n hasWalletProviderConnectMethod({ walletProvider })\n );\n\n return filteredWalletProviders.map((walletProvider) => ({\n chain: walletProvider.chain,\n groupKey: walletProvider.groupKey,\n key: walletProvider.key,\n metadata: walletProvider.metadata,\n walletProviderType: walletProvider.walletProviderType,\n }));\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\n\ntype GetConnectedAddressesParams = {\n walletProviderKey: string;\n};\n\n/**\n * Retrieves all connected addresses for a specific wallet provider.\n *\n * This function returns the list of wallet addresses that are currently\n * connected and available through the specified wallet provider.\n *\n * @param params.walletProviderKey - The unique key of the wallet provider to query.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of connected wallet addresses.\n * @not-instrumented\n */\nexport const getConnectedAddresses = (\n { walletProviderKey }: GetConnectedAddressesParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n return walletProvider.getConnectedAddresses();\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { getWalletAccounts } from '../getWalletAccounts';\nimport { getVerifiedCredentialForWalletAccount } from '../utils/getVerifiedCredentialForWalletAccount';\n\ntype GetOwnerWalletAccountForSmartWalletAccountParams = {\n smartWalletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getOwnerWalletAccountForSmartWalletAccount = (\n { smartWalletAccount }: GetOwnerWalletAccountForSmartWalletAccountParams,\n client = getDefaultClient()\n): WalletAccount | undefined => {\n const smartWalletVerifiedCredential = getVerifiedCredentialForWalletAccount(\n { walletAccount: smartWalletAccount },\n client\n );\n\n assertDefined(\n smartWalletVerifiedCredential?.signerRefId,\n 'Invalid smart wallet account'\n );\n\n return getWalletAccounts(client).find(\n (walletAccount) =>\n walletAccount.verifiedCredentialId ===\n smartWalletVerifiedCredential.signerRefId\n );\n};\n","import type { WalletAccount, WalletAddressType } from '../walletAccount';\n\ntype GetWalletAccountAddressByTypeParams = {\n type: WalletAddressType;\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getWalletAccountAddressByType = ({\n type,\n walletAccount,\n}: GetWalletAccountAddressByTypeParams) => {\n return walletAccount.addressesWithTypes?.find(\n (address) => address.type === type\n )?.address;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { WalletProviderData } from '../walletProvider';\n\ntype GetWalletProviderDataByKeyParams = {\n walletProviderKey: string;\n};\n\n/**\n * Retrieves data for a specific wallet provider that can be used for display or connection.\n *\n * @param params.walletProviderKey - The key of the wallet provider to retrieve data for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The data for the wallet provider.\n * @not-instrumented\n */\nexport const getWalletProviderDataByKey = (\n { walletProviderKey }: GetWalletProviderDataByKeyParams,\n client = getDefaultClient()\n): WalletProviderData => {\n const { chain, groupKey, key, metadata, walletProviderType } =\n getWalletProviderByKey({ walletProviderKey }, client);\n\n return { chain, groupKey, key, metadata, walletProviderType };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletAccounts } from '../getWalletAccounts';\n\n/**\n * Checks whether the session has at least one connected wallet account.\n *\n * Both verified and unverified wallet accounts count as connected. This is a\n * single building block for a custom signed-in check — combine it with whatever\n * else your app considers \"signed in\" (e.g. `client.user`, completed onboarding,\n * a required embedded wallet, …).\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if the session has at least one wallet account, false otherwise.\n * @not-instrumented\n */\nexport const isAnyWalletAccountConnected = (\n client = getDefaultClient()\n): boolean => getWalletAccounts(client).length > 0;\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet.types';\n\ntype CanConnectWithHardwareWalletParams = {\n hardwareWalletVendor: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Checks whether a wallet provider supports connecting with a specific hardware wallet vendor.\n *\n * @param params.walletProviderKey - The key of the wallet provider to check.\n * @param params.hardwareWalletVendor - The hardware wallet vendor to check for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Whether the wallet provider supports the specified hardware wallet vendor.\n * @not-instrumented\n */\nexport const canConnectWithHardwareWallet = (\n {\n walletProviderKey,\n hardwareWalletVendor,\n }: CanConnectWithHardwareWalletParams,\n client = getDefaultClient()\n): boolean => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey },\n client\n );\n\n return (\n walletProvider.metadata.supportedHardwareWalletVendors?.includes(\n hardwareWalletVendor\n ) ?? false\n );\n};\n","import type { WalletAccount } from '../../walletAccount';\n\ntype IsHardwareWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks whether a wallet account was connected via a hardware wallet.\n *\n * @param params.walletAccount - The wallet account to check.\n * @returns Whether the wallet account has a hardware wallet vendor set.\n * @not-instrumented\n */\nexport const isHardwareWalletAccount = ({\n walletAccount,\n}: IsHardwareWalletAccountParams): boolean =>\n walletAccount.hardwareWalletVendor !== undefined;\n","import type { WalletAccount } from '../walletAccount';\n\ntype isWalletAccountVerifiedParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks if a wallet account has been verified by a user.\n *\n * @param walletAccount - The wallet account to check.\n * @returns True if the wallet account has been verified, false otherwise.\n * @not-instrumented\n */\nexport const isWalletAccountVerified = ({\n walletAccount,\n}: isWalletAccountVerifiedParams) => {\n return walletAccount.verifiedCredentialId !== null;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { NetworkAddingUnavailableError } from '../../../../errors/NetworkAddingUnavailableError';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\nimport type { NetworkData } from '../networkProvider/networkProvider.types';\n\ntype AddNetworkParams = {\n networkData: NetworkData;\n walletAccount: WalletAccount;\n};\n\n/**\n * Adds a network to the wallet provider.\n *\n * This function requests that the wallet provider add a network\n * to its list of available networks.\n *\n * @param params.networkData - The network configuration data to add to the wallet.\n * @param params.walletAccount - The wallet account to add the network for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the network addition is complete.\n * @throws NetworkAddingUnavailableError If the wallet provider doesn't support adding networks.\n * @instrumented\n */\nexport const addNetwork = async (\n { networkData, walletAccount }: AddNetworkParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n if (walletProvider.addNetwork === undefined) {\n throw new NetworkAddingUnavailableError({\n extraMessages: [\n `Wallet provider ${walletAccount.walletProviderKey} does not have addNetwork method`,\n ],\n originalError: null,\n walletProviderKey: walletAccount.walletProviderKey,\n });\n }\n\n return walletProvider.addNetwork({ networkData });\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getNetworksData } from '../getNetworksData';\n\ntype GetActiveNetworkDataParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Retrieves the network configuration data for the currently active network.\n *\n * This function returns detailed network information including RPC URLs,\n * native currency details, and block explorer URLs for the network that\n * the wallet account is currently connected to.\n *\n * @param params.walletAccount - The wallet account to get network data for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the network data, or undefined if not found.\n * @not-instrumented\n */\nexport const getActiveNetworkData = async (\n { walletAccount }: GetActiveNetworkDataParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const networksData = getNetworksData(client);\n\n const activeNetworkData = networksData.find(\n (data) =>\n data.networkId === networkId && data.chain === walletProvider.chain\n );\n\n return { networkData: activeNetworkData };\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype GetActiveNetworkIdParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * This function returns the network identifier that this wallet account's provider is currently connected to.\n *\n * @param params.walletAccount - The wallet account to get the network ID for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the active network ID for the wallet account.\n * @not-instrumented\n */\nexport const getActiveNetworkId = (\n { walletAccount }: GetActiveNetworkIdParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n return walletProvider.getActiveNetworkId();\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getNetworkProviderFromNetworkId } from '../getNetworkProviderFromNetworkId';\n\ntype GetNativeBalanceParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Retrieves the native token balance for a wallet account on its active\n * network. Reads directly from the chain's network provider (RPC), not\n * the Dynamic API.\n *\n * Use this when you only need the user's gas / native-currency balance\n * (ETH, SOL, BTC, etc.). For token balances, use\n * {@link getTokenBalances}; for a multi-chain portfolio snapshot, use\n * {@link getMultichainTokenBalances}.\n *\n * @param params.walletAccount - The wallet account to get the balance for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the balance as a string or null.\n * @not-instrumented\n */\nexport const getNativeBalance = async (\n { walletAccount }: GetNativeBalanceParams,\n client = getDefaultClient()\n): Promise<{ balance: string | null }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const networkProvider = getNetworkProviderFromNetworkId(\n { chain: walletProvider.chain, networkId },\n client\n );\n\n return networkProvider.getBalance({ address: walletAccount.address });\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { Chain } from '../../../chain';\nimport { getNetworkProviderFromNetworkId } from '../getNetworkProviderFromNetworkId';\n\ntype GetBalanceForAddressParams = {\n address: string;\n chain: Chain;\n networkId: string;\n};\n\n/**\n * Retrieves the native token balance for a specific address on a given network.\n *\n * This function queries the balance directly for any address without requiring\n * a connected wallet account, useful for checking balances of external addresses.\n *\n * @param params.address - The wallet address to check the balance for.\n * @param params.chain - The chain (e.g., 'EVM', 'SOL').\n * @param params.networkId - The specific network ID within the chain.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the balance as a string or null.\n * @not-instrumented\n */\nexport const getBalanceForAddress = async (\n { address, chain, networkId }: GetBalanceForAddressParams,\n client = getDefaultClient()\n): Promise<{ balance: string | null }> => {\n const networkProvider = getNetworkProviderFromNetworkId(\n { chain, networkId },\n client\n );\n\n assertDefined(\n networkProvider,\n `No network found for chain ${chain} and network id ${networkId}. Please ensure you've enabled this network in the Dashboard.`\n );\n\n return networkProvider.getBalance({ address });\n};\n","import type {\n ChainEnum,\n WalletTransactionsResponse,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { Chain } from '../../../chain/chain.types';\n\nexport type GetTransactionHistoryParams = {\n address: string;\n chain: Chain;\n limit?: number;\n networkId: number;\n offset?: string;\n tokenAddress?: string;\n};\n\nexport type GetTransactionHistoryResponse = WalletTransactionsResponse;\n\n/**\n * Retrieves the transaction history for a given wallet address, chain and network.\n *\n * This function fetches the transaction history for a specified wallet address and chain,\n * returning a list of transactions associated with that address along with nextOffset for pagination.\n *\n * @param params.address - The wallet address to query transactions for.\n * @param params.chain - The chain to query transactions for.\n * @param [params.limit] - The maximum number of transactions to return.\n * @param params.networkId - The network ID to query transactions for.\n * @param [params.offset] - The offset to use for pagination.\n * @param [params.tokenAddress] - Optional token contract address (EVM) or SPL mint address (Solana) to filter transaction history by token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the transaction history along with nextOffset for the given wallet address and chain.\n * @not-instrumented\n */\nexport const getTransactionHistory = async (\n params: GetTransactionHistoryParams,\n client = getDefaultClient()\n): Promise<WalletTransactionsResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.getWalletTransactions({\n address: params.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.chain as ChainEnum,\n environmentId: core.environmentId,\n limit: params.limit,\n networkId: params.networkId,\n offset: params.offset,\n tokenAddress: params.tokenAddress,\n });\n\n return response;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype IsProgrammaticNetworkSwitchAvailableParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks if programmatic network switching is available for a wallet account.\n *\n * This function determines whether the wallet provider supports automatic\n * network switching without requiring the user to manually switch networks on their wallet app.\n *\n * @param params.walletAccount - The wallet account to check network switching support for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if programmatic network switching is available, false otherwise.\n * @not-instrumented\n */\nexport const isProgrammaticNetworkSwitchAvailable = (\n { walletAccount }: IsProgrammaticNetworkSwitchAvailableParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n return walletProvider.switchActiveNetwork !== undefined;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { NetworkSwitchingUnavailableError } from '../../../../errors/NetworkSwitchingUnavailableError';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype SwitchActiveNetworkParams = {\n networkId: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Switches the active network for a wallet account.\n *\n * This function programmatically changes the network\n * that the wallet is currently connected to.\n *\n * @param params.networkId - The identifier of the network to switch to. Should match the networkId of the network data.\n * @param params.walletAccount - The wallet account to switch networks for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the network switch is complete.\n * @throws NetworkSwitchingUnavailableError If the wallet provider doesn't support network switching.\n * @instrumented\n */\nexport const switchActiveNetwork = async (\n { networkId, walletAccount }: SwitchActiveNetworkParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n if (walletProvider.switchActiveNetwork === undefined) {\n throw new NetworkSwitchingUnavailableError({\n extraMessages: [\n `Wallet provider ${walletAccount.walletProviderKey} does not have switchActiveNetwork method`,\n ],\n originalError: null,\n walletProviderKey: walletAccount.walletProviderKey,\n });\n }\n\n return walletProvider.switchActiveNetwork({ networkId });\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../../auth/updateAuthFromVerifyResponse';\nimport { setUnverifiedWalletAccounts } from '../../unverifiedWalletAccounts/setUnverifiedWalletAccounts';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getPrimaryWalletAccount } from './../getPrimaryWalletAccount';\n\ntype SelectPrimaryWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Make the wallet account provided as the primary wallet account.\n * @instrumented\n */\nexport const selectPrimaryWalletAccount = async (\n { walletAccount }: SelectPrimaryWalletAccountParams,\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n\n const currentPrimaryWalletAccount = getPrimaryWalletAccount(client);\n\n if (currentPrimaryWalletAccount?.id === walletAccount.id) {\n return;\n }\n\n if (walletAccount.verifiedCredentialId) {\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.selectUserWallet({\n environmentId: core.environmentId,\n userWalletSelectionRequest: {\n walletId: walletAccount.verifiedCredentialId,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n } else {\n const updatedWalletAccount = {\n ...walletAccount,\n lastSelectedAt: new Date(),\n };\n\n setUnverifiedWalletAccounts(\n {\n unverifiedWalletAccountsToUpdate: [updatedWalletAccount],\n },\n client\n );\n }\n};\n","import type { DynamicClient } from '../../../client/types';\nimport { NoWalletProviderFoundError } from '../../../errors/NoWalletProviderFoundError';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype DisconnectWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * This function disconnects the specified wallet account with the wallet provider.\n *\n * The wallet account is not removed from the user's profile or from dynamic's state,\n * it is only responsible for terminating the connection with the wallet provider.\n * @not-instrumented\n */\nexport const disconnectWalletAccount = async (\n { walletAccount }: DisconnectWalletAccountParams,\n client: DynamicClient\n): Promise<void> => {\n try {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n await walletProvider.disconnectWalletAccount?.({ walletAccount });\n } catch (error) {\n // If there is no wallet provider, we don't need to do anything\n // as the wallet account is not connected. It's fine to ignore this error.\n if (error instanceof NoWalletProviderFoundError) {\n return;\n }\n\n throw error;\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { disconnectWalletAccount } from '../disconnectWalletAccount';\nimport { removeUnverifiedWalletAccount } from '../unverifiedWalletAccounts/removeUnverifiedWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype RemoveWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Removes a wallet account from the current session or user (if authenticated).\n *\n * This function both disconnects and removes the specified wallet account,\n * updating local state and server records (if there is an authenticated user).\n * For verified wallets, it will unlink them from the user's account.\n *\n * @param params.walletAccount - The wallet account to remove.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the wallet account is successfully removed.\n * @instrumented\n */\nexport const removeWalletAccount = async (\n { walletAccount }: RemoveWalletAccountParams,\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await disconnectWalletAccount({ walletAccount }, client);\n\n if (!walletAccount.verifiedCredentialId) {\n removeUnverifiedWalletAccount(\n { unverifiedWalletAccount: walletAccount },\n client\n );\n\n return;\n }\n\n const response = await apiClient.verifyUnlink({\n environmentId: core.environmentId,\n verifyUnlinkRequest: {\n walletId: walletAccount.verifiedCredentialId,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype SignMessageParams = {\n message: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Signs a message using the specified wallet account.\n *\n * This function uses the wallet's private key to cryptographically sign\n * the provided message.\n *\n * @param params.walletAccount - The wallet account to use for signing.\n * @param params.message - The message to sign.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the signature.\n * @instrumented\n */\nexport const signMessage = async (\n { walletAccount, message }: SignMessageParams,\n client = getDefaultClient()\n): Promise<{ signature: string }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'signMessage');\n\n const { signature } = await walletProvider.signMessage({\n message,\n walletAccount,\n });\n\n return { signature };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { TransferAmountParams } from '../walletProvider/walletProvider.types';\n\n/**\n * Transfers an amount of currency from the wallet account to a recipient.\n *\n * Supports native token transfers and, where supported by the chain,\n * fungible/token transfers via the optional `token` parameter.\n *\n * @param params.walletAccount - The wallet account to transfer from.\n * @param params.amount - The amount to transfer as a decimal string (e.g. \"1.5\").\n * @param params.recipient - The recipient address.\n * @param params.token - Optional token info for non-native transfers.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the transaction hash.\n * @throws If the wallet provider does not support the transfer amount method.\n * @instrumented\n */\nexport const transferAmount = async (\n { walletAccount, amount, recipient, token }: TransferAmountParams,\n client = getDefaultClient()\n): Promise<{ transactionHash: string }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'transferAmount');\n\n const { transactionHash } = await walletProvider.transferAmount({\n amount,\n recipient,\n token,\n walletAccount,\n });\n\n return { transactionHash };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { connectWithWalletProvider } from '../connectWithWalletProvider';\nimport { verifyWalletAccountForSignInOrTransfer } from '../verifyWalletAccountForSignInOrTransfer';\n\ntype TransferWalletAccountParams = {\n walletProviderKey: string;\n};\n\n/**\n * Transfer a wallet account to the current user's account.\n *\n * This function requires the user to sign a message to prove wallet ownership,\n * then transfers the wallet account to the current user's account.\n *\n * @param params.walletProviderKey - The key of the wallet provider of the wallet account to transfer.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the transferred wallet account.\n * @instrumented\n */\nexport const transferWalletAccount = async (\n { walletProviderKey }: TransferWalletAccountParams,\n client = getDefaultClient()\n) => {\n const walletAccount = await connectWithWalletProvider(\n { addToDynamicWalletAccounts: false, walletProviderKey },\n client\n );\n\n return verifyWalletAccountForSignInOrTransfer(\n {\n isTransfer: true,\n walletAccount,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport type { Chain } from '../../../chain';\nimport { getWalletAccounts } from '../../getWalletAccounts';\n\ntype GetWalletAccountFromAddressParams = {\n address: string;\n chain: Chain;\n};\n\n/**\n * Finds a wallet account by address and blockchain.\n *\n * This function searches through the current session's wallet accounts\n * to find one matching the specified address and chain.\n *\n * @param params.address - The wallet address to search for.\n * @param params.chain - The blockchain the wallet belongs to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The matching wallet account, or undefined if not found.\n * @not-instrumented\n */\nexport const getWalletAccountFromAddress = (\n { address, chain }: GetWalletAccountFromAddressParams,\n client = getDefaultClient()\n) => {\n const walletAccounts = getWalletAccounts(client);\n\n return walletAccounts.find(\n (walletAccount) =>\n walletAccount.address === address && walletAccount.chain === chain\n );\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../../getWalletProviderByKey';\nimport { assertWalletProviderMethodDefined } from '../../../utils/assertWalletProviderMethodDefined';\nimport type { WalletProviderEvents } from '../walletProviderEvents.types';\n\ntype OffWalletProviderEventParams<\n E extends Extract<keyof WalletProviderEvents, string>\n> = {\n callback: WalletProviderEvents[E];\n event: E;\n walletProviderKey: string;\n};\n\n/**\n * Removes a listener from a wallet provider event.\n * You can alternatively use the returned function from `onWalletProviderEvent` instead of using this function.\n *\n * @param params.callback - The callback function to remove. This should be the same function that was passed to the `onWalletProviderEvent` function.\n * @see onWalletProviderEvent\n * @param params.event - The event name to remove the listener from.\n * @param params.walletProviderKey - The unique key identifying the wallet provider to remove the listener from.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @not-instrumented\n */\nexport const offWalletProviderEvent = <\n E extends Extract<keyof WalletProviderEvents, string>\n>(\n { callback, event, walletProviderKey }: OffWalletProviderEventParams<E>,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n assertWalletProviderMethodDefined(walletProvider, 'events');\n\n // We use any here because typescript is messing up the type inference\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.off(event, callback as any);\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../../getWalletProviderByKey';\nimport { assertWalletProviderMethodDefined } from '../../../utils/assertWalletProviderMethodDefined';\nimport type { WalletProviderEvents } from '../walletProviderEvents.types';\n\nexport type OnWalletProviderEventParams<\n E extends Extract<keyof WalletProviderEvents, string>\n> = {\n callback: WalletProviderEvents[E];\n event: E;\n walletProviderKey: string;\n};\n\n/**\n * Listens to a wallet provider event.\n *\n * @param params.callback - The callback function to execute when the event is fired.\n * @param params.event - The event name to listen for.\n * @param params.walletProviderKey - The unique key identifying the wallet provider to listen to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A function that can be called to remove the listener.\n * @not-instrumented\n */\nexport const onWalletProviderEvent = <\n E extends Extract<keyof WalletProviderEvents, string>\n>(\n { callback, event, walletProviderKey }: OnWalletProviderEventParams<E>,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n assertWalletProviderMethodDefined(walletProvider, 'events');\n\n // We use any here because typescript is messing up the type inference\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.on(event, callback as any);\n\n return () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.off(event, callback as any);\n };\n};\n","type ParseUserAgentParams = {\n userAgent: string;\n};\n\ntype ParsedUserAgent = {\n displayText: string;\n type: 'mobile' | 'desktop';\n};\n\nconst browserMatchers = [\n { name: 'Edge', pattern: /Edg(e|A|iOS)?\\// },\n { name: 'Opera', pattern: /OPR\\/|Opera/ },\n { name: 'Samsung Browser', pattern: /SamsungBrowser/ },\n { name: 'Firefox', pattern: /Firefox/ },\n { name: 'Safari', pattern: /^(?!.*(?:Chrome|Chromium|CriOS)).*Safari/ },\n { name: 'Chrome', pattern: /Chrome|CriOS/ },\n] as const;\n\nconst mobileOsNames = new Set(['iPhone', 'iPad', 'Android']);\n\nconst osMatchers = [\n { name: 'iPhone', pattern: /iPhone/ },\n { name: 'iPad', pattern: /iPad/ },\n { name: 'Android', pattern: /Android/ },\n { name: 'Windows', pattern: /Windows/ },\n { name: 'macOS', pattern: /Macintosh|Mac OS X/ },\n { name: 'Linux', pattern: /Linux/ },\n { name: 'ChromeOS', pattern: /CrOS/ },\n] as const;\n\n/** @not-instrumented */\nexport const parseUserAgent = ({\n userAgent,\n}: ParseUserAgentParams): ParsedUserAgent | null => {\n if (!userAgent?.trim()) {\n return null;\n }\n\n const browser = browserMatchers.find(({ pattern }) =>\n pattern.test(userAgent),\n )?.name;\n\n const os = osMatchers.find(({ pattern }) => pattern.test(userAgent))?.name;\n\n if (!browser && !os) {\n return null;\n }\n\n const isMobile = os ? mobileOsNames.has(os) : false;\n\n const displayText =\n browser && os ? `${browser} on ${os}` : (browser ?? os ?? '');\n\n return {\n displayText,\n type: isMobile ? 'mobile' : 'desktop',\n };\n};\n","/* eslint-disable import/no-unassigned-import */\n\nimport { assertPackageVersion } from '@dynamic-labs-sdk/assert-package-version';\n\nimport {\n name as packageName,\n version as packageVersion,\n} from '../../package.json';\nassertPackageVersion(packageName, packageVersion);\n\n// Import the modules states so that they are available in the global scope.\nimport '../modules/auth/state';\nimport '../modules/captcha/state';\nimport '../modules/initializeClient/state';\nimport '../modules/mfa/state';\nimport '../modules/projectSettings/state';\nimport '../modules/sessionKeys/state';\nimport '../modules/wallets/unverifiedWalletAccounts/state';\nimport '../modules/wallets/walletProvider/walletProviderKeyMap/state';\nimport '../utils/getNonce/state';\n\n// Import the event types for the modules so that they are available in the global scope.\nimport '../modules/auth/events';\nimport '../modules/deviceRegistration/events';\nimport '../modules/mfa/events';\nimport '../modules/state/raiseStateEvents/events';\nimport '../modules/wallets/walletAccount/events';\nimport '../modules/wallets/walletProviderRegistry/events';\n\nexport { appendConnectionUriToDeeplink } from '../utils/appendConnectionUriToDeeplink/appendConnectionUriToDeeplink';\nexport { MFAAction } from '@dynamic-labs/sdk-api-core';\nexport type {\n CreateMfaToken,\n DeviceRegistrationResponse,\n TokenScope,\n UserPasskey,\n VerifyResponse,\n} from '@dynamic-labs/sdk-api-core';\nexport type { DynamicCoreConfig } from '../client/core/types';\nexport { createDynamicClient } from '../client/createDynamicClient';\nexport { getDefaultClient } from '../client/defaultClient';\nexport type { DynamicClient, DynamicClientConfig } from '../client/types';\nexport { BaseError, type BaseErrorParameters } from '../errors/base';\nexport { CheckoutSessionTokenMissingError } from '../errors/CheckoutSessionTokenMissingError';\nexport { ClientAlreadyInitializedError } from '../errors/ClientAlreadyInitializedError';\nexport { DeeplinkConnectAndVerifyUnsupportedError } from '../errors/DeeplinkConnectAndVerifyUnsupportedError';\nexport { FeeEstimationFailedError } from '../errors/FeeEstimationFailedError';\nexport { InvalidDeviceRegistrationRedirectError } from '../errors/InvalidDeviceRegistrationRedirectError';\nexport { InvalidExternalAuthError } from '../errors/InvalidExternalAuthError';\nexport { InvalidParamError } from '../errors/InvalidParamError';\nexport { InvalidRedirectStorageStateError } from '../errors/InvalidRedirectStorageStateError';\nexport { InvalidSocialCallbackOriginError } from '../errors/InvalidSocialCallbackOriginError';\nexport { UserCancelledSocialPopUpError } from '../errors/UserCancelledSocialPopUpError';\nexport { LinkCredentialError } from '../errors/LinkCredentialError';\nexport { MfaInvalidOtpError } from '../errors/MfaInvalidOtpError';\nexport { MfaRateLimitedError } from '../errors/MfaRateLimitedError';\nexport { MissingRedirectStorageStateError } from '../errors/MissingRedirectStorageStateError';\nexport { MissingSocialUrlParamError } from '../errors/MissingSocialUrlParamError';\nexport { MissingUserVerificationError } from '../errors/MissingUserVerificationError';\nexport { NetworkAddingUnavailableError } from '../errors/NetworkAddingUnavailableError';\nexport { NetworkNotAddedError } from '../errors/NetworkNotAddedError';\nexport { NetworkSwitchingUnavailableError } from '../errors/NetworkSwitchingUnavailableError';\nexport { NoAddressFoundError } from '../errors/NoAddressFoundError';\nexport { NoNetworkProvidersError } from '../errors/NoNetworkProvidersError';\nexport { NoPasskeyCredentialsFoundError } from '../errors/NoPasskeyCredentialsFoundError';\nexport { NoSmartWalletAccountSignerFoundError } from '../errors/NoSmartWalletAccountSignerFoundError';\nexport { NotWaasWalletAccountError } from '../errors/NotWaasWalletAccountError';\nexport { NoWebAuthNSupportError } from '../errors/NoWebAuthNSupportError';\nexport { SandboxMaximumThresholdReachedError } from '../errors/SandboxMaximumThresholdReachedError';\nexport { SimulationFailedError } from '../errors/SimulationFailedError';\nexport { TokenSwapError } from '../errors/TokenSwapError';\nexport { UnauthorizedError } from '../errors/UnauthorizedError';\nexport { UnavailableInServerSideError } from '../errors/UnavailableInServerSideError';\nexport { UnrecognizedNetworkError } from '../errors/UnrecognizedNetworkError';\nexport { UserNotAuthenticatedError } from '../errors/UserNotAuthenticatedError';\nexport { UserRejectedError } from '../errors/UserRejectedError';\nexport { WalletAccountAlreadyVerifiedError } from '../errors/WalletAccountAlreadyVerifiedError';\nexport { WalletAccountNotSelectedError } from '../errors/WalletAccountNotSelectedError';\nexport { WalletAlreadyLinkedToAnotherUserError } from '../errors/WalletAlreadyLinkedToAnotherUserError';\nexport { WalletProviderMethodUnavailableError } from '../errors/WalletProviderMethodUnavailableError';\nexport { checkStepUpAuth } from '../modules/auth/checkStepUpAuth';\nexport type { LogoutEventMetadata } from '../modules/auth/events';\nexport { requestExternalAuthElevatedToken } from '../modules/auth/externalAuth/requestExternalAuthElevatedToken';\nexport { signInWithExternalJwt } from '../modules/auth/externalAuth/signInWithExternalJwt';\nexport { getElevatedAccessToken } from '../modules/auth/getElevatedAccessToken';\n/** @deprecated Compose your own signed-in check from the SDK primitives instead. See {@link isSignedIn}. */\nexport { isSignedIn } from '../modules/auth/isSignedIn';\nexport { logout } from '../modules/auth/logout';\nexport type { LogoutReason } from '../modules/auth/logoutReason';\nexport { deletePasskey } from '../modules/auth/passkeys/deletePasskey';\nexport { getPasskeys } from '../modules/auth/passkeys/getPasskeys';\nexport { registerPasskey } from '../modules/auth/passkeys/registerPasskey';\nexport { signInWithPasskey } from '../modules/auth/passkeys/signInWithPasskey';\nexport { getUserSocialAccounts } from '../modules/auth/social/getUserSocialAccounts';\nexport { signInWithSocialRedirect } from '../modules/auth/social/oauth/signInWithSocialRedirect';\nexport { signInWithSocialPopUp } from '../modules/auth/social/oauth/signInWithSocialPopUp';\nexport { detectSocialRedirectUrl } from '../modules/auth/social/oauth/detectSocialRedirectUrl';\nexport { completeSocialRedirect } from '../modules/auth/social/oauth/completeSocialRedirect';\n/** @deprecated Use {@link signInWithSocialRedirect} instead. */\nexport { authenticateWithSocial } from '../modules/auth/social/oauth/authenticateWithSocial';\n/** @deprecated Use {@link completeSocialRedirect} instead. */\nexport { completeSocialAuthentication } from '../modules/auth/social/oauth/completeSocialAuthentication';\n/** @deprecated Use {@link detectSocialRedirectUrl} instead. */\nexport { detectOAuthRedirect } from '../modules/auth/social/oauth/detectOAuthRedirect';\nexport { unlinkSocialAccount } from '../modules/auth/social/oauth/unlinkSocialAccount';\nexport type {\n SocialAccount,\n SocialProvider,\n} from '../modules/auth/social/social.types';\nexport {\n getTokenBalances,\n type GetTokenBalancesParams,\n} from '../modules/balances/getTokenBalances';\nexport {\n getMultichainTokenBalances,\n type GetMultichainTokenBalancesParams,\n} from '../modules/balances/getMultichainTokenBalances';\n/** @deprecated Use {@link getTokenBalances} instead. */\nexport {\n getBalances,\n type GetBalancesParams,\n} from '../modules/balances/getBalances';\n/** @deprecated Use {@link getMultichainTokenBalances} instead. */\nexport {\n getMultichainBalances,\n type GetMultichainBalancesParams,\n} from '../modules/balances/getMultichainBalances';\nexport { isCaptchaRequired } from '../modules/captcha/isCaptchaRequired';\nexport { setCaptchaToken } from '../modules/captcha/setCaptchaToken';\nexport type { Chain } from '../modules/chain';\nexport { attachCheckoutTransactionSource } from '../modules/checkout/attachCheckoutTransactionSource';\nexport type { AttachCheckoutTransactionSourceParams } from '../modules/checkout/attachCheckoutTransactionSource';\nexport { broadcastCheckoutTransaction } from '../modules/checkout/broadcastCheckoutTransaction';\nexport type { BroadcastCheckoutTransactionParams } from '../modules/checkout/broadcastCheckoutTransaction';\nexport { cancelCheckoutTransaction } from '../modules/checkout/cancelCheckoutTransaction';\nexport type { CancelCheckoutTransactionParams } from '../modules/checkout/cancelCheckoutTransaction';\nexport type {\n CheckoutExecutionState,\n CheckoutFailure,\n CheckoutFeeBreakdown,\n CheckoutRiskState,\n CheckoutSettlementData,\n CheckoutSettlementState,\n CheckoutSourceType,\n CheckoutSupportedExchangeProvider,\n CheckoutTransaction,\n CheckoutTransactionCreateResponse,\n CheckoutTransactionQuote,\n} from '../modules/checkout/checkout.types';\nexport { createCheckoutTransaction } from '../modules/checkout/createCheckoutTransaction';\nexport type { CreateCheckoutTransactionParams } from '../modules/checkout/createCheckoutTransaction';\nexport type {\n CheckoutTransactionExecutionStateChangedEvent,\n CheckoutTransactionSettlementStateChangedEvent,\n} from '../modules/checkout/events';\nexport { getCheckoutTransaction } from '../modules/checkout/getCheckoutTransaction';\nexport type { GetCheckoutTransactionParams } from '../modules/checkout/getCheckoutTransaction';\nexport { getCheckoutTransactionQuote } from '../modules/checkout/getCheckoutTransactionQuote';\nexport type { GetCheckoutTransactionQuoteParams } from '../modules/checkout/getCheckoutTransactionQuote';\nexport { prepareCheckoutTransaction } from '../modules/checkout/prepareCheckoutTransaction';\nexport type { PrepareCheckoutTransactionParams } from '../modules/checkout/prepareCheckoutTransaction';\nexport { submitCheckoutTransaction } from '../modules/checkout/submitCheckoutTransaction';\nexport type { SubmitCheckoutTransactionParams } from '../modules/checkout/submitCheckoutTransaction';\nexport { trackCheckoutTransaction } from '../modules/checkout/trackCheckoutTransaction';\nexport type { TrackCheckoutTransactionParams } from '../modules/checkout/trackCheckoutTransaction';\nexport { requiresConversion } from '../modules/checkout/utils/requiresConversion';\nexport type { RequiresConversionParams } from '../modules/checkout/utils/requiresConversion';\nexport { offEvent, onceEvent, onEvent } from '../modules/clientEvents';\nexport type {\n DynamicEvents,\n OffEventParams,\n OnceEventParams,\n OnEventParams,\n} from '../modules/clientEvents/clientEvents.types';\nexport { completeDeviceRegistration } from '../modules/deviceRegistration/completeDeviceRegistration';\nexport { detectDeviceRegistrationRedirect } from '../modules/deviceRegistration/detectDeviceRegistrationRedirect';\nexport { getDeviceRegistrationTokenFromUrl } from '../modules/deviceRegistration/getDeviceRegistrationTokenFromUrl';\nexport { getRegisteredDevices } from '../modules/deviceRegistration/getRegisteredDevices';\nexport { isDeviceRegistrationRequired } from '../modules/deviceRegistration/isDeviceRegistrationRequired';\nexport { revokeAllRegisteredDevices } from '../modules/deviceRegistration/revokeAllRegisteredDevices';\nexport { revokeRegisteredDevice } from '../modules/deviceRegistration/revokeRegisteredDevice';\nexport { hasExtension } from '../modules/extension/hasExtension';\nexport { addCoinbaseOnrampOrderEventListener } from '../modules/funding/coinbase/addCoinbaseOnrampOrderEventListener';\nexport type {\n CoinbaseCreateOnrampOrderRequest,\n CoinbaseOnrampFeeType,\n CoinbaseOnrampGetBuyUrlRequest,\n CoinbaseOnrampGetBuyUrlResponse,\n CoinbaseOnrampMissingVerificationErrorCode,\n CoinbaseOnrampOrderPaymentLinkType,\n CoinbaseOnrampOrderPaymentMethod,\n CoinbaseOnrampOrderResponse,\n CoinbaseOnrampOrderStatus,\n FieldMissingVerificationForCoinbaseOnramp,\n} from '../modules/funding/coinbase/coinbase.types';\nexport { createCoinbaseOnrampOrder } from '../modules/funding/coinbase/createCoinbaseOnrampOrder';\nexport { getCoinbaseBuyUrl } from '../modules/funding/coinbase/getCoinbaseBuyUrl';\nexport { getMissingVerificationForCoinbaseOnrampOrder } from '../modules/funding/coinbase/getMissingVerificationForCoinbaseOnrampOrder';\nexport { createCryptoDotComPayment } from '../modules/funding/cryptoDotCom/createCryptoDotComPayment';\nexport type {\n CryptoDotComPaymentCreateRequest,\n CryptoDotComPaymentResponse,\n} from '../modules/funding/cryptoDotCom/cryptoDotCom.types';\nexport { getMoonPayCurrencies } from '../modules/funding/moonpay/getMoonPayCurrencies';\nexport { getMoonPayUrl } from '../modules/funding/moonpay/getMoonPayUrl';\nexport type {\n GetMoonPayCurrenciesParams,\n GetMoonPayUrlParams,\n MoonPayCurrency,\n} from '../modules/funding/moonpay/moonpay.types';\nexport {\n createKrakenExchangeTransfer,\n type KrakenTransferRequest,\n} from '../modules/funding/kraken/createKrakenExchangeTransfer';\nexport {\n getKrakenAccounts,\n type GetKrakenAccountsParams,\n} from '../modules/funding/kraken/getKrakenAccounts';\nexport { getKrakenWhitelistedAddresses } from '../modules/funding/kraken/getKrakenWhitelistedAddresses';\nexport type {\n ExchangeTransferResponse,\n KrakenAccount,\n TransferDestinationResponse,\n} from '../modules/funding/kraken/kraken.types';\nexport { initializeClient } from '../modules/initializeClient';\nexport type { DynamicInitStatus } from '../modules/initializeClient/state';\nexport { waitForClientInitialized } from '../modules/initializeClient/waitForClientInitialized';\nexport { setInstrumentationEnabled } from '../modules/instrumentation/setInstrumentationEnabled/setInstrumentationEnabled';\nexport { getWalletConnectCatalog } from '../modules/legacyWalletBook/getWalletConnectCatalog';\nexport type {\n WalletConnectCatalog,\n WalletConnectCatalogDeepLinks,\n WalletConnectCatalogGroup,\n WalletConnectCatalogWallet,\n} from '../modules/legacyWalletBook/getWalletConnectCatalog';\nexport { excludeInstalledFromCatalog } from '../modules/legacyWalletBook/excludeInstalledFromCatalog';\nexport { getWalletConnectCatalogWalletByWalletProviderKey } from '../modules/legacyWalletBook/getWalletConnectCatalogWalletByWalletProviderKey';\nexport { getInstallationLinkForCurrentPlatform } from '../modules/walletOptionsCatalogue/getInstallationLinkForCurrentPlatform';\nexport { getWalletOptionsCatalogue } from '../modules/walletOptionsCatalogue/getWalletOptionsCatalogue/getWalletOptionsCatalogue';\nexport type {\n GetWalletOptionsCatalogueParams,\n InAppBrowserConnectionOption,\n InstallationUrls,\n UriDeeplinkConnectionOption,\n WalletConnectionOption,\n WalletOption,\n WalletOptionOrdering,\n WalletOptionsCatalogue,\n WithWalletProviderConnectionOption,\n WithWalletProviderSource,\n} from '../modules/walletOptionsCatalogue/walletOptionsCatalogue.types';\nexport { matchWalletProvidersToCatalogGroup } from '../modules/legacyWalletBook/matchWalletProvidersToCatalogGroup';\nexport { acknowledgeRecoveryCodes } from '../modules/mfa/acknowledgeRecoveryCodes';\nexport { authenticateMfaRecoveryCode } from '../modules/mfa/authenticateMfaRecoveryCode';\nexport { authenticatePasskeyMFA } from '../modules/mfa/authenticatePasskeyMFA';\nexport { authenticateTotpMfaDevice } from '../modules/mfa/authenticateTotpMfaDevice';\nexport { consumeMfaToken } from '../modules/mfa/consumeMfaToken';\nexport { createNewMfaRecoveryCodes } from '../modules/mfa/createNewMfaRecoveryCodes';\nexport { deleteMfaDevice } from '../modules/mfa/deleteMfaDevice';\nexport { getMfaDevices } from '../modules/mfa/getMfaDevices';\nexport { getMfaMethods } from '../modules/mfa/getMfaMethods';\nexport { getMfaRecoveryCodes } from '../modules/mfa/getMfaRecoveryCodes';\nexport { isMfaRequiredForAction } from '../modules/mfa/isMfaRequiredForAction';\nexport { isPendingRecoveryCodesAcknowledgment } from '../modules/mfa/isPendingRecoveryCodesAcknowledgment';\nexport { isUserMissingMfaAuth } from '../modules/mfa/isUserMissingMfaAuth';\nexport type { MFADevice } from '../modules/mfa/mfa.types';\nexport { registerTotpMfaDevice } from '../modules/mfa/registerTotpMfaDevice';\nexport { setDefaultMfaDevice } from '../modules/mfa/setDefaultMfaDevice';\nexport type { OTPVerification } from '../modules/otp/otp.types';\nexport { sendEmailOTP } from '../modules/otp/sendEmailOTP';\nexport { sendSmsOTP } from '../modules/otp/sendSmsOTP';\nexport {\n supportedCountries,\n type CountryCode,\n} from '../modules/otp/sendSmsOTP/supportedCountries';\nexport { verifyOTP } from '../modules/otp/verifyOTP';\nexport { fetchProjectSettings } from '../modules/projectSettings/fetchProjectSettings';\nexport type {\n BlockaidValidation,\n SimulationResult,\n TransactionFeeData,\n} from '../modules/simulation/simulation.types';\nexport { executeSwapTransaction } from '../modules/swap/executeSwapTransaction';\nexport type { ExecuteSwapTransactionParams } from '../modules/swap/executeSwapTransaction';\nexport { getSwapQuote } from '../modules/swap/getSwapQuote';\nexport type { GetSwapQuoteParams } from '../modules/swap/getSwapQuote';\nexport { getSwapStatus } from '../modules/swap/getSwapStatus';\nexport type { GetSwapStatusParams } from '../modules/swap/getSwapStatus';\nexport type {\n SwapQuoteOrder,\n SwapQuoteResponse,\n SwapStatus,\n SwapStatusResponse,\n SwapSubstatus,\n SwapSubstatusDone,\n SwapSubstatusFailed,\n SwapSubstatusPending,\n SwapTransactionSigningPayload,\n} from '../modules/swap/swap.types';\nexport { deleteUser } from '../modules/user/deleteUser';\nexport { isUserOnboardingComplete } from '../modules/user/isUserOnboardingComplete';\nexport { refreshAuth } from '../modules/user/refreshAuth';\nexport { refreshUser } from '../modules/user/refreshUser';\nexport { updateUser } from '../modules/user/updateUser';\nexport type { UpdateUserFields } from '../modules/user/user.types';\nexport { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../modules/walletBackup/googleDrive/constants';\nexport { findMissingGoogleDriveBackupScopes } from '../modules/walletBackup/googleDrive/findMissingGoogleDriveBackupScopes';\nexport { getGoogleDriveBackupReadiness } from '../modules/walletBackup/googleDrive/getGoogleDriveBackupReadiness';\nexport type {\n GoogleDriveBackupReadiness,\n GoogleDriveBackupReadinessStatus,\n} from '../modules/walletBackup/googleDrive/googleDrive.types';\nexport { hasAllGoogleDriveBackupScopes } from '../modules/walletBackup/googleDrive/hasAllGoogleDriveBackupScopes';\nexport { isInsufficientGoogleDriveScopesError } from '../modules/walletBackup/googleDrive/isInsufficientGoogleDriveScopesError';\nexport { assertWalletAccountSigningAvailability } from '../modules/wallets/assertWalletAccountSigningAvailability';\nexport { confirmTransaction } from '../modules/wallets/confirmTransaction';\nexport { connectAndVerifyWithWalletProvider } from '../modules/wallets/connectAndVerifyWithWalletProvider';\nexport { connectWithWalletProvider } from '../modules/wallets/connectWithWalletProvider';\nexport { getAvailableWalletProvidersData } from '../modules/wallets/getAvailableWalletProvidersData';\nexport { getConnectedAddresses } from '../modules/wallets/getConnectedAddresses';\nexport { getOwnerWalletAccountForSmartWalletAccount } from '../modules/wallets/getOwnerWalletAccountForSmartWalletAccount';\nexport { getWalletAccountAddressByType } from '../modules/wallets/getWalletAccountAddressByType';\nexport { getWalletAccounts } from '../modules/wallets/getWalletAccounts';\nexport { getWalletProviderDataByKey } from '../modules/wallets/getWalletProviderDataByKey';\nexport { isAnyWalletAccountConnected } from '../modules/wallets/isAnyWalletAccountConnected';\nexport { canConnectWithHardwareWallet } from '../modules/wallets/hardwareWallet/canConnectWithHardwareWallet';\nexport type { HardwareWalletVendor } from '../modules/wallets/hardwareWallet/hardwareWallet.types';\nexport { isHardwareWalletAccount } from '../modules/wallets/hardwareWallet/isHardwareWalletAccount';\nexport { isWalletAccountVerified } from '../modules/wallets/isWalletAccountVerified';\nexport { addNetwork } from '../modules/wallets/networks/addNetwork';\nexport { getActiveNetworkData } from '../modules/wallets/networks/getActiveNetworkData';\nexport { getActiveNetworkId } from '../modules/wallets/networks/getActiveNetworkId';\nexport { getNativeBalance } from '../modules/wallets/networks/getNativeBalance';\n/** @deprecated Use {@link getNativeBalance} instead. */\nexport { getBalance } from '../modules/wallets/networks/getBalance';\nexport { getBalanceForAddress } from '../modules/wallets/networks/getBalanceForAddress';\nexport { getNetworksData } from '../modules/wallets/networks/getNetworksData';\nexport {\n getTransactionHistory,\n type GetTransactionHistoryParams,\n type GetTransactionHistoryResponse,\n} from '../modules/wallets/networks/getTransactionHistory';\nexport { isProgrammaticNetworkSwitchAvailable } from '../modules/wallets/networks/isProgrammaticNetworkSwitchAvailable';\nexport type { NetworkProvider } from '../modules/wallets/networks/networkProvider';\nexport type { NetworkData } from '../modules/wallets/networks/networkProvider/networkProvider.types';\nexport { switchActiveNetwork } from '../modules/wallets/networks/switchActiveNetwork';\nexport { getPrimaryWalletAccount } from '../modules/wallets/primaryWalletAccount/getPrimaryWalletAccount';\nexport { selectPrimaryWalletAccount } from '../modules/wallets/primaryWalletAccount/selectPrimaryWalletAccount';\nexport { proveWalletAccountOwnership } from '../modules/wallets/proveWalletAccountOwnership';\nexport { removeWalletAccount } from '../modules/wallets/removeWalletAccount';\nexport { signMessage } from '../modules/wallets/signMessage';\nexport { transferAmount } from '../modules/wallets/transferAmount';\nexport { transferWalletAccount } from '../modules/wallets/transferWalletAccount';\nexport { assertWalletProviderMethodDefined } from '../modules/wallets/utils/assertWalletProviderMethodDefined';\nexport { getWalletAccountFromAddress } from '../modules/wallets/utils/getWalletAccountFromAddress';\nexport { verifyWalletAccount } from '../modules/wallets/verifyWalletAccount';\nexport type {\n WalletAccount,\n WalletAddressType,\n} from '../modules/wallets/walletAccount';\nexport type {\n ConfirmTransactionParams,\n TransferAmountParams,\n WalletProviderData,\n WalletProviderMetadata,\n} from '../modules/wallets/walletProvider';\nexport type { WalletProviderUriConnectionResult } from '../modules/wallets/walletProviderUriConnection.types';\nexport { offWalletProviderEvent } from '../modules/wallets/walletProvider/events/offWalletProviderEvent';\nexport { onWalletProviderEvent } from '../modules/wallets/walletProvider/events/onWalletProviderEvent';\nexport type { OnWalletProviderEventParams } from '../modules/wallets/walletProvider/events/onWalletProviderEvent/onWalletProviderEvent';\nexport type { WalletProviderEvents } from '../modules/wallets/walletProvider/events/walletProviderEvents.types';\nexport { isDeeplinkWalletProvider } from '../modules/wallets/walletProvider/isDeeplinkWalletProvider';\nexport type { DeviceSigner } from '../services/deviceSigner';\nexport { isMobile } from '../utils/isMobile';\nexport { parseUserAgent } from '../utils/parseUserAgent';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,MAAa,oBAAoB;CAC/B,YAAY;CACZ,UAAU;CACV,iBAAiB;CACjB,kBAAkB;CAClB,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;ACYD,MAAa,iCAAiC,EAC5C,eACA,kBACiD;CACjD,MAAM,MAAM,IAAI,IAAI,YAAY;AAEhC,KAAI,aAAa,IAAI,OAAO,cAAc;AAE1C,QAAO,IAAI;;;;;;AC7Bb,MAAa,yBAAyB,OACpC,WACkB;AAGlB,KAFa,QAAQ,OAAO,CAEnB,MAAM,KAAK,CAAC,iBAAiB,U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,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;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xB,EAAE;CAEH,MAAM,KAAK,WAAW,MAAM,EAAE,cAAc,QAAQ,KAAK,UAAU,CAAC,EAAE;AAEtE,KAAI,CAAC,WAAW,CAAC,GACf,QAAO;CAGT,MAAMC,aAAW,KAAK,cAAc,IAAI,GAAG,GAAG;AAK9C,QAAO;EACL,aAHA,WAAW,KAAK,GAAG,QAAQ,MAAM,OAAQ,WAAW,MAAM;EAI1D,MAAMA,aAAW,WAAW;EAC7B;;;;;AChDH,qBAAqBC,MAAaC,QAAe"}
1
+ {"version":3,"file":"index.esm.js","names":["timeoutId: ReturnType<typeof setTimeout> | null","clearExpirationTimeout: VoidFunction | null","logoutWithReason","blob: LegacySessionKeysBlob","stateChanges: Partial<DynamicCoreState>","eventEmitter: AsyncTrackEmitter","EventEmitter","track: AsyncTrack['track']","name","waitForAll: AsyncTrack['waitForAll']","getTracker: AsyncTrack['getTracker']","transport: InstrumentationTransport | undefined","config: InstrumentationConfig","queue: InstrumentationEvent[]","resolutionPromise","getInitialState","logoutWithReason","numberArray: number[]","checkout","urlObject: URL","fieldsMissingVerification: FieldMissingVerificationForCoinbaseOnramp[]","groups: Record<string, WalletConnectCatalogGroup>","wallets: Record<string, WalletConnectCatalogWallet>","normalize","wallets: WalletConnectCatalog['wallets']","groups: WalletConnectCatalog['groups']","result: ConnectionOptionForWalletOption[]","METAMASK_SDK_URI_SUPPORTED_CHAINS: readonly Chain[]","WALLETCONNECT_SUPPORTED_CHAINS: ReadonlySet<Chain>","result: ConnectionOptionForWalletOption[]","result: WithWalletProviderOptionForWalletOption[]","EXCLUDED_WALLET_OPTION_KEYS: ReadonlySet<string>","CONNECTION_OPTION_PRIORITY: Record<WalletConnectionOption['type'], number>","PRIORITY_WALLET_KEYS: readonly string[]","installed: WalletOption[]","connectable: WalletOption[]","installOnly: WalletOption[]","EMPTY_WALLET_BOOK: WalletBookSchema","allConnectionOptions: ConnectionOptionForWalletOption[]","installationUrlsByKey: Map<string, InstallationUrls>","walletOptions: WalletOption[]","formattedOptions: PublicKeyCredentialRequestOptionsJSON","supportedCountries: CountryPhoneData","verifyRequest:\n | EmailVerificationVerifyRequest\n | SmsVerificationVerifyRequest","from: SwapStatusRequestChain | undefined","to: SwapStatusRequestChain | undefined","proveWalletAccountOwnership","isMobile","packageName","packageVersion"],"sources":["../src/modules/state/raiseStateEvents/events.ts","../src/utils/appendConnectionUriToDeeplink/appendConnectionUriToDeeplink.ts","../src/utils/getNonce/prefetchNoncesIfNeeded/prefetchNoncesIfNeeded.ts","../src/services/runtimeServices/createRuntimeServices/createRuntimeServices.ts","../src/modules/auth/initializeAuth/setLongTimeout/setLongTimeout.ts","../src/modules/auth/initializeAuth/initializeAuth.ts","../src/modules/crossTabEventSync/setupCrossTabEventSync/setupCrossTabEventSync.ts","../src/modules/wallets/unverifiedWalletAccounts/schema.ts","../src/modules/wallets/walletProvider/walletProviderKeyMap/schema.ts","../src/modules/storageSync/schema.ts","../src/modules/keychainMigration/migrateSessionKeyToKeychain/KeyMigrationError.ts","../src/modules/keychainMigration/migrateSessionKeyToKeychain/migrateSessionKeyToKeychain.ts","../src/modules/state/raiseStateEvents/raiseStateEvents.ts","../src/modules/storageSync/hydrateStateWithStorage/hydrateStateWithStorage.ts","../src/modules/storageSync/syncStateWithStorage/syncStateWithStorage.ts","../src/modules/storageSync/initializeStorageSync.ts","../src/modules/user/refreshUser/refreshUser.ts","../src/errors/ClientAlreadyInitializedError.ts","../src/modules/initializeClient/initializeClient.ts","../src/services/asyncTrack/createAsyncTrack.ts","../src/services/eventEmitter/createEventEmitter.ts","../src/errors/UnavailableInServerSideError.ts","../src/services/fetch/createWebFetch.ts","../src/services/instrumentation/connectLoggerToInstrumentation/connectLoggerToInstrumentation.ts","../src/services/instrumentation/createInstrumentation/createInstrumentation.ts","../src/services/instrumentation/transports/createDynamicTransport/createDynamicTransport.ts","../src/services/navigate/createNavigationHandler/createNavigationHandler.ts","../src/services/openDeeplink/createWebDeeplinkOpener/createWebDeeplinkOpener.ts","../src/services/passkey/createPasskeyService/createPasskeyService.ts","../src/utils/debouncedMutex/createDebouncedMutex/createDebouncedMutex.ts","../src/errors/InvalidStorageValue.ts","../src/utils/observable/createObservableState/createObservableState.ts","../src/client/consts.ts","../src/client/core/createCore/getInitialState.ts","../src/client/core/createCore/createCore.ts","../src/client/createDynamicClient/createDynamicClient.ts","../src/errors/CheckoutSessionTokenMissingError.ts","../src/errors/DeeplinkConnectAndVerifyUnsupportedError.ts","../src/errors/FeeEstimationFailedError.ts","../src/errors/InvalidDeviceRegistrationRedirectError.ts","../src/errors/InvalidRedirectStorageStateError.ts","../src/errors/InvalidSocialCallbackOriginError.ts","../src/errors/UserCancelledSocialPopUpError.ts","../src/errors/MissingRedirectStorageStateError.ts","../src/errors/MissingSocialUrlParamError.ts","../src/errors/MissingUserVerificationError.ts","../src/errors/NetworkAddingUnavailableError.ts","../src/errors/NetworkNotAddedError.ts","../src/errors/NetworkSwitchingUnavailableError.ts","../src/errors/NoAddressFoundError.ts","../src/errors/NoPasskeyCredentialsFoundError.ts","../src/errors/NoSmartWalletAccountSignerFoundError.ts","../src/errors/NoWebAuthNSupportError.ts","../src/errors/SimulationFailedError.ts","../src/errors/TokenSwapError.ts","../src/errors/UnrecognizedNetworkError.ts","../src/errors/UserNotAuthenticatedError.ts","../src/errors/UserRejectedError.ts","../src/errors/WalletAccountAlreadyVerifiedError.ts","../src/errors/WalletAccountNotSelectedError.ts","../src/errors/WalletProviderMethodUnavailableError.ts","../src/modules/auth/checkStepUpAuth/checkStepUpAuth.ts","../src/modules/auth/externalAuth/requestExternalAuthElevatedToken/requestExternalAuthElevatedToken.ts","../src/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.ts","../src/modules/auth/logout/logout.ts","../src/modules/auth/passkeys/deletePasskey/deletePasskey.ts","../src/modules/auth/passkeys/getPasskeys/getPasskeys.ts","../src/modules/auth/passkeys/getPasskeyRegistrationOptions/getPasskeyRegistrationOptions.ts","../src/modules/auth/passkeys/serverRegisterPasskey/serverRegisterPasskey.ts","../src/modules/auth/passkeys/registerPasskey/registerPasskey.ts","../src/modules/auth/passkeys/getPasskeyAuthenticationSignInOptions/getPasskeyAuthenticationSignInOptions.ts","../src/modules/auth/passkeys/serverSigninPasskey/serverSigninPasskey.ts","../src/modules/auth/passkeys/signInWithPasskey/signInWithPasskey.ts","../src/modules/auth/social/getUserSocialAccounts/getUserSocialAccounts.ts","../src/modules/auth/social/removeDynamicOauthParamsFromUrl/removeDynamicOauthParamsFromUrl.ts","../src/modules/auth/social/oauth/redirectStateStorageSchema/redirectStateStorageSchema.ts","../src/utils/digestSHA256/digestSHA256.ts","../src/utils/encodeBase64Url/encodeBase64Url.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/addOAuthUrlParams/addOAuthUrlParams.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/getOAuthBaseUrl/getOAuthBaseUrl.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/buildOAuthUrl/buildOAuthUrl.ts","../src/modules/auth/social/oauth/signInWithSocialRedirect/signInWithSocialRedirect.ts","../src/modules/auth/social/oauth/signInWithSocialPopUp/signInWithSocialPopUp.ts","../src/modules/auth/social/oauth/detectSocialRedirectUrl/detectSocialRedirectUrl.ts","../src/modules/auth/social/oauth/processSocialCallback/processSocialCallback.ts","../src/modules/auth/social/oauth/completeSocialRedirect/completeSocialRedirect.ts","../src/modules/auth/social/oauth/authenticateWithSocial/authenticateWithSocial.ts","../src/modules/auth/social/oauth/completeSocialAuthentication/completeSocialAuthentication.ts","../src/modules/auth/social/oauth/detectOAuthRedirect/detectOAuthRedirect.ts","../src/modules/wallets/primaryWalletAccount/getPrimaryWalletAccount/getPrimaryWalletAccount.ts","../src/modules/auth/social/oauth/unlinkSocialAccount/unlinkSocialAccount.ts","../src/modules/balances/getTokenBalances/getTokenBalances.ts","../src/modules/balances/getMultichainTokenBalances/getMultichainTokenBalances.ts","../src/modules/balances/getBalances/getBalances.ts","../src/modules/balances/getMultichainBalances/getMultichainBalances.ts","../src/modules/checkout/utils/createCheckoutSessionTokenStorageKey/createCheckoutSessionTokenStorageKey.ts","../src/modules/checkout/utils/createCheckoutApiClient/createCheckoutApiClient.ts","../src/modules/checkout/utils/clearCheckoutSessionToken/clearCheckoutSessionToken.ts","../src/modules/checkout/utils/withCheckoutSessionTokenCleanupOn401/withCheckoutSessionTokenCleanupOn401.ts","../src/modules/checkout/attachCheckoutTransactionSource/attachCheckoutTransactionSource.ts","../src/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.ts","../src/modules/checkout/cancelCheckoutTransaction/cancelCheckoutTransaction.ts","../src/modules/checkout/getCheckouts/getCheckouts.ts","../src/modules/checkout/createCheckoutTransaction/createCheckoutTransaction.ts","../src/modules/checkout/getCheckoutTransaction/getCheckoutTransaction.ts","../src/modules/checkout/getCheckoutTransactionQuote/getCheckoutTransactionQuote.ts","../src/modules/checkout/prepareCheckoutTransaction/prepareCheckoutTransaction.ts","../src/modules/wallets/utils/assertWalletProviderMethodDefined/assertWalletProviderMethodDefined.ts","../src/modules/swap/constants.ts","../src/modules/swap/utils/ensureCorrectActiveNetwork/ensureCorrectActiveNetwork.ts","../src/modules/swap/executeSwapTransaction/executeSwapTransaction.ts","../src/modules/checkout/submitCheckoutTransaction/submitCheckoutTransaction.ts","../src/modules/checkout/trackCheckoutTransaction/trackCheckoutTransaction.ts","../src/modules/checkout/utils/requiresConversion/requiresConversion.ts","../src/modules/deviceRegistration/completeDeviceRegistration/completeDeviceRegistration.ts","../src/modules/deviceRegistration/getDeviceRegistrationTokenFromUrl/getDeviceRegistrationTokenFromUrl.ts","../src/modules/deviceRegistration/detectDeviceRegistrationRedirect/detectDeviceRegistrationRedirect.ts","../src/modules/deviceRegistration/getRegisteredDevices/getRegisteredDevices.ts","../src/modules/deviceRegistration/isDeviceRegistrationRequired/isDeviceRegistrationRequired.ts","../src/modules/deviceRegistration/revokeAllRegisteredDevices/revokeAllRegisteredDevices.ts","../src/modules/deviceRegistration/revokeRegisteredDevice/revokeRegisteredDevice.ts","../src/modules/funding/coinbase/addCoinbaseOnrampOrderEventListener/addCoinbaseOnrampOrderEventListener.ts","../src/modules/funding/coinbase/getMissingVerificationForCoinbaseOnrampOrder/getMissingVerificationForCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/utils/validateUserCredentialsForCoinbaseOnrampOrder/validateUserCredentialsForCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/createCoinbaseOnrampOrder/createCoinbaseOnrampOrder.ts","../src/modules/funding/coinbase/getCoinbaseBuyUrl/getCoinbaseBuyUrl.ts","../src/modules/funding/cryptoDotCom/createCryptoDotComPayment/createCryptoDotComPayment.ts","../src/modules/funding/moonpay/getMoonPayCurrencies/getMoonPayCurrencies.ts","../src/modules/funding/moonpay/errors/MoonPayInvalidUrlError.ts","../src/modules/funding/moonpay/errors/MoonPayProviderNotAvailableError.ts","../src/modules/funding/moonpay/getMoonPayUrl/getMoonPayUrl.ts","../src/modules/funding/kraken/createKrakenExchangeTransfer/createKrakenExchangeTransfer.ts","../src/modules/funding/kraken/getKrakenAccounts/getKrakenAccounts.ts","../src/modules/funding/kraken/getKrakenWhitelistedAddresses/getKrakenWhitelistedAddresses.ts","../src/modules/initializeClient/waitForClientInitialized/waitForClientInitialized.ts","../src/modules/instrumentation/setInstrumentationEnabled/setInstrumentationEnabled.ts","../src/modules/legacyWalletBook/getWalletBookCdnUrl/getWalletBookCdnUrl.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/fetchWithTimeout/fetchWithTimeout.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/walletBookCacheStorageKeySchema.ts","../src/modules/legacyWalletBook/fetchLegacyWalletBook/fetchLegacyWalletBook.ts","../src/modules/legacyWalletBook/shouldFilterWallet/shouldFilterWallet.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect.ts","../src/modules/legacyWalletBook/getSpriteUrl/getSpriteUrl.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformGroup/transformGroup.ts","../src/utils/getChainFromWalletBookIdentifier/getChainFromWalletBookIdentifier.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getChainFromWalletSchema/getChainFromWalletSchema.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformWallet/transformWallet.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/transformWalletBook/transformWalletBook.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getWalletConnectCatalog.ts","../src/modules/legacyWalletBook/matchWalletProvidersToCatalogGroup/matchWalletProvidersToCatalogGroup.ts","../src/modules/legacyWalletBook/excludeInstalledFromCatalog/collectInstalledGroupIds/collectInstalledGroupIds.ts","../src/modules/legacyWalletBook/excludeInstalledFromCatalog/excludeInstalledFromCatalog.ts","../src/modules/wallets/walletProvider/extractChainFromNormalizedName/extractChainFromNormalizedName.ts","../src/modules/legacyWalletBook/getWalletConnectCatalogWalletByWalletProviderKey/getWalletConnectCatalogWalletByWalletProviderKey.ts","../src/utils/isMobile/isMobile.ts","../src/modules/walletOptionsCatalogue/getInstallationLinkForCurrentPlatform/getInstallationLinkForCurrentPlatform.ts","../src/modules/walletOptionsCatalogue/resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey.ts","../src/modules/walletOptionsCatalogue/buildInAppBrowserOptions/getInAppBrowserUrl/getInAppBrowserUrl.ts","../src/modules/walletOptionsCatalogue/buildInAppBrowserOptions/buildInAppBrowserOptions.ts","../src/modules/walletOptionsCatalogue/buildInstallationUrls/buildInstallationUrls.ts","../src/modules/walletOptionsCatalogue/buildInstallationUrlsByWalletOptionKey/buildInstallationUrlsByWalletOptionKey.ts","../src/modules/legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink.ts","../src/modules/walletOptionsCatalogue/buildMetaMaskSdkUriOptions/buildMetaMaskSdkUriOptions.ts","../src/modules/legacyWalletBook/getWalletConnectCatalog/getChainsFromWalletSchema/getChainsFromWalletSchema.ts","../src/modules/walletOptionsCatalogue/buildWalletConnectOptions/buildWalletConnectOptions.ts","../src/modules/walletOptionsCatalogue/buildWalletOption/buildWalletOption.ts","../src/modules/wallets/hasWalletProviderConnectMethod/hasWalletProviderConnectMethod.ts","../src/modules/walletOptionsCatalogue/classifyWithWalletProviderSource/classifyWithWalletProviderSource.ts","../src/modules/wallets/utils/stripChainSuffix/stripChainSuffix.ts","../src/modules/walletOptionsCatalogue/normalizeWalletDisplayName/normalizeWalletDisplayName.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/findByNameMatch/findByNameMatch.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/resolveWalletOptionKey/resolveWalletOptionKey.ts","../src/modules/walletOptionsCatalogue/findWalletOptionKeyForProviderKey/findWalletOptionKeyForProviderKey.ts","../src/modules/walletOptionsCatalogue/buildWithWalletProviderOptions/buildWithWalletProviderOptions.ts","../src/modules/walletOptionsCatalogue/excludedWalletOptionKeys/excludedWalletOptionKeys.ts","../src/modules/walletOptionsCatalogue/groupOptionsByWalletOption/groupOptionsByWalletOption.ts","../src/modules/walletOptionsCatalogue/getConnectionOptionPriority/getConnectionOptionPriority.ts","../src/modules/walletOptionsCatalogue/sortConnectionOptions/sortConnectionOptions.ts","../src/modules/legacyWalletBook/priorityWalletKeys/priorityWalletKeys.ts","../src/modules/walletOptionsCatalogue/getPriorityIndex/getPriorityIndex.ts","../src/modules/walletOptionsCatalogue/compareByRelevance/compareByRelevance.ts","../src/modules/walletOptionsCatalogue/hasAnyConnectionOption/hasAnyConnectionOption.ts","../src/modules/walletOptionsCatalogue/hasInstalledProvider/hasInstalledProvider.ts","../src/modules/walletOptionsCatalogue/sortWalletOptions/sortWalletOptions.ts","../src/modules/walletOptionsCatalogue/getWalletOptionsCatalogue/getWalletOptionsCatalogue.ts","../src/modules/user/updateUser/updateUser.ts","../src/modules/mfa/acknowledgeRecoveryCodes/acknowledgeRecoveryCodes.ts","../src/modules/mfa/authenticateMfaRecoveryCode/authenticateMfaRecoveryCode.ts","../src/modules/auth/passkeys/getPasskeyAuthenticationOptions/getPasskeyAuthenticationOptions.ts","../src/modules/auth/passkeys/serverAuthenticatePasskey/serverAuthenticatePasskey.ts","../src/modules/mfa/authenticatePasskeyMFA/authenticatePasskeyMFA.ts","../src/modules/mfa/authenticateTotpMfaDevice/authenticateTotpMfaDevice.ts","../src/modules/mfa/createNewMfaRecoveryCodes/createNewMfaRecoveryCodes.ts","../src/modules/mfa/deleteMfaDevice/deleteMfaDevice.ts","../src/modules/mfa/getMfaDevices/getMfaDevices.ts","../src/modules/mfa/getMfaRecoveryCodes/getMfaRecoveryCodes.ts","../src/modules/mfa/isPendingRecoveryCodesAcknowledgment/isPendingRecoveryCodesAcknowledgment.ts","../src/modules/mfa/registerTotpMfaDevice/registerTotpMfaDevice.ts","../src/modules/mfa/setDefaultMfaDevice/setDefaultMfaDevice.ts","../src/modules/otp/sendEmailOTP/sendEmailOTP.ts","../src/modules/otp/sendSmsOTP/supportedCountries.ts","../src/modules/otp/sendSmsOTP/sendSmsOTP.ts","../src/modules/otp/verifyOTP/verifyOTPForUserSignIn/verifyOTPForUserSignIn.ts","../src/modules/otp/verifyOTP/verifyOTPForUserUpdate/verifyOTPForUserUpdate.ts","../src/modules/otp/verifyOTP/verifyOTP.ts","../src/modules/swap/getSwapQuote/getSwapQuote.ts","../src/modules/swap/getSwapStatus/getSwapStatus.ts","../src/modules/user/deleteUser/deleteUser.ts","../src/modules/user/isUserOnboardingComplete/isUserOnboardingComplete.ts","../src/modules/walletBackup/googleDrive/constants.ts","../src/modules/walletBackup/googleDrive/findMissingGoogleDriveBackupScopes/findMissingGoogleDriveBackupScopes.ts","../src/modules/walletBackup/googleDrive/utils/fetchGoogleDriveOauthAccess/fetchGoogleDriveOauthAccess.ts","../src/modules/walletBackup/googleDrive/utils/findGoogleOauthAccountId/findGoogleOauthAccountId.ts","../src/modules/walletBackup/googleDrive/getGoogleDriveBackupReadiness/getGoogleDriveBackupReadiness.ts","../src/modules/walletBackup/googleDrive/hasAllGoogleDriveBackupScopes/hasAllGoogleDriveBackupScopes.ts","../src/modules/walletBackup/googleDrive/isInsufficientGoogleDriveScopesError/isInsufficientGoogleDriveScopesError.ts","../src/modules/wallets/assertWalletAccountSigningAvailability/assertWalletAccountSigningAvailability.ts","../src/modules/wallets/confirmTransaction/confirmTransaction.ts","../src/modules/wallets/utils/getAddressesWithTypesFromConnectionResult/getAddressesWithTypesFromConnectionResult.ts","../src/modules/wallets/connectWithWalletProvider/connectWithWalletProvider.ts","../src/modules/wallets/hardwareWallet/formatSignatureForHardwareWallet/formatSignatureForHardwareWallet.ts","../src/modules/wallets/utils/getChainIdForAccountVerification/getChainIdForAccountVerification.ts","../src/modules/wallets/utils/getSignInMessage/getSignInMessage.ts","../src/modules/wallets/proveWalletAccountOwnership/proveWalletAccountOwnership.ts","../src/modules/wallets/utils/isSameAddress/isSameAddress.ts","../src/modules/wallets/verifyWalletAccountForSignInOrTransfer/verifyWalletAccountForSignInOrTransfer.ts","../src/modules/wallets/verifyWalletAccount/verifyWalletAccount.ts","../src/modules/wallets/walletProvider/isDeeplinkWalletProvider/isDeeplinkWalletProvider.ts","../src/modules/wallets/connectAndVerifyWithWalletProvider/connectAndVerifyWithWalletProvider.ts","../src/modules/wallets/getAvailableWalletProvidersData/getAvailableWalletProvidersData.ts","../src/modules/wallets/getConnectedAddresses/getConnectedAddresses.ts","../src/modules/wallets/getOwnerWalletAccountForSmartWalletAccount/getOwnerWalletAccountForSmartWalletAccount.ts","../src/modules/wallets/getWalletAccountAddressByType/getWalletAccountAddressByType.ts","../src/modules/wallets/getWalletProviderDataByKey/getWalletProviderDataByKey.ts","../src/modules/wallets/isAnyWalletAccountConnected/isAnyWalletAccountConnected.ts","../src/modules/wallets/hardwareWallet/canConnectWithHardwareWallet/canConnectWithHardwareWallet.ts","../src/modules/wallets/hardwareWallet/isHardwareWalletAccount/isHardwareWalletAccount.ts","../src/modules/wallets/isWalletAccountVerified/isWalletAccountVerified.ts","../src/modules/wallets/networks/addNetwork/addNetwork.ts","../src/modules/wallets/networks/getActiveNetworkData/getActiveNetworkData.ts","../src/modules/wallets/networks/getActiveNetworkId/getActiveNetworkId.ts","../src/modules/wallets/networks/getNativeBalance/getNativeBalance.ts","../src/modules/wallets/networks/getBalance/getBalance.ts","../src/modules/wallets/networks/getBalanceForAddress/getBalanceForAddress.ts","../src/modules/wallets/networks/getTransactionHistory/getTransactionHistory.ts","../src/modules/wallets/networks/isProgrammaticNetworkSwitchAvailable/isProgrammaticNetworkSwitchAvailable.ts","../src/modules/wallets/networks/switchActiveNetwork/switchActiveNetwork.ts","../src/modules/wallets/primaryWalletAccount/selectPrimaryWalletAccount/selectPrimaryWalletAccount.ts","../src/modules/wallets/disconnectWalletAccount/disconnectWalletAccount.ts","../src/modules/wallets/removeWalletAccount/removeWalletAccount.ts","../src/modules/wallets/signMessage/signMessage.ts","../src/modules/wallets/transferAmount/transferAmount.ts","../src/modules/wallets/transferWalletAccount/transferWalletAccount.ts","../src/modules/wallets/utils/getWalletAccountFromAddress/getWalletAccountFromAddress.ts","../src/modules/wallets/walletProvider/events/offWalletProviderEvent/offWalletProviderEvent.ts","../src/modules/wallets/walletProvider/events/onWalletProviderEvent/onWalletProviderEvent.ts","../src/utils/parseUserAgent/parseUserAgent.ts","../src/exports/index.ts"],"sourcesContent":["import type { DynamicClient } from '../../../client/types';\n\n/**\n * Maps the state keys to the event names.\n *\n * This is mainly to ensure that whenever a new state key is added, the developer\n * will have to come to this file and remember to add it here and in the interface.\n */\nexport const stateChangeEvents = {\n initError: 'initErrorChanged',\n initStatus: 'initStatusChanged',\n mfaToken: 'mfaTokenChanged',\n projectSettings: 'projectSettingsChanged',\n sessionExpiresAt: 'sessionExpiresAtChanged',\n token: 'tokenChanged',\n user: 'userChanged',\n} satisfies {\n [K in keyof DynamicClient]: `${K}Changed`;\n};\n\n// Add the state change events to the global events interface.\ndeclare global {\n interface DynamicEvents {\n initErrorChanged: (args: {\n initError: DynamicClient['initError'];\n }) => void;\n\n initStatusChanged: (args: {\n initStatus: DynamicClient['initStatus'];\n }) => void;\n\n mfaTokenChanged: (args: { mfaToken: DynamicClient['mfaToken'] }) => void;\n\n projectSettingsChanged: (args: {\n projectSettings: DynamicClient['projectSettings'];\n }) => void;\n\n sessionExpiresAtChanged: (args: {\n sessionExpiresAt: DynamicClient['sessionExpiresAt'];\n }) => void;\n\n tokenChanged: (args: { token: DynamicClient['token'] }) => void;\n\n userChanged: (args: { user: DynamicClient['user'] }) => void;\n }\n}\n\nexport type DynamicStateChangeEvents =\n DynamicEvents[(typeof stateChangeEvents)[keyof typeof stateChangeEvents]];\n","type AppendConnectionUriToDeeplinkParams = {\n connectionUri: string;\n deeplinkUrl: string;\n};\n\n/**\n * Appends a wallet connection URI to a deeplink URL.\n *\n * Generic across URI-deeplink connection options — works for both\n * WalletConnect pairing URIs and MetaMask SDK URIs. Determines the\n * appropriate query parameter separator based on whether the deeplink\n * already contains query parameters.\n *\n * @param params.deeplinkUrl - The base deeplink URL (e.g., `walletapp://wc` or `walletapp://wc?param=value`).\n * @param params.connectionUri - The connection URI to append.\n * @returns The deeplink URL with the connection URI appended as a query parameter.\n *\n * @example\n * ```ts\n * appendConnectionUriToDeeplink({ deeplinkUrl: 'walletapp://wc', connectionUri: 'wc:123-456' })\n * // Returns: 'walletapp://wc?uri=wc%3A123-456'\n *\n * appendConnectionUriToDeeplink({ deeplinkUrl: 'walletapp://wc?param=value', connectionUri: 'wc:123-456' })\n * // Returns: 'walletapp://wc?param=value&uri=wc%3A123-456'\n * ```\n * @not-instrumented\n */\nexport const appendConnectionUriToDeeplink = ({\n connectionUri,\n deeplinkUrl,\n}: AppendConnectionUriToDeeplinkParams): string => {\n const url = new URL(deeplinkUrl);\n\n url.searchParams.set('uri', connectionUri);\n\n return url.href;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { NONCE_POOL_SIZE } from '../constants';\nimport { fetchAndStoreNonces } from '../fetchAndStoreNonces/fetchAndStoreNonces';\n\n/** @not-instrumented */\nexport const prefetchNoncesIfNeeded = async (\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n if (core.state.get().prefetchedNonces.length >= NONCE_POOL_SIZE) {\n return;\n }\n\n await fetchAndStoreNonces(client);\n};\n","import type { RuntimeServices } from '../runtimeServices.types';\n\n/**\n * Creates a new runtime services instance that manages service registration and retrieval.\n *\n * @returns A RuntimeServices object with methods to get, register, and unregister services\n * @not-instrumented\n */\nexport const createRuntimeServices = (): RuntimeServices => {\n const registry = new Map<string, unknown>();\n\n return {\n getByKey: <T>(key: string) => registry.get(key) as T | null,\n // eslint-disable-next-line custom-rules/require-single-object-param\n register: (key: string, service: unknown) => registry.set(key, service),\n unregister: (key: string) => registry.delete(key),\n };\n};\n","export type SetLongTimeoutOptions = {\n /** The function to invoke after the delay elapses. */\n callback: () => void;\n\n /** The delay in milliseconds before invoking the callback. */\n delay: number;\n};\n\n/**\n * A replacement for setTimeout that supports delays longer than 2147483647ms (~24.8 days).\n * @not-instrumented\n */\nexport const setLongTimeout = ({\n callback,\n delay,\n}: SetLongTimeoutOptions): VoidFunction => {\n const MAX_DELAY = 2147483647; // Maximum delay for setTimeout (2^31 - 1)\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let remaining = delay;\n\n const run = () => {\n if (remaining <= MAX_DELAY) {\n timeoutId = setTimeout(callback, remaining);\n } else {\n timeoutId = setTimeout(() => {\n remaining -= MAX_DELAY;\n run();\n }, MAX_DELAY);\n }\n };\n\n run();\n\n // Return a cancel function\n return () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n };\n};\n","import type { DynamicClient } from '../../../client/types';\nimport { getCore } from '../../../client/core/getCore';\nimport { subscribeWithSelector } from '../../../utils/observable/subscribeWithSelector';\nimport { logoutWithReason } from '../logoutWithReason';\nimport { setLongTimeout } from './setLongTimeout';\n\n/**\n * Sets up a timeout to log out the user when their token expires.\n * @not-instrumented\n */\nexport const initializeAuth = (client: DynamicClient) => {\n const core = getCore(client);\n\n let clearExpirationTimeout: VoidFunction | null = null;\n\n const onChangeExpiration = subscribeWithSelector(\n core.state,\n (state) => state.sessionExpiresAt\n );\n\n const checkExpiration = () => {\n const expiration = core.state.get().sessionExpiresAt;\n\n clearExpirationTimeout?.();\n\n if (!expiration) {\n return;\n }\n\n const now = new Date();\n\n const timeUntilExpiration = expiration.getTime() - now.getTime();\n\n if (timeUntilExpiration <= 0) {\n void logoutWithReason({ reason: 'token-expired' }, client);\n return;\n }\n\n // Wait for token expiration\n clearExpirationTimeout = setLongTimeout({\n callback: checkExpiration,\n delay: timeUntilExpiration,\n });\n };\n\n onChangeExpiration(checkExpiration);\n\n checkExpiration();\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { emitEvent } from '../../clientEvents';\n\n/**\n * Sets up bidirectional event synchronization between the core event emitter\n * and the CrossTabBroadcast service.\n *\n * This enables events fired in one tab to be received in other tabs.\n *\n * **Local → Cross-Tab (Forwarding)**\n * - Listens to specific events on core.eventEmitter\n * - Forwards them to other tabs via core.crossTabBroadcast.send()\n *\n * **Cross-Tab → Local (Receiving)**\n * - Listens to cross-tab events via core.crossTabBroadcast.on()\n * - Emits corresponding \"*InAnotherTab\" events on core.eventEmitter\n *\n * @param client - The Dynamic client instance\n * @not-instrumented\n */\nexport const setupCrossTabEventSync = (client: DynamicClient) => {\n const core = getCore(client);\n\n // === FORWARDING: Local events → Cross-Tab ===\n // Listen to deviceRegistrationCompleted and forward to other tabs\n const handleDeviceRegistrationCompleted = () => {\n core.crossTabBroadcast.send({ event: 'deviceRegistrationCompleted' });\n };\n\n core.eventEmitter.on(\n 'deviceRegistrationCompleted',\n handleDeviceRegistrationCompleted\n );\n\n // === RECEIVING: Cross-Tab → Local events ===\n // Listen to cross-tab deviceRegistrationCompleted and emit local variant\n const handleCrossTabDeviceRegistrationCompleted = () => {\n emitEvent({ event: 'deviceRegistrationCompletedInAnotherTab' }, client);\n };\n\n core.crossTabBroadcast.on(\n 'deviceRegistrationCompleted',\n handleCrossTabDeviceRegistrationCompleted\n );\n};\n","import * as z from 'zod/mini';\n\nimport type { Chain } from '../../chain';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport type { WalletAddressType } from '../walletAccount';\n\nexport const unverifiedWalletAccountSchema = z.object({\n address: z.string(),\n addressesWithTypes: z.optional(\n z.array(\n z.object({\n address: z.string(),\n publicKey: z.optional(z.string()),\n type: z.custom<WalletAddressType>((val) => typeof val === 'string'),\n })\n )\n ),\n chain: z.custom<Chain>((val) => typeof val === 'string'),\n hardwareWalletVendor: z.optional(\n z.custom<HardwareWalletVendor>((val) => typeof val === 'string')\n ),\n id: z.string(),\n lastSelectedAt: z.nullable(z.date()),\n walletProviderKey: z.string(),\n});\n","import * as z from 'zod/mini';\n\nexport const walletProviderKeyMapSchema = z.record(z.string(), z.string());\n","import type { ProjectSettings, SdkUser } from '@dynamic-labs/sdk-api-core';\nimport * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../services/storage';\nimport { unverifiedWalletAccountSchema } from '../wallets/unverifiedWalletAccounts';\nimport { walletProviderKeyMapSchema } from '../wallets/walletProvider/walletProviderKeyMap/schema';\n\nexport const stateStorageKeySchema = createStorageKeySchema({\n key: 'state',\n schema: z.object({\n apiVersion: z.string(),\n prefetchedNonces: z.array(z.string()),\n prefetchedNoncesExpiration: z.nullable(z.number()),\n projectSettings: z.custom<ProjectSettings | null>(),\n unverifiedWalletAccounts: z.array(unverifiedWalletAccountSchema),\n user: z.custom<SdkUser | null>(),\n walletProviderKeyMap: walletProviderKeyMapSchema,\n }),\n});\n\nexport const sessionStorageKeySchema = createStorageKeySchema({\n config: { storageTier: 'secure' },\n key: 'session',\n schema: z.object({\n /**\n * The current available captcha token.\n */\n captchaToken: z.nullable(z.string()),\n\n /**\n * The current available elevated access tokens.\n */\n elevatedAccessTokens: z.array(\n z.object({\n /**\n * Milliseconds since epoch of token expiration.\n */\n expiresAt: z.number(),\n /**\n * The scopes of the token.\n */\n scopes: z.array(z.string()),\n /**\n * Whether the token is single use.\n */\n singleUse: z.nullable(z.boolean()),\n /**\n * The token string.\n */\n token: z.string(),\n })\n ),\n\n /**\n * Legacy token will be undefined in environments with cookie based sessions.\n *\n * @deprecated Use `token` instead.\n */\n legacyToken: z.nullable(z.string()),\n\n /**\n * The current available MFA token.\n */\n mfaToken: z.nullable(z.string()),\n\n /**\n * Milliseconds since epoch of session expiration.\n */\n sessionExpiration: z.number(),\n\n /**\n * The current session keys.\n */\n sessionKeys: z.nullable(z.string()),\n\n /**\n * Token will be undefined in environments with cookie based sessions.\n */\n token: z.nullable(z.string()),\n }),\n});\n","import { BaseError } from '../../../errors/base';\n\nexport class KeyMigrationError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(expectedPublicKey: string, importedPublicKey: string) {\n super({\n cause: null,\n code: 'key_migration_public_key_mismatch',\n docsUrl: null,\n name: 'KeyMigrationError',\n shortMessage: `Public key mismatch after import: expected \"${expectedPublicKey}\", got \"${importedPublicKey}\"`,\n });\n }\n}\n","import type { DynamicCoreState } from '../../../client/core/types';\nimport type { KeychainService } from '../../../services/keychain';\nimport type { Logger } from '../../../services/logger';\nimport type { Storage } from '../../../services/storage/storage.types';\nimport { getBuffer } from '../../../utils/getBuffer';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { ObservableState } from '../../../utils/observable/observable.types';\nimport { sessionStorageKeySchema } from '../../storageSync/schema';\nimport { KeyMigrationError } from './KeyMigrationError';\n\ntype LegacySessionKeysBlob = {\n privateKeyJwk?: JsonWebKey;\n publicKey?: string;\n};\n\ntype MigrateSessionKeyToKeychainParams = {\n keychain: KeychainService;\n logger: Logger;\n state: ObservableState<DynamicCoreState>;\n storage: Storage;\n};\n\n/**\n * Migrates legacy session keys from the hydrated state into the IndexedDB keychain\n * as non-extractable CryptoKey objects.\n *\n * Must run after hydrateStateWithStorage so that state.sessionKeys already holds\n * the legacy base64 blob (or the new public key hex if already migrated).\n *\n * Idempotent: skips if the keychain already has a `session` key.\n * Throws on failure — callers should handle errors (e.g. .catch(() => logout(client))).\n * @not-instrumented\n */\nexport const migrateSessionKeyToKeychain = async ({\n keychain,\n logger,\n state,\n storage,\n}: MigrateSessionKeyToKeychainParams): Promise<void> => {\n if (isServerSideRendering()) {\n return;\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Checking for existing session key in keychain');\n\n if (await keychain.hasKey('session')) {\n logger.debug('[migrateSessionKeyToKeychain] Session key already exists in keychain, skipping migration');\n return;\n }\n\n const encodedSessionKeys = state.get().sessionKeys;\n\n if (!encodedSessionKeys) {\n logger.debug('[migrateSessionKeyToKeychain] No session keys in state, nothing to migrate');\n return;\n }\n\n let blob: LegacySessionKeysBlob;\n\n try {\n blob = JSON.parse(\n getBuffer().from(encodedSessionKeys, 'base64').toString()\n ) as LegacySessionKeysBlob;\n } catch {\n // Not a legacy base64 blob — already a public key hex string or invalid\n logger.debug('[migrateSessionKeyToKeychain] Session keys are not a legacy blob, skipping migration');\n return;\n }\n\n const { privateKeyJwk, publicKey } = blob;\n\n if (!privateKeyJwk || !publicKey) {\n logger.debug('[migrateSessionKeyToKeychain] Legacy blob missing privateKeyJwk or publicKey, skipping migration');\n return;\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Found legacy session key, importing into keychain', {\n expectedPublicKey: publicKey,\n });\n\n const importedPublicKey = await keychain.importKey('session', privateKeyJwk);\n\n logger.debug('[migrateSessionKeyToKeychain] Key imported', {\n expectedPublicKey: publicKey,\n importedPublicKey,\n });\n\n if (importedPublicKey !== publicKey) {\n throw new KeyMigrationError(publicKey, importedPublicKey);\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Public key validated, updating state and storage');\n\n state.set({ sessionKeys: importedPublicKey });\n\n const currentSession = await storage.getItem(sessionStorageKeySchema);\n\n if (currentSession) {\n await storage.setItem(sessionStorageKeySchema, {\n ...currentSession,\n sessionKeys: importedPublicKey,\n });\n }\n\n logger.debug('[migrateSessionKeyToKeychain] Migration complete');\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicCoreState } from '../../../client/core/types';\nimport type { DynamicClient } from '../../../client/types';\nimport { isEqualShallow } from '../../../utils/isEqualShallow';\nimport { emitEvent } from '../../clientEvents';\nimport { stateChangeEvents } from './events';\n\n/** @not-instrumented */\nexport const raiseStateEvents = (client: DynamicClient) => {\n const core = getCore(client);\n\n core.state.subscribe((value, previous) => {\n const eventEntries = Object.entries(stateChangeEvents) as Array<\n [keyof DynamicCoreState, keyof DynamicEvents]\n >;\n\n eventEntries.forEach(([key, event]) => {\n // Check if this key had a change\n if (isEqualShallow(value[key], previous[key])) return;\n\n emitEvent(\n {\n args: { [key]: value[key] },\n event,\n },\n client\n );\n });\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicCoreState } from '../../../client/core/types';\nimport type { DynamicClient } from '../../../client/types';\nimport { SDK_API_CORE_VERSION } from '../../../constants';\nimport { checkAndRaiseWalletAccountsChangedEvent } from '../../auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent';\nimport { sessionStorageKeySchema, stateStorageKeySchema } from '../schema';\n\n/** @not-instrumented */\nexport const hydrateStateWithStorage = async (\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n const previousState = core.state.get();\n\n const stateChanges: Partial<DynamicCoreState> = {};\n\n // ================ TOKEN =================\n\n const session = await core.storage.getItem(sessionStorageKeySchema);\n\n const isSessionValid =\n session?.sessionExpiration && session.sessionExpiration > Date.now();\n\n if (isSessionValid) {\n stateChanges.token = session.token;\n stateChanges.legacyToken = session.legacyToken;\n stateChanges.sessionExpiresAt = new Date(session.sessionExpiration);\n stateChanges.mfaToken = session.mfaToken;\n stateChanges.elevatedAccessTokens = session.elevatedAccessTokens.map((token) => ({\n expiresAt: new Date(token.expiresAt),\n scopes: token.scopes,\n singleUse: token.singleUse ?? false,\n token: token.token,\n }));\n stateChanges.captchaToken = session.captchaToken;\n stateChanges.sessionKeys = session.sessionKeys;\n }\n\n // ================ STATE =================\n\n const storedState = await core.storage.getItem(stateStorageKeySchema);\n\n // Only hydrate state if it came from an API with the same version as the current SDK\n if (storedState?.apiVersion === SDK_API_CORE_VERSION) {\n stateChanges.unverifiedWalletAccounts =\n storedState.unverifiedWalletAccounts;\n\n stateChanges.walletProviderKeyMap = storedState.walletProviderKeyMap;\n\n if (storedState.prefetchedNoncesExpiration && storedState.prefetchedNoncesExpiration > Date.now()) {\n stateChanges.prefetchedNonces = storedState.prefetchedNonces;\n stateChanges.prefetchedNoncesExpiration = storedState.prefetchedNoncesExpiration;\n }\n\n // Variables that should only be hydrated if the session is valid\n if (isSessionValid) {\n stateChanges.user = storedState.user;\n }\n\n // if there's a session/user or connected unverified wallets, we should hydrate project settings\n // so we don't refetch it on initial load\n if (\n isSessionValid ||\n (storedState.unverifiedWalletAccounts ?? []).length > 0\n ) {\n stateChanges.projectSettings = storedState.projectSettings;\n }\n }\n\n if (Object.keys(stateChanges).length > 0) {\n core.state.set(stateChanges);\n }\n\n checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { SDK_API_CORE_VERSION } from '../../../constants';\nimport { sessionStorageKeySchema, stateStorageKeySchema } from '../schema';\n\n/** @not-instrumented */\nexport const syncStateWithStorage = (client: DynamicClient) => {\n const core = getCore(client);\n\n core.state.subscribe((state) => {\n if (state.sessionExpiresAt === null) {\n void core.storage.removeItem(sessionStorageKeySchema);\n } else {\n void core.storage.setItem(sessionStorageKeySchema, {\n captchaToken: state.captchaToken,\n elevatedAccessTokens: (state.elevatedAccessTokens || []).map(\n (token) => ({\n expiresAt: token.expiresAt.getTime(),\n scopes: token.scopes,\n singleUse: token.singleUse ?? null,\n token: token.token,\n })\n ),\n legacyToken: state.legacyToken,\n mfaToken: state.mfaToken,\n sessionExpiration: state.sessionExpiresAt.getTime(),\n sessionKeys: state.sessionKeys,\n token: state.token,\n });\n }\n\n void core.storage.setItem(stateStorageKeySchema, {\n apiVersion: SDK_API_CORE_VERSION,\n prefetchedNonces: state.prefetchedNonces,\n prefetchedNoncesExpiration: state.prefetchedNoncesExpiration,\n projectSettings: state.projectSettings,\n unverifiedWalletAccounts: state.unverifiedWalletAccounts,\n user: state.user,\n walletProviderKeyMap: state.walletProviderKeyMap,\n });\n });\n};\n","import type { DynamicClient } from '../../client/types';\nimport { hydrateStateWithStorage } from './hydrateStateWithStorage';\nimport { syncStateWithStorage } from './syncStateWithStorage';\n\n/** @not-instrumented */\nexport const initializeStorageSync = async (client: DynamicClient) => {\n // Initialize the state value with what's stored in the storage\n await hydrateStateWithStorage(client);\n\n // Keep the storage up to date with the state\n syncStateWithStorage(client);\n};\n","import type { SdkUser } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { checkAndRaiseWalletAccountsChangedEvent } from '../../auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent';\n\n/**\n * Refreshes the current user's data from the server.\n *\n * This function fetches the latest authenticated user information from the backend\n * and updates the local user state.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authenticated user.\n * @instrumented\n */\nexport const refreshUser = async (\n client = getDefaultClient()\n): Promise<SdkUser> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const previousState = { ...core.state.get() };\n\n const user = await apiClient.getAuthenticatedUser({\n environmentId: core.environmentId,\n });\n\n core.state.set({ user });\n\n checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);\n\n return user;\n};\n","import { BaseError } from './base';\n\nexport class ClientAlreadyInitializedError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'client_already_initialized_error',\n docsUrl: null,\n name: 'ClientAlreadyInitializedError',\n shortMessage: 'Client must not be initialized more than once',\n });\n }\n}\n","import { getCore } from '../../client/core/getCore';\nimport { getDefaultClient } from '../../client/defaultClient';\nimport { prefetchNoncesIfNeeded } from '../../utils/getNonce/prefetchNoncesIfNeeded/prefetchNoncesIfNeeded';\nimport { initializeAuth } from '../auth/initializeAuth';\nimport { logoutWithReason } from '../auth/logoutWithReason';\nimport { setupCrossTabEventSync } from '../crossTabEventSync';\nimport { migrateSessionKeyToKeychain } from '../keychainMigration/migrateSessionKeyToKeychain/migrateSessionKeyToKeychain';\nimport { fetchProjectSettings } from '../projectSettings/fetchProjectSettings';\nimport { isCookieEnabled } from '../projectSettings/isCookieEnabled';\nimport { generateSessionKeys } from '../sessionKeys/generateSessionKeys';\nimport { raiseStateEvents } from '../state/raiseStateEvents';\nimport { initializeStorageSync } from '../storageSync';\nimport { refreshAuth } from '../user/refreshAuth';\nimport { refreshUser } from '../user/refreshUser';\nimport { restoreUserSharesForAllWalletAccounts } from '../waas/restoreUserSharesForAllWalletAccounts';\nimport { ClientAlreadyInitializedError } from './../../errors/ClientAlreadyInitializedError';\nimport {\n FETCH_PROJECT_SETTINGS_TRACKER_KEY,\n GENERATE_SESSION_KEYS_TRACKER_KEY,\n INITIALIZE_STORAGE_SYNC_TRACKER_KEY,\n REFRESH_USER_STATE_FROM_COOKIE_TRACKER_KEY,\n REFRESH_USER_STATE_FROM_VALID_TOKEN_TRACKER_KEY,\n} from './consts';\n\n/**\n * Initializes the Dynamic client and all its modules and services.\n *\n * This function orchestrates the initialization of authentication, project settings,\n * session keys, and storage sync. It manages the initialization status and handles\n * any errors that occur during the process.\n *\n * You only need to call this function if you are not using `autoInitialize: true` in createDynamicClient.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when initialization is complete.\n * @throws ClientAlreadyInitializedError If the client is already initialized.\n * @instrumented\n */\nexport const initializeClient = async (client = getDefaultClient()) => {\n const core = getCore(client);\n\n core.logger.debug(\n '[initializeClient] Initializing client. Current init status',\n core.state.get().initStatus\n );\n\n if (core.state.get().initStatus !== 'uninitialized') {\n throw new ClientAlreadyInitializedError();\n }\n\n core.state.set({ initError: null, initStatus: 'in-progress' });\n\n initializeAuth(client);\n\n raiseStateEvents(client);\n\n setupCrossTabEventSync(client);\n\n const initializeStorageSyncPromise = initializeStorageSync(client);\n\n const migrationPromise: Promise<void> = initializeStorageSyncPromise.then(\n async () => {\n await migrateSessionKeyToKeychain({\n keychain: core.keychain,\n logger: core.logger,\n state: core.state,\n storage: core.storage,\n }).catch(() =>\n logoutWithReason({ reason: 'keychain-migration-failed' }, client)\n );\n\n // If session keys exist in state but the keychain key is absent (e.g. IndexedDB\n // was cleared after a new-format session was written), sign the user out.\n if (\n core.state.get().sessionKeys &&\n !(await core.keychain.hasKey('session'))\n ) {\n await logoutWithReason({ reason: 'keychain-key-missing' }, client);\n }\n }\n );\n\n const fetchProjectSettingsPromise: Promise<void> = migrationPromise.then(\n async () => {\n if (!core.state.get().projectSettings) {\n await fetchProjectSettings(client);\n }\n }\n );\n\n // Prefetch nonces in the background so they are ready when a wallet\n // signing operation starts. Not tracked — failures are non-blocking.\n void fetchProjectSettingsPromise\n .then(() => prefetchNoncesIfNeeded(client))\n .catch((error) => {\n core.logger.error('Failed to prefetch nonces:', error);\n });\n\n /**\n * Generate session keys if they don't exist\n */\n const generateSessionKeysPromise: Promise<void> =\n fetchProjectSettingsPromise.then(async () => {\n if (!core.state.get().sessionKeys) {\n await generateSessionKeys(client);\n }\n });\n\n /**\n * Refresh user state on initialization when cookie is enabled.\n * This is necessary for supporting multiple subdomain domains.\n *\n * When a user logs in on sub1.example.com, they will have a cookie set. However, when they access\n * sub2.example.com, the cookie will be present but the user state will not be present.\n * We need to fetch the user to access the expiration date of the cookie on the new subdomain.\n *\n * This is also needed in case a user logs in with a new user on sub1.example.com and then accesses\n * sub2.example.com that had the original logged-in user. We need to fetch the user to refresh\n * the user state with the correct logged-in user.\n */\n const refreshUserStateFromCookiePromise: Promise<void> =\n fetchProjectSettingsPromise.then(async () => {\n /**\n * When cookies are enabled, we need to refresh the user as part of the initialization process\n * to ensure the user is logged in and sync the auth state with the server.\n *\n * This call can fail with a 401 error if the user is not logged in and the SDK should finish its initialization process\n * without throwing an error because that is an expected behavior.\n */\n if (isCookieEnabled(client)) {\n await refreshAuth(client).catch(async (error) => {\n if (error.status === 401) {\n core.logger.error('Session expired during initialization', error);\n\n if (client.user) {\n await logoutWithReason(\n { reason: 'session-refresh-unauthorized' },\n client\n );\n }\n } else {\n throw error;\n }\n });\n }\n });\n\n /**\n * When a token is persisted but the user state was lost (e.g. storage cleared\n * partially), re-fetch the user from the server. This path is skipped when\n * cookies are enabled because the token is not stored in SDK state.\n */\n const refreshUserStateFromValidTokenPromise: Promise<void> =\n refreshUserStateFromCookiePromise.then(async () => {\n if (core.state.get().token && !core.state.get().user) {\n await refreshUser(client).catch(async () => {\n await logoutWithReason({ reason: 'user-refresh-failed' }, client);\n });\n }\n });\n\n core.initTrack.track({\n name: INITIALIZE_STORAGE_SYNC_TRACKER_KEY,\n promise: initializeStorageSyncPromise,\n });\n\n core.initTrack.track({\n name: FETCH_PROJECT_SETTINGS_TRACKER_KEY,\n promise: fetchProjectSettingsPromise,\n });\n\n core.initTrack.track({\n name: GENERATE_SESSION_KEYS_TRACKER_KEY,\n promise: generateSessionKeysPromise,\n });\n\n core.initTrack.track({\n name: REFRESH_USER_STATE_FROM_COOKIE_TRACKER_KEY,\n promise: refreshUserStateFromCookiePromise,\n });\n\n core.initTrack.track({\n name: REFRESH_USER_STATE_FROM_VALID_TOKEN_TRACKER_KEY,\n promise: refreshUserStateFromValidTokenPromise,\n });\n\n try {\n await core.initTrack.waitForAll();\n\n core.state.set({ initStatus: 'finished' });\n } catch (error) {\n core.logger.error('Client initialization failed', error);\n core.state.set({\n initError: error instanceof Error ? error : null,\n initStatus: 'failed',\n });\n\n throw error;\n }\n\n if (client.user) {\n void restoreUserSharesForAllWalletAccounts(client);\n }\n};\n","import { EventEmitter } from 'eventemitter3';\n\nimport { createDeferredPromise } from '../../utils/deferredPromise';\nimport { CannotTrackError } from './../../errors/CannotTrackError';\nimport type {\n AsyncProcessEntry,\n AsyncTrack,\n AsyncTrackEmitter,\n} from './asyncTrack.types';\n\n/**\n * Creates a tracker that associates names with promises and raises as promises resolve.\n * @not-instrumented\n */\nexport const createAsyncTrack = (): AsyncTrack => {\n /**\n * Whether tracking is enabled.\n * All processes must be tracked on the same node tick.\n *\n * This ensures no process is missed (as it would throw when tracked on a different node tick).\n */\n let isTrackEnabled = true;\n\n const eventEmitter: AsyncTrackEmitter = new EventEmitter();\n\n const allSettledPromise = createDeferredPromise<void>();\n\n const tracker = new Map<string, AsyncProcessEntry>();\n\n /**\n * Checks if all processes are initialized and resolves the main promise if they are.\n */\n const checkIfAllSettled = () => {\n const allSettled = Array.from(tracker.values()).every(\n ({ status }) => status === 'resolved'\n );\n\n if (!allSettled) return;\n\n allSettledPromise.resolve();\n };\n\n const track: AsyncTrack['track'] = ({ name, promise }) => {\n if (!isTrackEnabled) {\n throw new CannotTrackError();\n }\n\n // Disable tracking in the next node tick\n void Promise.resolve().then(() => (isTrackEnabled = false));\n\n tracker.set(name, { promise, status: 'pending' });\n\n promise\n .then(() => {\n tracker.set(name, { promise, status: 'resolved' });\n\n eventEmitter.emit('resolved', name);\n\n checkIfAllSettled();\n })\n .catch((error) => {\n tracker.set(name, { promise, status: 'failed' });\n\n eventEmitter.emit('failed', name, error);\n\n allSettledPromise.reject(error);\n });\n };\n\n const waitForAll: AsyncTrack['waitForAll'] = () => allSettledPromise.promise;\n\n const getTracker: AsyncTrack['getTracker'] = <T>(trackerKey: string) =>\n tracker.get(trackerKey) as AsyncProcessEntry<T>;\n\n return {\n getTracker,\n off: eventEmitter.off.bind(eventEmitter),\n on: eventEmitter.on.bind(eventEmitter),\n track,\n waitForAll,\n };\n};\n","import EventEmitter from 'eventemitter3';\n\n/** @not-instrumented */\nexport const createEventEmitter = () => new EventEmitter();\n","import { BaseError } from './base';\n\nexport class UnavailableInServerSideError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(unavailableFeature: string) {\n super({\n cause: null,\n code: 'unavailable_in_server_side_error',\n docsUrl: null,\n name: 'UnavailableInServerSideError',\n shortMessage: `This function is not available in server-side rendering: ${unavailableFeature}`,\n });\n }\n}\n","import { UnavailableInServerSideError } from '../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../utils/isServerSideRendering';\nimport type { Fetch } from './fetch.types';\n\n/**\n * Creates a fetch instance that uses the native window.fetch API.\n * @not-instrumented\n */\nexport const createWebFetch = (): Fetch => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(new UnavailableInServerSideError('createWebFetch'));\n }\n\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for fetch\n return window.fetch.bind(window);\n};\n","import type { Logger } from '../../logger/logger.types';\nimport { getOperatingSystem } from '../../../utils/getOperatingSystem/getOperatingSystem';\nimport { getPlatform } from '../../../utils/getPlatform/getPlatform';\nimport { getUserAgent } from '../../../utils/getUserAgent/getUserAgent';\nimport type { ObservableState } from '../../../utils/observable/observable.types';\nimport { extractSessionId } from '../../../modules/auth/extractSessionId/extractSessionId';\nimport type { Instrumentation } from '../instrumentation.types';\nimport { scrubParameters } from '../scrubParameters';\n\ntype ConnectLoggerToInstrumentationParams = {\n environmentId: string;\n extensions: Set<string>;\n instrumentation: Instrumentation;\n logger: Logger;\n sdkSessionId: string;\n sdkVersion: string;\n state: ObservableState<DynamicCoreState>;\n};\n\n/**\n * Subscribes to the logger's 'log' event and forwards every entry to the\n * instrumentation service as an InstrumentationEvent.\n *\n * Bridges the logger and instrumentation subsystems without coupling them\n * at construction time — either can exist without the other.\n * Only error-level log entries are forwarded.\n * @not-instrumented\n */\nexport const connectLoggerToInstrumentation = ({\n environmentId,\n extensions,\n instrumentation,\n logger,\n sdkSessionId,\n sdkVersion,\n state,\n}: ConnectLoggerToInstrumentationParams) => {\n logger.on('log', (level, message, ...args) => {\n if (level !== 'error') {\n return;\n }\n\n const { token, user } = state.get();\n\n instrumentation.log({\n environmentId,\n operatingSystem: getOperatingSystem(),\n // Callers occasionally pass plain objects (or serialized Errors) to\n // `logger.error` that include credentials or PII. Route them through\n // `scrubParameters` so the same redaction rules used by the @instrumented\n // function wrappers apply here too — otherwise this path silently\n // bypasses key-based PII scrubbing.\n parameters: scrubParameters({\n piiFields: instrumentation.config.piiFields,\n value: { args, message },\n }),\n platform: getPlatform(),\n registeredExtensionKeys: Array.from(extensions),\n sdkSessionId,\n sdkVersion,\n // Logger bridge only forwards error-level entries, so status is always 'error'.\n status: 'error',\n timestamp: new Date().toISOString(),\n tokenSessionId: token ? extractSessionId(token) : null,\n userAgent: getUserAgent(),\n userId: user?.id ?? null,\n });\n });\n};\n","import { DEFAULT_PII_FIELDS } from '../constants';\nimport type {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationEvent,\n InstrumentationTransport,\n} from '../instrumentation.types';\n\ntype CreateInstrumentationParams = {\n config?: Partial<InstrumentationConfig>;\n};\n\n// eslint-disable-next-line custom-rules/require-single-object-param\nconst buildPiiFields = (customFields: string[] = []): string[] => {\n const merged = [...DEFAULT_PII_FIELDS, ...customFields];\n const deduplicated = new Set(merged);\n return [...deduplicated];\n};\n\n/**\n * Creates the instrumentation service that gates event emission behind an\n * enabled flag and delegates to a pluggable transport.\n *\n * The transport is intentionally optional at creation time — it is wired in\n * later via setTransport so the SDK can initialise without one. Events logged\n * before a transport is set are simply dropped.\n *\n * Custom piiFields are merged with and deduplicated against the defaults so\n * callers only need to list additional fields, not replicate the baseline.\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const createInstrumentation = ({\n config: inputConfig,\n}: CreateInstrumentationParams = {}): Instrumentation => {\n let transport: InstrumentationTransport | undefined;\n\n const config: InstrumentationConfig = {\n enabled: inputConfig?.enabled ?? true,\n piiFields: buildPiiFields(inputConfig?.piiFields),\n };\n\n const emit = (event: InstrumentationEvent) => {\n if (!config.enabled || !transport) {\n return;\n }\n transport.log(event);\n };\n\n return {\n config,\n log: emit,\n logFunction: emit,\n setEnabled: (value) => {\n config.enabled = value;\n },\n setTransport: (t) => {\n transport = t;\n },\n };\n};\n","import type { Fetch } from '../../../fetch';\nimport type {\n InstrumentationEvent,\n InstrumentationTransport,\n} from '../../instrumentation.types';\n\nconst LOGS_BASE_URL = 'https://logs.dynamicauth.com/api/v1';\n\ntype CreateDynamicTransportParams = {\n environmentId: string;\n fetch: Fetch;\n};\n\n/**\n * Creates a batched transport that ships instrumentation events to Dynamic's\n * log ingestion endpoint.\n *\n * Events are queued synchronously and flushed as a single HTTP batch in the\n * next microtask (via queueMicrotask). Multiple log() calls within the same\n * synchronous tick are coalesced into one request, avoiding a round-trip per\n * event.\n *\n * Fetch errors are swallowed to prevent an instrumentation failure from\n * triggering another instrumentation event and causing an infinite loop.\n *\n * Works in both browser and SSR environments — fetch is injected and\n * queueMicrotask is available in Node.js >= 11.\n * @not-instrumented\n */\nexport const createDynamicTransport = (\n params: CreateDynamicTransportParams\n): InstrumentationTransport => {\n const queue: InstrumentationEvent[] = [];\n let flushScheduled = false;\n\n const flush = () => {\n flushScheduled = false;\n // splice(0) atomically drains the queue and returns all accumulated events.\n // Using splice rather than reassigning the array reference ensures events\n // logged between flush scheduling and flush execution are not silently dropped.\n const events = queue.splice(0);\n\n if (events.length === 0) return;\n\n const url = `${LOGS_BASE_URL}/${params.environmentId}`;\n\n void params\n .fetch(url, {\n body: JSON.stringify(events),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n .catch(() => {\n // Swallow fetch errors to prevent instrumentation failure from causing\n // an infinite loop of instrumentation events.\n });\n };\n\n return {\n log: (event) => {\n queue.push(event);\n\n if (!flushScheduled) {\n flushScheduled = true;\n queueMicrotask(flush);\n }\n },\n };\n};\n","import { UnavailableInServerSideError } from '../../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { NavigationHandler } from '../navigate.types';\n\n/**\n * Creates a navigation handler that uses the native window.location API.\n * @not-instrumented\n */\nexport const createNavigationHandler = (): NavigationHandler => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(\n new UnavailableInServerSideError('createNavigationHandler')\n );\n }\n\n return async (url) => {\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for navigation\n window.location.href = url;\n };\n};\n","import { UnavailableInServerSideError } from '../../../errors/UnavailableInServerSideError';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering';\nimport type { OpenDeeplink } from '../openDeeplink.types';\n\n/**\n * Creates a deeplink opener that navigates the current tab to the deeplink URL.\n *\n * Uses `window.location.assign` instead of `window.open` deliberately.\n * This matters for Phantom redirect specifically, which is the only deep link\n * provider that redirects back to the app in a new tab. With `window.open`,\n * the browser first opens an `about:blank` tab before the native wallet app\n * handles the deep link. When Phantom redirects back, it opens yet another\n * tab. The user ends up with three tabs (original, about:blank, redirect) and\n * the browser focuses the lingering about:blank after the redirect tab closes.\n * `window.location.assign` reuses the current tab, avoiding the extra tab\n * entirely.\n * @not-instrumented\n */\nexport const createWebDeeplinkOpener = (): OpenDeeplink => {\n if (isServerSideRendering()) {\n return () =>\n Promise.reject(\n new UnavailableInServerSideError('createWebDeeplinkOpener')\n );\n }\n\n return async (url) => {\n // eslint-disable-next-line no-restricted-globals -- this is the abstraction for opening a deeplink\n window.location.assign(url);\n };\n};\n","/**\n * Because this is the web implementation of the passkey service, we need to\n * import the browser's WebAuthn API directly.\n * @not-instrumented\n */\nimport {\n // eslint-disable-next-line no-restricted-syntax\n browserSupportsWebAuthn,\n // eslint-disable-next-line no-restricted-syntax\n startAuthentication,\n // eslint-disable-next-line no-restricted-syntax\n startRegistration,\n} from '@simplewebauthn/browser';\n\nimport type {\n CreatePasskeyServiceParams,\n PasskeyService,\n} from '../passkey.types';\n\n/**\n * Create a passkey service that uses the browser's WebAuthn API.\n *\n * Metadata is accepted for parity with the native implementation (which uses\n * `universalLink` to validate the associated domain) but is unused on web —\n * the browser derives the relying party from `window.location.origin`.\n * @not-instrumented\n */\nexport const createPasskeyService = (\n _params?: CreatePasskeyServiceParams\n): PasskeyService => ({\n authenticate: (options) => startAuthentication(options),\n isSupported: () => browserSupportsWebAuthn(),\n register: (options) => startRegistration(options),\n});\n","import { assertDefined } from '../../assertDefined';\nimport type { DeferredPromise } from '../../deferredPromise';\nimport { createDeferredPromise } from '../../deferredPromise';\nimport type { DebouncedMutex } from '../debouncedMutex.types';\n\n/**\n * State for a debounced mutex.\n */\ntype DebouncedMutexState = {\n /**\n * Next callback to run.\n */\n nextCallback: (() => Promise<void>) | null;\n /**\n * Promise that resolves when the debounced mutex is released.\n */\n queuePromise: Promise<void>;\n /**\n * Promises that allow callers to await the completion of the next callback execution.\n * Each invocation adds a promise to this array, which gets resolved when the callback finishes.\n */\n resolutionPromises: DeferredPromise<void>[];\n /**\n * Timer for the debounced mutex.\n *\n * Uses `ReturnType<typeof setTimeout>` because the project's lib includes both\n * \"dom\" and \"@types/node\" — DOM's setTimeout returns `number`, Node's returns\n * `Timeout`. This makes the type portable between web and native builds.\n */\n timer: ReturnType<typeof setTimeout> | null;\n};\n\n/** @not-instrumented */\nexport const createDebouncedMutex = (): DebouncedMutex => {\n const mutexState = new Map<string, DebouncedMutexState>();\n\n return async ({ lockKey, callback, debounceTime = 0 }) => {\n const resolutionPromise = createDeferredPromise<void>();\n\n // Prefill the state for this key if it doesn't exist to avoid needing to check for existence later.\n if (!mutexState.has(lockKey)) {\n mutexState.set(lockKey, {\n nextCallback: null,\n queuePromise: Promise.resolve(),\n resolutionPromises: [],\n timer: null,\n });\n }\n\n const currentState = mutexState.get(lockKey);\n\n // This should never happen, but we'll assert it for TS safety.\n assertDefined(currentState, `Mutex state for key ${lockKey} not found`);\n\n currentState.resolutionPromises.push(resolutionPromise);\n\n if (currentState.timer) {\n clearTimeout(currentState.timer);\n }\n\n // The last invocation wins. Always.\n currentState.nextCallback = callback;\n\n const addCallbackToQueue = async () => {\n currentState.queuePromise = currentState.queuePromise.then(async () => {\n if (!currentState.nextCallback) {\n return;\n }\n\n // We can't just use the callback param directly because later invocations\n // should override previous ones.\n // Scenario to illustrate this (none of these will use the timer param for simplicity):\n // 1. Very long running promise callback A runs\n // 2. While it's running, we invoke callback B, which queues itself with \"then\" and overrides nextCallback with B.\n // 3. While A is still running, we invoke callback C, same thing happens, now nextCallback is C.\n // 4. A resolves, nextCallback is invoked with C.\n // 5. After C resolves, nextCallback is invoked with null, so it doesn't run.\n // Conclusion: B was never executed and only the last invocation runs.\n const { nextCallback } = currentState;\n\n currentState.nextCallback = null;\n\n const promisesToResolve = currentState.resolutionPromises;\n\n currentState.resolutionPromises = [];\n\n try {\n await nextCallback();\n\n promisesToResolve.forEach((resolutionPromise) =>\n resolutionPromise.resolve()\n );\n } catch (error) {\n promisesToResolve.forEach((resolutionPromise) =>\n resolutionPromise.reject(error)\n );\n }\n });\n };\n\n if (debounceTime > 0) {\n currentState.timer = setTimeout(addCallbackToQueue, debounceTime);\n } else {\n await addCallbackToQueue();\n }\n\n return resolutionPromise.promise;\n };\n};\n","import { BaseError } from './base';\n\nexport class InvalidStorageValue extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(key: string, value: unknown) {\n super({\n cause: null,\n code: 'invalid_storage_value',\n docsUrl: null,\n name: 'InvalidStorageValue',\n shortMessage: `Tried to store state with a forbidden value. Key: ${key}, Value: ${value}`,\n });\n }\n}\n","import { InvalidStorageValue } from '../../../errors/InvalidStorageValue';\nimport type { ObservableState } from '../observable.types';\n\n/**\n * Creates an observable state object that allows subscribing to immutable state changes.\n *\n * This function creates a state management system with the following capabilities:\n * - Get the current state\n * - Update state partially\n * - Subscribe to state changes\n * - Unsubscribe from state changes\n *\n * @param getInitialState - A function that returns the initial state object\n * @returns An ObservableState object with methods to manage and observe state changes\n * @example\n * ```typescript\n * const state = createObservableState(() => ({\n * count: 0,\n * name: 'John'\n * }));\n *\n * // Subscribe to changes\n * const unsubscribe = state.subscribe((current, previous) => {\n * console.log('State changed:', current, 'Previous:', previous);\n * });\n *\n * // Update state\n * state.set({ count: 1 });\n *\n * // Get current state\n * const currentState = state.get();\n *\n * // Unsubscribe when done\n * unsubscribe();\n * ```\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const createObservableState = <T extends Record<string, unknown>>(\n getInitialState: () => T\n): ObservableState<T> => {\n // ===============\n // NOTIFICATIONS\n // ===============\n const subscribers = new Set<(value: T, previous: T) => void>();\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const notifySubscribers = (value: T, previous: T) => {\n subscribers.forEach((callback) => callback(value, previous));\n };\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const subscribe = (\n callback: (value: Readonly<T>, previous: Readonly<T>) => void\n ) => {\n subscribers.add(callback);\n\n return () => unsubscribe(callback);\n };\n\n // eslint-disable-next-line custom-rules/require-single-object-param\n const unsubscribe = (\n callback: (value: Readonly<T>, previous: Readonly<T>) => void\n ) => {\n subscribers.delete(callback);\n };\n\n // ===============\n // STATE\n // ===============\n\n let currentState = getInitialState();\n\n const get = () => currentState;\n\n const set = (partial: Partial<T>) => {\n const previous = currentState;\n\n Object.entries(partial).forEach(([key, value]) => {\n if (value === undefined) {\n throw new InvalidStorageValue(key, value);\n }\n });\n\n currentState = Object.assign({}, currentState, partial);\n\n notifySubscribers(currentState, previous);\n };\n\n return {\n get,\n getInitialState,\n set,\n subscribe,\n unsubscribe,\n };\n};\n","/**\n * The default API base URL for Dynamic apps in production.\n */\nexport const DEFAULT_API_BASE_URL = 'https://app.dynamicauth.com/api/v0';\n","import type { DynamicCoreState } from '../types';\n\n/**\n * The initial values for the state of the client.\n * @not-instrumented\n */\nexport const getInitialState = (): DynamicCoreState => ({\n captchaToken: null,\n elevatedAccessTokens: [],\n initError: null,\n initStatus: 'uninitialized',\n legacyToken: null,\n mfaToken: null,\n nonceFetchInFlight: null,\n prefetchedNonces: [],\n prefetchedNoncesExpiration: null,\n projectSettings: null,\n sessionExpiresAt: null,\n sessionKeys: null,\n token: null,\n unverifiedWalletAccounts: [],\n user: null,\n walletProviderKeyMap: {},\n});\n","import { version } from '../../../../package.json';\nimport { createAsyncTrack } from '../../../services/asyncTrack';\nimport { createCrossTabBroadcast } from '../../../services/crossTabBroadcast/createCrossTabBroadcast';\nimport { createEventEmitter } from '../../../services/eventEmitter';\nimport { createWebFetch } from '../../../services/fetch/createWebFetch';\nimport { connectLoggerToInstrumentation } from '../../../services/instrumentation/connectLoggerToInstrumentation';\nimport { createInstrumentation } from '../../../services/instrumentation/createInstrumentation';\nimport { createDynamicTransport } from '../../../services/instrumentation/transports/createDynamicTransport';\nimport { createLogger } from '../../../services/logger/createLogger';\nimport { createNavigationHandler } from '../../../services/navigate/createNavigationHandler';\nimport { createKeychainService } from '../../../services/keychain';\nimport { createWebDeeplinkOpener } from '../../../services/openDeeplink/createWebDeeplinkOpener';\nimport { createPasskeyService } from '../../../services/passkey';\nimport { createRealtimeService } from '../../../services/realtime/createRealtimeService';\nimport { createRuntimeServices } from '../../../services/runtimeServices';\nimport {\n createLocalStorageAdapter,\n createStorage,\n} from '../../../services/storage';\nimport { createDebouncedMutex } from '../../../utils/debouncedMutex/createDebouncedMutex';\nimport { getKeychainIndexedDBName } from '../../../utils/getKeychainIndexedDBName';\nimport { isServerSideRendering } from '../../../utils/isServerSideRendering/isServerSideRendering';\nimport { createObservableState } from '../../../utils/observable/createObservableState';\nimport { randomString } from '../../../utils/randomString/randomString';\nimport { DEFAULT_API_BASE_URL } from '../../consts';\nimport type { DynamicClientConfig } from '../../types';\nimport type { DynamicCore, DynamicCoreState } from '../types';\nimport { getInitialState } from './getInitialState';\n\n/**\n * Creates a core instance that contains all the services and state of the Dynamic SDK client.\n * @not-instrumented\n */\nexport const createCore = (config: DynamicClientConfig): DynamicCore => {\n const apiBaseUrl = config.coreConfig?.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n const logger =\n config.coreConfig?.logger ?? createLogger({ level: config.logLevel });\n\n const storage = createStorage({\n prefix: `dynamic_${config.environmentId}`,\n storageAdapter:\n config.coreConfig?.storageAdapter ?? createLocalStorageAdapter(),\n });\n\n const fetch = config.coreConfig?.fetch ?? createWebFetch();\n\n const openDeeplink =\n config.coreConfig?.openDeeplink ?? createWebDeeplinkOpener();\n\n const openAuthSession = config.coreConfig?.openAuthSession;\n\n const navigate = config.coreConfig?.navigate ?? createNavigationHandler();\n\n const state = createObservableState<DynamicCoreState>(getInitialState);\n\n const debouncedMutex = createDebouncedMutex();\n\n const eventEmitter = createEventEmitter();\n\n const initTrack = createAsyncTrack();\n\n const sdkSessionId = randomString({ length: 32 });\n\n const instrumentation = createInstrumentation({\n config: config.instrumentation,\n });\n\n const extensions = new Set<string>();\n\n connectLoggerToInstrumentation({\n environmentId: config.environmentId,\n extensions,\n instrumentation,\n logger,\n sdkSessionId,\n sdkVersion: version,\n state,\n });\n\n if (!isServerSideRendering()) {\n instrumentation.setTransport(\n createDynamicTransport({\n environmentId: config.environmentId,\n fetch,\n })\n );\n }\n\n const runtimeServices = createRuntimeServices();\n\n const metadata = {\n ...config.metadata,\n universalLink:\n config.metadata?.universalLink ??\n // eslint-disable-next-line no-restricted-globals\n (isServerSideRendering() ? undefined : window.location.origin),\n };\n\n const passkey =\n config.coreConfig?.passkey ?? createPasskeyService({ metadata });\n\n const realtime = config.coreConfig?.realtime ?? createRealtimeService();\n\n const deviceSigner = config.coreConfig?.deviceSigner;\n\n const keychain =\n config.coreConfig?.keychain ??\n createKeychainService({\n dbName: getKeychainIndexedDBName({\n environmentId: config.environmentId,\n }),\n });\n\n const crossTabBroadcast =\n config.coreConfig?.crossTabBroadcast ??\n createCrossTabBroadcast({\n channelName: `dynamic_${config.environmentId}_broadcast`,\n });\n\n return {\n apiBaseUrl,\n crossTabBroadcast,\n debouncedMutex,\n deviceSigner,\n environmentId: config.environmentId,\n eventEmitter,\n extensions,\n fetch,\n getApiHeaders: config.coreConfig?.getApiHeaders ?? (() => ({})),\n initTrack,\n instrumentation,\n keychain,\n logger,\n metadata,\n navigate,\n openAuthSession,\n openDeeplink,\n passkey,\n realtime,\n runtimeServices,\n sdkSessionId,\n state,\n storage,\n transformers: config.transformers,\n version,\n waas: config.waas,\n };\n};\n","import { initializeClient } from '../../modules/initializeClient';\nimport { isServerSideRendering } from '../../utils/isServerSideRendering';\nimport { createCore } from '../core/createCore';\nimport { setDefaultClient } from '../defaultClient';\nimport type { DynamicClient, DynamicClientConfig } from '../types';\n\n/**\n * Creates a new DynamicClient instance.\n *\n * Notice the `autoInitialize` flag is true by default (unless you're running\n * in SSR), so the client will be automatically initialized when created — if\n * you want to manually initialize the client, you can set the `autoInitialize`\n * flag to false and then later call the `initializeClient` function.\n *\n * Manually calling `initializeClient` also allows you to catch any potential\n * errors that may occur during initialization.\n *\n * @param config - The configuration for the Dynamic client, like the environment ID, app url, etc.\n * @returns The Dynamic client instance.\n * @instrumented\n */\nexport const createDynamicClient = (\n config: DynamicClientConfig\n): DynamicClient => {\n const core = createCore(config);\n\n const client = {\n get __core() {\n return core;\n },\n get initError() {\n return core.state.get().initError;\n },\n get initStatus() {\n return core.state.get().initStatus;\n },\n get mfaToken() {\n return core.state.get().mfaToken;\n },\n get projectSettings() {\n return core.state.get().projectSettings;\n },\n get sessionExpiresAt() {\n return core.state.get().sessionExpiresAt;\n },\n get token() {\n return core.state.get().token;\n },\n get user() {\n return core.state.get().user;\n },\n };\n\n // Define if SDK should auto initialize, default to true\n const autoInitialize = config.autoInitialize ?? true;\n\n // Prevent the auto initialization in SSR\n const shouldAutoInitialize = isServerSideRendering() ? false : autoInitialize;\n\n core.logger.debug('[createDynamicClient] Creating client...');\n\n if (shouldAutoInitialize) {\n core.logger.debug('[createDynamicClient] Initializing client...');\n void initializeClient(client);\n }\n\n setDefaultClient(client);\n\n return client;\n};\n","import { BaseError } from './base';\n\nexport class CheckoutSessionTokenMissingError extends BaseError {\n constructor({ transactionId }: { transactionId: string }) {\n super({\n cause: null,\n code: 'checkout_session_token_missing',\n docsUrl: null,\n name: 'CheckoutSessionTokenMissingError',\n shortMessage: `No session token found for transaction ${transactionId}. Session tokens are issued once at transaction creation and cannot be recovered.`,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype DeeplinkConnectAndVerifyUnsupportedErrorParams = {\n walletProviderKey: string;\n};\n\nexport class DeeplinkConnectAndVerifyUnsupportedError extends BaseError {\n constructor({\n walletProviderKey,\n }: DeeplinkConnectAndVerifyUnsupportedErrorParams) {\n super({\n cause: null,\n code: 'deeplink_connect_and_verify_unsupported',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n 'On mobile, deep link wallet providers (e.g. Phantom redirect) cannot connect and verify in a single step.',\n 'iOS does not allow two sequential deep links — the second one is silently ignored because it is no longer tied to a user gesture.',\n 'Android may handle sequential deep links differently, but this guard applies to all mobile platforms to ensure a stable experience and prevent production-only errors.',\n 'Use connectWithWalletProvider() first, then call verifyWalletAccount() from a separate user action (e.g. a \"Verify Ownership\" button).',\n ],\n name: 'DeeplinkConnectAndVerifyUnsupportedError',\n shortMessage:\n 'connectAndVerifyWithWalletProvider is not supported for deep link wallet providers on mobile. Use connectWithWalletProvider and verifyWalletAccount separately.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class FeeEstimationFailedError extends BaseError {\n constructor(params: { cause?: Error; message: string }) {\n super({\n cause: params.cause || null,\n code: 'fee_estimation_failed_error',\n docsUrl: null,\n name: 'FeeEstimationFailedError',\n shortMessage: params.message,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class InvalidDeviceRegistrationRedirectError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'invalid_device_registration_redirect_error',\n docsUrl: null,\n metaMessages: [\n 'To check if a URL is a valid device registration redirect before extracting the token, use detectDeviceRegistrationRedirect from the @dynamic-labs-sdk/client package.',\n ],\n name: 'InvalidDeviceRegistrationRedirectError',\n shortMessage:\n 'The provided URL is not a valid device registration redirect.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class InvalidRedirectStorageStateError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'invalid_redirect_storage_state_error',\n docsUrl: null,\n name: 'InvalidRedirectStorageStateError',\n shortMessage:\n 'The social redirect data found in local storage does not match the expected state. Try connecting again.',\n });\n }\n}\n","import { BaseError } from './base';\n\ntype InvalidSocialCallbackOriginErrorParams = {\n actualOrigin: string;\n expectedOrigin: string;\n};\n\nexport class InvalidSocialCallbackOriginError extends BaseError {\n constructor({\n actualOrigin,\n expectedOrigin,\n }: InvalidSocialCallbackOriginErrorParams) {\n super({\n cause: null,\n code: 'invalid_social_callback_origin_error',\n docsUrl: null,\n name: 'InvalidSocialCallbackOriginError',\n shortMessage: `OAuth callback URL origin mismatch. Expected ${expectedOrigin}, got ${actualOrigin}. This may indicate a compromised auth session or misconfigured redirect URL.`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class UserCancelledSocialPopUpError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'user_cancelled_social_popup_error',\n docsUrl: null,\n name: 'UserCancelledSocialPopUpError',\n shortMessage:\n 'The user cancelled (or dismissed) the social authentication pop-up.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class MissingRedirectStorageStateError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'missing_redirect_storage_state_error',\n docsUrl: null,\n name: 'MissingRedirectStorageStateError',\n shortMessage:\n 'The social redirect data was not found in local storage. Try connecting again.',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class MissingSocialUrlParamError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(param: string) {\n super({\n cause: null,\n code: 'missing_social_url_param_error',\n docsUrl: null,\n name: 'MissingSocialParamError',\n shortMessage: `To complete social sign in, the following URL query parameter is required to be set but was not found: ${param}`,\n });\n }\n}\n","import type { UserFields } from '@dynamic-labs/sdk-api-core';\n\nimport { BaseError } from './base';\n\ntype MissingUserVerificationErrorParams = {\n informationToVerify: Extract<keyof UserFields, 'email' | 'phoneNumber'>;\n message?: string;\n};\n\nexport class MissingUserVerificationError extends BaseError {\n public readonly informationToVerify: MissingUserVerificationErrorParams['informationToVerify'];\n\n constructor({\n informationToVerify,\n message,\n }: MissingUserVerificationErrorParams) {\n super({\n cause: null,\n code: 'missing_user_verification_error',\n docsUrl: null,\n name: 'MissingUserVerificationError',\n shortMessage:\n message ??\n `The user is missing verification for ${informationToVerify}. Please verify the user's ${informationToVerify}`,\n });\n\n this.informationToVerify = informationToVerify;\n }\n}\n","import { BaseError } from './base';\n\ntype NetworkAddingUnavailableErrorParams = {\n extraMessages?: string[];\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkAddingUnavailableError extends BaseError {\n constructor({\n walletProviderKey,\n originalError,\n extraMessages,\n }: NetworkAddingUnavailableErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_adding_unavailable',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n ...(extraMessages ?? []),\n ],\n name: 'NetworkAddingUnavailableError',\n shortMessage: `Network adding is not available for this wallet provider. The user should manually add the network in their wallet`,\n });\n }\n}\n","import type { NetworkData } from '../modules/wallets/networks/networkProvider/networkProvider.types';\nimport { BaseError } from './base';\n\ntype NetworkNotAddedErrorParams = {\n networkData: NetworkData;\n networkId: string;\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkNotAddedError extends BaseError {\n readonly networkData: NetworkData;\n\n constructor({\n networkData,\n networkId,\n originalError,\n walletProviderKey,\n }: NetworkNotAddedErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_not_added',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n `Network ID: ${networkId}`,\n 'The network is not added to the wallet. If the wallet provider supports adding networks, call the `addNetwork` method before switching.',\n 'The network data is available in the error payload as `error.networkData` and can be passed directly to `addNetwork`.',\n ],\n name: 'NetworkNotAddedError',\n shortMessage: `Cannot switch to network ${networkId} because it is not added to the wallet. If the wallet provider supports it, call \\`addNetwork\\` with the network data from \\`error.networkData\\` first.`,\n });\n\n this.networkData = networkData;\n }\n}\n","import { BaseError } from './base';\n\ntype NetworkSwitchingUnavailableErrorParams = {\n extraMessages?: string[];\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class NetworkSwitchingUnavailableError extends BaseError {\n constructor({\n walletProviderKey,\n originalError,\n extraMessages,\n }: NetworkSwitchingUnavailableErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'network_switching_unavailable',\n docsUrl: null,\n metaMessages: [\n `Wallet provider key: ${walletProviderKey}`,\n ...(extraMessages ?? []),\n ],\n name: 'NetworkSwitchingUnavailableError',\n shortMessage: `Network switching is not available at this time. The user should manually switch networks in their wallet`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoAddressFoundError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_address_found_error',\n docsUrl: null,\n name: 'NoAddressFoundError',\n shortMessage: 'No address is connected to the wallet',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoPasskeyCredentialsFoundError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_passkey_credentials_found_error',\n docsUrl: null,\n name: 'NoPasskeyCredentialsFoundError',\n shortMessage: 'No passkey credentials found',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoSmartWalletAccountSignerFoundError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(smartWalletAddress: string) {\n super({\n cause: null,\n code: 'no_smart_wallet_account_signer_found_error',\n docsUrl: null,\n name: 'NoSmartWalletAccountSignerFoundError',\n shortMessage: `No signer wallet account found for smart wallet account ${smartWalletAddress}`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class NoWebAuthNSupportError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'no_webauthn_support_error',\n docsUrl: null,\n name: 'NoWebAuthNSupportError',\n shortMessage: 'Browser does not support WebAuthn',\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class SimulationFailedError extends BaseError {\n constructor(params: { cause?: Error; message: string }) {\n super({\n cause: params.cause || null,\n code: 'simulation_failed_error',\n docsUrl: null,\n name: 'SimulationFailedError',\n shortMessage: params.message,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype TokenSwapErrorParams = {\n message: string;\n originalError?: unknown;\n};\n\nexport class TokenSwapError extends BaseError {\n constructor({ message, originalError }: TokenSwapErrorParams) {\n const cause =\n originalError && originalError instanceof Error ? originalError : null;\n super({\n cause,\n code: 'token_swap_error',\n docsUrl: null,\n name: 'TokenSwapError',\n shortMessage: message,\n });\n }\n}\n","import { BaseError } from './base';\n\ntype UnrecognizedNetworkErrorParams = {\n networkId: string;\n originalError: unknown;\n walletProviderKey: string;\n};\n\nexport class UnrecognizedNetworkError extends BaseError {\n constructor({\n networkId,\n originalError,\n walletProviderKey,\n }: UnrecognizedNetworkErrorParams) {\n const cause = originalError instanceof Error ? originalError : null;\n\n super({\n cause,\n code: 'unrecognized_network',\n docsUrl: null,\n metaMessages: [`Wallet provider key: ${walletProviderKey}`],\n name: 'UnrecognizedNetworkError',\n shortMessage: `Attempt to switch to unrecognized network of ID ${networkId}. Please enable this network in your dashboard configuration first.`,\n });\n }\n}\n","import { BaseError, type BaseErrorParameters } from './base';\n\nexport class UserNotAuthenticatedError extends BaseError {\n constructor({\n shortMessage,\n }: Partial<Pick<BaseErrorParameters, 'shortMessage'>> = {}) {\n super({\n cause: null,\n code: 'user_not_authenticated_error',\n docsUrl: null,\n name: 'UserNotAuthenticatedError',\n shortMessage: shortMessage ?? 'User not authenticated',\n });\n }\n}\n","import { BaseError } from './base';\n\ntype UserRejectedErrorParams = {\n action: string;\n};\n\nexport class UserRejectedError extends BaseError {\n constructor({ action }: UserRejectedErrorParams) {\n super({\n cause: null,\n code: 'user_rejected',\n docsUrl: null,\n name: 'UserRejectedError',\n shortMessage: `User rejected action \"${action}\"`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class WalletAccountAlreadyVerifiedError extends BaseError {\n // eslint-disable-next-line custom-rules/require-single-object-param\n constructor(address: string) {\n super({\n cause: null,\n code: 'wallet_account_already_verified_error',\n docsUrl: null,\n name: 'WalletAccountAlreadyVerifiedError',\n shortMessage: `Wallet account ${address} is already verified`,\n });\n }\n}\n","import { BaseError } from './base';\n\nexport class WalletAccountNotSelectedError extends BaseError {\n public readonly expectedAddress: string;\n public readonly selectedAddress: string;\n\n constructor(params: { expectedAddress: string; selectedAddress: string }) {\n const currentAccountInfo = params.selectedAddress\n ? ` (currently ${params.selectedAddress})`\n : '';\n super({\n cause: null,\n code: 'wallet_account_not_selected_error',\n docsUrl: null,\n name: 'WalletAccountNotSelected',\n shortMessage: `This wallet only supports signing with its selected account${currentAccountInfo}. Please select account ${params.expectedAddress} in your wallet app and try again`,\n });\n\n this.expectedAddress = params.expectedAddress;\n this.selectedAddress = params.selectedAddress;\n }\n}\n","import { BaseError } from './base';\n\ntype WalletProviderMethodUnavailableErrorParams = {\n methodName: string;\n walletProviderKey: string;\n};\n\nexport class WalletProviderMethodUnavailableError extends BaseError {\n constructor({\n methodName,\n walletProviderKey,\n }: WalletProviderMethodUnavailableErrorParams) {\n super({\n cause: null,\n code: 'wallet_provider_method_unavailable_error',\n docsUrl: null,\n name: 'WalletProviderMethodUnavailableError',\n shortMessage: `Wallet provider ${walletProviderKey} does not have ${methodName} available`,\n });\n }\n}\n","import { type StepUpCheckResponse, type TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createApiClient } from '../../apiClient/createApiClient';\nimport { getElevatedAccessToken } from '../getElevatedAccessToken';\n\nconst STEP_UP_REQUIRED_DEFAULT: StepUpCheckResponse = {\n credentials: [],\n isRequired: true,\n};\n\n/**\n * Checks whether step-up authentication is required for a given scope\n * and returns the available credentials to satisfy it.\n *\n * First performs a fast local check — if a valid elevated access token already\n * exists for the scope, returns `{ isRequired: false }` immediately without\n * an API call.\n *\n * Otherwise, calls the backend `stepUp/check` endpoint which evaluates\n * feature flags, SDK version, MFA settings, and action-based requirements\n * to determine if step-up is needed. The response includes the available\n * credentials and a recommended default credential.\n *\n * If the request fails for any reason, defaults to `{ isRequired: true }`\n * as a safety measure.\n *\n * @param params.scope - The scope to check (e.g., 'wallet:export').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The step-up check result with `isRequired`, `credentials`, and `defaultCredentialId`.\n *\n * @example\n * ```typescript\n * const result = await checkStepUpAuth({ scope: TokenScope.Walletexport });\n * if (result.isRequired) {\n * // Show step-up auth UI using result.credentials\n * }\n * ```\n * @instrumented\n */\nexport const checkStepUpAuth = async (\n { scope }: { scope: TokenScope },\n client: DynamicClient = getDefaultClient()\n): Promise<StepUpCheckResponse> => {\n // Fast local check: if we already have a valid elevated token, no step-up needed\n const existingToken = getElevatedAccessToken(\n { consume: false, scope },\n client\n );\n\n if (existingToken) {\n return { credentials: [], isRequired: false };\n }\n\n try {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.stepUpCheck({\n environmentId: core.environmentId,\n stepUpCheckRequest: { scope },\n });\n\n return {\n credentials: response.credentials ?? [],\n defaultCredentialId: response.defaultCredentialId,\n isRequired: response.isRequired,\n };\n } catch {\n // Default to requiring step-up on any failure for safety\n return STEP_UP_REQUIRED_DEFAULT;\n }\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { parseElevatedAccessToken } from '../../updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken';\nimport { upsertElevatedAccessToken } from '../../updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken';\n\ntype RequestExternalAuthElevatedTokenParams = {\n externalJwt: string;\n};\n\n/**\n * Requests an elevated access token using an external auth assertion JWT.\n *\n * The assertion JWT must be signed by the customer's backend using the same key\n * registered in the environment's external auth JWKS URL. It must include\n * `sub`, `scope`, `jti`, and `exp` claims.\n *\n * The returned elevated access token is automatically parsed and stored in state,\n * and can be retrieved via `getElevatedAccessToken`.\n *\n * @param params.externalJwt - The assertion JWT signed by the customer's backend.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the assertion response containing the elevated access token.\n * @instrumented\n * @redact-params\n */\nexport const requestExternalAuthElevatedToken = async (\n { externalJwt }: RequestExternalAuthElevatedTokenParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.externalAuthVerify({\n environmentId: core.environmentId,\n externalAuthSigninRequest: {\n jwt: externalJwt,\n },\n });\n\n const parsedToken = parseElevatedAccessToken({\n token: response.elevatedAccessToken,\n });\n if (parsedToken) {\n const currentTokens = core.state.get().elevatedAccessTokens || [];\n core.state.set({\n elevatedAccessTokens: upsertElevatedAccessToken({\n currentTokens,\n newToken: parsedToken,\n }),\n });\n }\n\n return response;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\n\ntype SignInWithExternalJwtParams = {\n externalJwt?: string;\n sessionPublicKey?: string;\n};\n\n/**\n * Signs in a user using an external JWT token.\n *\n * This function allows authentication using JWT tokens from external providers,\n * enabling integration with custom authentication systems.\n *\n * @param [params.externalJwt] - Optional external JWT token to authenticate with. Not required when using cookie based auth.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authentication response from the server.\n * @instrumented\n * @redact-params\n */\nexport const signInWithExternalJwt = async (\n { externalJwt, sessionPublicKey }: SignInWithExternalJwtParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.externalAuthSignin({\n environmentId: core.environmentId,\n externalAuthSigninRequest: {\n jwt: externalJwt,\n sessionPublicKey,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { logoutWithReason } from '../logoutWithReason';\n\n/**\n * Logs out the current user and clears all authentication data.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the logout process is complete.\n * @not-instrumented\n */\nexport const logout = async (client = getDefaultClient()) => {\n /**\n * Delegates to `logoutWithReason` with `'user-intent'` so telemetry correctly\n * attributes the logout to an explicit user action. Instrumentation lives on\n * `logoutWithReason` — this wrapper is intentionally not instrumented so that\n * Datadog sees a single function name per logout regardless of entry point.\n */\n return logoutWithReason({ reason: 'user-intent' }, client);\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\n\n/**\n * Deletes a passkey for the current user.\n *\n * @param params.passkeyId - The unique identifier of the passkey to delete.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the passkey is successfully deleted.\n * @instrumented\n */\nexport const deletePasskey = async (\n { passkeyId }: { passkeyId: string },\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient(\n {\n elevatedAccessTokenScope: TokenScope.Credentialunlink,\n includeMfaToken: true,\n },\n client\n );\n\n await apiClient.deletePasskey({\n deleteUserPasskeyRequest: {\n passkeyId,\n },\n environmentId: core.environmentId,\n });\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\n\n/**\n * Retrieves all passkeys associated with the current user.\n *\n * This function fetches the list of registered passkeys (WebAuthn credentials)\n * that the user can use for multi-factor authentication.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of the user's registered passkeys.\n * @not-instrumented\n */\nexport const getPasskeys = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.getUserPasskeys({\n environmentId: core.environmentId,\n });\n\n return response.passkeys;\n};\n","import type { GetPasskeyRegistrationOptionsResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\n/** @not-instrumented */\nexport const getPasskeyRegistrationOptions = async (\n client: DynamicClient\n): Promise<PublicKeyCredentialCreationOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyRegistrationOptionsResponse =\n await apiClient.getPasskeyRegistrationOptions({\n environmentId: core.environmentId,\n });\n\n return options as PublicKeyCredentialCreationOptionsJSON;\n};\n","import type { CreateMfaToken } from '@dynamic-labs/sdk-api-core';\nimport { TokenScope } from '@dynamic-labs/sdk-api-core';\nimport { type RegistrationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerRegisterPasskeyParams = {\n createMfaToken?: CreateMfaToken;\n registration: RegistrationResponseJSON;\n};\n\n/** @not-instrumented */\nexport const serverRegisterPasskey = async (\n { registration, createMfaToken }: ServerRegisterPasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentiallink },\n client\n );\n\n const response = await apiClient.registerPasskey({\n environmentId: core.environmentId,\n passkeyRegisterRequest: {\n ...registration,\n createMfaToken,\n response: {\n ...registration.response,\n clientDataJson: registration.response.clientDataJSON,\n },\n } as Parameters<\n typeof apiClient.registerPasskey\n >[0]['passkeyRegisterRequest'],\n });\n\n return response;\n};\n","import type { CreateMfaToken } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { NoWebAuthNSupportError } from '../../../../errors/NoWebAuthNSupportError';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\nimport { getPasskeyRegistrationOptions } from '../getPasskeyRegistrationOptions';\nimport { serverRegisterPasskey } from '../serverRegisterPasskey';\n\ntype RegisterPasskeyParams = {\n createMfaToken?: CreateMfaToken;\n};\n\n/**\n * Registers a new passkey for the current user.\n *\n * This function creates a new WebAuthn credential that can be used for\n * passwordless authentication. The user will be prompted to create a passkey\n * using their device's biometric authentication or security key.\n *\n * @param [params.createMfaToken] - Optional configuration for MFA token creation.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the registration response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @instrumented\n * @redact-params\n */\nexport const registerPasskey = async (\n { createMfaToken }: RegisterPasskeyParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyRegistrationOptions(client);\n\n const registration = await core.passkey.register({\n optionsJSON: options as PublicKeyCredentialCreationOptionsJSON,\n });\n\n const response = await serverRegisterPasskey(\n { createMfaToken, registration },\n client\n );\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type { GetPasskeyAuthenticationOptionsResponse } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\nexport type GetPasskeyAuthenticationSignInOptionsParams = {\n relatedOriginRpId?: string;\n};\n\n/** @not-instrumented */\nexport const getPasskeyAuthenticationSignInOptions = async (\n { relatedOriginRpId }: GetPasskeyAuthenticationSignInOptionsParams = {},\n client: DynamicClient\n): Promise<PublicKeyCredentialRequestOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyAuthenticationOptionsResponse =\n await apiClient.getPasskeyAuthenticationSigninOptions({\n environmentId: core.environmentId,\n relatedOriginRpId: relatedOriginRpId,\n });\n\n return options as PublicKeyCredentialRequestOptionsJSON;\n};\n","import type {\n CreateMfaToken,\n PasskeyAuthRequest,\n} from '@dynamic-labs/sdk-api-core';\nimport type { AuthenticationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerSigninPasskeyParams = {\n authentication: AuthenticationResponseJSON;\n createMfaToken?: CreateMfaToken;\n};\n\n/** @not-instrumented */\nexport const serverSigninPasskey = async (\n { authentication, createMfaToken }: ServerSigninPasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.signinWithPasskey({\n environmentId: core.environmentId,\n passkeyAuthRequest: {\n ...authentication,\n createMfaToken,\n response: {\n ...authentication.response,\n clientDataJson: authentication.response.clientDataJSON,\n },\n } as PasskeyAuthRequest,\n });\n\n return response;\n};\n","import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { NoWebAuthNSupportError } from '../../../../errors/NoWebAuthNSupportError';\nimport { updateAuthFromVerifyResponse } from '../../updateAuthFromVerifyResponse';\nimport { getPasskeyAuthenticationSignInOptions } from '../getPasskeyAuthenticationSignInOptions';\nimport { serverSigninPasskey } from '../serverSigninPasskey';\n\nexport type SignInWithPasskeyParams = {\n relatedOriginRpId?: string;\n};\n\n/**\n * Signs in the user using a registered passkey.\n *\n * This function authenticates the user with a previously registered WebAuthn\n * credential, providing passwordless authentication using biometrics or\n * security keys.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authentication response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @instrumented\n * @redact-params\n */\nexport const signInWithPasskey = async (\n { relatedOriginRpId }: SignInWithPasskeyParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyAuthenticationSignInOptions(\n { relatedOriginRpId },\n client\n );\n\n const formattedOptions: PublicKeyCredentialRequestOptionsJSON = {\n ...options,\n };\n\n const authentication = await core.passkey.authenticate({\n optionsJSON: formattedOptions,\n });\n\n const response = await serverSigninPasskey({ authentication }, client);\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { SocialAccount, SocialProvider } from '../social.types';\n\n/**\n * Retrieves all social accounts associated with the current user.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of `SocialAccount` objects associated with the user.\n * @not-instrumented\n */\nexport const getUserSocialAccounts = (\n client = getDefaultClient()\n): SocialAccount[] => {\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const socialCredentials =\n user.verifiedCredentials.filter(\n (credential) =>\n credential.format === JwtVerifiedCredentialFormatEnum.Oauth\n ) ?? [];\n\n return socialCredentials.map((credential) => ({\n accountId: credential.oauthAccountId ?? undefined,\n displayName: credential.oauthDisplayName ?? undefined,\n emails: credential.oauthEmails ?? [],\n photos: credential.oauthAccountPhotos ?? [],\n provider: credential.oauthProvider as SocialProvider,\n username: credential.oauthUsername ?? undefined,\n verifiedCredentialId: credential.id,\n }));\n};\n","/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const removeDynamicOauthParamsFromUrl = (url: string) => {\n const urlObject = new URL(url);\n\n urlObject.searchParams.delete('dynamicOauthState');\n urlObject.searchParams.delete('dynamicOauthCode');\n\n return urlObject.toString();\n};\n","import { ProviderEnum } from '@dynamic-labs/sdk-api-core';\nimport * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../../../services/storage';\n\n/** The schema to track the state of the OAuth flow. */\nexport const redirectStateStorageKeySchema = createStorageKeySchema({\n key: 'redirectState',\n schema: z.object({\n codeVerifier: z.optional(z.string()),\n provider: z.enum(ProviderEnum),\n state: z.string(),\n }),\n});\n","/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const digestSHA256 = (str: string) => {\n const encoder = new TextEncoder();\n const data = encoder.encode(str);\n return crypto.subtle.digest('SHA-256', data);\n};\n","/**\n * Encodes a string to base64url.\n *\n * @param str - The string to encode as an ArrayBuffer.\n * @returns The base64url encoded string.\n * @not-instrumented\n */\nexport const encodeBase64Url = (str: ArrayBuffer) => {\n const numberArray: number[] = [];\n new Uint8Array(str).forEach((item) => numberArray.push(item));\n\n // Deprecated btoa used for web compatibility\n return btoa(String.fromCharCode.apply(null, numberArray))\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n};\n","import { type Provider, ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { assertDefined } from '../../../../../../../utils/assertDefined';\n\nconst APPLE_RESPONSE_MODE = 'form_post' as const;\nconst APPLE_RESPONSE_TYPE = 'code id_token' as const;\n\nexport type AddOAuthUrlParamsOptions = {\n /** The base URL to add OAuth parameters to. */\n baseUrl: URL;\n\n /** When true, adds prompt=consent to force Google to return a fresh refresh token. * @not-instrumented\n */\n isGoogleDriveBackupEnabled?: boolean;\n\n /** The provider configuration to build the URL for. */\n provider: Provider;\n};\n\n/** Helper function to add OAuth URL parameters to a given base URL. * @not-instrumented\n */\nexport const addOAuthUrlParams = ({\n baseUrl,\n isGoogleDriveBackupEnabled,\n provider,\n}: AddOAuthUrlParamsOptions): URL => {\n assertDefined(provider.clientId, 'Client ID not found');\n assertDefined(provider.provider, 'Provider type not found');\n assertDefined(provider.redirectUrl, 'Redirect URL not found');\n\n const providerType = provider.provider;\n\n baseUrl.searchParams.set('client_id', provider.clientId);\n baseUrl.searchParams.set('response_type', 'code');\n baseUrl.searchParams.set('redirect_uri', provider.redirectUrl);\n\n if (providerType === ProviderEnum.Tiktok) {\n baseUrl.searchParams.delete('client_id');\n baseUrl.searchParams.set('client_key', provider.clientId);\n }\n\n if (providerType === ProviderEnum.Google) {\n baseUrl.searchParams.set('access_type', 'offline');\n\n if (isGoogleDriveBackupEnabled) {\n baseUrl.searchParams.set('prompt', 'consent');\n }\n }\n\n // Add logic for providers that require additional parameters\n if (providerType === ProviderEnum.Apple) {\n baseUrl.searchParams.set('response_mode', APPLE_RESPONSE_MODE);\n baseUrl.searchParams.set('response_type', APPLE_RESPONSE_TYPE);\n }\n\n if (provider.scopes) {\n baseUrl.searchParams.set('scope', provider.scopes);\n }\n\n return baseUrl;\n};\n","import { type Provider, ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { assertDefined } from '../../../../../../../utils/assertDefined';\n\n/** Helper function to build the OAuth base URL for a given provider. * @not-instrumented\n */\nexport const getOAuthBaseUrl = (provider: Provider): URL => {\n assertDefined(provider.provider, 'Provider type not found');\n\n const providerType = provider.provider;\n\n if (providerType === ProviderEnum.Telegram) {\n assertDefined(\n provider.authorizationUrl,\n 'Telegram authorization URL not found'\n );\n return new URL(provider.authorizationUrl);\n }\n\n assertDefined(provider.baseAuthUrl, 'Base auth URL not found');\n\n if (providerType === ProviderEnum.Shopify) {\n assertDefined(\n provider.shopifyStore,\n 'Shopify store value not found in provider'\n );\n const loginBaseUrl = provider.baseAuthUrl.replace(\n '{{shopifyStore}}',\n provider.shopifyStore\n );\n return new URL(loginBaseUrl);\n }\n\n return new URL(provider.baseAuthUrl);\n};\n","import {\n type ProviderEnum,\n WaasBackupOptionsEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicCore } from '../../../../../../client/core/types';\nimport { assertDefined } from '../../../../../../utils/assertDefined';\nimport { digestSHA256 } from '../../../../../../utils/digestSHA256';\nimport { encodeBase64Url } from '../../../../../../utils/encodeBase64Url';\nimport { randomString } from '../../../../../../utils/randomString';\nimport { addOAuthUrlParams } from './addOAuthUrlParams';\nimport { getOAuthBaseUrl } from './getOAuthBaseUrl';\n\nconst providersRequiringPkce = ['twitter', 'github'];\n\ntype OAuthUrl = {\n /** A randomly generated string for PKCE flows. * @not-instrumented\n */\n codeVerifier?: string;\n\n /** A randomly generated string for the OAuth flow. */\n state: string;\n\n /** The OAuth URL for the given provider. */\n url: URL;\n};\n\n/** Helper function to build the OAuth URL for a given provider. * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const buildOAuthUrl = async (\n /** The core instance. */\n core: DynamicCore,\n\n /** The provider to build the OAuth URL for. */\n provider: ProviderEnum\n): Promise<OAuthUrl> => {\n const { projectSettings } = core.state.get();\n\n // Check if the provider is supported\n assertDefined(projectSettings, 'Project settings not found');\n assertDefined(projectSettings.providers, 'Project providers not found');\n\n const socialProvider = projectSettings.providers.find(\n (p) => p.provider === provider\n );\n\n assertDefined(socialProvider, `Social provider ${provider} not supported`);\n\n // Check if Google Drive backup is enabled for WaaS\n const isGoogleDriveBackupEnabled =\n projectSettings.sdk.waas?.backupOptions?.includes(\n WaasBackupOptionsEnum.GoogleDrive\n );\n\n // Build the OAuth URL\n const loginBaseUrl = getOAuthBaseUrl(socialProvider);\n const socialProviderUrl = addOAuthUrlParams({\n baseUrl: loginBaseUrl,\n isGoogleDriveBackupEnabled,\n provider: socialProvider,\n });\n\n // Add PKCE and state parameters\n const usingPkce = providersRequiringPkce.includes(provider);\n const state = randomString({ length: 32 });\n const codeVerifier = randomString({ length: 43 });\n\n socialProviderUrl.searchParams.set('state', state);\n socialProviderUrl.searchParams.set('response_type', 'code');\n\n if (usingPkce) {\n const digest = await digestSHA256(codeVerifier);\n\n socialProviderUrl.searchParams.set(\n 'code_challenge',\n encodeBase64Url(digest)\n );\n socialProviderUrl.searchParams.set('code_challenge_method', 'S256');\n }\n\n return {\n codeVerifier: usingPkce ? codeVerifier : undefined,\n state,\n url: socialProviderUrl,\n };\n};\n","import type { ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { createApiClient } from '../../../../apiClient';\nimport { removeDynamicOauthParamsFromUrl } from '../../removeDynamicOauthParamsFromUrl';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\nimport { buildOAuthUrl } from './buildOAuthUrl';\nimport type { SignInWithSocialRedirectParams } from './signInWithSocialRedirect.types';\n\nexport type { SignInWithSocialRedirectParams } from './signInWithSocialRedirect.types';\n\n/**\n * Initiates social authentication by redirecting to the OAuth provider.\n *\n * This function redirects the user to the specified social provider's\n * authorization page to complete the OAuth authentication flow.\n * After the flow is complete, the user is redirected back to your app.\n * Call `detectSocialRedirectUrl` to check whether the user was redirected\n * back because of this flow, then call `completeSocialRedirect` to finish\n * the social authentication.\n *\n * @param params.provider - The social provider to authenticate with (e.g., 'google', 'github').\n * @param params.redirectUrl - The URL to redirect back to after authentication.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @instrumented\n */\nexport const signInWithSocialRedirect = async (\n { provider, redirectUrl }: SignInWithSocialRedirectParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await core.initTrack.waitForAll();\n\n const providerType = provider as ProviderEnum;\n\n const { url, state, codeVerifier } = await buildOAuthUrl(core, providerType);\n\n await apiClient.initAuth({\n environmentId: core.environmentId,\n oauthInitAuthRequest: {\n redirectUrl: removeDynamicOauthParamsFromUrl(redirectUrl),\n state,\n },\n providerType,\n });\n\n await core.storage.setItem(redirectStateStorageKeySchema, {\n codeVerifier,\n provider: providerType,\n state,\n });\n\n await core.navigate(url.toString());\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { MethodNotImplementedError } from '../../../../../errors/MethodNotImplementedError';\nimport type { User } from '../../../../user/user.types';\nimport type { SignInWithSocialPopUpParams } from './signInWithSocialPopUp.types';\n\nexport type { SignInWithSocialPopUpParams } from './signInWithSocialPopUp.types';\n\n/**\n * Sign in with a social provider via an in-app popup (ASWebAuthenticationSession\n * on iOS, Chrome Custom Tabs on Android).\n *\n * This method is **only available on React Native**. On web, use\n * {@link signInWithSocialRedirect} + {@link completeSocialRedirect} instead —\n * the browser already owns the tab so there is no popup to open.\n *\n * @throws MethodNotImplementedError Always on web.\n * @instrumented\n */\nexport const signInWithSocialPopUp = async (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- params required to match standard signature in check-platform-types; destructure pattern cannot be renamed\n { provider }: SignInWithSocialPopUpParams,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- client default required by check-dynamic-client-param-in-external-functions\n client = getDefaultClient()\n): Promise<User | null> => {\n throw new MethodNotImplementedError(\n 'signInWithSocialPopUp (only available on React Native — use signInWithSocialRedirect on web)'\n );\n};\n","import { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\nimport type { DetectSocialRedirectUrlParams } from './detectSocialRedirectUrl.types';\n\nexport type { DetectSocialRedirectUrlParams } from './detectSocialRedirectUrl.types';\n\n/**\n * Detects whether the given URL is an OAuth redirect from a social provider.\n *\n * Examines the URL parameters to determine whether it carries OAuth callback\n * data that originated from a social authentication flow started by\n * `signInWithSocialRedirect`.\n *\n * @param params.url - The URL to check for OAuth redirect parameters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to true if the URL is an OAuth redirect, false otherwise.\n * @not-instrumented\n */\nexport const detectSocialRedirectUrl = async (\n { url }: DetectSocialRedirectUrlParams,\n client = getDefaultClient()\n): Promise<boolean> => {\n const core = getCore(client);\n\n const dynamicOauthState = url.searchParams.get('dynamicOauthState');\n const dynamicOauthCode = url.searchParams.get('dynamicOauthCode');\n\n if (!dynamicOauthState || !dynamicOauthCode) {\n return false;\n }\n\n // Wait for SDK to load\n await core.initTrack.waitForAll();\n\n const storedSocialRedirectState = await core.storage.getItem(\n redirectStateStorageKeySchema\n );\n\n return storedSocialRedirectState?.state === dynamicOauthState;\n};\n","import type { TokenScope, VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../../client/types';\nimport { InvalidRedirectStorageStateError } from '../../../../../errors/InvalidRedirectStorageStateError';\nimport { MissingRedirectStorageStateError } from '../../../../../errors/MissingRedirectStorageStateError';\nimport { MissingSocialUrlParamError } from '../../../../../errors/MissingSocialUrlParamError';\nimport { createApiClient } from '../../../../apiClient';\nimport { consumeCaptchaToken } from '../../../../captcha/consumeCaptchaToken';\nimport type { User } from '../../../../user/user.types';\nimport { updateAuthFromVerifyResponse } from '../../../updateAuthFromVerifyResponse';\nimport { redirectStateStorageKeySchema } from '../redirectStateStorageSchema';\n\ntype ProcessSocialCallbackParams = {\n requestedScopes?: TokenScope[];\n url: URL;\n};\n\n/**\n * Platform-agnostic OAuth callback processor used by both the web redirect\n * flow (`completeSocialRedirect`) and the native pop-up flow\n * (`signInWithSocialPopUp`). Intentionally has no `.native.ts` variant — the\n * logic (parse URL, validate state, call oauthSignIn/oauthVerify, update auth)\n * works identically on every platform.\n *\n * Not exported from the public SDK surface; public callers go through\n * `completeSocialRedirect` or `signInWithSocialPopUp` instead.\n *\n * @param params.url - The callback URL containing OAuth response parameters.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token when verifying (linking) a social account.\n * @param client - The Dynamic client instance.\n * @returns The authenticated user, or null if the verify response had none.\n * @throws MissingSocialUrlParamError If required OAuth parameters are missing.\n * @throws MissingRedirectStorageStateError If no stored redirect state exists.\n * @throws InvalidRedirectStorageStateError If the stored state doesn't match the URL state.\n * @instrumented\n */\nexport const processSocialCallback = async (\n { url, requestedScopes }: ProcessSocialCallbackParams,\n client: DynamicClient\n): Promise<User | null> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await core.initTrack.waitForAll();\n\n const dynamicOauthState = url.searchParams.get('dynamicOauthState');\n const dynamicOauthCode = url.searchParams.get('dynamicOauthCode');\n\n if (!dynamicOauthState) {\n throw new MissingSocialUrlParamError('dynamicOauthState');\n }\n\n if (!dynamicOauthCode) {\n throw new MissingSocialUrlParamError('dynamicOauthCode');\n }\n\n const storedSocialRedirectState = await core.storage.getItem(\n redirectStateStorageKeySchema\n );\n\n if (!storedSocialRedirectState) {\n throw new MissingRedirectStorageStateError();\n }\n\n if (storedSocialRedirectState.state !== dynamicOauthState) {\n throw new InvalidRedirectStorageStateError();\n }\n\n const { provider, codeVerifier } = storedSocialRedirectState;\n\n await core.storage.removeItem(redirectStateStorageKeySchema);\n\n let response: VerifyResponse;\n\n // If the user is already authenticated, we're verifying the social auth to link it to the user\n if (client.user) {\n response = await apiClient.oauthVerify({\n environmentId: core.environmentId,\n oauthRequest: {\n code: dynamicOauthCode,\n codeVerifier,\n requestedScopes,\n state: dynamicOauthState,\n },\n providerType: provider,\n });\n } else {\n // Otherwise we're signing in with the social auth\n response = await apiClient.oauthSignIn({\n environmentId: core.environmentId,\n oauthRequest: {\n captchaToken: consumeCaptchaToken(client),\n code: dynamicOauthCode,\n codeVerifier,\n state: dynamicOauthState,\n },\n providerType: provider,\n });\n }\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response.user;\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { User } from '../../../../user/user.types';\nimport { processSocialCallback } from '../processSocialCallback';\nimport type { CompleteSocialRedirectParams } from './completeSocialRedirect.types';\n\nexport type { CompleteSocialRedirectParams } from './completeSocialRedirect.types';\n\n/**\n * Completes the social authentication flow after the OAuth redirect.\n *\n * Processes the OAuth callback URL with the authorization code and finishes\n * authenticating (or linking) the user with the social provider. This is the\n * final step after `signInWithSocialRedirect` + `detectSocialRedirectUrl`.\n *\n * @param params.url - The callback URL containing OAuth response parameters.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token when verifying (linking) a social account.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the authenticated user or null.\n * @throws MissingSocialUrlParamError If required OAuth parameters are missing.\n * @throws InvalidRedirectStorageStateError If the stored state doesn't match.\n * @instrumented\n */\nexport const completeSocialRedirect = (\n { url, requestedScopes }: CompleteSocialRedirectParams,\n client = getDefaultClient()\n): Promise<User | null> =>\n processSocialCallback({ requestedScopes, url }, client);\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { SocialProvider } from '../../social.types';\nimport { signInWithSocialRedirect } from '../signInWithSocialRedirect';\n\ntype AuthenticateWithSocialParams = {\n provider: SocialProvider;\n redirectUrl: string;\n};\n\n/**\n * @deprecated Renamed to {@link signInWithSocialRedirect}. This alias will be\n * removed in a future major version.\n *\n * @instrumented\n */\nexport const authenticateWithSocial = (\n params: AuthenticateWithSocialParams,\n client = getDefaultClient()\n) => signInWithSocialRedirect(params, client);\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport type { User } from '../../../../user/user.types';\nimport { completeSocialRedirect } from '../completeSocialRedirect';\n\ntype CompleteSocialAuthenticationParams = {\n requestedScopes?: TokenScope[];\n url: URL;\n};\n\n/**\n * @deprecated Renamed to {@link completeSocialRedirect}. This alias will be\n * removed in a future major version.\n *\n * @instrumented\n */\nexport const completeSocialAuthentication = (\n params: CompleteSocialAuthenticationParams,\n client = getDefaultClient()\n): Promise<User | null> => completeSocialRedirect(params, client);\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { detectSocialRedirectUrl } from '../detectSocialRedirectUrl';\n\ntype DetectOAuthRedirectParams = {\n url: URL;\n};\n\n/**\n * @deprecated Renamed to {@link detectSocialRedirectUrl}. This alias will be\n * removed in a future major version.\n *\n * @not-instrumented\n */\nexport const detectOAuthRedirect = (\n params: DetectOAuthRedirectParams,\n client = getDefaultClient()\n): Promise<boolean> => detectSocialRedirectUrl(params, client);\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletAccounts } from '../../getWalletAccounts';\nimport type { WalletAccount } from '../../walletAccount';\n\n/**\n * Get the primary wallet account.\n * The primary wallet account is the one that was last selected by the user.\n * This information is stored in both unverified and verified wallet accounts.\n * This function consolidates this information to determine which wallet was most recently selected.\n * @not-instrumented\n */\nexport const getPrimaryWalletAccount = (\n client = getDefaultClient()\n): WalletAccount | null => {\n const walletAccounts = getWalletAccounts(client);\n\n const sortedLastSelectedWalletAccounts = walletAccounts\n .filter(\n (\n walletAccount\n ): walletAccount is WalletAccount & { lastSelectedAt: Date } =>\n Boolean(walletAccount.lastSelectedAt)\n )\n .sort((a, b) => b.lastSelectedAt.getTime() - a.lastSelectedAt.getTime());\n\n if (sortedLastSelectedWalletAccounts.length === 0) {\n return null;\n }\n\n const [primaryWalletAccount] = sortedLastSelectedWalletAccounts;\n\n return primaryWalletAccount;\n};\n","import type { VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../../client/defaultClient';\nimport { createApiClient } from '../../../../apiClient';\nimport { getPrimaryWalletAccount } from '../../../../wallets/primaryWalletAccount/getPrimaryWalletAccount';\nimport { updateAuthFromVerifyResponse } from '../../../updateAuthFromVerifyResponse';\n\ntype UnlinkSocialAccountParams = {\n verifiedCredentialId: string;\n};\n\n/**\n * Unlinks a social account from the user's account.\n *\n * @param params.verifiedCredentialId - The verified credential ID of the social account to unlink.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verify response.\n * @instrumented\n * @redact-params\n */\nexport const unlinkSocialAccount = async (\n { verifiedCredentialId }: UnlinkSocialAccountParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n // the api seems to require us to pass the primary wallet id when\n // unlinking a social account if the user has wallets\n const primaryWalletAccount = getPrimaryWalletAccount(client);\n const walletId = primaryWalletAccount?.verifiedCredentialId?.replace(\n '-zerodev',\n ''\n );\n\n const response = await apiClient.verifyUnlink({\n environmentId: core.environmentId,\n verifyUnlinkRequest: {\n verifiedCredentialId,\n walletId: walletId ?? undefined,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type { ChainEnum, TokenBalance } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { getWalletProviderFromWalletAccount } from '../../wallets/utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../wallets/walletAccount';\n\ntype GetTokenBalancesBaseParams = {\n /**\n * Whether to filter out spam tokens.\n * Defaults to true.\n * @not-instrumented\n */\n filterSpamTokens?: boolean;\n /** Whether to force a refresh of the balances instead of using the api cached value. */\n forceRefresh?: boolean;\n /** Whether to include the native token balance. */\n includeNative?: boolean;\n /** Whether to include the prices of the tokens. */\n includePrices?: boolean;\n /** The wallet account to get the balances for. */\n walletAccount: WalletAccount;\n /** If provided, only return balances for the specified contracts. */\n whitelistedContracts?: Array<string>;\n};\n\nexport type GetTokenBalancesParams = GetTokenBalancesBaseParams &\n (\n | {\n /**\n * The network ID to get the balances for.\n * If neither `networkId` nor `networkIds` is provided, the active network ID will be used.\n * Mutually exclusive with `networkIds`.\n */\n networkId?: number;\n networkIds?: never;\n }\n | {\n networkId?: never;\n /**\n * The network IDs to get the balances for.\n * Mutually exclusive with `networkId`.\n */\n networkIds?: string[];\n }\n );\n\n/**\n * Retrieves the token balances for a wallet account on one chain. Fetched\n * from the Dynamic API.\n *\n * Use this for ERC-20-style token balances scoped to a single wallet\n * account. Supports optional spam filtering, price inclusion, native-token\n * inclusion, and one-or-many networks within the wallet's chain.\n *\n * For native-only balance, use {@link getNativeBalance}. For a\n * multi-chain portfolio across many addresses, use\n * {@link getMultichainTokenBalances}.\n *\n * @param params.walletAccount - The wallet account to get the balances for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of token balances.\n * @not-instrumented\n */\nexport const getTokenBalances = async (\n {\n walletAccount,\n networkId,\n networkIds,\n includePrices,\n includeNative,\n filterSpamTokens,\n whitelistedContracts,\n forceRefresh,\n }: GetTokenBalancesParams,\n client = getDefaultClient()\n): Promise<TokenBalance[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n if (!networkId && !networkIds) {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n const activeNetworkId = await walletProvider.getActiveNetworkId();\n networkId = Number(activeNetworkId.networkId);\n }\n\n const balances = await apiClient.getAccountBalances({\n accountAddress: walletAccount.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: walletAccount.chain as ChainEnum,\n environmentId: core.environmentId,\n filterSpamTokens,\n forceRefresh,\n includeNative,\n includePrices,\n networkId,\n networkIds,\n whitelistedContracts,\n });\n\n return balances;\n};\n","import type {\n MultichainAccountBalanceResponse,\n MultichainAccountBalancesRequest,\n MultichainAccountBalancesRequestBalanceRequests,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain/chain.types';\n\nexport type GetMultichainTokenBalancesBalanceRequest =\n Omit<MultichainAccountBalancesRequest, 'balanceRequests'> & {\n balanceRequests: Array<\n Omit<MultichainAccountBalancesRequestBalanceRequests, 'chain'> & {\n chain: Chain;\n }\n >;\n };\n\nexport type GetMultichainTokenBalancesParams = {\n balanceRequest: GetMultichainTokenBalancesBalanceRequest;\n};\n\n/**\n * Retrieves token balances across multiple chains, networks, and addresses\n * in a single batched API request.\n *\n * Use this for portfolio-style views that need to render a user's holdings\n * across their entire multi-chain wallet set. For a single account on one\n * chain, use {@link getTokenBalances}; for native-only balance, use\n * {@link getNativeBalance}.\n *\n * @param params.balanceRequest - The balance request configuration specifying which chains, networks and addresses to query.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the chain balances across multiple networks.\n * @not-instrumented\n */\nexport const getMultichainTokenBalances = async (\n { balanceRequest }: GetMultichainTokenBalancesParams,\n client = getDefaultClient()\n): Promise<MultichainAccountBalanceResponse['chainBalances']> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.postMultichainAccountBalances({\n environmentId: core.environmentId,\n multichainAccountBalancesRequest:\n balanceRequest as MultichainAccountBalancesRequest,\n });\n\n return response.chainBalances;\n};\n","import type { GetTokenBalancesParams } from '../getTokenBalances/getTokenBalances';\nimport { getTokenBalances } from '../getTokenBalances/getTokenBalances';\nimport { getDefaultClient } from '../../../client/defaultClient';\n\n/**\n * @deprecated Use {@link GetTokenBalancesParams} instead. Renamed for clarity.\n */\nexport type GetBalancesParams = GetTokenBalancesParams;\n\n/**\n * @deprecated Use {@link getTokenBalances} instead. Renamed so its name\n * states what it returns (a wallet account's token balances) and is no\n * longer confusable with the native-only `getBalance` or the\n * multi-chain `getMultichainTokenBalances`.\n *\n * @not-instrumented\n */\n// Wrapper, not an `export { … as … }` alias: TS does not surface a\n// deprecation tag on a re-export line, so the tag would never warn consumers.\nexport const getBalances = (\n params: GetTokenBalancesParams,\n client = getDefaultClient()\n): ReturnType<typeof getTokenBalances> => getTokenBalances(params, client);\n","import type {\n GetMultichainTokenBalancesBalanceRequest,\n GetMultichainTokenBalancesParams,\n} from '../getMultichainTokenBalances/getMultichainTokenBalances';\nimport { getMultichainTokenBalances } from '../getMultichainTokenBalances/getMultichainTokenBalances';\nimport { getDefaultClient } from '../../../client/defaultClient';\n\n/**\n * @deprecated Use {@link GetMultichainTokenBalancesBalanceRequest} instead. Renamed for clarity.\n */\nexport type GetMultichainBalancesBalanceRequest =\n GetMultichainTokenBalancesBalanceRequest;\n\n/**\n * @deprecated Use {@link GetMultichainTokenBalancesParams} instead. Renamed for clarity.\n */\nexport type GetMultichainBalancesParams = GetMultichainTokenBalancesParams;\n\n/**\n * @deprecated Use {@link getMultichainTokenBalances} instead. Renamed so\n * the name aligns with `getTokenBalances` and signals that this fetches\n * token balances (not native-only) across multiple chains.\n *\n * @not-instrumented\n */\n// Wrapper, not an `export { … as … }` alias: TS does not surface a\n// deprecation tag on a re-export line, so the tag would never warn consumers.\nexport const getMultichainBalances = (\n params: GetMultichainTokenBalancesParams,\n client = getDefaultClient()\n): ReturnType<typeof getMultichainTokenBalances> =>\n getMultichainTokenBalances(params, client);\n","import * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../../services/storage';\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const createCheckoutSessionTokenStorageKey = (transactionId: string) => {\n return createStorageKeySchema({\n key: `checkoutSessionToken:${transactionId}`,\n schema: z.string(),\n });\n};\n","import type { SDKApi } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { CheckoutSessionTokenMissingError } from '../../../../errors/CheckoutSessionTokenMissingError';\nimport { createApiClient } from '../../../apiClient';\nimport { createCheckoutSessionTokenStorageKey } from '../createCheckoutSessionTokenStorageKey';\n\ntype CreateCheckoutApiClientParams = {\n transactionId: string;\n};\n\ntype CheckoutApiClientResult = {\n apiClient: SDKApi;\n environmentId: string;\n sessionToken: string;\n};\n\n/** @not-instrumented */\nexport const createCheckoutApiClient = async (\n { transactionId }: CreateCheckoutApiClientParams,\n client: DynamicClient\n): Promise<CheckoutApiClientResult> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const sessionToken = await core.storage.getItem(\n createCheckoutSessionTokenStorageKey(transactionId)\n );\n\n if (!sessionToken) {\n throw new CheckoutSessionTokenMissingError({ transactionId });\n }\n\n return {\n apiClient,\n environmentId: core.environmentId,\n sessionToken,\n };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createCheckoutSessionTokenStorageKey } from '../createCheckoutSessionTokenStorageKey';\n\nexport type ClearCheckoutSessionTokenParams = {\n transactionId: string;\n};\n\n/**\n * Removes the locally stored checkout session token for the given transaction.\n *\n * The checkout session token is the anonymous credential that authorizes\n * mutations to a single in-flight checkout transaction. Once the transaction\n * has reached a terminal state (cancelled, expired, failed, completed) it can\n * no longer be advanced, and the token is dead weight that should not be\n * persisted in browser storage — leaving it around lets a later XSS payload\n * exfiltrate a credential with no further use, and it can also confuse the\n * SDK on subsequent loads into believing an active session exists.\n *\n * The server-side revocation lives in dashboard-api; this is the SDK-side\n * defense-in-depth.\n *\n * @not-instrumented\n */\nexport const clearCheckoutSessionToken = async (\n { transactionId }: ClearCheckoutSessionTokenParams,\n client: DynamicClient\n): Promise<void> => {\n const core = getCore(client);\n\n await core.storage.removeItem(\n createCheckoutSessionTokenStorageKey(transactionId)\n );\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { APIError } from '../../../../errors/APIError';\nimport type { DynamicClient } from '../../../../client/types';\nimport { clearCheckoutSessionToken } from '../clearCheckoutSessionToken';\n\nexport type WithCheckoutSessionTokenCleanupOn401Params<T> = {\n call: () => Promise<T>;\n transactionId: string;\n};\n\n/**\n * Checkout mutation routes are guarded server-side only by session-token\n * validation, so a 401 means the token is dead (revoked, expired, deleted,\n * or invalid). Leaving a dead token in `localStorage` widens the XSS\n * exfiltration surface for no benefit and makes the next SDK load attempt\n * requests that are guaranteed to fail.\n *\n * @not-instrumented\n */\nexport const withCheckoutSessionTokenCleanupOn401 = async <T>(\n { call, transactionId }: WithCheckoutSessionTokenCleanupOn401Params<T>,\n client: DynamicClient\n): Promise<T> => {\n try {\n return await call();\n } catch (error) {\n if (error instanceof APIError && error.status === 401) {\n try {\n await clearCheckoutSessionToken({ transactionId }, client);\n } catch (cleanupError) {\n getCore(client).logger.error(\n 'Failed to clear checkout session token after 401',\n cleanupError\n );\n }\n }\n throw error;\n }\n};\n","import type {\n AttachSourceRequest,\n ChainEnum,\n ExchangeKeyEnum,\n FlowSourceTypeEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { Chain } from '../../chain';\nimport type {\n CheckoutSupportedExchangeProvider,\n CheckoutTransaction,\n} from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\ntype AttachCheckoutTransactionSourceWalletParams = {\n /** The address of the user's wallet. */\n fromAddress: string;\n /** The network id for the token that the user is paying with. */\n fromChainId: string;\n /** The chain name of the user's wallet. */\n fromChainName: Chain;\n /** @defaultValue `'wallet'` */\n sourceType?: 'wallet';\n transactionId: string;\n};\n\ntype AttachCheckoutTransactionSourceExchangeParams = {\n /**\n * The exchange provider key (e.g. `'coinbase'`).\n * The backend uses this to look up the exchange configuration,\n * generate a buy URL, and create the exchange source record.\n */\n exchangeProvider: CheckoutSupportedExchangeProvider;\n sourceType: 'exchange';\n transactionId: string;\n};\n\n/**\n * Parameters for {@link attachCheckoutTransactionSource}.\n *\n * This is a discriminated union on `sourceType`:\n * - `'wallet'` (default) — requires `fromAddress`, `fromChainId`, `fromChainName`\n * - `'exchange'` — requires `exchangeProvider`\n */\nexport type AttachCheckoutTransactionSourceParams =\n | AttachCheckoutTransactionSourceWalletParams\n | AttachCheckoutTransactionSourceExchangeParams;\n\n/**\n * Attaches a payment source to a checkout transaction.\n *\n * For exchange sources, the backend generates the buy URL and creates the\n * exchange source record. The response includes `exchangeSource.metadata.url`\n * which can be embedded in an iframe for the user to complete payment.\n *\n * @param params AttachCheckoutTransactionSourceParams - The source details to attach.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction (with exchangeSource if sourceType is 'exchange')\n * @instrumented\n */\nexport const attachCheckoutTransactionSource = async (\n params: AttachCheckoutTransactionSourceParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { transactionId, sourceType = 'wallet' } = params;\n\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n const attachSourceRequest: AttachSourceRequest = {\n sourceType: sourceType as FlowSourceTypeEnum,\n };\n\n if (params.sourceType === 'exchange') {\n attachSourceRequest.exchangeProvider =\n params.exchangeProvider as ExchangeKeyEnum;\n } else {\n attachSourceRequest.fromAddress = params.fromAddress;\n attachSourceRequest.fromChainId = params.fromChainId;\n // eslint-disable-next-line custom-rules/ban-chain-enum\n attachSourceRequest.fromChainName = params.fromChainName as ChainEnum;\n }\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.attachSource({\n attachSourceRequest,\n environmentId,\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import type { CheckoutTransaction } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type BroadcastCheckoutTransactionParams = {\n transactionId: string;\n /**\n * The on-chain transaction hash. Required for wallet sources, optional\n * for exchange sources (the user may not have it).\n */\n txHash?: string;\n};\n\n/**\n * Records that a checkout transaction has been broadcasted.\n *\n * For wallet sources, pass the `txHash` from the on-chain transaction.\n * For exchange sources, `txHash` can be omitted — the user confirms\n * they completed the payment and the transaction moves to `broadcasted`.\n *\n * @param params BroadcastCheckoutTransactionParams - The transaction ID and optional tx hash.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction\n * @instrumented\n */\nexport const broadcastCheckoutTransaction = async (\n { transactionId, txHash }: BroadcastCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.recordCheckoutBroadcast({\n environmentId,\n flowRecordBroadcastRequest: { txHash },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { clearCheckoutSessionToken } from '../utils/clearCheckoutSessionToken';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type CancelCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Cancels a checkout transaction before it has been broadcasted\n *\n * @param params CancelCheckoutTransactionParams - The transaction to cancel.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The cancelled checkout transaction\n * @instrumented\n */\nexport const cancelCheckoutTransaction = async (\n { transactionId }: CancelCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n const result = await withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.cancelCheckoutTransaction({\n environmentId,\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n\n await clearCheckoutSessionToken({ transactionId }, client);\n\n return result;\n};\n","import type { Checkout } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\n\n/** @not-instrumented */\nexport const getCheckouts = async (\n client: DynamicClient\n): Promise<Checkout[]> => {\n const projectSettings = client.projectSettings;\n\n assertDefined(projectSettings, 'Project settings are not available');\n\n return projectSettings.checkouts ?? [];\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { CheckoutTransactionCreateResponse } from '../checkout.types';\nimport { getCheckouts } from '../getCheckouts';\nimport { createCheckoutSessionTokenStorageKey } from '../utils/createCheckoutSessionTokenStorageKey';\n// TODO(realtime): Re-enable the realtime auto-subscribe once the Ably API key\n// is provisioned in the dashboard-api environment. The `realtime/auth`\n// endpoint currently returns \"Realtime service is not configured\" for\n// environments without Ably wiring, so we are temporarily disabling the\n// auto-subscribe to avoid surfacing connection errors to customers. See\n// https://dynamiclabsgroup.slack.com/archives/C03DWBF0LE8/p1778590548698209\n// import { subscribeToCheckoutTransaction } from '../utils/subscribeToCheckoutTransaction';\n\nexport type DestinationAddress = {\n address: string;\n chain: Chain;\n};\n\nexport type CreateCheckoutTransactionParams = {\n amount: string;\n checkoutId?: string;\n currency: string;\n /**\n * The destination addresses for each settlement token destination.\n * Must be provided for each settlement token chain, unless the\n * addresses have already been provided on the checkout creation.\n */\n destinationAddresses?: DestinationAddress[];\n expiresIn?: number;\n memo?: object;\n};\n\n/**\n * Creates a new checkout transaction and stores the session token for subsequent calls\n *\n * @param params CreateCheckoutTransactionParams - The parameters for the checkout transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created transaction with session token\n * @instrumented\n */\nexport const createCheckoutTransaction = async (\n params: CreateCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransactionCreateResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const checkouts = await getCheckouts(client);\n\n // If no checkout ID is provided, try to fallback to the first checkout in the list\n const checkoutId = params.checkoutId || checkouts?.[0]?.id;\n\n assertDefined(\n checkoutId,\n 'No checkout found. Please make sure you have a Checkout setup in the Dashboard.'\n );\n\n const result = await apiClient.createCheckoutTransaction({\n checkoutId,\n checkoutTransactionCreateRequest: {\n amount: params.amount,\n currency: params.currency,\n destinationAddresses: params.destinationAddresses?.map((address) => ({\n address: address.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: address.chain as ChainEnum,\n })),\n expiresIn: params.expiresIn,\n memo: params.memo,\n },\n environmentId: core.environmentId,\n });\n\n await core.storage.setItem(\n createCheckoutSessionTokenStorageKey(result.transaction.id),\n result.sessionToken\n );\n\n // TODO(realtime): Re-enable the realtime auto-subscribe once the Ably API\n // key is provisioned in the dashboard-api environment. See the import\n // block above for context.\n // subscribeToCheckoutTransaction(\n // { transactionId: result.transaction.id },\n // client\n // ).catch((error) => {\n // core.logger.error(\n // 'Failed to subscribe to checkout transaction realtime channel',\n // error\n // );\n // });\n\n return result;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\nimport { createApiClient } from '../../apiClient';\nimport type { CheckoutTransaction } from '../checkout.types';\n\nexport type GetCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Fetches the current state of a checkout transaction\n *\n * @param params GetCheckoutTransactionParams - The parameters for fetching the transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The checkout transaction\n * @not-instrumented\n */\nexport const getCheckoutTransaction = async (\n { transactionId }: GetCheckoutTransactionParams,\n client: DynamicClient = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getCheckoutTransaction({\n environmentId: core.environmentId,\n transactionId,\n });\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type GetCheckoutTransactionQuoteParams = {\n /**\n * Optional chain identifier the source funds will originate from for this\n * quote. When provided, this overrides the fromChainId recorded at\n * attachSource time. The chain family (fromChainName) and source address\n * (fromAddress) are locked at attachSource time — to switch chain families\n * or wallets, call attachSource again.\n */\n fromChainId?: string;\n /**\n * When omitted, defaults to native token for the chain specified in\n * fromChainName in the attach source step.\n */\n fromTokenAddress?: string;\n slippage?: number;\n transactionId: string;\n};\n\n/**\n * Fetches a quote for a checkout transaction\n *\n * @param params GetCheckoutTransactionQuoteParams - The quote parameters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction with quote data\n * @not-instrumented\n */\nexport const getCheckoutTransactionQuote = async (\n {\n fromChainId,\n fromTokenAddress,\n slippage,\n transactionId,\n }: GetCheckoutTransactionQuoteParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.quoteCheckoutTransaction({\n environmentId,\n flowQuoteRequest: {\n fromChainId,\n fromTokenAddress,\n slippage,\n },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport { createCheckoutApiClient } from '../utils/createCheckoutApiClient';\nimport { withCheckoutSessionTokenCleanupOn401 } from '../utils/withCheckoutSessionTokenCleanupOn401';\n\nexport type PrepareCheckoutTransactionParams = {\n /**\n * Whether to assert the balance for the gas cost of the transaction.\n * If true, the prepare signing request will fail if the balance is not sufficient for the gas cost.\n * @default false\n */\n assertBalanceForGasCost?: boolean;\n /**\n * Whether to assert the balance for the transfer amount of the transaction.\n * If true, the prepare signing request will fail if the balance is not sufficient for the transfer amount.\n * @default false\n */\n assertBalanceForTransferAmount?: boolean;\n transactionId: string;\n};\n\n/**\n * Prepares a checkout transaction for signing\n * This should be called immediately before triggering the transaction signing.\n * It will confirm the quote is still valid, the risk state is cleared, and the transaction is ready to be signed.\n *\n * @param params PrepareCheckoutTransactionParams - The transaction to prepare.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The updated checkout transaction\n * @instrumented\n */\nexport const prepareCheckoutTransaction = async (\n {\n assertBalanceForGasCost,\n assertBalanceForTransferAmount,\n transactionId,\n }: PrepareCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const { apiClient, environmentId, sessionToken } =\n await createCheckoutApiClient({ transactionId }, client);\n\n return withCheckoutSessionTokenCleanupOn401(\n {\n call: () =>\n apiClient.prepareCheckoutTransaction({\n environmentId,\n flowPrepareSigningRequest: {\n assertBalanceForGasCost: assertBalanceForGasCost ?? false,\n assertBalanceForTransferAmount:\n assertBalanceForTransferAmount ?? false,\n },\n transactionId,\n xDynamicCheckoutSessionToken: sessionToken,\n }),\n transactionId,\n },\n client\n );\n};\n","/* eslint-disable func-style -- javascript requires this to be a function */\n\nimport { WalletProviderMethodUnavailableError } from '../../../../errors/WalletProviderMethodUnavailableError';\nimport type { WalletProvider } from '../../walletProvider/walletProvider.types';\n\n/**\n * Asserts that a specific wallet provider method is defined, throwing an error if it's not.\n * This function acts as a type guard, narrowing the type to ensure the method exists.\n *\n * @template T - The specific wallet provider method key being checked\n * @param walletProvider - The wallet provider object to check\n * @param methodName - The name of the method to check for availability\n * @throws Throws WalletProviderMethodUnavailableError if the method is not defined\n * @example\n * ```typescript\n * const walletProvider: WalletProvider = getWalletProvider();\n * assertWalletProviderMethodDefined(walletProvider, 'connect');\n * // walletProvider.connect is now guaranteed to be defined\n * await walletProvider.connect();\n * ```\n */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport function assertWalletProviderMethodDefined<\n T extends keyof WalletProvider\n>(\n walletProvider: WalletProvider,\n methodName: T\n): asserts walletProvider is WalletProvider &\n Required<Pick<WalletProvider, T>> {\n if (walletProvider[methodName] === undefined) {\n throw new WalletProviderMethodUnavailableError({\n methodName: methodName as string,\n walletProviderKey: walletProvider.key,\n });\n }\n}\n","export const SWAP_SUPPORTED_CHAINS = ['BTC', 'EVM', 'SOL', 'SUI', 'TRON'];\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport type { WalletProvider } from '../../../wallets/walletProvider';\n\nexport type EnsureCorrectActiveNetworkParams = {\n requiredNetworkId: string;\n walletProvider: WalletProvider;\n};\n\n/**\n * Ensures the wallet provider is on the correct active network if possible.\n * If the wallet provider is not on the correct active network, it will try to switch to the correct active network.\n * It's not a blocker, so it will just log the error and skip the step if it fails.\n *\n * @not-instrumented\n */\nexport const ensureCorrectActiveNetwork = async (\n { requiredNetworkId, walletProvider }: EnsureCorrectActiveNetworkParams,\n client: DynamicClient\n) => {\n const { logger } = getCore(client);\n\n // Skip if no network id to switch to or the wallet provider doesn't support network switching\n if (!requiredNetworkId || !walletProvider.switchActiveNetwork) {\n return;\n }\n\n logger.debug(\n '[ensureCorrectActiveNetwork] Required network id',\n requiredNetworkId\n );\n\n try {\n const { networkId: activeNetworkId } =\n await walletProvider.getActiveNetworkId();\n\n logger.debug(\n '[ensureCorrectActiveNetwork] Check if should switch network',\n {\n activeNetworkId,\n requiredNetworkId,\n }\n );\n\n if (!activeNetworkId || activeNetworkId === requiredNetworkId) {\n logger.debug(\n '[ensureCorrectActiveNetwork] No active network id found or active network id is the same as the required network id - skipping this step'\n );\n return;\n }\n\n await walletProvider.switchActiveNetwork({\n networkId: requiredNetworkId,\n });\n } catch (error) {\n // intentionally swallowed: network switching is best-effort and the swap\n // should proceed even if we can't verify or change the active network\n logger.debug(\n '[ensureCorrectActiveNetwork] Error getting active network id or switching network - skipping this step',\n error\n );\n }\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { assertWalletProviderMethodDefined } from '../../wallets/utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../../wallets/utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { SWAP_SUPPORTED_CHAINS } from '../constants';\nimport type { SwapTransactionSigningPayload } from '../swap.types';\nimport { ensureCorrectActiveNetwork } from '../utils/ensureCorrectActiveNetwork';\n\nexport type ExecuteSwapTransactionParams = {\n /**\n * The callback to invoke when the transaction execution step changes.\n *\n * 'approval' - The approval step begins. (only happens for ERC-20 tokens when the allowance is insufficient)\n * 'transaction' - The transaction step begins.\n */\n onStepChange?: (step: 'approval' | 'transaction') => void;\n /**\n * The signing payload for the swap transaction.\n * Usually obtained from a `getSwapQuote` call.\n */\n signingPayload: SwapTransactionSigningPayload;\n /**\n * Controls whether the swap is routed through Dynamic's gas sponsorship.\n *\n * - `'auto'` (default): the swap is sponsored when gas sponsorship is enabled\n * for the chain AND the wallet is a Dynamic embedded wallet. Otherwise the\n * user pays gas.\n * - `'off'`: the swap is never sponsored, regardless of project settings or\n * wallet capabilities. The user pays gas.\n *\n * @default 'auto'\n */\n sponsorshipMode?: 'auto' | 'off';\n /**\n * The wallet account to execute the swap transaction on.\n */\n walletAccount: WalletAccount;\n};\n\n/**\n * Executes a swap transaction\n *\n * @param params ExecuteSwapTransactionParams - The parameters for the swap transaction.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The transaction hash.\n * @instrumented\n */\nexport const executeSwapTransaction = async (\n {\n walletAccount,\n signingPayload,\n onStepChange,\n sponsorshipMode,\n }: ExecuteSwapTransactionParams,\n client = getDefaultClient()\n): Promise<{ transactionHash: string }> => {\n if (!SWAP_SUPPORTED_CHAINS.includes(walletAccount.chain)) {\n throw new InvalidParamError(\n `Chain ${walletAccount.chain} is not supported for swap transactions`\n );\n }\n\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'executeSwapTransaction');\n\n await ensureCorrectActiveNetwork(\n {\n requiredNetworkId: signingPayload.chainId,\n walletProvider,\n },\n client\n );\n\n const { transactionHash } = await walletProvider.executeSwapTransaction({\n onStepChange,\n signingPayload,\n sponsorshipMode,\n walletAccount,\n });\n\n return { transactionHash };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { executeSwapTransaction } from '../../swap/executeSwapTransaction';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { broadcastCheckoutTransaction } from '../broadcastCheckoutTransaction';\nimport type { CheckoutTransaction } from '../checkout.types';\nimport type { PrepareCheckoutTransactionParams } from '../prepareCheckoutTransaction';\nimport { prepareCheckoutTransaction } from '../prepareCheckoutTransaction';\n\nexport type SubmitCheckoutTransactionParams = {\n onStepChange?: (step: 'approval' | 'transaction') => void;\n transactionId: string;\n walletAccount: WalletAccount;\n} & PrepareCheckoutTransactionParams;\n\n/**\n * Prepares, signs, and broadcasts a checkout transaction in one call.\n *\n * Orchestrates the full submission flow:\n * 1. Calls prepareCheckoutTransaction to advance to signing state and lock the quote\n * 2. Ensures the wallet is on the correct network for the transaction\n * 3. Delegates on-chain signing to the wallet provider's executeSwapTransaction method\n * 4. Calls broadcastCheckoutTransaction with the resulting txHash\n *\n * @param params SubmitCheckoutTransactionParams - The transaction ID, wallet account, and optional step callback.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The broadcasted checkout transaction\n * @instrumented\n */\nexport const submitCheckoutTransaction = async (\n {\n onStepChange,\n transactionId,\n walletAccount,\n assertBalanceForGasCost,\n assertBalanceForTransferAmount,\n }: SubmitCheckoutTransactionParams,\n client = getDefaultClient()\n): Promise<CheckoutTransaction> => {\n const prepared = await prepareCheckoutTransaction(\n { assertBalanceForGasCost, assertBalanceForTransferAmount, transactionId },\n client\n );\n\n const signingPayload = prepared.quote?.signingPayload;\n\n assertDefined(\n signingPayload,\n 'No signing payload returned from prepare — quote may be missing transaction data'\n );\n\n const { transactionHash } = await executeSwapTransaction(\n {\n onStepChange,\n signingPayload,\n walletAccount,\n },\n client\n );\n\n return broadcastCheckoutTransaction(\n { transactionId, txHash: transactionHash },\n client\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\n// TODO(realtime): Re-enable the realtime subscribe call once the Ably API key\n// is provisioned in the dashboard-api environment. The `realtime/auth`\n// endpoint currently returns \"Realtime service is not configured\" for\n// environments without Ably wiring, so we are temporarily turning this into\n// a no-op to avoid surfacing connection errors to customers. See\n// https://dynamiclabsgroup.slack.com/archives/C03DWBF0LE8/p1778590548698209\n// import { subscribeToCheckoutTransaction } from '../utils/subscribeToCheckoutTransaction';\n\nexport type TrackCheckoutTransactionParams = {\n transactionId: string;\n};\n\n/**\n * Subscribes to realtime `checkoutTransactionExecutionStateChanged` and\n * `checkoutTransactionSettlementStateChanged` events for an existing\n * checkout transaction.\n *\n * This is only needed after a page refresh to re-establish the subscription.\n * Transactions created with {@link createCheckoutTransaction} are automatically\n * subscribed — calling this again for those is unnecessary unless the page\n * has been reloaded.\n *\n * NOTE: Temporarily a no-op while the Ably API key is being provisioned for\n * the realtime checkout transaction channel. Will be re-enabled once the\n * dashboard-api environment has the Ably wiring in place.\n *\n * @param params.transactionId - The ID of the checkout transaction to track.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @not-instrumented\n */\nexport const trackCheckoutTransaction = (\n _params: TrackCheckoutTransactionParams,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n client: DynamicClient = getDefaultClient()\n): Promise<void> => {\n // TODO(realtime): Re-enable once the Ably API key is configured. See the\n // import block above for context.\n // return subscribeToCheckoutTransaction({ transactionId }, client);\n return Promise.resolve();\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { InvalidParamError } from '../../../../errors/InvalidParamError';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { CheckoutTransaction } from '../../checkout.types';\nimport { getCheckouts } from '../../getCheckouts';\n\nexport type RequiresConversionParams = {\n transaction: CheckoutTransaction;\n};\n\n/**\n * Determines whether a token conversion (swap/bridge) is required for a checkout transaction.\n *\n * Returns `true` when the from token does not match any settlement token defined in\n * the checkout's settlement config for the given chain — meaning the asset must be\n * converted before it can settle.\n * Returns `false` when the from token already matches a settlement token, so no\n * conversion is needed.\n *\n * @param params - The from token details and the checkout's settlement config.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Whether a token conversion is required\n * @not-instrumented\n */\nexport const requiresConversion = async (\n { transaction }: RequiresConversionParams,\n client = getDefaultClient()\n): Promise<boolean> => {\n if (\n !transaction.fromChainId ||\n !transaction.fromChainName ||\n !transaction.fromToken\n ) {\n throw new InvalidParamError(\n 'Transaction is missing source information. Make sure that attachCheckoutTransactionSource has been called before calling this function.'\n );\n }\n\n const allCheckouts = await getCheckouts(client);\n\n const checkout = allCheckouts.find(\n (checkout) => checkout.id === transaction.checkoutId\n );\n\n assertDefined(\n checkout,\n 'Could not find checkout associated with transaction.'\n );\n\n return !checkout.settlementConfig.settlements.some(\n (settlement) =>\n settlement.chainName === transaction.fromChainName &&\n settlement.chainId === transaction.fromChainId &&\n settlement.tokenAddress === transaction.fromToken\n );\n};\n","import type { VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\nconst DEVICE_REGISTRATION_TOKEN_HEADER = 'x-dynamic-device-registration-token';\n\ntype CompleteDeviceRegistrationParams = {\n deviceToken: string;\n};\n\n/** @instrumented */\nexport const completeDeviceRegistration = async (\n { deviceToken }: CompleteDeviceRegistrationParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n assertDefined(deviceToken, 'deviceToken is required');\n\n const core = getCore(client);\n const apiClient = createApiClient(\n {\n headers: {\n [DEVICE_REGISTRATION_TOKEN_HEADER]: deviceToken,\n },\n },\n client\n );\n\n const response = await apiClient.deviceRegistration({\n environmentId: core.environmentId,\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n // Emit event after successful registration\n emitEvent({ event: 'deviceRegistrationCompleted' }, client);\n\n return response;\n};\n","import { InvalidDeviceRegistrationRedirectError } from '../../../errors/InvalidDeviceRegistrationRedirectError';\n\ntype GetDeviceRegistrationTokenFromUrlParams = {\n url: string;\n};\n\n/**\n * Safely extracts the device token from a device registration redirect URL.\n *\n * This function validates that the URL is a valid device registration redirect\n * then extracts and returns the deviceToken.\n *\n * @returns The device token as a string if valid.\n * @throws InvalidDeviceRegistrationRedirectError If the URL is not a valid device registration redirect.\n * @not-instrumented\n */\nexport const getDeviceRegistrationTokenFromUrl = ({\n url,\n}: GetDeviceRegistrationTokenFromUrlParams): string => {\n let urlObject: URL;\n\n try {\n urlObject = new URL(url);\n } catch {\n throw new InvalidDeviceRegistrationRedirectError();\n }\n\n const deviceRegistrationToken = urlObject.searchParams.get(\n 'deviceRegistrationToken'\n );\n\n if (!deviceRegistrationToken || deviceRegistrationToken.trim() === '') {\n throw new InvalidDeviceRegistrationRedirectError();\n }\n\n return deviceRegistrationToken;\n};\n","import { getDeviceRegistrationTokenFromUrl } from '../getDeviceRegistrationTokenFromUrl';\n\ntype DetectDeviceRegistrationRedirectParams = {\n url: string;\n};\n\n/**\n * Detects if the current URL is a device registration redirect.\n *\n * This function uses getDeviceRegistrationTokenFromUrl to validate the URL and determine\n * if it contains device registration redirect data from a device authentication flow.\n *\n * @returns True if the URL is a device registration redirect, false otherwise.\n * @not-instrumented\n */\nexport const detectDeviceRegistrationRedirect = ({\n url,\n}: DetectDeviceRegistrationRedirectParams): boolean => {\n try {\n getDeviceRegistrationTokenFromUrl({ url });\n return true;\n } catch {\n return false;\n }\n};\n","import type { DeviceRegistrationResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { UnauthorizedError } from '../../../errors/UnauthorizedError';\nimport { createApiClient } from '../../apiClient';\n\n/** @not-instrumented */\nexport const getRegisteredDevices = async (\n client = getDefaultClient()\n): Promise<DeviceRegistrationResponse[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.listDeviceRegistrations({\n environmentId: core.environmentId,\n });\n\n return response.deviceRegistrations;\n } catch (error) {\n /**\n * The API will return 401 when no devices are registered when there are no\n * devices registered. We need to handle this case gracefully.\n */\n if (error instanceof UnauthorizedError) {\n return [];\n }\n\n throw error;\n }\n};\n","import type { User } from '../../user/user.types';\n\n/**\n * Checks if device registration is required for the given user.\n *\n * This function determines if the user has the deviceRegistration\n * scope, indicating that device registration is required.\n *\n * @param user - The user to check.\n * @returns True if device registration is required, false otherwise.\n * @not-instrumented\n */\nexport const isDeviceRegistrationRequired = (user: User) =>\n Boolean(user.scope?.includes('device:register'));\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\n/** @instrumented */\nexport const revokeAllRegisteredDevices = async (\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await apiClient.deleteAllDeviceRegistrations({\n environmentId: core.environmentId,\n });\n\n await logoutWithReason({ reason: 'all-devices-revoked' }, client);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\ntype RevokeRegisteredDeviceParams = {\n deviceRegistrationId: string;\n};\n\n/** @instrumented */\nexport const revokeRegisteredDevice = async (\n { deviceRegistrationId }: RevokeRegisteredDeviceParams,\n client = getDefaultClient()\n): Promise<void> => {\n assertDefined(deviceRegistrationId, 'deviceRegistrationId is required');\n\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.deleteDeviceRegistration({\n deviceRegistrationId,\n environmentId: core.environmentId,\n });\n\n if (response.currentDeviceRevoked) {\n await logoutWithReason({ reason: 'device-revoked' }, client);\n }\n};\n","/* eslint-disable no-restricted-globals */\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { ValueMustBeDefinedError } from '../../../../errors/ValueMustBeDefinedError';\n\ntype AddCoinbaseOnrampOrderEventListenerParams = {\n listener: (event: {\n data: Record<string, unknown>;\n eventName: string;\n }) => void;\n};\n\n/**\n * Adds a listener for Coinbase onramp order events.\n *\n * @param params.listener - The listener function to call when an event is received.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A function to remove the listener.\n * @throws {ValueMustBeDefinedError} If the window is not available.\n * @docs https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api#events-names\n * @not-instrumented\n */\nexport const addCoinbaseOnrampOrderEventListener = (\n { listener }: AddCoinbaseOnrampOrderEventListenerParams,\n client = getDefaultClient()\n): VoidFunction => {\n const core = getCore(client);\n\n if (typeof window === 'undefined') {\n throw new ValueMustBeDefinedError(\n 'Window is not available to listen for Coinbase onramp order events'\n );\n }\n\n const handleMessageEvent = (event: MessageEvent) => {\n if (event.origin !== 'https://pay.coinbase.com') {\n return;\n }\n\n core.logger.debug(\n '[addCoinbaseOnrampOrderEventListener] pay.coinbase.com event received',\n { event }\n );\n\n try {\n const coinbaseOnrampOrderEventData = JSON.parse(event.data);\n\n if (!coinbaseOnrampOrderEventData.eventName?.startsWith('onramp_api.')) {\n return;\n }\n\n listener({\n data: coinbaseOnrampOrderEventData.data,\n eventName: coinbaseOnrampOrderEventData.eventName,\n });\n } catch (error) {\n core.logger.debug(\n '[addCoinbaseOnrampOrderEventListener] Failed to parse Coinbase onramp order event data',\n {\n error,\n }\n );\n }\n };\n\n window.addEventListener('message', handleMessageEvent);\n\n return () => {\n window.removeEventListener('message', handleMessageEvent);\n };\n};\n","import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { InvalidParamError } from '../../../../errors/InvalidParamError';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type {\n CoinbaseOnrampOrderPaymentMethod,\n FieldMissingVerificationForCoinbaseOnramp,\n} from '../coinbase.types';\n\ntype GetMissingVerificationForCoinbaseOnrampOrderResponse =\n FieldMissingVerificationForCoinbaseOnramp[];\n\ntype GetMissingVerificationForCoinbaseOnrampOrderParams = {\n paymentMethod: CoinbaseOnrampOrderPaymentMethod;\n};\n\n/**\n * This function is used to get a list of fields that are missing verification for a Coinbase onramp order\n *\n * - If the user is missing information for an email or phone number, the field will be returned with the error code MISSING_INFORMATION\n * - If the user is missing verification for an email or phone number, the field will be returned with the error code MISSING_VERIFICATION\n * and the existing unverified email or phone number will be included in the data field.\n * - If the user's phone number has not been verified in the last 60 days, the field will be returned with the error code VERIFICATION_EXPIRED\n * and the existing phone number will be included in the data field.\n *\n * @param params.paymentMethod - The payment method that will be used to create the onramp order\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns FieldMissingVerificationForCoinbaseOnramp[] - An array of fields that are missing verification for a Coinbase onramp order\n * @throws {InvalidParamError} - If the payment method is not valid\n * @throws {ValueMustBeDefinedError} - If the user is not authenticated\n * @not-instrumented\n */\nexport const getMissingVerificationForCoinbaseOnrampOrder = (\n { paymentMethod }: GetMissingVerificationForCoinbaseOnrampOrderParams,\n client = getDefaultClient()\n): GetMissingVerificationForCoinbaseOnrampOrderResponse => {\n // adding the payment method as a param for now just so a user has to pass an object as the first param\n // that way, when we add more payment methods, we can easily add them to the param object\n // and not have to change the function signature\n if (paymentMethod !== 'GUEST_CHECKOUT_APPLE_PAY') {\n throw new InvalidParamError(`Invalid payment method: ${paymentMethod}`);\n }\n\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const fieldsMissingVerification: FieldMissingVerificationForCoinbaseOnramp[] =\n [];\n\n const emailVerifiedCredential = user.verifiedCredentials.find(\n (credential) => credential.format === JwtVerifiedCredentialFormatEnum.Email\n );\n\n if (!user.email) {\n // when user has no email at all (verified or not)\n fieldsMissingVerification.push({\n errorCode: 'MISSING_INFORMATION',\n field: 'email',\n });\n } else if (!emailVerifiedCredential) {\n // when user has an email but it is not verified\n fieldsMissingVerification.push({\n data: user.email,\n errorCode: 'MISSING_VERIFICATION',\n field: 'email',\n });\n }\n\n const phoneVerifiedCredential = user.verifiedCredentials.find(\n (credential) =>\n credential.format === JwtVerifiedCredentialFormatEnum.PhoneNumber\n );\n\n const phoneNumberVerifiedInPast60Days =\n phoneVerifiedCredential?.verifiedAt &&\n phoneVerifiedCredential.verifiedAt >=\n new Date(Date.now() - 60 * 24 * 60 * 60 * 1000);\n\n if (!user.phoneNumber) {\n // when user has no phone number at all (verified or not)\n fieldsMissingVerification.push({\n errorCode: 'MISSING_INFORMATION',\n field: 'phoneNumber',\n });\n } else if (!phoneVerifiedCredential) {\n // when user has a phone number but it is not verified\n fieldsMissingVerification.push({\n data: user.phoneNumber,\n errorCode: 'MISSING_VERIFICATION',\n field: 'phoneNumber',\n });\n } else if (!phoneNumberVerifiedInPast60Days) {\n // when user has a verified phone number but it is not verified in the last 60 days\n fieldsMissingVerification.push({\n data: user.phoneNumber,\n errorCode: 'VERIFICATION_EXPIRED',\n field: 'phoneNumber',\n });\n }\n\n return fieldsMissingVerification;\n};\n","import { type SdkUser } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../../../client/types/DynamicClient';\nimport { MissingUserVerificationError } from '../../../../../errors/MissingUserVerificationError';\nimport { assertDefined } from '../../../../../utils/assertDefined';\nimport { getMissingVerificationForCoinbaseOnrampOrder } from '../../getMissingVerificationForCoinbaseOnrampOrder';\n\n/** @not-instrumented */\nexport const validateUserCredentialsForCoinbaseOnrampOrder = (\n client: DynamicClient\n): SdkUser => {\n const { user } = client;\n\n assertDefined(user, 'User is not authenticated');\n\n const fieldsMissingVerification =\n getMissingVerificationForCoinbaseOnrampOrder(\n { paymentMethod: 'GUEST_CHECKOUT_APPLE_PAY' },\n client\n );\n\n const missingEmailVerification = fieldsMissingVerification.find(\n (field) => field.field === 'email'\n );\n\n if (missingEmailVerification) {\n throw new MissingUserVerificationError({\n informationToVerify: 'email',\n message:\n 'User must have a verified email to create a Coinbase onramp order',\n });\n }\n\n const missingPhoneNumberVerification = fieldsMissingVerification.find(\n (field) => field.field === 'phoneNumber'\n );\n\n if (\n missingPhoneNumberVerification &&\n missingPhoneNumberVerification.errorCode !== 'VERIFICATION_EXPIRED'\n ) {\n throw new MissingUserVerificationError({\n informationToVerify: 'phoneNumber',\n message:\n 'User must have a verified phone number to create a Coinbase onramp order',\n });\n }\n\n // this is a requirement for Coinbase Onramp\n // https://docs.cdp.coinbase.com/api-reference/v2/rest-api/onramp/create-an-onramp-order#body-phone-number-verified-at\n if (\n missingPhoneNumberVerification &&\n missingPhoneNumberVerification.errorCode === 'VERIFICATION_EXPIRED'\n ) {\n throw new MissingUserVerificationError({\n informationToVerify: 'phoneNumber',\n message:\n \"The user's phone number has not been verified in the last 60 days. Please re-verify the user's phone number\",\n });\n }\n\n return user;\n};\n","import type { CoinbaseOnrampOrderPaymentMethod } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CoinbaseCreateOnrampOrderRequest,\n CoinbaseOnrampOrderResponse,\n} from '../coinbase.types';\nimport { validateUserCredentialsForCoinbaseOnrampOrder } from '../utils/validateUserCredentialsForCoinbaseOnrampOrder';\n\n/**\n * Creates a Coinbase onramp order\n *\n * @param orderParams CoinbaseCreateOnrampOrderRequest - The parameters for the onramp order.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created order\n * @throws {MissingUserVerificationError} If the user is missing verification for email or phone\n * @instrumented\n */\nexport const createCoinbaseOnrampOrder = async (\n orderParams: CoinbaseCreateOnrampOrderRequest,\n client = getDefaultClient()\n): Promise<CoinbaseOnrampOrderResponse> => {\n const user = validateUserCredentialsForCoinbaseOnrampOrder(client);\n\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const { isSandbox, ...restOrderParams } = orderParams;\n\n const orderResponse = await apiClient.createCoinbaseOnrampOrder({\n coinbaseOnrampOrderCreateRequest: {\n ...restOrderParams,\n // to create a sandbox order, we need to prefix the partner user ref with 'sandbox-'\n // https://docs.cdp.coinbase.com/onramp-&-offramp/onramp-apis/apple-pay-onramp-api#testing\n partnerUserRef:\n orderParams.partnerUserRef ??\n (isSandbox ? `sandbox-${user.id}` : user.id),\n paymentMethod:\n orderParams.paymentMethod as CoinbaseOnrampOrderPaymentMethod,\n },\n environmentId: core.environmentId,\n });\n\n if (!isSandbox || !orderResponse.paymentLink) {\n return orderResponse;\n }\n\n return {\n ...orderResponse,\n paymentLink: {\n ...orderResponse.paymentLink,\n url: `${orderResponse.paymentLink.url}&useApplePaySandbox=true`,\n },\n };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CoinbaseOnrampGetBuyUrlRequest,\n CoinbaseOnrampGetBuyUrlResponse,\n} from '../coinbase.types';\n\n/**\n * Gets a Coinbase buy URL\n *\n * @param buyUrlParams CoinbaseOnrampGetBuyUrlRequest - The parameters for the buy URL.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns an object containing the buy URL\n * @not-instrumented\n */\nexport const getCoinbaseBuyUrl = async (\n buyUrlParams: CoinbaseOnrampGetBuyUrlRequest,\n client = getDefaultClient()\n): Promise<CoinbaseOnrampGetBuyUrlResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.generateCoinbaseOnrampBuyUrl({\n coinbaseOnrampGetBuyUrlRequest: buyUrlParams,\n environmentId: core.environmentId,\n });\n\n return response;\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type {\n CryptoDotComPaymentCreateRequest,\n CryptoDotComPaymentResponse,\n} from '../cryptoDotCom.types';\n\n/**\n * Creates a crypto.com payment\n *\n * @param paymentParams CryptoDotComPaymentCreateRequest - The parameters for the payment.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created payment\n * @instrumented\n */\nexport const createCryptoDotComPayment = async (\n paymentParams: CryptoDotComPaymentCreateRequest,\n client = getDefaultClient()\n): Promise<CryptoDotComPaymentResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.createCryptoDotComPayment({\n cryptoDotComPaymentCreateRequest: {\n ...paymentParams,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chain: paymentParams.chain as ChainEnum,\n },\n environmentId: core.environmentId,\n });\n\n return response;\n};\n","/* eslint-disable custom-rules/ban-chain-enum */\nimport type { ChainEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { GetMoonPayCurrenciesParams, MoonPayCurrency } from '../moonpay.types';\n\n/**\n * Fetches the list of crypto currencies supported by MoonPay for the given chain\n * and network, filtered to active currencies only. Requires a MoonPay publishable\n * API key to be configured for the environment.\n *\n * @param params - The chain and optional network ID to filter currencies by.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of supported MoonPay currencies.\n * @instrumented\n */\nexport const getMoonPayCurrencies = async (\n params: GetMoonPayCurrenciesParams,\n client: DynamicClient = getDefaultClient()\n): Promise<MoonPayCurrency[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getMoonPayCurrencies({\n // Chain is typed as ChainEnum in the generated API client; our public type\n // is Chain (string literal union). The values are identical at runtime.\n chain: params.chain as unknown as ChainEnum,\n environmentId: core.environmentId,\n ...(params.networkId ? { networkId: params.networkId } : {}),\n });\n\n return response.currencies ?? [];\n};\n","import { BaseError } from '../../../../errors/base';\n\nexport class MoonPayInvalidUrlError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'moonpay_invalid_url_error',\n docsUrl: null,\n name: 'MoonPayInvalidUrlError',\n shortMessage:\n 'MoonPay is configured but returned an invalid or untrusted URL. This may indicate a misconfiguration — please contact support if the issue persists.',\n });\n }\n}\n","import { BaseError } from '../../../../errors/base';\n\nexport class MoonPayProviderNotAvailableError extends BaseError {\n constructor() {\n super({\n cause: null,\n code: 'moonpay_provider_not_available_error',\n docsUrl: null,\n name: 'MoonPayProviderNotAvailableError',\n shortMessage:\n 'MoonPay provider not available. Ensure MoonPay is enabled and a publishable API key is configured in the Dynamic dashboard.',\n });\n }\n}\n","import { ProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport { MoonPayInvalidUrlError } from '../errors/MoonPayInvalidUrlError';\nimport { MoonPayProviderNotAvailableError } from '../errors/MoonPayProviderNotAvailableError';\nimport type { GetMoonPayUrlParams } from '../moonpay.types';\n\n/**\n * Returns the signed MoonPay URL for the given wallet and token.\n *\n * Uses the Dynamic onramp API to retrieve the pre-signed URL that can be\n * opened in a browser tab to allow the user to purchase crypto via MoonPay.\n *\n * @param params - Parameters including chain, wallet address, and optional token/currency filters.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The signed MoonPay URL.\n * @instrumented\n */\nexport const getMoonPayUrl = async (\n params: GetMoonPayUrlParams,\n client: DynamicClient = getDefaultClient()\n): Promise<string> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getSupportedOnramps({\n chain: params.chain,\n currency: params.currency,\n environmentId: core.environmentId,\n includeDisabled: true,\n merchantName: params.merchantName,\n networkId: params.networkId,\n token: params.token,\n tokenAmount: params.tokenAmount,\n walletAddress: params.walletAddress,\n });\n\n const moonPayProvider = response.onramps?.find(\n (provider) => provider.provider === ProviderEnum.MoonPay\n );\n\n if (!moonPayProvider?.url) {\n throw new MoonPayProviderNotAvailableError();\n }\n\n // Validate scheme and host before returning — the URL is opened in a browser tab\n // and a compromised API response could inject a javascript: URI or phishing URL.\n // Use exact match or dot-prefixed subdomain check to block lookalikes like evilmoonpay.com.\n const parsedUrl = new URL(moonPayProvider.url);\n const isValidHost =\n parsedUrl.hostname === 'moonpay.com' || parsedUrl.hostname.endsWith('.moonpay.com');\n if (parsedUrl.protocol !== 'https:' || !isValidHost) {\n core.logger.error('[getMoonPayUrl] Invalid URL returned by onramp API', {\n url: moonPayProvider.url,\n });\n throw new MoonPayInvalidUrlError();\n }\n\n return moonPayProvider.url;\n};\n","import type { CreateExchangeTransferRequest } from '@dynamic-labs/sdk-api-core';\nimport { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { ExchangeTransferResponse } from '../kraken.types';\n\n// Kraken transfer request includes accountId + transfer parameters\nexport type KrakenTransferRequest = CreateExchangeTransferRequest & {\n /**\n * The Kraken account ID to transfer from (get from getKrakenAccounts)\n * @instrumented\n */\n accountId: string;\n};\n\n/**\n * Creates a Kraken exchange transfer to send crypto from a Kraken account to a whitelisted address\n *\n * @param transferParams - The parameters for the transfer including accountId\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The created transfer\n * @not-instrumented\n */\nexport const createKrakenExchangeTransfer = async (\n transferParams: KrakenTransferRequest,\n client = getDefaultClient()\n): Promise<ExchangeTransferResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const { accountId, ...createExchangeTransferRequest } = transferParams;\n\n const response = await apiClient.postExchangeAccountTransfer({\n accountId,\n createExchangeTransferRequest,\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n });\n\n return response;\n};\n","import type { ChainEnum } from '@dynamic-labs/sdk-api-core';\nimport { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { Chain } from '../../../chain';\nimport type { KrakenAccount } from '../kraken.types';\n\nexport type GetKrakenAccountsParams = {\n /**\n * Optional chain filter\n * @not-instrumented\n */\n chainName?: Chain;\n /**\n * Optional network ID filter\n */\n networkId?: number;\n};\n\n/**\n * Gets the Kraken accounts (balances) for the authenticated user\n *\n * @param [params] GetKrakenAccountsParams - Optional filters for the accounts.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Array of Kraken accounts with balances\n * @not-instrumented\n */\nexport const getKrakenAccounts = async (\n params?: GetKrakenAccountsParams,\n client = getDefaultClient()\n): Promise<KrakenAccount[]> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getUserAccounts({\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params?.chainName as ChainEnum,\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n networkId: params?.networkId,\n });\n\n return response;\n};\n","import { ExchangeKeyEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { TransferDestinationResponse } from '../kraken.types';\n\n/**\n * Gets the whitelisted addresses for Kraken transfers\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Transfer destinations response with whitelisted addresses\n * @not-instrumented\n */\nexport const getKrakenWhitelistedAddresses = async (\n client = getDefaultClient()\n): Promise<TransferDestinationResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.getExchangeTransferDestinations({\n environmentId: core.environmentId,\n exchangeKey: ExchangeKeyEnum.Kraken,\n });\n\n return response;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\n\n/**\n * Allows waiting until all modules of the client have been properly initialized\n * and are ready for use.\n *\n * @returns a promise that resolves once the client is fully initialized.\n * @not-instrumented\n */\nexport const waitForClientInitialized = async (client = getDefaultClient()) => {\n const core = getCore(client);\n\n await core.initTrack.waitForAll();\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport type { DynamicClient } from '../../../client/types';\n\nexport type SetInstrumentationEnabledOptions = {\n /** Whether event collection should be active. */\n enabled: boolean;\n};\n\n/**\n * Enables or disables event collection for the client's instrumentation service.\n *\n * When enabled, events are forwarded to the configured transport on every\n * instrumented function call. When disabled, instrumented functions run\n * normally but emit no telemetry.\n * @instrumented\n */\nexport const setInstrumentationEnabled = (\n { enabled }: SetInstrumentationEnabledOptions,\n client: DynamicClient = getDefaultClient()\n) => {\n getCore(client).instrumentation.setEnabled(enabled);\n};\n","/**\n * Default CDN URL for the wallet book.\n * @not-instrumented\n */\nconst DEFAULT_WALLET_BOOK_CDN_URL =\n 'https://dynamic-static-assets.com/wallet-book/v1/stable/wallet-book.json';\n\n/**\n * Gets the wallet book CDN URL from environment variables with fallback to default.\n *\n * Checks for environment variables in the following order:\n * 1. WALLET_BOOK_CDN_URL\n * 2. NEXT_PUBLIC_WALLET_BOOK_CDN_URL\n * 4. Default CDN URL\n *\n * @returns The wallet book CDN URL to use.\n * @not-instrumented\n */\nexport const getWalletBookCdnUrl = (): string => {\n if (typeof process !== 'undefined' && process.env) {\n const envVar =\n process.env.WALLET_BOOK_CDN_URL ||\n process.env.NEXT_PUBLIC_WALLET_BOOK_CDN_URL;\n\n if (envVar) {\n return envVar;\n }\n }\n\n return DEFAULT_WALLET_BOOK_CDN_URL;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { APIError } from '../../../../errors/APIError';\nimport { getWalletBookCdnUrl } from '../../getWalletBookCdnUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\n\n/**\n * The timeout for each fetch attempt in milliseconds.\n * @not-instrumented\n */\nconst FETCH_TIMEOUT_MS = 30000; // 30 seconds\n\n/**\n * Fetches the wallet book from the CDN endpoint with timeout handling.\n *\n * @param client - The Dynamic client instance.\n * @returns A promise that resolves to the wallet book data.\n * @not-instrumented\n */\nexport const fetchWithTimeout = async (\n client: DynamicClient\n): Promise<WalletBookSchema> => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n const core = getCore(client);\n\n try {\n const response = await core.fetch(getWalletBookCdnUrl(), {\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new APIError(\n `Failed to fetch wallet book: ${response.status} ${response.statusText}`,\n 'wallet_book_fetch_error',\n response.status\n );\n }\n\n const data = (await response.json()) as WalletBookSchema;\n\n return data;\n } finally {\n clearTimeout(timeoutId);\n }\n};\n","import * as z from 'zod/mini';\n\nimport { createStorageKeySchema } from '../../../services/storage';\nimport type { WalletBookSchema } from '../legacyWalletBook.types';\n\n/**\n * The schema to store the cached wallet book data.\n */\nexport const walletBookCacheStorageKeySchema = createStorageKeySchema({\n key: 'legacyWalletBookCache',\n schema: z.object({\n groups: z.record(z.string(), z.any()),\n wallets: z.record(z.string(), z.any()),\n }) as z.ZodMiniType<WalletBookSchema>,\n});\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types';\nimport { retryOnFail } from '../../../utils/retryOnFail';\nimport type { WalletBookSchema } from '../legacyWalletBook.types';\nimport { fetchWithTimeout } from './fetchWithTimeout';\nimport { walletBookCacheStorageKeySchema } from './walletBookCacheStorageKeySchema';\n\n/**\n * The maximum number of retry attempts.\n * @not-instrumented\n */\nconst MAX_RETRIES = 3;\n\n/**\n * The delay between retries in milliseconds.\n */\nconst RETRY_DELAY_MS = 100;\n\n/**\n * Fetches the legacy wallet book from Dynamic's CDN endpoint.\n *\n * This function implements a two-tier fallback strategy:\n * 1. Primary: Fetch from CDN endpoint (with retries)\n * 2. Secondary: Use cached version from localStorage if available\n *\n * @param client - The Dynamic client instance.\n * @returns A promise that resolves to the wallet book data.\n * @throws If both CDN fetch and cache retrieval fail.\n * @not-instrumented\n */\nexport const fetchLegacyWalletBook = async (\n client: DynamicClient\n): Promise<WalletBookSchema> => {\n const core = getCore(client);\n\n core.logger.debug('[fetchLegacyWalletBook] Fetching wallet book...');\n\n // Try to fetch from CDN with retry logic\n try {\n const walletBook = await retryOnFail({\n delay: RETRY_DELAY_MS,\n fn: async () => fetchWithTimeout(client),\n maxRetries: MAX_RETRIES,\n });\n\n await core.storage.setItem(walletBookCacheStorageKeySchema, walletBook);\n\n core.logger.debug(\n '[fetchLegacyWalletBook] Successfully fetched wallet book from CDN'\n );\n\n return walletBook;\n } catch (error) {\n core.logger.debug(\n '[fetchLegacyWalletBook] Failed to fetch from CDN, trying cache...',\n error\n );\n\n // Try to get from cache\n const cachedWalletBook = await core.storage.getItem(\n walletBookCacheStorageKeySchema\n );\n\n if (cachedWalletBook) {\n core.logger.debug('[fetchLegacyWalletBook] Using cached wallet book');\n\n return cachedWalletBook as WalletBookSchema;\n }\n\n // If both CDN and cache fail, throw the original error\n core.logger.debug(\n '[fetchLegacyWalletBook] Failed to fetch from CDN and no cache available'\n );\n\n throw error;\n }\n};\n","import type { WalletSchema } from '../legacyWalletBook.types';\n\n/**\n * Embedded wallet keys that should be filtered out from any external-wallet\n * catalogue. These wallets are not products the user \"connects\" to from the\n * wallet selection list — they are embedded sign-in methods that live behind\n * different SDK entry points.\n * @not-instrumented\n */\nexport const EMBEDDED_WALLET_KEYS = [\n 'magicemailotp',\n 'magiclink',\n 'magicsocial',\n 'turnkey',\n 'turnkeyhd',\n 'zerodev',\n 'dynamicwaas',\n 'coinbasempc',\n 'mpcvault',\n 'mpcwallet',\n];\n\nexport type ShouldFilterWalletParams = {\n /** The wallet schema to check. */\n wallet: WalletSchema;\n\n /** The wallet key identifier. */\n walletKey: string;\n};\n\n/**\n * Generic \"is this wallet eligible for an external-wallet catalogue\" check.\n * Filters out:\n *\n * 1. Embedded sign-in methods (see {@link EMBEDDED_WALLET_KEYS}).\n * 2. Wallets that only ship a browser-extension injection (`injectedConfig`)\n * with no mobile or desktop links — these have no surface a customer\n * catalogue UI can drive to.\n *\n * Channel-specific eligibility (WalletConnect support, in-app browser URL,\n * installation links, …) is the caller's responsibility — wrap this helper\n * with an additional check, e.g.\n * {@link shouldFilterWalletForWalletConnect}.\n *\n * @returns True if the wallet should be filtered out, false otherwise.\n * @not-instrumented\n */\nexport const shouldFilterWallet = ({\n wallet,\n walletKey,\n}: ShouldFilterWalletParams): boolean => {\n if (EMBEDDED_WALLET_KEYS.includes(walletKey)) {\n return true;\n }\n\n const hasInjectedConfig =\n wallet.injectedConfig && wallet.injectedConfig.length > 0;\n const hasMobileLinks = Boolean(\n wallet.mobile?.androidId ||\n wallet.mobile?.iosId ||\n wallet.mobile?.native ||\n wallet.mobile?.universal\n );\n const hasDesktopLinks = Boolean(\n wallet.desktop?.chromeId ||\n wallet.desktop?.edgeId ||\n wallet.desktop?.firefoxId ||\n wallet.desktop?.operaId ||\n wallet.desktop?.safariId ||\n wallet.desktop?.universal\n );\n\n return Boolean(hasInjectedConfig && !hasMobileLinks && !hasDesktopLinks);\n};\n","import { shouldFilterWallet } from '../../shouldFilterWallet/shouldFilterWallet';\nimport type { ShouldFilterWalletParams } from '../../shouldFilterWallet/shouldFilterWallet';\n\n/**\n * WalletConnect-specific filter. Applies the generic\n * {@link shouldFilterWallet} eligibility rules and additionally drops\n * wallets that do not advertise WalletConnect `sign_v2` support — the\n * protocol version Dynamic pairs against.\n *\n * @returns True if the wallet should be excluded from the WalletConnect\n * catalog, false otherwise.\n * @not-instrumented\n */\nexport const shouldFilterWalletForWalletConnect = ({\n wallet,\n walletKey,\n}: ShouldFilterWalletParams): boolean => {\n if (shouldFilterWallet({ wallet, walletKey })) {\n return true;\n }\n\n return !wallet.walletConnect?.sdks.includes('sign_v2');\n};\n","import { DYNAMIC_ICONIC_SPRITE_URL } from '../../../constants';\n\ntype GetSpriteUrlParams = {\n spriteId: string;\n};\n\n/**\n * Gets the sprite URL for a given sprite ID.\n *\n * @param params.spriteId - The sprite identifier from the wallet book.\n * @returns The full URL to the sprite icon\n * @not-instrumented\n */\nexport const getSpriteUrl = ({ spriteId }: GetSpriteUrlParams): string =>\n `${DYNAMIC_ICONIC_SPRITE_URL}#${spriteId}`;\n","import { getSpriteUrl } from '../../getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport type { WalletConnectCatalogGroup } from '../getWalletConnectCatalog.types';\n\ntype TransformGroupParams = {\n group: WalletBookSchema['groups'][string];\n};\n\n/**\n * Transforms a wallet group schema into a WalletConnect catalog group.\n * @not-instrumented\n */\nexport const transformGroup = ({\n group,\n}: TransformGroupParams): WalletConnectCatalogGroup => {\n const spriteId = group.brand?.spriteId ?? '';\n\n return {\n key: group.key,\n name: group.name,\n primaryColor: group.brand?.primaryColor,\n spriteUrl: spriteId ? getSpriteUrl({ spriteId }) : '',\n };\n};\n","import type { Chain } from '../../modules/chain';\nimport { CHAINS_INFO_MAP } from '../../modules/wallets/constants';\n\ntype GetChainFromWalletBookIdentifierParams = {\n identifier: string;\n};\n\n/**\n * Resolves a wallet-book chain identifier (as found in\n * `injectedConfig[].chain` or as an alias embedded in a wallet key) to a\n * {@link Chain}. Looks up by `apiChainName` first, then by any\n * `legacyWalletBookAliases` declared on the corresponding `CHAINS_INFO_MAP`\n * entry.\n *\n * Returns `undefined` when the identifier doesn't match any known chain,\n * letting the caller pick its own fallback (e.g. defaulting to EVM, or\n * trying a different lookup strategy).\n *\n * Centralised here rather than in `legacyWalletBook` so all chain naming\n * knowledge stays alongside `CHAINS_INFO_MAP`.\n * @not-instrumented\n */\nexport const getChainFromWalletBookIdentifier = ({\n identifier,\n}: GetChainFromWalletBookIdentifierParams): Chain | undefined => {\n const normalised = identifier.toLowerCase();\n const chains = Object.keys(CHAINS_INFO_MAP) as Chain[];\n\n return chains.find((chain) => {\n const info = CHAINS_INFO_MAP[chain];\n\n return (\n info.apiChainName === normalised ||\n info.legacyWalletBookAliases?.includes(normalised) === true\n );\n });\n};\n","import type { Chain } from '../../../chain';\nimport { getChainFromVerifiedCredentialChain } from '../../../../utils/getChainFromVerifiedCredentialChain';\nimport { getChainFromWalletBookIdentifier } from '../../../../utils/getChainFromWalletBookIdentifier';\nimport { CHAINS_INFO_MAP } from '../../../wallets/constants';\nimport type { WalletSchema } from '../../legacyWalletBook.types';\n\ntype ExtractChainPrefixParams = {\n chainIdentifier: string;\n};\n\n/**\n * Extracts the chain prefix from a chain identifier string.\n * For example, \"eip155:1\" -> \"eip155\", \"solana:...\" -> \"solana\"\n *\n * Exported so {@link getChainsFromWalletSchema} can apply the same\n * parsing to its multi-chain pass without duplicating the logic.\n * @not-instrumented\n */\nexport const extractChainPrefix = ({\n chainIdentifier,\n}: ExtractChainPrefixParams): string => {\n const colonIndex = chainIdentifier.indexOf(':');\n\n if (colonIndex === -1) {\n return chainIdentifier;\n }\n\n return chainIdentifier.substring(0, colonIndex);\n};\n\ntype GetChainFromWalletKeyParams = {\n walletKey: string;\n};\n\n/**\n * Attempts to extract the chain from a wallet key by looking for embedded\n * chain identifiers (apiChainName + legacyWalletBookAliases from CHAINS_INFO_MAP).\n *\n * Derives patterns dynamically so adding a chain in `CHAINS_INFO_MAP`\n * picks it up here — no parallel hardcoded list.\n *\n * @param params.walletKey - The wallet key identifier.\n * @returns The chain type if found, undefined otherwise.\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nconst getChainFromWalletKey = ({\n walletKey,\n}: GetChainFromWalletKeyParams): Chain | undefined => {\n const lowerKey = walletKey.toLowerCase();\n const chains = Object.keys(CHAINS_INFO_MAP) as Chain[];\n\n for (const chain of chains) {\n const info = CHAINS_INFO_MAP[chain];\n const patterns = [info.apiChainName, ...(info.legacyWalletBookAliases ?? [])];\n\n if (patterns.some((pattern) => lowerKey.includes(pattern))) {\n return chain;\n }\n }\n\n return undefined;\n};\n\ntype GetChainFromWalletSchemaParams = {\n wallet: WalletSchema;\n walletKey?: string;\n};\n\n/**\n * Gets the chain from a wallet book entry.\n * Checks injectedConfig first, then falls back to the chains array, then the wallet key.\n * If no chain can be determined, defaults to EVM.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @param params.walletKey - The wallet key identifier (optional, used as last resort fallback).\n * @returns The chain type, defaults to EVM if no chain can be determined.\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const getChainFromWalletSchema = ({\n wallet,\n walletKey,\n}: GetChainFromWalletSchemaParams): Chain => {\n // First, check injectedConfig for the chain field\n if (wallet.injectedConfig && wallet.injectedConfig.length > 0) {\n const injectedChain = wallet.injectedConfig[0].chain;\n\n if (injectedChain) {\n const chain = getChainFromWalletBookIdentifier({\n identifier: injectedChain,\n });\n\n if (chain) {\n return chain;\n }\n }\n }\n\n // Fall back to checking the chains array\n if (wallet.chains && wallet.chains.length > 0) {\n const firstChain = wallet.chains[0];\n const chainPrefix = extractChainPrefix({ chainIdentifier: firstChain });\n\n try {\n return getChainFromVerifiedCredentialChain(chainPrefix);\n } catch {\n // If the chain prefix is not recognized, fall back to wallet key check\n }\n }\n\n // Last resort: try to extract chain from wallet key\n if (walletKey) {\n const chainFromKey = getChainFromWalletKey({ walletKey });\n\n if (chainFromKey) {\n return chainFromKey;\n }\n }\n\n // Default to EVM if no chain can be determined\n return 'EVM';\n};\n","import { getSpriteUrl } from '../../getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport { getChainFromWalletSchema } from '../getChainFromWalletSchema';\nimport type { WalletConnectCatalogWallet } from '../getWalletConnectCatalog.types';\n\ntype TransformWalletParams = {\n wallet: WalletBookSchema['wallets'][string];\n walletKey: string;\n};\n\n/**\n * Transforms a wallet schema into a WalletConnect catalog wallet entry.\n * @not-instrumented\n */\nexport const transformWallet = ({\n wallet,\n walletKey,\n}: TransformWalletParams): WalletConnectCatalogWallet => {\n const spriteId = wallet.brand?.spriteId ?? '';\n\n const androidId = wallet.mobile?.androidId;\n const iosId = wallet.mobile?.iosId;\n\n return {\n chain: getChainFromWalletSchema({ wallet, walletKey }),\n deeplinks: {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n },\n downloadLinks: {\n androidUrl: androidId\n ? `https://play.google.com/store/apps/details?id=${androidId}`\n : undefined,\n iosUrl: iosId ? `https://apps.apple.com/app/${iosId}` : undefined,\n },\n groupId: wallet.group,\n name: wallet.name,\n primaryColor: wallet.brand?.primaryColor,\n spriteUrl: spriteId ? getSpriteUrl({ spriteId }) : '',\n };\n};\n","import type { WalletBookSchema } from '../../legacyWalletBook.types';\nimport type {\n WalletConnectCatalog,\n WalletConnectCatalogGroup,\n WalletConnectCatalogWallet,\n} from '../getWalletConnectCatalog.types';\nimport { shouldFilterWalletForWalletConnect } from '../shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect';\nimport { transformGroup } from '../transformGroup';\nimport { transformWallet } from '../transformWallet';\n\ntype TransformWalletBookParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Transforms the legacy wallet book into a WalletConnect catalog structure.\n * Filters out embedded wallets and injected-only wallets.\n * @not-instrumented\n */\nexport const transformWalletBook = ({\n walletBook,\n}: TransformWalletBookParams): WalletConnectCatalog => {\n const groups: Record<string, WalletConnectCatalogGroup> = {};\n\n for (const [groupKey, group] of Object.entries(walletBook.groups)) {\n groups[groupKey] = transformGroup({ group });\n }\n\n const wallets: Record<string, WalletConnectCatalogWallet> = {};\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWalletForWalletConnect({ wallet, walletKey })) {\n continue;\n }\n\n wallets[walletKey] = transformWallet({ wallet, walletKey });\n }\n\n return { groups, wallets };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { fetchLegacyWalletBook } from '../fetchLegacyWalletBook';\nimport type { WalletConnectCatalog } from './getWalletConnectCatalog.types';\nimport { transformWalletBook } from './transformWalletBook';\n\n/**\n * Retrieves the WalletConnect catalog from Dynamic's wallet book.\n *\n * This function fetches the wallet book and returns a WalletConnect catalog structure\n * that can be used for displaying wallet information and performing deep links for mobile wallet connections.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the WalletConnect catalog containing groups and wallets.\n * @throws If unable to fetch the wallet book from the API (when both CDN fetch and cache retrieval fail).\n * @not-instrumented\n */\nexport const getWalletConnectCatalog = async (\n client = getDefaultClient()\n): Promise<WalletConnectCatalog> => {\n const walletBook = await fetchLegacyWalletBook(client);\n\n return transformWalletBook({ walletBook });\n};\n","import type { WalletProviderData } from '../../wallets/walletProvider/walletProvider.types';\n\ntype MatchWalletProvidersToCatalogGroupParams = {\n catalogGroupKey: string;\n catalogGroupName?: string;\n walletProviders: WalletProviderData[];\n};\n\nconst normalize = (value: string): string =>\n value.toLowerCase().replace(/\\s+/g, '').replace(/wallet/g, '');\n\n/**\n * Returns the wallet providers that belong to the same wallet group as the\n * given WalletConnect catalog entry. Useful for de-duplicating \"installed\"\n * vs \"available via WalletConnect\" wallets when rendering a combined list.\n *\n * Matching is done on normalized identifiers — lowercased, whitespace removed,\n * and the literal substring \"wallet\" stripped — so that variations like:\n * - catalog key `\"trust\"` + catalog name `\"Trust Wallet\"`\n * - provider `groupKey: \"trustwallet\"` + `displayName: \"Trust Wallet\"`\n * collapse into a single match.\n *\n * @param params.catalogGroupKey - Key of the catalog group (e.g. `\"metamask\"`).\n * @param [params.catalogGroupName] - Optional display name (e.g. `\"Trust Wallet\"`); matched as a fallback when the key is opaque.\n * @param params.walletProviders - Currently available wallet providers (from `getAvailableWalletProvidersData`).\n * @returns The subset of `walletProviders` that match the catalog group.\n * @not-instrumented\n */\nexport const matchWalletProvidersToCatalogGroup = ({\n catalogGroupKey,\n catalogGroupName,\n walletProviders,\n}: MatchWalletProvidersToCatalogGroupParams): WalletProviderData[] => {\n const targets = new Set<string>([normalize(catalogGroupKey)]);\n if (catalogGroupName) targets.add(normalize(catalogGroupName));\n\n return walletProviders.filter((provider) => {\n const candidates = [\n normalize(provider.groupKey),\n normalize(provider.metadata.displayName),\n ];\n return candidates.some((candidate) => targets.has(candidate));\n });\n};\n","import type { WalletProviderData } from '../../../wallets/walletProvider/walletProvider.types';\nimport type { WalletConnectCatalog } from '../../getWalletConnectCatalog/getWalletConnectCatalog.types';\nimport { matchWalletProvidersToCatalogGroup } from '../../matchWalletProvidersToCatalogGroup';\n\ntype CollectInstalledGroupIdsParams = {\n catalog: WalletConnectCatalog;\n walletProviders: WalletProviderData[];\n};\n\n/**\n * Scans the catalog and returns the set of group identifiers for which at\n * least one installed wallet provider matches.\n *\n * Walks the catalog twice on purpose:\n * - First through `wallets`, to cover wallets that point to a `groupId`\n * with no matching entry in `groups` (we fall back to the wallet's own\n * name for matching in that case).\n * - Then through `groups`, to catch orphan group entries that have no\n * wallet referencing them.\n *\n * The check is skipped for any group already known to be installed, so a\n * multi-chain wallet (same `groupId` across EVM + SOL entries) only runs\n * the match once.\n *\n * @not-instrumented\n */\nexport const collectInstalledGroupIds = ({\n catalog,\n walletProviders,\n}: CollectInstalledGroupIdsParams): Set<string> => {\n const installedGroupIds = new Set<string>();\n\n // First pass: iterate wallets so we can use each wallet's own `name` as a\n // fallback when its group has no metadata entry in `catalog.groups`.\n for (const [walletKey, wallet] of Object.entries(catalog.wallets)) {\n const groupId = wallet.groupId || walletKey;\n if (installedGroupIds.has(groupId)) continue;\n\n const groupName = catalog.groups[groupId]?.name || wallet.name;\n\n const matches = matchWalletProvidersToCatalogGroup({\n catalogGroupKey: groupId,\n catalogGroupName: groupName,\n walletProviders,\n });\n\n if (matches.length > 0) installedGroupIds.add(groupId);\n }\n\n // Second pass: pick up groups that exist in `catalog.groups` but are not\n // referenced by any wallet (e.g. brand-only entries).\n for (const [groupKey, group] of Object.entries(catalog.groups)) {\n if (installedGroupIds.has(groupKey)) continue;\n\n const matches = matchWalletProvidersToCatalogGroup({\n catalogGroupKey: groupKey,\n catalogGroupName: group.name,\n walletProviders,\n });\n\n if (matches.length > 0) installedGroupIds.add(groupKey);\n }\n\n return installedGroupIds;\n};\n","import type { WalletProviderData } from '../../wallets/walletProvider/walletProvider.types';\nimport type { WalletConnectCatalog } from '../getWalletConnectCatalog/getWalletConnectCatalog.types';\nimport { collectInstalledGroupIds } from './collectInstalledGroupIds';\n\ntype ExcludeInstalledFromCatalogParams = {\n catalog: WalletConnectCatalog;\n walletProviders: WalletProviderData[];\n};\n\n/**\n * Returns a new WalletConnect catalog with the wallets and groups that the\n * user already has installed removed.\n *\n * Useful when rendering a combined wallet list (installed + WalletConnect\n * catalog) where each wallet should appear exactly once: installed wallets\n * win and the corresponding catalog entries get hidden.\n *\n * Matching is delegated to {@link collectInstalledGroupIds}, so a single\n * installed provider removes every wallet that shares its group — e.g. an\n * installed MetaMask hides both the EVM and SOL catalog entries.\n *\n * The original catalog object is not mutated.\n *\n * @param params.catalog - The full WalletConnect catalog (typically from `getWalletConnectCatalog`).\n * @param params.walletProviders - Currently available wallet providers.\n * @returns A new catalog with only the wallets and groups the user does not have installed.\n * @not-instrumented\n */\nexport const excludeInstalledFromCatalog = ({\n catalog,\n walletProviders,\n}: ExcludeInstalledFromCatalogParams): WalletConnectCatalog => {\n // Step 1: figure out which catalog groups the user already has installed.\n // We compute this up front so filtering wallets and groups below is a\n // simple set lookup per entry.\n const installedGroupIds = collectInstalledGroupIds({\n catalog,\n walletProviders,\n });\n\n // Step 2: keep only wallets whose effective group id is not installed.\n // Wallets without an explicit `groupId` are treated as their own group,\n // which mirrors how the catalog itself associates wallets to groups.\n const wallets: WalletConnectCatalog['wallets'] = {};\n for (const [walletKey, wallet] of Object.entries(catalog.wallets)) {\n const groupId = wallet.groupId || walletKey;\n if (installedGroupIds.has(groupId)) continue;\n wallets[walletKey] = wallet;\n }\n\n // Step 3: keep only group metadata entries that are not installed. This\n // prevents the caller from rendering an empty/orphan group with no\n // wallets behind it.\n const groups: WalletConnectCatalog['groups'] = {};\n for (const [groupKey, group] of Object.entries(catalog.groups)) {\n if (installedGroupIds.has(groupKey)) continue;\n groups[groupKey] = group;\n }\n\n return { groups, wallets };\n};\n","import type { Chain } from '../../../chain';\nimport { CHAINS_INFO_MAP } from '../../constants';\n\ntype ExtractChainFromNormalizedNameParams = {\n normalizedWalletNameWithChain: string;\n};\n\n/**\n * Extracts the chain from a normalized wallet name with chain suffix.\n * The chain is appended in lowercase at the end (e.g., \"metamaskevm\" -> \"EVM\").\n *\n * @param params.normalizedWalletNameWithChain - The normalized wallet name with chain suffix.\n * @returns The chain if found, undefined otherwise.\n * @not-instrumented\n */\nexport const extractChainFromNormalizedName = ({\n normalizedWalletNameWithChain,\n}: ExtractChainFromNormalizedNameParams): Chain | undefined => {\n const lowerName = normalizedWalletNameWithChain.toLowerCase();\n\n // Get all chain names in lowercase, sorted by length (longest first) to match longest suffix first\n const chainSuffixes = (Object.keys(CHAINS_INFO_MAP) as Chain[])\n .map((chain) => chain.toLowerCase())\n .sort((a, b) => b.length - a.length);\n\n for (const suffix of chainSuffixes) {\n if (lowerName.endsWith(suffix)) {\n return suffix.toUpperCase() as Chain;\n }\n }\n\n return undefined;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { extractChainFromNormalizedName } from '../../wallets/walletProvider/extractChainFromNormalizedName';\nimport { splitWalletProviderKey } from '../../wallets/walletProvider/splitWalletProviderKey';\nimport { getWalletConnectCatalog } from '../getWalletConnectCatalog';\nimport type { WalletConnectCatalogWallet } from '../getWalletConnectCatalog/getWalletConnectCatalog.types';\n\ntype GetWalletConnectCatalogWalletByWalletProviderKeyParams = {\n walletProviderKey: string;\n};\n\n/**\n * Gets the WalletConnect catalog wallet entry for a given wallet provider key.\n *\n * This function extracts the wallet name and chain from the wallet provider key and matches it\n * against the WalletConnect catalog to find the corresponding wallet entry, which includes\n * deep link information for mobile wallet connections.\n *\n * @param params.walletProviderKey - The wallet provider key to get the catalog wallet entry for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the WalletConnect catalog wallet entry, or undefined if not found.\n * @not-instrumented\n */\nexport const getWalletConnectCatalogWalletByWalletProviderKey = async (\n { walletProviderKey }: GetWalletConnectCatalogWalletByWalletProviderKeyParams,\n client = getDefaultClient()\n): Promise<WalletConnectCatalogWallet | undefined> => {\n const { normalizedWalletNameWithChain } =\n splitWalletProviderKey(walletProviderKey);\n\n const chain = extractChainFromNormalizedName({\n normalizedWalletNameWithChain,\n });\n\n if (!chain) {\n return undefined;\n }\n\n // Remove chain suffix from wallet name (e.g., \"metamaskevm\" -> \"metamask\")\n let walletProviderName = normalizedWalletNameWithChain.toLowerCase();\n\n if (walletProviderName.endsWith(chain.toLowerCase())) {\n walletProviderName = walletProviderName.slice(0, -chain.length);\n }\n\n // Remove \"wallet\" substring (e.g., \"trustwallet\" -> \"trust\", \"okxwallet\" -> \"okx\")\n walletProviderName = walletProviderName.replace(/wallet/g, '');\n\n const walletConnectCatalog = await getWalletConnectCatalog(client);\n\n for (const [walletKey, wallet] of Object.entries(\n walletConnectCatalog.wallets\n )) {\n if (wallet.chain !== chain) {\n continue;\n }\n\n const walletKeyLower = walletKey.toLowerCase();\n const walletNameLower = wallet.name.toLowerCase().replace(/\\s+/g, '');\n\n if (\n walletKeyLower.includes(walletProviderName) ||\n walletNameLower.includes(walletProviderName)\n ) {\n return wallet;\n }\n }\n\n return undefined;\n};\n","/* eslint-disable no-useless-escape */\n/* eslint-disable no-restricted-globals */\n/**\n * Sourced from http://detectmobilebrowsers.com/\n * @not-instrumented\n */\n\nconst userAgentRegex1 =\n /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ios|ipad|playbook|silk/i;\n\nconst userAgentRegex2 =\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i;\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const isMobile = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return (\n userAgentRegex1.test(navigator.userAgent) ||\n userAgentRegex2.test(navigator.userAgent.substring(0, 4)) ||\n isIPad(maxTouchPointsOverride) ||\n isIPhone()\n );\n};\n\n/** @not-instrumented */\n \nexport const isIPhone = () =>\n typeof window === 'undefined' || typeof navigator === 'undefined'\n ? false\n : /iPhone|ios/.test(navigator.userAgent);\n\n/** @not-instrumented */\n \nexport const isIPhone8OrEarlier = () =>\n typeof window === 'undefined' || typeof navigator === 'undefined'\n ? false\n : iPhoneLegacyRegex.some(({ regex }) => regex.test(navigator.userAgent));\n\n/**\n * @param [optional] maxTouchPointsOverride - this is used for testing since\n * it seems that JSDOM doesn't support maxTouchPoints, so it was impossible\n * to mock it\n * @not-instrumented\n */\n// eslint-disable-next-line custom-rules/one-function-per-file, custom-rules/require-single-object-param\nexport const isIPad = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n const maxTouchPoints = maxTouchPointsOverride || navigator.maxTouchPoints;\n\n return (\n /iPad/.test(navigator.userAgent) ||\n (/Mac/.test(navigator.userAgent) && maxTouchPoints === 5)\n );\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file, custom-rules/require-single-object-param\nexport const isIOS = (maxTouchPointsOverride?: number) => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return isIPhone() || isIPad(maxTouchPointsOverride);\n};\n\n/** @not-instrumented */\n \nexport const isAndroid = () => isMobile() && !isIOS();\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isLegacySafari = () => {\n // We need to check if window.CSS exists and if it has supports function.\n // We can use it only in browsers. This prevents customer tests from failing because of that.\n if (\n typeof window === 'undefined' ||\n !window.CSS ||\n typeof window.CSS.supports !== 'function'\n ) {\n return false;\n }\n\n // Older versions of Safari <15 are not supporting aspect-ratio css property.\n // We can use that to check if user is on older browser.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio\n const cssValue = 'aspect-ratio: 1 / 1';\n\n return !CSS.supports(cssValue);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isSamsungBrowser = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return navigator.userAgent.includes('SamsungBrowser');\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isSafariBrowser = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n const { userAgent } = navigator;\n\n const isSafari =\n userAgent.includes('Safari') &&\n !userAgent.includes('Chrome') &&\n !userAgent.includes('Chromium');\n\n return isSafari;\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isEdgeBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\bEdg\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isOperaBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\b(OPR|Opera)\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isFirefoxBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n return /\\bFirefox\\//.test(navigator.userAgent);\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isChromeBrowser = () => {\n if (globalThis.window === undefined || globalThis.navigator === undefined) {\n return false;\n }\n\n // Chromium-based browsers (Edge, Opera, Brave, ...) all carry \"Chrome\"\n // in their UA, so the more specific brands must be excluded here.\n return (\n /\\bChrome\\//.test(navigator.userAgent) &&\n !isEdgeBrowser() &&\n !isOperaBrowser()\n );\n};\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const isWindows = () => {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return false;\n }\n\n return navigator.userAgent.indexOf('Windows') !== -1;\n};\n\n// regex from: https://github.com/matomo-org/device-detector/blob/master/regexes/device/mobiles.yml\nconst iPhoneLegacyRegex = [\n {\n model: 'iPhone 5',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?5[C,_]12|5)$/,\n },\n {\n model: 'iPhone 5C',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?5[C,_]34)$/,\n },\n {\n model: 'iPhone 5S',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?6[C,_]12|5S)$/,\n },\n {\n model: 'iPhone 6 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?7[C,_]1|1C2%257enohPi|6PLUS)$/,\n },\n {\n model: 'iPhone 6',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?7[C,_]2|6)$/,\n },\n {\n model: 'iPhone 6s Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]2|6SPLUS)$/,\n },\n {\n model: 'iPhone 6s',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]1|iPhone[ /]6s|6S)$/,\n },\n {\n model: 'iPhone SE',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?8[C,_]4|SE)$/,\n },\n {\n model: 'iPhone 7',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?9[C,_]13|iphone7|7)$/,\n },\n {\n model: 'iPhone 7 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?9[C,_]24|7PLUS)$/,\n },\n {\n model: 'iPhone 8',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?10[C,_]14|8)$/,\n },\n {\n model: 'iPhone 8 Plus',\n regex: /(?:MDCR_|ICRU_|Apple-)?(?:iPh(?:one)?10[C,_]25|8PLUS)$/,\n },\n];\n\n/** @not-instrumented */\n// eslint-disable-next-line custom-rules/one-function-per-file\nexport const getAndroidVersion = () => {\n if (typeof navigator === 'undefined') {\n return;\n }\n\n const androidVersionMatch = navigator.userAgent.match(\n /Android (\\d+(\\.\\d+)?)/\n );\n\n if (!androidVersionMatch) {\n return;\n }\n\n const androidVersion = parseFloat(androidVersionMatch[1]);\n\n return androidVersion;\n};\n","import {\n isAndroid,\n isChromeBrowser,\n isEdgeBrowser,\n isFirefoxBrowser,\n isIOS,\n isOperaBrowser,\n isSafariBrowser,\n} from '../../../utils/isMobile/isMobile';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\ntype GetInstallationLinkForCurrentPlatformParams = {\n installationUrls: InstallationUrls;\n};\n\n/**\n * Resolves the {@link InstallationUrls} field that matches the platform\n * the SDK is currently running on:\n *\n * - iOS → `ios`\n * - Android → `android`\n * - Edge → `edge`\n * - Opera → `opera`\n * - Firefox → `firefox`\n * - Safari → `safari`\n * - Chrome (or other Chromium-based browsers) → `chrome`\n *\n * Returns `undefined` when no entry exists for the detected platform —\n * callers typically render a \"not available on this device\" affordance\n * in that case rather than offering a download targeted at a different\n * browser/OS.\n *\n * Each branch returns exactly the field for the detected platform — no\n * fallback to a different browser's URL. If you'd rather surface every\n * link a wallet's manifest publishes so the user can pick where to\n * install, read `installationUrls` directly instead of going through\n * this helper.\n *\n * @param params.installationUrls - The wallet option's `installationUrls`\n * record (from `getWalletOptionsCatalogue`).\n * @returns The install URL for the detected platform, or `undefined`.\n * @not-instrumented\n */\nexport const getInstallationLinkForCurrentPlatform = ({\n installationUrls,\n}: GetInstallationLinkForCurrentPlatformParams): string | undefined => {\n if (isIOS()) return installationUrls.ios;\n if (isAndroid()) return installationUrls.android;\n if (isEdgeBrowser()) return installationUrls.edge;\n if (isOperaBrowser()) return installationUrls.opera;\n if (isFirefoxBrowser()) return installationUrls.firefox;\n if (isSafariBrowser()) return installationUrls.safari;\n if (isChromeBrowser()) return installationUrls.chrome;\n return undefined;\n};\n","import type { WalletSchema } from '../../legacyWalletBook/legacyWalletBook.types';\n\ntype ResolveWalletBookWalletOptionKeyParams = {\n wallet: WalletSchema;\n walletKey: string;\n};\n\n/**\n * Resolves which wallet option (group) a wallet book entry belongs to. Used\n * by the catalogue's wallet-book-driven transformers (URI deeplink,\n * `inAppBrowser`, `installation`) to bucket their emitted options.\n *\n * Wallet book entries inconsistently use `group` / `chainGroup` /\n * `walletGroup` for the same idea. The wallet key itself acts as the wallet\n * option key when no group field is set.\n *\n * @param params.wallet - The wallet entry.\n * @param params.walletKey - The wallet's key in `walletBook.wallets`.\n * @returns The wallet option key.\n * @not-instrumented\n */\nexport const resolveWalletBookWalletOptionKey = ({\n wallet,\n walletKey,\n}: ResolveWalletBookWalletOptionKeyParams): string =>\n wallet.group ?? wallet.chainGroup ?? wallet.walletGroup ?? walletKey;\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype GetInAppBrowserUrlParams = {\n wallet: WalletBookSchema['wallets'][string];\n};\n\n/**\n * Returns the wallet's in-app browser URL template, preferring the v2\n * field. `inAppBrowser` is deprecated but some wallet book entries\n * still carry only the v1 value, so it acts as a fallback. Trailing\n * `?? undefined` collapses the schema's `string | null` typing down to\n * the `string | undefined` return contract.\n *\n * @param params.wallet - The wallet book wallet entry.\n * @returns The in-app browser URL, or `undefined` if neither field is set.\n * @not-instrumented\n */\nexport const getInAppBrowserUrl = ({\n wallet,\n}: GetInAppBrowserUrlParams): string | undefined =>\n wallet.mobile?.inAppBrowserV2 ?? wallet.mobile?.inAppBrowser ?? undefined; // NOSONAR\n","import { getChainFromWalletSchema } from '../../legacyWalletBook/getWalletConnectCatalog/getChainFromWalletSchema/getChainFromWalletSchema';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\nimport { getInAppBrowserUrl } from './getInAppBrowserUrl/getInAppBrowserUrl';\n\ntype BuildInAppBrowserOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `inAppBrowser` catalogue options from the wallet book. A wallet\n * qualifies when it exposes a mobile in-app-browser URL — typically a\n * `cb_url={{encodedDappURI}}`-style template the customer fills in with the\n * current page URL before opening.\n *\n * Reuses the generic `shouldFilterWallet` rules — embedded sign-in methods\n * and injected-only wallets are dropped — so the catalogue's notion of\n * \"external wallet\" stays consistent across option types.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `inAppBrowser` options paired with their wallet option keys.\n * @not-instrumented\n */\nexport const buildInAppBrowserOptions = ({\n walletBook,\n}: BuildInAppBrowserOptionsParams): ConnectionOptionForWalletOption[] => {\n const result: ConnectionOptionForWalletOption[] = [];\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n const url = getInAppBrowserUrl({ wallet });\n\n if (!url) {\n continue;\n }\n\n result.push({\n option: {\n chain: getChainFromWalletSchema({ wallet, walletKey }),\n type: 'inAppBrowser',\n url,\n },\n walletOptionKey: resolveWalletBookWalletOptionKey({ wallet, walletKey }),\n });\n }\n\n return result;\n};\n","import type { WalletSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\nconst PLAY_STORE_URL_TEMPLATE =\n 'https://play.google.com/store/apps/details?id=';\nconst APP_STORE_URL_TEMPLATE = 'https://apps.apple.com/app/';\nconst CHROME_WEB_STORE_URL_TEMPLATE =\n 'https://chrome.google.com/webstore/detail/';\nconst FIREFOX_ADDONS_URL_TEMPLATE =\n 'https://addons.mozilla.org/firefox/addon/';\nconst EDGE_ADDONS_URL_TEMPLATE =\n 'https://microsoftedge.microsoft.com/addons/detail/';\n\ntype BuildInstallationUrlsParams = {\n wallet: WalletSchema;\n};\n\n/**\n * Builds the install/download URL bag for a wallet book entry. Returns the\n * concrete URLs assembled from each store's ID field — Play Store, App\n * Store, Chrome Web Store, Firefox Add-ons, Edge Add-ons — plus the wallet's\n * own `desktop.universal` / `desktop.native` URLs when set.\n *\n * Fields the wallet book does not carry are left undefined; callers should\n * skip emitting an installation option for a wallet whose URL bag is empty.\n *\n * @param params.wallet - The wallet book entry.\n * @returns The URL bag, omitting fields the wallet does not provide.\n * @not-instrumented\n */\nexport const buildInstallationUrls = ({\n wallet,\n}: BuildInstallationUrlsParams): InstallationUrls => {\n const androidId = wallet.mobile?.androidId;\n const iosId = wallet.mobile?.iosId;\n const chromeId = wallet.desktop?.chromeId;\n const firefoxId = wallet.desktop?.firefoxId;\n const edgeId = wallet.desktop?.edgeId;\n const native = wallet.desktop?.universal ?? wallet.desktop?.native;\n\n return {\n android: androidId ? `${PLAY_STORE_URL_TEMPLATE}${androidId}` : undefined,\n chrome: chromeId\n ? `${CHROME_WEB_STORE_URL_TEMPLATE}${chromeId}`\n : undefined,\n edge: edgeId ? `${EDGE_ADDONS_URL_TEMPLATE}${edgeId}` : undefined,\n firefox: firefoxId\n ? `${FIREFOX_ADDONS_URL_TEMPLATE}${firefoxId}`\n : undefined,\n ios: iosId ? `${APP_STORE_URL_TEMPLATE}${iosId}` : undefined,\n native: native || undefined,\n };\n};\n","import type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport { buildInstallationUrls } from '../buildInstallationUrls/buildInstallationUrls';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\nimport type { InstallationUrls } from '../walletOptionsCatalogue.types';\n\ntype HasAnyInstallationUrlParams = {\n urls: InstallationUrls;\n};\n\n/**\n * `buildInstallationUrls` always returns an object, but it can be fully\n * `undefined`-valued when the wallet book entry has no installable surface.\n * Skip those wallets — emitting an empty URL bag helps nobody.\n */\nconst hasAnyInstallationUrl = ({ urls }: HasAnyInstallationUrlParams): boolean =>\n Object.values(urls).some(Boolean);\n\ntype BuildInstallationUrlsByWalletOptionKeyParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Collects install / download URLs for every wallet book entry that has\n * at least one installable surface, keyed by the wallet option key the\n * wallet groups under. The catalogue assembly step merges this map into\n * the per-key wallet option shell so `WalletOption.installationUrls` is\n * populated alongside (or instead of) `connectionOptions`.\n *\n * First-seen URLs win when multiple wallet book entries resolve to the\n * same wallet option key — wallet book authors put the most accurate\n * install links on the canonical entry, so the first-seen one is the\n * right pick.\n *\n * Reuses the generic `shouldFilterWallet` rules so embedded wallets do\n * not appear here either — they're not user-installable products.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns A map from wallet option key to its install URL bag.\n * @not-instrumented\n */\nexport const buildInstallationUrlsByWalletOptionKey = ({\n walletBook,\n}: BuildInstallationUrlsByWalletOptionKeyParams): Map<\n string,\n InstallationUrls\n> => {\n const map = new Map<string, InstallationUrls>();\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n const urls = buildInstallationUrls({ wallet });\n\n if (!hasAnyInstallationUrl({ urls })) {\n continue;\n }\n\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n if (!map.has(walletOptionKey)) {\n map.set(walletOptionKey, urls);\n }\n }\n\n return map;\n};\n","import type { WalletSchema } from '../legacyWalletBook.types';\n\ntype HasUsableDeeplinkParams = {\n wallet: WalletSchema;\n};\n\n/**\n * Whether a wallet book entry exposes at least one mobile deeplink the\n * catalogue can drive — either a native scheme (`metamask://`) or a\n * universal link (`https://metamask.app.link`). Used by the URI-deeplink\n * builders (`buildWalletConnectOptions`, `buildMetaMaskSdkUriOptions`)\n * to skip wallets that have no app to launch.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @returns True when the wallet has a native or universal mobile link.\n * @not-instrumented\n */\nexport const hasUsableDeeplink = ({\n wallet,\n}: HasUsableDeeplinkParams): boolean =>\n Boolean(wallet.mobile?.native || wallet.mobile?.universal);\n","import type { Chain } from '../../chain';\nimport { hasUsableDeeplink } from '../../legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { shouldFilterWallet } from '../../legacyWalletBook/shouldFilterWallet/shouldFilterWallet';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\n\n/**\n * Wallet option key the MetaMask SDK URI extension targets.\n */\nconst METAMASK_WALLET_OPTION_KEY = 'metamask';\n\n/**\n * Chains the MetaMask SDK URI pairing supports.\n *\n * Unlike WalletConnect — whose per-wallet chain support is read from the\n * wallet book — the MetaMask SDK URI is a single Dynamic integration whose\n * chain coverage is defined by which `connectWithMetaMaskUri<Chain>`\n * primitives the SDK ships (EVM + SOL). The MetaMask wallet-book entry only\n * advertises its EVM (`eip155`) chains, so deriving the chain from the book\n * would never surface the Solana pairing; the SDK's own capabilities are\n * listed explicitly instead.\n */\nconst METAMASK_SDK_URI_SUPPORTED_CHAINS: readonly Chain[] = ['EVM', 'SOL'];\n\ntype BuildMetaMaskSdkUriOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `metamaskSdkUri`-discriminator catalogue options from a\n * fetched wallet book. The MetaMask SDK URI extension only targets the\n * MetaMask wallet, so the builder iterates the book looking for the\n * entry whose resolved wallet option key is `'metamask'`.\n *\n * Applies the generic `shouldFilterWallet` rules (drops embedded keys +\n * injected-only-without-links entries). Crucially does NOT require WC\n * `sign_v2` support — MetaMask SDK URI is a different protocol from\n * WalletConnect, so the WC-specific filter does not apply here.\n *\n * Emits one `metamaskSdkUri` option per chain the MetaMask SDK URI pairing\n * supports (see {@link METAMASK_SDK_URI_SUPPORTED_CHAINS}) so the picker can\n * offer both the EVM and Solana pairings for the single MetaMask entry.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `metamaskSdkUri` options for MetaMask if eligible, otherwise an empty array.\n * @not-instrumented\n */\nexport const buildMetaMaskSdkUriOptions = ({\n walletBook,\n}: BuildMetaMaskSdkUriOptionsParams): ConnectionOptionForWalletOption[] => {\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n if (walletOptionKey !== METAMASK_WALLET_OPTION_KEY) {\n continue;\n }\n\n if (shouldFilterWallet({ wallet, walletKey })) {\n continue;\n }\n\n if (!hasUsableDeeplink({ wallet })) {\n continue;\n }\n\n const deeplinks = {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n };\n\n // One option per supported chain so the wallet picker can offer (and\n // chain-switch between) MetaMask's EVM and Solana URI pairings.\n return METAMASK_SDK_URI_SUPPORTED_CHAINS.map((chain) => ({\n option: {\n chain,\n deeplinks,\n type: 'metamaskSdkUri',\n },\n walletOptionKey,\n }));\n }\n\n return [];\n};\n","import { getChainFromVerifiedCredentialChain } from '../../../../utils/getChainFromVerifiedCredentialChain';\nimport { getChainFromWalletBookIdentifier } from '../../../../utils/getChainFromWalletBookIdentifier';\nimport type { Chain } from '../../../chain';\nimport type { WalletSchema } from '../../legacyWalletBook.types';\nimport {\n extractChainPrefix,\n getChainFromWalletSchema,\n} from '../getChainFromWalletSchema/getChainFromWalletSchema';\n\ntype GetChainsFromWalletSchemaParams = {\n wallet: WalletSchema;\n walletKey?: string;\n};\n\n/**\n * Returns every chain a wallet book entry advertises support for —\n * deduped, in `injectedConfig` order, then `chains` order. Used by the\n * catalogue's WalletConnect builder so a multi-chain wallet (e.g. Trust\n * supports EVM + SOL) gets one option per chain rather than one option\n * for whichever chain `getChainFromWalletSchema` happened to pick first.\n *\n * Falls back to {@link getChainFromWalletSchema}'s single-result behavior\n * (`['EVM']` default) when neither field is populated, so the helper\n * never returns an empty array — every eligible wallet emits at least\n * one option.\n *\n * @param params.wallet - The wallet schema from the wallet book.\n * @param [params.walletKey] - The wallet key identifier (used as last-resort fallback).\n * @returns Ordered, deduped array of Chains.\n * @not-instrumented\n */\nexport const getChainsFromWalletSchema = ({\n wallet,\n walletKey,\n}: GetChainsFromWalletSchemaParams): Chain[] => {\n // Set keeps insertion order, so collect → toArray preserves the\n // injectedConfig-first, chains-second emission order without a parallel\n // dedupe array.\n const chains = new Set<Chain>();\n\n for (const entry of wallet.injectedConfig ?? []) {\n if (!entry.chain) continue;\n\n const chain = getChainFromWalletBookIdentifier({ identifier: entry.chain });\n\n if (chain) chains.add(chain);\n }\n\n for (const identifier of wallet.chains ?? []) {\n const prefix = extractChainPrefix({ chainIdentifier: identifier });\n\n try {\n const chain = getChainFromVerifiedCredentialChain(prefix);\n chains.add(chain);\n } catch {\n // Unknown prefix — skip.\n }\n }\n\n if (chains.size === 0) {\n const chain = getChainFromWalletSchema({ wallet, walletKey });\n chains.add(chain);\n }\n\n return Array.from(chains);\n};\n","import type { Chain } from '../../chain';\nimport { getChainsFromWalletSchema } from '../../legacyWalletBook/getWalletConnectCatalog/getChainsFromWalletSchema/getChainsFromWalletSchema';\nimport { shouldFilterWalletForWalletConnect } from '../../legacyWalletBook/getWalletConnectCatalog/shouldFilterWalletForWalletConnect/shouldFilterWalletForWalletConnect';\nimport { hasUsableDeeplink } from '../../legacyWalletBook/hasUsableDeeplink/hasUsableDeeplink';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { resolveWalletBookWalletOptionKey } from '../resolveWalletBookWalletOptionKey/resolveWalletBookWalletOptionKey';\n\n/**\n * Chains Dynamic ships a WalletConnect extension for. Anything else a\n * wallet book entry advertises (Cosmos, BTC, …) gets filtered out — the\n * catalogue should not surface a chain the SDK has no `connectWithWalletConnect<Chain>`\n * primitive for.\n */\nconst WALLETCONNECT_SUPPORTED_CHAINS: ReadonlySet<Chain> = new Set([\n 'EVM',\n 'SOL',\n]);\n\ntype BuildWalletConnectOptionsParams = {\n walletBook: WalletBookSchema;\n};\n\n/**\n * Builds the `walletConnect`-discriminator catalogue options from a fetched\n * wallet book. Applies the WalletConnect-specific eligibility filter\n * (`shouldFilterWalletForWalletConnect`) so embedded wallets and entries\n * without `sign_v2` support are excluded — same surface as\n * `getWalletConnectCatalog`.\n *\n * Skips the MetaMask wallet entry: MetaMask is steered to its own URI\n * connection extension via `buildMetaMaskSdkUriOptions`. Keeping the two\n * builders separate means each protocol owns its own eligibility rules\n * (WC needs `sign_v2`; MM SDK URI does not), so excluding one\n * discriminator via `excludedConnectionOptionTypes` doesn't accidentally\n * gate the other.\n *\n * @param params.walletBook - The fetched wallet book.\n * @returns Tagged `walletConnect` options paired with their wallet option keys.\n * @not-instrumented\n */\nexport const buildWalletConnectOptions = ({\n walletBook,\n}: BuildWalletConnectOptionsParams): ConnectionOptionForWalletOption[] => {\n const result: ConnectionOptionForWalletOption[] = [];\n\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (shouldFilterWalletForWalletConnect({ wallet, walletKey })) {\n continue;\n }\n\n if (!hasUsableDeeplink({ wallet })) {\n continue;\n }\n\n const walletOptionKey = resolveWalletBookWalletOptionKey({\n wallet,\n walletKey,\n });\n\n // MetaMask is steered to the MetaMask SDK URI builder.\n if (walletOptionKey === 'metamask') {\n continue;\n }\n\n const chains = getChainsFromWalletSchema({ wallet, walletKey }).filter(\n (chain) => WALLETCONNECT_SUPPORTED_CHAINS.has(chain)\n );\n\n for (const chain of chains) {\n result.push({\n option: {\n chain,\n deeplinks: {\n native: wallet.mobile?.native,\n universal: wallet.mobile?.universal,\n },\n type: 'walletConnect',\n },\n walletOptionKey,\n });\n }\n }\n\n return result;\n};\n","import { getSpriteUrl } from '../../legacyWalletBook/getSpriteUrl/getSpriteUrl';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport type { WithWalletProviderDisplayOverride } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport type {\n InstallationUrls,\n WalletConnectionOption,\n WalletOption,\n} from '../walletOptionsCatalogue.types';\n\ntype BuildWalletOptionParams = {\n connectionOptions: WalletConnectionOption[];\n displayOverride?: WithWalletProviderDisplayOverride;\n installationUrls?: InstallationUrls;\n walletBook: WalletBookSchema;\n walletOptionKey: string;\n};\n\n/**\n * Assembles a `WalletOption` for a resolved wallet option key, populated\n * with the connection options the transformers produced for it plus an\n * optional install / download URL bag.\n *\n * Display merge rules (provider self-announced metadata wins where set):\n *\n * - `name`: `displayOverride.name` ?? wallet book group name ?? wallet\n * book wallet name ?? bare key.\n * - `iconUrl`: `displayOverride.iconUrl` ?? wallet book group sprite URL\n * ?? wallet book wallet sprite URL ?? `''`.\n * - `primaryColor`: wallet book group brand color ?? wallet book wallet\n * brand color (providers do not ship a primary color in their\n * announcement metadata).\n * - `installationUrls`: copied through if present.\n *\n * The per-wallet fallback handles wallets that exist as individual entries\n * in the book (e.g. Rainbow) rather than as members of a multi-wallet group\n * — those don't get a `walletBook.groups[…]` shell.\n *\n * Why provider precedence: a registered wallet provider knows its own\n * brand best (EIP-6963 / Wallet Standard / vendor SDK announcement is the\n * wallet authoring its own identity). The wallet book fills in fields the\n * announcement does not carry — currently only `primaryColor`.\n *\n * @param params.connectionOptions - The connections to attach to this wallet option.\n * @param [params.displayOverride] - Provider-announced display info that overrides the wallet book's name and iconUrl.\n * @param [params.installationUrls] - Install/download URL bag for this wallet.\n * @param params.walletBook - The fetched wallet book.\n * @param params.walletOptionKey - The wallet option key.\n * @returns The constructed wallet option.\n * @not-instrumented\n */\nexport const buildWalletOption = ({\n connectionOptions,\n displayOverride,\n installationUrls,\n walletBook,\n walletOptionKey,\n}: BuildWalletOptionParams): WalletOption => {\n const group = walletBook.groups[walletOptionKey];\n const groupSpriteId = group?.brand?.spriteId;\n const groupIconUrl = groupSpriteId\n ? getSpriteUrl({ spriteId: groupSpriteId })\n : undefined;\n\n // Fall back to the wallet entry's own brand when the wallet option key\n // matches an individual wallet (e.g. Rainbow) rather than a multi-wallet\n // group — those entries don't get a `walletBook.groups[…]` shell, so\n // `group.brand` is undefined and we'd otherwise emit an empty iconUrl.\n const walletEntry = walletBook.wallets[walletOptionKey];\n const walletSpriteId = walletEntry?.brand?.spriteId;\n const walletIconUrl = walletSpriteId\n ? getSpriteUrl({ spriteId: walletSpriteId })\n : undefined;\n\n return {\n connectionOptions,\n iconUrl:\n displayOverride?.iconUrl ?? groupIconUrl ?? walletIconUrl ?? '',\n installationUrls,\n key: walletOptionKey,\n name:\n displayOverride?.name ?? group?.name ?? walletEntry?.name ?? walletOptionKey,\n primaryColor:\n group?.brand?.primaryColor ?? walletEntry?.brand?.primaryColor,\n };\n};\n","import type { WalletProvider } from '../walletProvider';\n\ntype HasWalletProviderConnectMethodParams = {\n walletProvider: WalletProvider;\n};\n\n/**\n * Returns true when the given wallet provider exposes a `connect` method,\n * which is the signal we use to decide whether it belongs in the external\n * wallet picker as an `available provider`.\n *\n * Providers that don't expose `connect` (embedded wallets,\n * account-abstraction wrappers, MetaMask SDK / WalletConnect-backed\n * providers) are still sign-in capable, but via different SDK entry\n * points — they should not appear in the external picker as a\n * `withWalletProvider`-style option.\n *\n * Centralizing the predicate means future tweaks (e.g. a registry of\n * provider keys to exclude) land in one place and every consumer stays\n * in lockstep.\n *\n * @param params.walletProvider - The wallet provider to test.\n * @returns True when the provider exposes a `connect` method.\n * @not-instrumented\n */\nexport const hasWalletProviderConnectMethod = ({\n walletProvider,\n}: HasWalletProviderConnectMethodParams): boolean =>\n Boolean(walletProvider.connect);\n","import { WalletProviderPriority } from '../../wallets/walletProviderRegistry';\nimport type { WalletProviderRegistryEntry } from '../../wallets/walletProviderRegistry';\nimport type { WithWalletProviderSource } from '../walletOptionsCatalogue.types';\n\ntype ClassifyWithWalletProviderSourceParams = {\n entry: WalletProviderRegistryEntry;\n};\n\n\n/**\n * Maps a registered wallet provider's registration priority to the\n * `WithWalletProviderSource` value that should appear on its catalogue option.\n *\n * Priority mapping (set by each chain extension when it calls\n * `registry.register`):\n *\n * - `WALLET_SDK` → `'sdk'` — branded SDKs wrapped by chain extensions\n * (Base Account via `@base-org/account`, MetaMask Connect, …).\n * - `WALLET_SELF_ANNOUNCEMENT_STANDARD` → `'selfAnnounced'` — in-page\n * self-announcement standards (EIP-6963 on EVM, Wallet Standard on\n * Solana / Sui / …).\n * - `WINDOW_INJECT` → `'windowInjected'` — legacy `window.*` injection.\n *\n * Returns `undefined` for providers whose registration priority does not\n * correspond to a connectable external-wallet source — callers filter these\n * out before emitting catalogue options.\n *\n * @param params.entry - The registry entry to classify.\n * @returns The matching source, or `undefined` if this entry should not\n * surface a `withWalletProvider` option.\n * @not-instrumented\n */\nexport const classifyWithWalletProviderSource = ({\n entry,\n}: ClassifyWithWalletProviderSourceParams):\n | WithWalletProviderSource\n | undefined => {\n const { priority } = entry;\n\n if (priority === WalletProviderPriority.WALLET_SDK) {\n return 'sdk';\n }\n\n if (priority === WalletProviderPriority.WALLET_SELF_ANNOUNCEMENT_STANDARD) {\n return 'selfAnnounced';\n }\n\n if (priority === WalletProviderPriority.WINDOW_INJECT) {\n return 'windowInjected';\n }\n\n return undefined;\n};\n","import type { Chain } from '../../../chain';\n\ntype StripChainSuffixParams = {\n chain: Chain;\n normalizedName: string;\n};\n\n/**\n * Removes the lowercased chain suffix that `normalizeWalletNameWithChain`\n * appends. Used by `findWalletOptionKeyForProviderKey` to recover the wallet\n * book wallet key candidate from a `walletProviderKey`. If the suffix is\n * not present (some chain extensions already bake the chain into the\n * display name), the input is returned unchanged.\n *\n * @param params.chain - The chain whose suffix should be stripped.\n * @param params.normalizedName - The normalized wallet-name-with-chain string.\n * @returns The name with the chain suffix removed, or the input unchanged.\n * @not-instrumented\n */\nexport const stripChainSuffix = ({\n chain,\n normalizedName,\n}: StripChainSuffixParams): string => {\n const suffix = chain.toLowerCase();\n\n if (normalizedName.endsWith(suffix)) {\n return normalizedName.slice(0, -suffix.length);\n }\n\n return normalizedName;\n};\n","/**\n * Normalizes a wallet's self-announced `displayName` into a stable wallet\n * option key. Used by `findWalletOptionKeyForProviderKey` as the off-book\n * fallback — registered providers whose `walletProviderKey` does not\n * resolve to any wallet book entry still surface in the catalogue under a\n * key derived from the name they ship in their metadata.\n *\n * The normalization (lowercase + whitespace-strip) intentionally matches\n * how the legacy wallet book composes its `wallets.<key>` keys, so a\n * self-described provider's option will merge cleanly with its book entry\n * if one ever lands later.\n *\n * Multi-chain registrations of the same wallet (e.g. Phantom announced via\n * EIP-6963 on EVM and via Wallet Standard on Solana) collapse onto the\n * same wallet option through this normalization, since each registration\n * announces the same `displayName`.\n *\n * @param displayName - The provider's `metadata.displayName`.\n * @returns The normalized wallet option key (lowercased, no whitespace).\n * @not-instrumented\n */\nexport const normalizeWalletDisplayName = (displayName: string): string =>\n displayName.toLowerCase().replace(/\\s+/g, '');\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype FindByNameMatchParams = {\n candidate: string;\n walletBook: WalletBookSchema;\n};\n\nconst normalize = (value: string | undefined): string | undefined =>\n value === undefined ? undefined : value.toLowerCase().replace(/\\s+/g, '');\n\n/**\n * Looks for a wallet book entry whose `name` or `shortName` normalizes to\n * the same string as `candidate`. Used as a fallback by\n * `findWalletOptionKeyForProviderKey` for providers whose\n * `walletProviderKey` strips down to a value that does not match any\n * `walletBook.wallets` key directly (e.g. an extension whose display name\n * happens to match the wallet's `shortName` instead of its book key).\n *\n * @param params.candidate - The lowercased, chain-suffix-stripped candidate.\n * @param params.walletBook - The fetched wallet book.\n * @returns The matching wallet book wallet key, or `undefined`.\n * @not-instrumented\n */\nexport const findByNameMatch = ({\n candidate,\n walletBook,\n}: FindByNameMatchParams): string | undefined => {\n for (const [walletKey, wallet] of Object.entries(walletBook.wallets)) {\n if (\n normalize(wallet.name) === candidate ||\n normalize(wallet.shortName) === candidate\n ) {\n return walletKey;\n }\n }\n\n return undefined;\n};\n","import type { WalletBookSchema } from '../../../legacyWalletBook/legacyWalletBook.types';\n\ntype ResolveWalletOptionKeyParams = {\n fallback: string;\n wallet: WalletBookSchema['wallets'][string];\n};\n\n/**\n * Picks the wallet option (group) key for a wallet book wallet. The wallet\n * book carries the group association under a few different field names\n * (`group`, `chainGroup`, `walletGroup`) depending on the wallet's\n * provenance — this helper centralises the lookup. When none of those\n * fields are set, the wallet key itself acts as its own wallet option key.\n *\n * @param params.fallback - Wallet key to return if no group field is set.\n * @param params.wallet - The wallet book wallet entry.\n * @returns The resolved wallet option key.\n * @not-instrumented\n */\nexport const resolveWalletOptionKey = ({\n fallback,\n wallet,\n}: ResolveWalletOptionKeyParams): string =>\n wallet.group ?? wallet.chainGroup ?? wallet.walletGroup ?? fallback;\n","import type { Chain } from '../../chain';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { splitWalletProviderKey } from '../../wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey';\nimport { stripChainSuffix } from '../../wallets/utils/stripChainSuffix/stripChainSuffix';\nimport type { WalletProvider } from '../../wallets/walletProvider/walletProvider.types';\nimport { normalizeWalletDisplayName } from '../normalizeWalletDisplayName/normalizeWalletDisplayName';\nimport { findByNameMatch } from './findByNameMatch/findByNameMatch';\nimport { resolveWalletOptionKey } from './resolveWalletOptionKey/resolveWalletOptionKey';\n\ntype FindWalletOptionKeyForProviderKeyParams = {\n chain: Chain;\n walletBook: WalletBookSchema;\n walletProvider: WalletProvider;\n};\n\n/**\n * Resolves a registered wallet provider to the wallet option key it should\n * be bucketed under. Always returns a key — providers with no wallet book\n * match fall back to their self-announced `metadata.displayName`, so the\n * catalogue surfaces them as self-described tiles instead of silently\n * dropping them.\n *\n * Resolution order (each step short-circuits on first hit):\n *\n * 1. **Direct wallet book lookup with chain suffix** — try\n * `walletBook.wallets[normalizedWalletNameWithChain]` as-is. Wallet\n * book entries are inconsistent about whether they keep the chain\n * suffix (e.g. `metamaskevm`) or strip it (e.g. `metamask`), so try\n * the suffixed form first.\n * 2. **Direct wallet book lookup without chain suffix** — strip the\n * suffix and retry.\n * 3. **Name match heuristic with chain suffix** — scan\n * `walletBook.wallets` for an entry whose normalized `name` or\n * `shortName` equals the suffixed candidate.\n * 4. **Name match heuristic without chain suffix** — same scan on the\n * stripped candidate.\n * 5. **Display-name fallback** — derive a stable key from\n * `walletProvider.metadata.displayName` via\n * {@link normalizeWalletDisplayName}. Multi-chain registrations of the\n * same self-described wallet (e.g. Phantom on EVM and Solana) collapse\n * onto the same tile because each announces the same display name.\n *\n * @param params.chain - The provider's chain (used to strip the suffix).\n * @param params.walletBook - The fetched wallet book.\n * @param params.walletProvider - The registered wallet provider.\n * @returns The wallet option key for this provider.\n * @not-instrumented\n */\nexport const findWalletOptionKeyForProviderKey = ({\n chain,\n walletBook,\n walletProvider,\n}: FindWalletOptionKeyForProviderKeyParams): string => {\n const { normalizedWalletNameWithChain } = splitWalletProviderKey(\n walletProvider.key\n );\n const strippedCandidate = stripChainSuffix({\n chain,\n normalizedName: normalizedWalletNameWithChain,\n });\n const candidates = [normalizedWalletNameWithChain, strippedCandidate];\n\n for (const candidate of candidates) {\n const directHit = walletBook.wallets[candidate];\n\n if (directHit) {\n return resolveWalletOptionKey({\n fallback: candidate,\n wallet: directHit,\n });\n }\n }\n\n for (const candidate of candidates) {\n const nameMatchKey = findByNameMatch({\n candidate,\n walletBook,\n });\n\n if (nameMatchKey) {\n return resolveWalletOptionKey({\n fallback: nameMatchKey,\n wallet: walletBook.wallets[nameMatchKey],\n });\n }\n }\n\n return normalizeWalletDisplayName(walletProvider.metadata.displayName);\n};\n","import { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { hasWalletProviderConnectMethod } from '../../wallets/hasWalletProviderConnectMethod';\nimport type { WalletProviderRegistryEntry } from '../../wallets/walletProviderRegistry';\nimport { classifyWithWalletProviderSource } from '../classifyWithWalletProviderSource/classifyWithWalletProviderSource';\nimport { findWalletOptionKeyForProviderKey } from '../findWalletOptionKeyForProviderKey/findWalletOptionKeyForProviderKey';\nimport type { WithWalletProviderConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * Display override sourced from a registered wallet provider's announced\n * metadata (EIP-6963 / Wallet Standard / vendor SDK). The outer\n * transformer applies these on top of any wallet book group entry — the\n * provider knows its own brand best, so `name` + `iconUrl` here win\n * over the wallet book's values when both exist.\n */\nexport type WithWalletProviderDisplayOverride = {\n iconUrl: string;\n name: string;\n};\n\n/**\n * One `WithWalletProviderConnectionOption` paired with the wallet option\n * key it should be bucketed under, plus the provider's self-announced\n * display metadata. The outer transformer groups by `walletOptionKey` and\n * uses `displayOverride` to build the wallet option shell, with provider\n * precedence over the wallet book's display fields.\n */\nexport type WithWalletProviderOptionForWalletOption = {\n displayOverride: WithWalletProviderDisplayOverride;\n option: WithWalletProviderConnectionOption;\n walletOptionKey: string;\n};\n\ntype BuildWithWalletProviderOptionsParams = {\n entries: WalletProviderRegistryEntry[];\n walletBook: WalletBookSchema;\n};\n\n/**\n * Converts each registered wallet provider entry into a\n * `WithWalletProviderConnectionOption` paired with its target wallet\n * option key and the provider's display override. Every classifiable\n * entry surfaces in the catalogue; the outer transformer uses the\n * carried `displayOverride` to override any wallet book branding for\n * that key (provider self-announcement wins over book).\n *\n * Entries whose registration priority is not recognised by\n * `classifyWithWalletProviderSource` are dropped from the catalogue and\n * an error is logged so Datadog surfaces the unknown registration path —\n * in production this should never happen, every chain extension is\n * expected to register with one of the documented priorities.\n *\n * @param params.entries - Snapshot of the registry's entries.\n * @param params.walletBook - The fetched wallet book.\n * @param client - The Dynamic client (used for logging unclassifiable entries).\n * @returns An array of tagged options, in input order.\n * @not-instrumented\n */\nexport const buildWithWalletProviderOptions = (\n { entries, walletBook }: BuildWithWalletProviderOptionsParams,\n client: DynamicClient\n): WithWalletProviderOptionForWalletOption[] => {\n const result: WithWalletProviderOptionForWalletOption[] = [];\n\n for (const entry of entries) {\n if (!hasWalletProviderConnectMethod({ walletProvider: entry.walletProvider })) {\n continue;\n }\n\n const source = classifyWithWalletProviderSource({ entry });\n\n if (!source) {\n getCore(client).logger.error(\n 'buildWithWalletProviderOptions: registered wallet provider has an unrecognised priority — unable to identify how this wallet was registered',\n {\n chain: entry.walletProvider.chain,\n displayName: entry.walletProvider.metadata.displayName,\n priority: entry.priority,\n walletProviderKey: entry.walletProvider.key,\n walletProviderType: entry.walletProvider.walletProviderType,\n }\n );\n continue;\n }\n\n const walletOptionKey = findWalletOptionKeyForProviderKey({\n chain: entry.walletProvider.chain,\n walletBook,\n walletProvider: entry.walletProvider,\n });\n\n result.push({\n displayOverride: {\n iconUrl: entry.walletProvider.metadata.icon,\n name: entry.walletProvider.metadata.displayName,\n },\n option: {\n chain: entry.walletProvider.chain,\n source,\n type: 'withWalletProvider',\n walletProviderKey: entry.walletProvider.key,\n },\n walletOptionKey,\n });\n }\n\n return result;\n};\n","/**\n * Wallet option keys `getWalletOptionsCatalogue` drops before returning.\n * Curated, product-level suppression.\n *\n * Example: Base Account SDK is the recommended entry point for\n * Coinbase-managed users, so the legacy Coinbase Wallet entries are\n * suppressed in favor of the SDK-backed `baseaccount` tile. Both the\n * wallet book group key (`coinbase`) and the normalized display-name\n * key (`coinbasewallet`) are listed so suppression holds regardless of\n * how the resolver lands on a key.\n *\n * Used in: `getWalletOptionsCatalogue`.\n */\nexport const EXCLUDED_WALLET_OPTION_KEYS: ReadonlySet<string> = new Set([\n 'coinbase',\n 'coinbasewallet',\n]);\n","import type { WithWalletProviderDisplayOverride } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * A `connectionOption` tagged with the wallet option key it belongs under.\n * Transformer outputs produce these; the catalogue groups them by\n * `walletOptionKey` before building wallet option shells.\n *\n * `displayOverride` is set only by the `withWalletProvider` transformer,\n * carrying the provider's self-announced `name` + `iconUrl`. The shell\n * builder applies it on top of any wallet book entry — provider\n * metadata wins over book branding.\n */\nexport type ConnectionOptionForWalletOption = {\n displayOverride?: WithWalletProviderDisplayOverride;\n option: WalletConnectionOption;\n walletOptionKey: string;\n};\n\n/**\n * Bucket of grouped options for a single wallet option key, plus the\n * first-seen display override (if any). Returned by\n * `groupOptionsByWalletOption` for the catalogue to feed into the shell\n * builder.\n */\nexport type GroupedWalletOption = {\n connectionOptions: WalletConnectionOption[];\n displayOverride?: WithWalletProviderDisplayOverride;\n};\n\ntype GroupOptionsByWalletOptionParams = {\n options: ConnectionOptionForWalletOption[];\n};\n\n/**\n * Buckets tagged connection options by their wallet option key. Preserves\n * first-seen order so that the caller's choice of\n * `walletOptionOrdering: 'relevance'` naturally inherits the upstream input\n * order (wallet book order for walletConnect/inAppBrowser/installation,\n * registry order for withWalletProvider).\n *\n * Carries through the first-seen `displayOverride` per wallet option\n * key, so the shell builder can apply provider-announced metadata on\n * top of any wallet book entry.\n *\n * @param params.options - The tagged options to group.\n * @returns A map from wallet option key to its grouped option bucket,\n * iterable in first-seen order.\n * @not-instrumented\n */\nexport const groupOptionsByWalletOption = ({\n options,\n}: GroupOptionsByWalletOptionParams): Map<string, GroupedWalletOption> => {\n const map = new Map<string, GroupedWalletOption>();\n\n for (const { displayOverride, option, walletOptionKey } of options) {\n const existing = map.get(walletOptionKey);\n\n if (existing) {\n existing.connectionOptions.push(option);\n if (!existing.displayOverride && displayOverride) {\n existing.displayOverride = displayOverride;\n }\n } else {\n map.set(walletOptionKey, {\n connectionOptions: [option],\n displayOverride,\n });\n }\n }\n\n return map;\n};\n","import type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\n/**\n * Numeric priority for each `WalletConnectionOption` type. Lower values rank\n * first. Used to sort each wallet option's `connectionOptions` array so the\n * best connection path lands at index 0. Has no bearing on how the outer\n * wallet-option list is ordered — that's controlled by\n * `WalletOptionOrdering`.\n *\n * `withWalletProvider > walletConnect / metamaskSdkUri > inAppBrowser`\n */\nconst CONNECTION_OPTION_PRIORITY: Record<WalletConnectionOption['type'], number> = {\n inAppBrowser: 2,\n metamaskSdkUri: 1,\n walletConnect: 1,\n withWalletProvider: 0,\n};\n\ntype GetConnectionOptionPriorityParams = {\n option: WalletConnectionOption;\n};\n\n/**\n * Returns the numeric priority of a `WalletConnectionOption` for sorting.\n * Lower numbers rank first.\n *\n * @param params.option - The connection option to inspect.\n * @returns The numeric priority — lower is better.\n * @not-instrumented\n */\nexport const getConnectionOptionPriority = ({\n option,\n}: GetConnectionOptionPriorityParams): number =>\n CONNECTION_OPTION_PRIORITY[option.type];\n","import { getConnectionOptionPriority } from '../getConnectionOptionPriority/getConnectionOptionPriority';\nimport type { WalletConnectionOption } from '../walletOptionsCatalogue.types';\n\ntype SortConnectionOptionsParams = {\n options: WalletConnectionOption[];\n};\n\n/**\n * Sorts a wallet option's `connectionOptions` so the most preferred option lands at\n * index 0. Primary sort is by option-type priority\n * (`withWalletProvider` > URI deeplink > `inAppBrowser`);\n * within a type, ties break alphabetically by `chain` for deterministic\n * output across calls.\n *\n * Returns a new array — the input is not mutated.\n *\n * @param params.options - The options to sort.\n * @returns A new array in priority order.\n * @not-instrumented\n */\nexport const sortConnectionOptions = ({\n options,\n}: SortConnectionOptionsParams): WalletConnectionOption[] =>\n [...options].sort((a, b) => {\n const priorityDelta =\n getConnectionOptionPriority({ option: a }) -\n getConnectionOptionPriority({ option: b });\n\n if (priorityDelta !== 0) {\n return priorityDelta;\n }\n\n return a.chain.localeCompare(b.chain);\n });\n","/**\n * Hand-curated list of wallet book group keys that should surface at the top\n * of catalogue listings. Lower index = higher priority. Anything not in this\n * list falls through to the secondary sort (alphabetical by name).\n *\n * Used by `sortWalletOptions` (relevance mode) and by the react-demo's\n * WalletConnect picker. Keep both in sync when adding entries.\n */\nexport const PRIORITY_WALLET_KEYS: readonly string[] = [\n 'metamask',\n 'coinbase',\n 'baseaccount',\n 'phantom',\n 'magiceden',\n 'trust',\n 'okxwallet',\n 'rainbow',\n 'argentx',\n 'backpack',\n 'xverse',\n 'onekey',\n 'solflare',\n 'braavos',\n 'brave',\n 'unisat',\n 'bitgetwallet',\n 'coin98',\n];\n","import { PRIORITY_WALLET_KEYS } from '../../legacyWalletBook/priorityWalletKeys/priorityWalletKeys';\nimport type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype GetPriorityIndexParams = {\n walletOption: WalletOption;\n};\n\n/**\n * Returns the index of a wallet option in `PRIORITY_WALLET_KEYS`, or\n * `Number.POSITIVE_INFINITY` when the wallet is not in the hand-curated\n * priority list. Lower index = higher priority.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns Numeric priority index — lower is better.\n * @not-instrumented\n */\nexport const getPriorityIndex = ({\n walletOption,\n}: GetPriorityIndexParams): number => {\n const index = PRIORITY_WALLET_KEYS.indexOf(walletOption.key);\n\n return index === -1 ? Number.POSITIVE_INFINITY : index;\n};\n","import { getPriorityIndex } from '../getPriorityIndex/getPriorityIndex';\nimport type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype CompareByRelevanceParams = {\n a: WalletOption;\n b: WalletOption;\n};\n\n/**\n * Compares two wallet options for relevance ordering: priority-list index\n * first, then alphabetical-by-name as the tie-break. Suitable for passing\n * straight to `Array.prototype.sort`.\n *\n * @param params.a - First wallet option.\n * @param params.b - Second wallet option.\n * @returns Negative when `a` ranks first, positive when `b` ranks first.\n * @not-instrumented\n */\nexport const compareByRelevance = ({\n a,\n b,\n}: CompareByRelevanceParams): number => {\n const aIndex = getPriorityIndex({ walletOption: a });\n const bIndex = getPriorityIndex({ walletOption: b });\n\n if (aIndex !== bIndex) {\n return aIndex - bIndex;\n }\n\n return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });\n};\n","import type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype HasAnyConnectionOptionParams = {\n walletOption: WalletOption;\n};\n\n/**\n * True when the wallet option has at least one connection — i.e. the user\n * can sign in right now. Install-only wallet options surface in the\n * catalogue too (they carry `installationUrls`) but have an empty\n * `connectionOptions` array; this predicate distinguishes them from\n * actually connectable wallets in the relevance sort.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns True when `connectionOptions` is non-empty.\n * @not-instrumented\n */\nexport const hasAnyConnectionOption = ({\n walletOption,\n}: HasAnyConnectionOptionParams): boolean =>\n walletOption.connectionOptions.length > 0;\n","import type { WalletOption } from '../walletOptionsCatalogue.types';\n\ntype HasInstalledProviderParams = {\n walletOption: WalletOption;\n};\n\n/**\n * True when the wallet option has a `withWalletProvider` connection — i.e.\n * the user already has the wallet available in the page (browser extension,\n * Wallet Standard announcement, window injection, or an SDK-backed provider\n * one of our chain extensions registered). `connectionOptions` is\n * pre-sorted, so a registered provider always sits at index 0 when present.\n *\n * @param params.walletOption - The wallet option to inspect.\n * @returns True when an installed provider is available.\n * @not-instrumented\n */\nexport const hasInstalledProvider = ({\n walletOption,\n}: HasInstalledProviderParams): boolean =>\n walletOption.connectionOptions[0]?.type === 'withWalletProvider';\n","import { compareByRelevance } from '../compareByRelevance/compareByRelevance';\nimport { hasAnyConnectionOption } from '../hasAnyConnectionOption/hasAnyConnectionOption';\nimport { hasInstalledProvider } from '../hasInstalledProvider/hasInstalledProvider';\nimport type {\n WalletOption,\n WalletOptionOrdering,\n} from '../walletOptionsCatalogue.types';\n\ntype SortWalletOptionsParams = {\n ordering: WalletOptionOrdering;\n walletOptions: WalletOption[];\n};\n\n/**\n * Sorts the outer wallet-option list. This is the only ordering controlled\n * by the customer; the inner `connectionOptions` array of each wallet\n * option is ordered separately by `sortConnectionOptions` using a fixed\n * option-type priority.\n *\n * - `'relevance'` (default): bucket wallet options into three tiers, in\n * this order:\n * 1. **Installed provider** — user already has the wallet available\n * (`withWalletProvider` at index 0).\n * 2. **Connectable** — has at least one connection (URI deeplink\n * or `inAppBrowser`) but no installed provider.\n * 3. **Install-only** — no connection at all; only `installationUrls`.\n * Within each tier, rank by the hand-curated {@link PRIORITY_WALLET_KEYS}\n * list (MetaMask, Coinbase, Phantom, …); unknown wallets fall through to\n * alphabetical-by-name order at the tail of their tier.\n * - `'alphabetical'`: case-insensitive sort by wallet option `name`,\n * without bucketing.\n *\n * Returns a new array — the input is not mutated.\n *\n * @param params.walletOptions - The wallet options to sort.\n * @param params.ordering - The requested ordering.\n * @returns A new array in the requested order.\n * @not-instrumented\n */\nexport const sortWalletOptions = ({\n walletOptions,\n ordering,\n}: SortWalletOptionsParams): WalletOption[] => {\n if (ordering === 'alphabetical') {\n return [...walletOptions].sort((a, b) =>\n a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })\n );\n }\n\n const installed: WalletOption[] = [];\n const connectable: WalletOption[] = [];\n const installOnly: WalletOption[] = [];\n\n for (const walletOption of walletOptions) {\n if (hasInstalledProvider({ walletOption })) {\n installed.push(walletOption);\n } else if (hasAnyConnectionOption({ walletOption })) {\n connectable.push(walletOption);\n } else {\n installOnly.push(walletOption);\n }\n }\n\n installed.sort((a, b) => compareByRelevance({ a, b }));\n connectable.sort((a, b) => compareByRelevance({ a, b }));\n installOnly.sort((a, b) => compareByRelevance({ a, b }));\n\n return [...installed, ...connectable, ...installOnly];\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { fetchLegacyWalletBook } from '../../legacyWalletBook/fetchLegacyWalletBook';\nimport type { WalletBookSchema } from '../../legacyWalletBook/legacyWalletBook.types';\nimport { getWalletProviderRegistry } from '../../wallets/walletProviderRegistry';\nimport { buildInAppBrowserOptions } from '../buildInAppBrowserOptions/buildInAppBrowserOptions';\nimport { buildInstallationUrlsByWalletOptionKey } from '../buildInstallationUrlsByWalletOptionKey/buildInstallationUrlsByWalletOptionKey';\nimport { buildMetaMaskSdkUriOptions } from '../buildMetaMaskSdkUriOptions/buildMetaMaskSdkUriOptions';\nimport { buildWalletConnectOptions } from '../buildWalletConnectOptions/buildWalletConnectOptions';\nimport { buildWalletOption } from '../buildWalletOption/buildWalletOption';\nimport { buildWithWalletProviderOptions } from '../buildWithWalletProviderOptions/buildWithWalletProviderOptions';\nimport { EXCLUDED_WALLET_OPTION_KEYS } from '../excludedWalletOptionKeys/excludedWalletOptionKeys';\nimport { groupOptionsByWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport type { ConnectionOptionForWalletOption } from '../groupOptionsByWalletOption/groupOptionsByWalletOption';\nimport { sortConnectionOptions } from '../sortConnectionOptions/sortConnectionOptions';\nimport { sortWalletOptions } from '../sortWalletOptions/sortWalletOptions';\nimport type {\n GetWalletOptionsCatalogueParams,\n InstallationUrls,\n WalletOption,\n WalletOptionsCatalogue,\n} from '../walletOptionsCatalogue.types';\n\nconst EMPTY_WALLET_BOOK: WalletBookSchema = { groups: {}, wallets: {} };\n\n/**\n * Returns the catalogue of external wallet options a user can sign in\n * with through this client. Always includes installed wallet providers;\n * pass `includeMobileOptions: true` to additionally surface\n * WalletConnect, in-app-browser, and install links.\n *\n * Pass `excludedConnectionOptionTypes` to drop specific connection types\n * from the catalogue (e.g. `['inAppBrowser']` on desktop). Wallets whose\n * only connection was an excluded type fall through to the install-only\n * tier of the relevance ordering.\n *\n * @param [params] - Inclusion flag + ordering preference + exclusions.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the wallet options catalogue.\n * @not-instrumented\n */\nexport const getWalletOptionsCatalogue = async (\n params: GetWalletOptionsCatalogueParams = {},\n client = getDefaultClient()\n): Promise<WalletOptionsCatalogue> => {\n const includeMobileOptions = params.includeMobileOptions ?? false;\n const walletOptionOrdering = params.walletOptionOrdering ?? 'relevance';\n const excludedConnectionOptionTypes = new Set(\n params.excludedConnectionOptionTypes ?? []\n );\n\n const walletBook = includeMobileOptions\n ? await fetchLegacyWalletBook(client)\n : EMPTY_WALLET_BOOK;\n\n const allConnectionOptions: ConnectionOptionForWalletOption[] = [];\n\n if (!excludedConnectionOptionTypes.has('withWalletProvider')) {\n const entries = getWalletProviderRegistry(client).listProviderEntries();\n allConnectionOptions.push(\n ...buildWithWalletProviderOptions({ entries, walletBook }, client)\n );\n }\n\n if (includeMobileOptions) {\n // Each URI-deeplink discriminator has its own builder with its own\n // eligibility filter (WC requires `sign_v2`; MM SDK URI does not).\n // Keeping them separate means excluding one discriminator never\n // accidentally gates the other.\n if (!excludedConnectionOptionTypes.has('walletConnect')) {\n allConnectionOptions.push(...buildWalletConnectOptions({ walletBook }));\n }\n if (!excludedConnectionOptionTypes.has('metamaskSdkUri')) {\n allConnectionOptions.push(...buildMetaMaskSdkUriOptions({ walletBook }));\n }\n if (!excludedConnectionOptionTypes.has('inAppBrowser')) {\n allConnectionOptions.push(...buildInAppBrowserOptions({ walletBook }));\n }\n }\n\n const installationUrlsByKey: Map<string, InstallationUrls> =\n includeMobileOptions\n ? buildInstallationUrlsByWalletOptionKey({ walletBook })\n : new Map();\n\n const grouped = groupOptionsByWalletOption({\n options: allConnectionOptions,\n });\n // Union keeps connection-bearing entries first (in their first-seen order)\n // and appends install-only entries — wallets the user can install but\n // cannot connect to yet via any other channel.\n const allWalletOptionKeys = new Set([\n ...grouped.keys(),\n ...installationUrlsByKey.keys(),\n ]);\n const walletOptions: WalletOption[] = [];\n\n for (const walletOptionKey of allWalletOptionKeys) {\n if (EXCLUDED_WALLET_OPTION_KEYS.has(walletOptionKey)) {\n continue;\n }\n\n const groupedEntry = grouped.get(walletOptionKey);\n const connectionOptions = groupedEntry\n ? sortConnectionOptions({ options: groupedEntry.connectionOptions })\n : [];\n\n walletOptions.push(\n buildWalletOption({\n connectionOptions,\n displayOverride: groupedEntry?.displayOverride,\n installationUrls: installationUrlsByKey.get(walletOptionKey),\n walletBook,\n walletOptionKey,\n })\n );\n }\n\n return sortWalletOptions({ ordering: walletOptionOrdering, walletOptions });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport type { OTPVerification } from '../../otp/otp.types';\nimport type { UpdateUserFields } from '../user.types';\n\ntype UpdateUserParams = {\n userFields: UpdateUserFields;\n};\n\n/**\n * Updates the current user's profile information.\n *\n * This function allows updating various user fields such as email, name,\n * and other profile information. Some updates may require OTP verification,\n * like email and phone number.\n *\n * @param params.userFields - The user fields to update.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to OTP verification details if verification is required, or undefined.\n * @instrumented\n * @redact-params\n */\nexport const updateUser = async (\n { userFields }: UpdateUserParams,\n client = getDefaultClient()\n): Promise<OTPVerification | undefined> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n const response = await apiClient.updateSelf({\n environmentId: core.environmentId,\n userFields,\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n if (response.emailVerification) {\n return {\n email: response.emailVerification.email,\n verificationUUID: response.emailVerification.verificationUUID,\n };\n }\n\n if (response.smsVerification) {\n return {\n isoCountryCode: response.smsVerification.isoCountryCode,\n phoneCountryCode: response.smsVerification.phoneCountryCode,\n phoneNumber: response.smsVerification.phoneNumber,\n verificationUUID: response.smsVerification.verificationUUID,\n };\n }\n\n return undefined;\n};\n","import { MfaBackupCodeAcknowledgement } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { updateUser } from '../../user/updateUser';\n\n/**\n * Acknowledges that the user has viewed and saved their MFA recovery codes.\n *\n * This function marks the recovery codes as acknowledged, indicating that\n * the user has properly backed up their MFA recovery codes for account recovery.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the acknowledgment is complete.\n * @instrumented\n */\nexport const acknowledgeRecoveryCodes = async (client = getDefaultClient()) => {\n return updateUser(\n {\n userFields: {\n mfaBackupCodeAcknowledgement: MfaBackupCodeAcknowledgement.Complete,\n },\n },\n client\n );\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticateMfaRecoveryCodeParams = {\n code: string;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaTokenOptions?: CreateMfaToken;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using an MFA recovery code.\n *\n * This function allows users to bypass normal MFA requirements by using\n * one of their backup recovery codes when none of the registered MFA methods are available.\n *\n * @param params.code - The recovery code to authenticate with.\n * @param [params.createMfaTokenOptions] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @not-instrumented\n */\nexport const authenticateMfaRecoveryCode = async (\n { code, createMfaTokenOptions, requestedScopes }: AuthenticateMfaRecoveryCodeParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.authMfaRecovery({\n environmentId: core.environmentId,\n mFAAuthRecoveryDevicePostRequest: {\n code,\n createMfaToken: createMfaTokenOptions,\n requestedScopes,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import type { GetPasskeyAuthenticationOptionsResponse } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\nexport type GetPasskeyAuthenticationOptionsParams = {\n relatedOriginRpId?: string;\n};\n\n/** @not-instrumented */\nexport const getPasskeyAuthenticationOptions = async (\n { relatedOriginRpId }: GetPasskeyAuthenticationOptionsParams = {},\n client: DynamicClient\n): Promise<PublicKeyCredentialRequestOptionsJSON> => {\n const core = getCore(client);\n\n const apiClient = createApiClient({}, client);\n\n const options: GetPasskeyAuthenticationOptionsResponse =\n await apiClient.getPasskeyAuthenticationOptions({\n environmentId: core.environmentId,\n relatedOriginRpId,\n });\n\n return options as PublicKeyCredentialRequestOptionsJSON;\n};\n","import type {\n CreateMfaToken,\n PasskeyAuthRequest,\n TokenScope,\n} from '@dynamic-labs/sdk-api-core';\nimport type { AuthenticationResponseJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\n\ntype ServerAuthenticatePasskeyParams = {\n authentication: AuthenticationResponseJSON;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaToken?: CreateMfaToken;\n requestedScopes?: TokenScope[];\n};\n\n/** @not-instrumented */\nexport const serverAuthenticatePasskey = async (\n { authentication, createMfaToken, requestedScopes }: ServerAuthenticatePasskeyParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.authenticateMfaPasskeyDevice({\n environmentId: core.environmentId,\n passkeyAuthRequest: {\n ...authentication,\n createMfaToken,\n requestedScopes,\n response: {\n ...authentication.response,\n clientDataJson: authentication.response.clientDataJSON,\n },\n } as PasskeyAuthRequest,\n });\n\n return response;\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\nimport type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { NoPasskeyCredentialsFoundError } from '../../../errors/NoPasskeyCredentialsFoundError';\nimport { NoWebAuthNSupportError } from '../../../errors/NoWebAuthNSupportError';\nimport { getPasskeyAuthenticationOptions } from '../../auth/passkeys/getPasskeyAuthenticationOptions';\nimport { serverAuthenticatePasskey } from '../../auth/passkeys/serverAuthenticatePasskey';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticatePasskeyMFAParams = {\n /** @deprecated Use `requestedScopes` instead. */\n createMfaToken?: CreateMfaToken;\n relatedOriginRpId?: string;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using a passkey for multi-factor authentication.\n *\n * This function prompts the user to authenticate with their registered\n * passkey to complete an MFA challenge and obtain an MFA token.\n *\n * @param [params.createMfaToken] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @throws NoWebAuthNSupportError If WebAuthn is not supported by the browser.\n * @throws NoPasskeyCredentialsFoundError If no passkey credentials are found.\n * @not-instrumented\n */\nexport const authenticatePasskeyMFA = async (\n {\n createMfaToken,\n relatedOriginRpId,\n requestedScopes,\n }: AuthenticatePasskeyMFAParams = {},\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n try {\n if (!core.passkey.isSupported()) {\n throw new NoWebAuthNSupportError();\n }\n\n const options = await getPasskeyAuthenticationOptions(\n { relatedOriginRpId },\n client\n );\n const allowCredentials = options.allowCredentials?.map((credential) => ({\n ...credential,\n type: 'public-key' as const,\n }));\n\n if (!allowCredentials?.length) {\n throw new NoPasskeyCredentialsFoundError();\n }\n\n // Ensure allowCredentials has the required type property\n const formattedOptions: PublicKeyCredentialRequestOptionsJSON = {\n ...options,\n allowCredentials,\n };\n\n const authentication = await core.passkey.authenticate({\n optionsJSON: formattedOptions,\n });\n\n const response = await serverAuthenticatePasskey(\n { authentication, createMfaToken, requestedScopes },\n client\n );\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import type { CreateMfaToken, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { emitEvent } from '../../clientEvents';\n\ntype AuthenticateTotpMfaDeviceParams = {\n code: string;\n /** @deprecated Use `requestedScopes` instead. */\n createMfaTokenOptions?: CreateMfaToken;\n deviceId?: string;\n requestedScopes?: TokenScope[];\n};\n\n/**\n * Authenticates using a TOTP (Time-based One-Time Password) MFA device.\n *\n * This function validates a TOTP code from an authenticator app and returns\n * an MFA token upon successful authentication.\n *\n * @param params.code - The 6-digit TOTP code from the authenticator app.\n * @param [params.deviceId] - The ID of the specific TOTP device to authenticate with.\n * @param [params.createMfaTokenOptions] - **Deprecated**: use `requestedScopes` instead. Optional configuration for MFA token creation.\n * @param [params.requestedScopes] - Optional scopes to request an elevated access token instead of an MFA token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the MFA authentication response.\n * @not-instrumented\n */\nexport const authenticateTotpMfaDevice = async (\n { deviceId, code, createMfaTokenOptions, requestedScopes }: AuthenticateTotpMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n try {\n const response = await apiClient.authMfaTotpDevice({\n environmentId: core.environmentId,\n mFAAuthTotpDevicePostRequest: {\n code,\n createMfaToken: createMfaTokenOptions,\n id: deviceId,\n requestedScopes,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n\n emitEvent(\n {\n args: { deviceId, mfaToken: response.mfaToken },\n event: 'mfaCompletionSuccess',\n },\n client\n );\n\n return response;\n } catch (error) {\n emitEvent(\n {\n args: { deviceId, error },\n event: 'mfaCompletionFailure',\n },\n client\n );\n throw error;\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Generates new MFA recovery codes for the current user.\n *\n * This function creates a fresh set of backup codes that can be used\n * to bypass MFA requirements if none of the registered MFA methods are available.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the newly generated recovery codes.\n * @instrumented\n * @redact-params\n */\nexport const createNewMfaRecoveryCodes = async (\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.createNewRecoveryCodes({\n environmentId: core.environmentId,\n });\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { getElevatedAccessToken } from '../../auth/getElevatedAccessToken';\nimport { createApiClient } from '../../apiClient';\n\ntype DeleteMfaDeviceParams = {\n deviceId: string;\n mfaAuthToken?: string;\n};\n\n/**\n * Deletes a specific MFA device from the user's account.\n *\n * When an elevated access token for `credential:unlink` is available,\n * it is sent via the `x-dyn-elevated-access-token` header and the\n * MFA auth token is not required. Otherwise, `mfaAuthToken` must be\n * provided for backward compatibility with the legacy MFA flow.\n *\n * @param params.deviceId - The unique identifier of the MFA device to delete.\n * @param params.mfaAuthToken - The MFA authentication token. Optional when using elevated access tokens.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the MFA device is successfully deleted.\n * @instrumented\n */\nexport const deleteMfaDevice = async (\n { deviceId, mfaAuthToken }: DeleteMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n\n assertDefined(deviceId, 'deviceId is required');\n\n // Check without consuming — createApiClient handles actual retrieval.\n const hasElevatedToken = getElevatedAccessToken(\n { consume: false, scope: TokenScope.Credentialunlink },\n client\n );\n\n if (!hasElevatedToken) {\n assertDefined(mfaAuthToken, 'mfaAuthToken is required');\n }\n\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentialunlink },\n client\n );\n\n return apiClient.deleteMfaDevice({\n environmentId: core.environmentId,\n mfaDeviceId: deviceId,\n // The generated SDK types xMfaAuthToken as required (string, not string?).\n // When using elevated tokens the backend skips this header entirely, but\n // we still need to satisfy the type. Once the OpenAPI spec marks it optional\n // this fallback can be removed.\n xMfaAuthToken: mfaAuthToken ?? '',\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Retrieves all MFA devices registered for the current user.\n *\n * This function fetches the list of multi-factor authentication devices\n * associated with the user's account, such as TOTP authenticators.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an array of the user's registered MFA devices.\n * @not-instrumented\n */\nexport const getMfaDevices = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const { devices } = await apiClient.getUserMfaDevices({\n environmentId: core.environmentId,\n });\n\n return devices;\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Retrieves the current MFA recovery codes for the user.\n *\n * This function fetches the backup codes that can be used to bypass\n * MFA requirements if none of the registered MFA methods are available.\n * If user doesn't have any recovery codes, it will create them,\n * otherwise it will return the existing ones.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the user's MFA recovery codes.\n * @not-instrumented\n */\nexport const getMfaRecoveryCodes = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getRecoveryCodes({\n environmentId: core.environmentId,\n });\n};\n","import { MfaBackupCodeAcknowledgement } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\n\n/**\n * Checks if the user is still pending acknowledgment of their MFA recovery codes.\n *\n * This function determines whether the user has been presented with recovery\n * codes that they have not yet acknowledged as saved or backed up.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if recovery codes are pending acknowledgment, false otherwise.\n * @not-instrumented\n */\nexport const isPendingRecoveryCodesAcknowledgment = (\n client = getDefaultClient()\n) => {\n const user = client.user;\n\n assertDefined(user, 'User not logged in');\n\n return (\n user.mfaBackupCodeAcknowledgement === MfaBackupCodeAcknowledgement.Pending\n );\n};\n","import { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\n\n/**\n * Registers a new TOTP (Time-based One-Time Password) MFA device.\n *\n * This function initiates the registration of a TOTP authenticator app\n * (like Google Authenticator or Authy) for multi-factor authentication.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the TOTP registration response containing setup information,\n * like the secret key and the OTP Auth URI.\n * @instrumented\n */\nexport const registerTotpMfaDevice = async (client = getDefaultClient()) => {\n const core = getCore(client);\n const apiClient = createApiClient(\n { elevatedAccessTokenScope: TokenScope.Credentiallink },\n client\n );\n\n return apiClient.registerTotpMfaDevice({\n environmentId: core.environmentId,\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { createApiClient } from '../../apiClient';\n\ntype SetDefaultMfaDeviceParams = {\n deviceId: string;\n};\n\n/**\n * Sets the default MFA device for the current user.\n *\n * This function designates a specific MFA TOTP device as the primary method\n * for multi-factor authentication challenges.\n *\n * @param params.deviceId - The unique identifier of the MFA device to set as default.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the default MFA device is successfully set.\n * @instrumented\n */\nexport const setDefaultMfaDevice = async (\n { deviceId }: SetDefaultMfaDeviceParams,\n client = getDefaultClient()\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n assertDefined(deviceId, 'deviceId is required');\n\n // All that this endpoint does is set the default device to the one provided.\n return apiClient.updateUserMfaDevice({\n environmentId: core.environmentId,\n mfaDeviceId: deviceId,\n });\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { consumeCaptchaToken } from '../../captcha/consumeCaptchaToken';\nimport type { OTPVerification } from '../otp.types';\n\nexport type SendEmailOTPParams = {\n email: string;\n};\n\n/**\n * Sends a one-time password (OTP) to the specified email address.\n *\n * Once you have the OTP code, you should then use `verifyOTP` to verify it and complete the authentication process.\n *\n * @param params.email - The email address to send the OTP to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an OTPVerification object containing the email and verification UUID.\n * @instrumented\n * @redact-params\n */\nexport const sendEmailOTP = async (\n { email }: SendEmailOTPParams,\n client = getDefaultClient()\n): Promise<OTPVerification> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const { verificationUUID } = await apiClient.createEmailVerification({\n emailVerificationCreateRequest: {\n captchaToken: consumeCaptchaToken(client),\n email,\n },\n environmentId: core.environmentId,\n });\n\n return { email, verificationUUID };\n};\n","// Source:\n// https://github.com/dynamic-labs/redcoast/blob/main/apps/dashboard/src/app/routes/Configurations/Providers/components/SmsProviderSection/utils/countries.ts\n\n// these are the countries was populated based on the wikipedia page\n// referenced in twilio's docs: https://www.twilio.com/docs/voice/api/dialingpermissions-country-resource\n// and this doc for country codes: https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.pdf\nexport type CountryCode =\n | 'AC'\n | 'AD'\n | 'AE'\n | 'AF'\n | 'AG'\n | 'AI'\n | 'AL'\n | 'AM'\n | 'AO'\n | 'AR'\n | 'AS'\n | 'AT'\n | 'AU'\n | 'AW'\n | 'AZ'\n | 'BA'\n | 'BB'\n | 'BD'\n | 'BE'\n | 'BF'\n | 'BG'\n | 'BH'\n | 'BI'\n | 'BJ'\n | 'BM'\n | 'BN'\n | 'BO'\n | 'BR'\n | 'BS'\n | 'BT'\n | 'BW'\n | 'BY'\n | 'BZ'\n | 'CA'\n | 'CD'\n | 'CF'\n | 'CG'\n | 'CH'\n | 'CI'\n | 'CK'\n | 'CL'\n | 'CM'\n | 'CN'\n | 'CO'\n | 'CR'\n | 'CU'\n | 'CV'\n | 'CW'\n | 'CY'\n | 'CZ'\n | 'DE'\n | 'DJ'\n | 'DK'\n | 'DM'\n | 'DO'\n | 'DZ'\n | 'EC'\n | 'EE'\n | 'EG'\n | 'ER'\n | 'ES'\n | 'ET'\n | 'FI'\n | 'FJ'\n | 'FK'\n | 'FM'\n | 'FO'\n | 'FR'\n | 'GA'\n | 'GB'\n | 'GD'\n | 'GE'\n | 'GF'\n | 'GG'\n | 'GH'\n | 'GI'\n | 'GL'\n | 'GM'\n | 'GN'\n | 'GP'\n | 'GQ'\n | 'GR'\n | 'GT'\n | 'GU'\n | 'GW'\n | 'GY'\n | 'HK'\n | 'HN'\n | 'HR'\n | 'HT'\n | 'HU'\n | 'IC'\n | 'ID'\n | 'IE'\n | 'IL'\n | 'IM'\n | 'IN'\n | 'IQ'\n | 'IR'\n | 'IS'\n | 'IT'\n | 'JM'\n | 'JO'\n | 'JP'\n | 'KE'\n | 'KG'\n | 'KH'\n | 'KI'\n | 'KM'\n | 'KN'\n | 'KP'\n | 'KR'\n | 'KW'\n | 'KY'\n | 'LA'\n | 'LB'\n | 'LC'\n | 'LI'\n | 'LK'\n | 'LR'\n | 'LS'\n | 'LT'\n | 'LU'\n | 'LV'\n | 'LY'\n | 'MA'\n | 'MC'\n | 'MD'\n | 'ME'\n | 'MG'\n | 'MH'\n | 'MK'\n | 'ML'\n | 'MM'\n | 'MN'\n | 'MO'\n | 'MP'\n | 'MQ'\n | 'MR'\n | 'MS'\n | 'MT'\n | 'MU'\n | 'MV'\n | 'MW'\n | 'MX'\n | 'MY'\n | 'MZ'\n | 'NA'\n | 'NC'\n | 'NE'\n | 'NF'\n | 'NG'\n | 'NI'\n | 'NL'\n | 'NO'\n | 'NP'\n | 'NU'\n | 'NZ'\n | 'OM'\n | 'PA'\n | 'PE'\n | 'PF'\n | 'PG'\n | 'PH'\n | 'PK'\n | 'PL'\n | 'PM'\n | 'PR'\n | 'PS'\n | 'PT'\n | 'PW'\n | 'PY'\n | 'QA'\n | 'RE'\n | 'RO'\n | 'RS'\n | 'RU'\n | 'RW'\n | 'SA'\n | 'SB'\n | 'SC'\n | 'SD'\n | 'SE'\n | 'SG'\n | 'SI'\n | 'SK'\n | 'SL'\n | 'SM'\n | 'SN'\n | 'SO'\n | 'SR'\n | 'SS'\n | 'ST'\n | 'SV'\n | 'SY'\n | 'SZ'\n | 'TC'\n | 'TD'\n | 'TG'\n | 'TH'\n | 'TJ'\n | 'TL'\n | 'TM'\n | 'TN'\n | 'TO'\n | 'TR'\n | 'TT'\n | 'TV'\n | 'TW'\n | 'TZ'\n | 'UA'\n | 'UG'\n | 'US'\n | 'UY'\n | 'UZ'\n | 'VA'\n | 'VC'\n | 'VE'\n | 'VG'\n | 'VI'\n | 'VN'\n | 'VU'\n | 'WF'\n | 'WS'\n | 'XK'\n | 'YE'\n | 'ZA'\n | 'ZM'\n | 'ZW';\n\nexport type CountryData = {\n code: string;\n name: string;\n};\n\nexport type CountryPhoneData = Record<CountryCode, CountryData>;\n\nexport const supportedCountries: CountryPhoneData = {\n AC: {\n code: '247',\n name: 'Ascension',\n },\n AD: {\n code: '376',\n name: 'Andorra',\n },\n AE: {\n code: '971',\n name: 'United Arab Emirates',\n },\n AF: {\n code: '93',\n name: 'Afghanistan',\n },\n AG: {\n code: '1268',\n name: 'Antigua and Barbuda',\n },\n AI: {\n code: '1264',\n name: 'Anguilla',\n },\n AL: {\n code: '355',\n name: 'Albania',\n },\n AM: {\n code: '374',\n name: 'Armenia',\n },\n AO: {\n code: '244',\n name: 'Angola',\n },\n AR: {\n code: '54',\n name: 'Argentina',\n },\n AS: {\n code: '1684',\n name: 'American Samoa',\n },\n AT: {\n code: '43',\n name: 'Austria',\n },\n AU: {\n code: '61',\n name: 'Australia/Cocos/Christmas Island',\n },\n AW: {\n code: '297',\n name: 'Aruba',\n },\n AZ: {\n code: '994',\n name: 'Azerbaijan',\n },\n BA: {\n code: '387',\n name: 'Bosnia and Herzegovina',\n },\n BB: {\n code: '1246',\n name: 'Barbados',\n },\n BD: {\n code: '880',\n name: 'Bangladesh',\n },\n BE: {\n code: '32',\n name: 'Belgium',\n },\n BF: {\n code: '226',\n name: 'Burkina Faso',\n },\n BG: {\n code: '359',\n name: 'Bulgaria',\n },\n BH: {\n code: '973',\n name: 'Bahrain',\n },\n BI: {\n code: '257',\n name: 'Burundi',\n },\n BJ: {\n code: '229',\n name: 'Benin',\n },\n BM: {\n code: '1441',\n name: 'Bermuda',\n },\n BN: {\n code: '673',\n name: 'Brunei',\n },\n BO: {\n code: '591',\n name: 'Bolivia',\n },\n BR: {\n code: '55',\n name: 'Brazil',\n },\n BS: {\n code: '1242',\n name: 'Bahamas',\n },\n BT: {\n code: '975',\n name: 'Bhutan',\n },\n BW: {\n code: '267',\n name: 'Botswana',\n },\n BY: {\n code: '375',\n name: 'Belarus',\n },\n BZ: {\n code: '501',\n name: 'Belize',\n },\n CA: {\n code: '1',\n name: 'Canada',\n },\n CD: {\n code: '243',\n name: 'Congo, Dem Rep',\n },\n CF: {\n code: '236',\n name: 'Central Africa',\n },\n CG: {\n code: '242',\n name: 'Congo',\n },\n CH: {\n code: '41',\n name: 'Switzerland',\n },\n CI: {\n code: '225',\n name: 'Ivory Coast',\n },\n CK: {\n code: '682',\n name: 'Cook Islands',\n },\n CL: {\n code: '56',\n name: 'Chile',\n },\n CM: {\n code: '237',\n name: 'Cameroon',\n },\n CN: {\n code: '86',\n name: 'China',\n },\n CO: {\n code: '57',\n name: 'Colombia',\n },\n CR: {\n code: '506',\n name: 'Costa Rica',\n },\n CU: {\n code: '53',\n name: 'Cuba',\n },\n CV: {\n code: '238',\n name: 'Cape Verde',\n },\n CW: {\n code: '599',\n name: 'Curaçao and Caribbean Netherlands (Bonaire, Sint Eustatius, Sint Maarten, Saba)',\n },\n CY: {\n code: '357',\n name: 'Cyprus',\n },\n CZ: {\n code: '420',\n name: 'Czech Republic',\n },\n DE: {\n code: '49',\n name: 'Germany',\n },\n DJ: {\n code: '253',\n name: 'Djibouti',\n },\n DK: {\n code: '45',\n name: 'Denmark',\n },\n DM: {\n code: '1767',\n name: 'Dominica',\n },\n DO: {\n code: '1829',\n name: 'Dominican Republic',\n },\n DZ: {\n code: '213',\n name: 'Algeria',\n },\n EC: {\n code: '593',\n name: 'Ecuador',\n },\n EE: {\n code: '372',\n name: 'Estonia',\n },\n EG: {\n code: '20',\n name: 'Egypt',\n },\n ER: {\n code: '291',\n name: 'Eritrea',\n },\n ES: {\n code: '34',\n name: 'Spain',\n },\n ET: {\n code: '251',\n name: 'Ethiopia',\n },\n FI: {\n code: '358',\n name: 'Finland/Aland Islands',\n },\n FJ: {\n code: '679',\n name: 'Fiji',\n },\n FK: {\n code: '500',\n name: 'Falkland Islands',\n },\n FM: {\n code: '691',\n name: 'Micronesia',\n },\n FO: {\n code: '298',\n name: 'Faroe Islands',\n },\n FR: {\n code: '33',\n name: 'France',\n },\n GA: {\n code: '241',\n name: 'Gabon',\n },\n GB: {\n code: '44',\n name: 'United Kingdom',\n },\n GD: {\n code: '1473',\n name: 'Grenada',\n },\n GE: {\n code: '995',\n name: 'Georgia',\n },\n GF: {\n code: '594',\n name: 'French Guiana',\n },\n GG: {\n code: '44',\n name: 'Guernsey/Jersey',\n },\n GH: {\n code: '233',\n name: 'Ghana',\n },\n GI: {\n code: '350',\n name: 'Gibraltar',\n },\n GL: {\n code: '299',\n name: 'Greenland',\n },\n GM: {\n code: '220',\n name: 'Gambia',\n },\n GN: {\n code: '224',\n name: 'Guinea',\n },\n GP: {\n code: '590',\n name: 'Guadeloupe',\n },\n GQ: {\n code: '240',\n name: 'Equatorial Guinea',\n },\n GR: {\n code: '30',\n name: 'Greece',\n },\n GT: {\n code: '502',\n name: 'Guatemala',\n },\n GU: {\n code: '1671',\n name: 'Guam',\n },\n GW: {\n code: '245',\n name: 'Guinea-Bissau',\n },\n GY: {\n code: '592',\n name: 'Guyana',\n },\n HK: {\n code: '852',\n name: 'Hong Kong',\n },\n HN: {\n code: '504',\n name: 'Honduras',\n },\n HR: {\n code: '385',\n name: 'Croatia',\n },\n HT: {\n code: '509',\n name: 'Haiti',\n },\n HU: {\n code: '36',\n name: 'Hungary',\n },\n IC: {\n code: '3491',\n name: 'Canary Islands',\n },\n ID: {\n code: '62',\n name: 'Indonesia',\n },\n IE: {\n code: '353',\n name: 'Ireland',\n },\n IL: {\n code: '972',\n name: 'Israel',\n },\n IM: {\n code: '44',\n name: 'Isle of Man',\n },\n IN: {\n code: '91',\n name: 'India',\n },\n IQ: {\n code: '964',\n name: 'Iraq',\n },\n IR: {\n code: '98',\n name: 'Iran',\n },\n IS: {\n code: '354',\n name: 'Iceland',\n },\n IT: {\n code: '39',\n name: 'Italy',\n },\n JM: {\n code: '1876',\n name: 'Jamaica',\n },\n JO: {\n code: '962',\n name: 'Jordan',\n },\n JP: {\n code: '81',\n name: 'Japan',\n },\n KE: {\n code: '254',\n name: 'Kenya',\n },\n KG: {\n code: '996',\n name: 'Kyrgyzstan',\n },\n KH: {\n code: '855',\n name: 'Cambodia',\n },\n KI: {\n code: '686',\n name: 'Kiribati',\n },\n KM: {\n code: '269',\n name: 'Comoros',\n },\n KN: {\n code: '1869',\n name: 'St Kitts and Nevis',\n },\n KP: {\n code: '850',\n name: \"Korea Dem People's Rep\",\n },\n KR: {\n code: '82',\n name: 'Korea Republic of',\n },\n KW: {\n code: '965',\n name: 'Kuwait',\n },\n KY: {\n code: '1345',\n name: 'Cayman Islands',\n },\n LA: {\n code: '856',\n name: 'Laos PDR',\n },\n LB: {\n code: '961',\n name: 'Lebanon',\n },\n LC: {\n code: '1758',\n name: 'St Lucia',\n },\n LI: {\n code: '423',\n name: 'Liechtenstein',\n },\n LK: {\n code: '94',\n name: 'Sri Lanka',\n },\n LR: {\n code: '231',\n name: 'Liberia',\n },\n LS: {\n code: '266',\n name: 'Lesotho',\n },\n LT: {\n code: '370',\n name: 'Lithuania',\n },\n LU: {\n code: '352',\n name: 'Luxembourg',\n },\n LV: {\n code: '371',\n name: 'Latvia',\n },\n LY: {\n code: '218',\n name: 'Libya',\n },\n MA: {\n code: '212',\n name: 'Morocco/Western Sahara',\n },\n MC: {\n code: '377',\n name: 'Monaco',\n },\n MD: {\n code: '373',\n name: 'Moldova',\n },\n ME: {\n code: '382',\n name: 'Montenegro',\n },\n MG: {\n code: '261',\n name: 'Madagascar',\n },\n MH: {\n code: '692',\n name: 'Marshall Islands',\n },\n MK: {\n code: '389',\n name: 'Republic of North Macedonia',\n },\n ML: {\n code: '223',\n name: 'Mali',\n },\n MM: {\n code: '95',\n name: 'Myanmar (Burma)',\n },\n MN: {\n code: '976',\n name: 'Mongolia',\n },\n MO: {\n code: '853',\n name: 'Macau',\n },\n MP: {\n code: '1670',\n name: 'Northern Mariana Islands',\n },\n MQ: {\n code: '596',\n name: 'Martinique',\n },\n MR: {\n code: '222',\n name: 'Mauritania',\n },\n MS: {\n code: '1664',\n name: 'Montserrat',\n },\n MT: {\n code: '356',\n name: 'Malta',\n },\n MU: {\n code: '230',\n name: 'Mauritius',\n },\n MV: {\n code: '960',\n name: 'Maldives',\n },\n MW: {\n code: '265',\n name: 'Malawi',\n },\n MX: {\n code: '52',\n name: 'Mexico',\n },\n MY: {\n code: '60',\n name: 'Malaysia',\n },\n MZ: {\n code: '258',\n name: 'Mozambique',\n },\n NA: {\n code: '264',\n name: 'Namibia',\n },\n NC: {\n code: '687',\n name: 'New Caledonia',\n },\n NE: {\n code: '227',\n name: 'Niger',\n },\n NF: {\n code: '672',\n name: 'Norfolk Island',\n },\n NG: {\n code: '234',\n name: 'Nigeria',\n },\n NI: {\n code: '505',\n name: 'Nicaragua',\n },\n NL: {\n code: '31',\n name: 'Netherlands',\n },\n NO: {\n code: '47',\n name: 'Norway',\n },\n NP: {\n code: '977',\n name: 'Nepal',\n },\n NU: {\n code: '683',\n name: 'Niue',\n },\n NZ: {\n code: '64',\n name: 'New Zealand',\n },\n OM: {\n code: '968',\n name: 'Oman',\n },\n PA: {\n code: '507',\n name: 'Panama',\n },\n PE: {\n code: '51',\n name: 'Peru',\n },\n PF: {\n code: '689',\n name: 'French Polynesia',\n },\n PG: {\n code: '675',\n name: 'Papua New Guinea',\n },\n PH: {\n code: '63',\n name: 'Philippines',\n },\n PK: {\n code: '92',\n name: 'Pakistan',\n },\n PL: {\n code: '48',\n name: 'Poland',\n },\n PM: {\n code: '508',\n name: 'St Pierre and Miquelon',\n },\n PR: {\n code: '1787',\n name: 'Puerto Rico',\n },\n PS: {\n code: '970, 972',\n name: 'Palestinian Territory',\n },\n PT: {\n code: '351',\n name: 'Portugal',\n },\n PW: {\n code: '680',\n name: 'Palau',\n },\n PY: {\n code: '595',\n name: 'Paraguay',\n },\n QA: {\n code: '974',\n name: 'Qatar',\n },\n RE: {\n code: '262',\n name: 'Reunion/Mayotte',\n },\n RO: {\n code: '40',\n name: 'Romania',\n },\n RS: {\n code: '381',\n name: 'Serbia',\n },\n RU: {\n code: '7',\n name: 'Russia/Kazakhstan',\n },\n RW: {\n code: '250',\n name: 'Rwanda',\n },\n SA: {\n code: '966',\n name: 'Saudi Arabia',\n },\n SB: {\n code: '677',\n name: 'Solomon Islands',\n },\n SC: {\n code: '248',\n name: 'Seychelles',\n },\n SD: {\n code: '249',\n name: 'Sudan',\n },\n SE: {\n code: '46',\n name: 'Sweden',\n },\n SG: {\n code: '65',\n name: 'Singapore',\n },\n SI: {\n code: '386',\n name: 'Slovenia',\n },\n SK: {\n code: '421',\n name: 'Slovakia',\n },\n SL: {\n code: '232',\n name: 'Sierra Leone',\n },\n SM: {\n code: '378',\n name: 'San Marino',\n },\n SN: {\n code: '221',\n name: 'Senegal',\n },\n SO: {\n code: '252',\n name: 'Somalia',\n },\n SR: {\n code: '597',\n name: 'Suriname',\n },\n SS: {\n code: '211',\n name: 'South Sudan',\n },\n ST: {\n code: '239',\n name: 'Sao Tome and Principe',\n },\n SV: {\n code: '503',\n name: 'El Salvador',\n },\n SY: {\n code: '963',\n name: 'Syria',\n },\n SZ: {\n code: '268',\n name: 'Swaziland',\n },\n TC: {\n code: '1649',\n name: 'Turks and Caicos Islands',\n },\n TD: {\n code: '235',\n name: 'Chad',\n },\n TG: {\n code: '228',\n name: 'Togo',\n },\n TH: {\n code: '66',\n name: 'Thailand',\n },\n TJ: {\n code: '992',\n name: 'Tajikistan',\n },\n TL: {\n code: '670',\n name: 'East Timor',\n },\n TM: {\n code: '993',\n name: 'Turkmenistan',\n },\n TN: {\n code: '216',\n name: 'Tunisia',\n },\n TO: {\n code: '676',\n name: 'Tonga',\n },\n TR: {\n code: '90',\n name: 'Turkiye',\n },\n TT: {\n code: '1868',\n name: 'Trinidad and Tobago',\n },\n TV: {\n code: '688',\n name: 'Tuvalu',\n },\n TW: {\n code: '886',\n name: 'Taiwan',\n },\n TZ: {\n code: '255',\n name: 'Tanzania',\n },\n UA: {\n code: '380',\n name: 'Ukraine',\n },\n UG: {\n code: '256',\n name: 'Uganda',\n },\n US: {\n code: '1',\n name: 'United States',\n },\n UY: {\n code: '598',\n name: 'Uruguay',\n },\n UZ: {\n code: '998',\n name: 'Uzbekistan',\n },\n VA: {\n code: '379',\n name: 'Vatican City',\n },\n VC: {\n code: '1784',\n name: 'St Vincent Grenadines',\n },\n VE: {\n code: '58',\n name: 'Venezuela',\n },\n VG: {\n code: '1284',\n name: 'Virgin Islands, British',\n },\n VI: {\n code: '1340',\n name: 'Virgin Islands, U.S.',\n },\n VN: {\n code: '84',\n name: 'Vietnam',\n },\n VU: {\n code: '678',\n name: 'Vanuatu',\n },\n WF: {\n code: '681',\n name: 'Wallis and Futuna',\n },\n WS: {\n code: '685',\n name: 'Samoa',\n },\n XK: {\n code: '383',\n name: 'Kosovo',\n },\n YE: {\n code: '967',\n name: 'Yemen',\n },\n ZA: {\n code: '27',\n name: 'South Africa',\n },\n ZM: {\n code: '260',\n name: 'Zambia',\n },\n ZW: {\n code: '263',\n name: 'Zimbabwe',\n },\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { consumeCaptchaToken } from '../../captcha/consumeCaptchaToken';\nimport type { OTPVerification } from '../otp.types';\nimport type { CountryCode } from './supportedCountries';\nimport { supportedCountries } from './supportedCountries';\n\nexport type SendSmsOTPParams = {\n isoCountryCode: CountryCode;\n phoneNumber: string;\n};\n\n/**\n * Sends a one-time password (OTP) via SMS to the specified phone number.\n *\n * @param params.isoCountryCode - The ISO country code for the phone number (e.g., 'US', 'CA', 'GB').\n * @param params.phoneNumber - The phone number to send the OTP to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an OTPVerification object containing the phone details and verification UUID.\n * @instrumented\n * @redact-params\n */\nexport const sendSmsOTP = async (\n { isoCountryCode, phoneNumber }: SendSmsOTPParams,\n client = getDefaultClient()\n): Promise<OTPVerification> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const phoneCountryCode = supportedCountries[isoCountryCode].code;\n\n const { verificationUUID } = await apiClient.createSmsVerification({\n environmentId: core.environmentId,\n smsVerificationCreateRequest: {\n captchaToken: consumeCaptchaToken(client),\n isoCountryCode,\n phoneCountryCode,\n phoneNumber,\n },\n });\n\n return { isoCountryCode, phoneCountryCode, phoneNumber, verificationUUID };\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { VerifyOTPParams } from '../verifyOTP';\n\n/** @not-instrumented */\nexport const verifyOTPForUserSignIn = async (\n { otpVerification, verificationToken }: VerifyOTPParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const verifyRequest = {\n verificationToken,\n verificationUUID: otpVerification.verificationUUID,\n };\n\n if (otpVerification.email) {\n return apiClient.signInWithEmailVerification({\n emailVerificationVerifyRequest: verifyRequest,\n environmentId: core.environmentId,\n });\n }\n\n return apiClient.signInWithSmsVerification({\n environmentId: core.environmentId,\n smsVerificationVerifyRequest: verifyRequest,\n });\n};\n","import type {\n EmailVerificationVerifyRequest,\n SmsVerificationVerifyRequest,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { createApiClient } from '../../../apiClient';\nimport type { VerifyOTPParams } from '../verifyOTP';\n\n/** @not-instrumented */\nexport const verifyOTPForUserUpdate = async (\n { otpVerification, verificationToken, requestedScopes }: VerifyOTPParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const verifyRequest:\n | EmailVerificationVerifyRequest\n | SmsVerificationVerifyRequest = {\n verificationToken,\n verificationUUID: otpVerification.verificationUUID,\n };\n if (requestedScopes) verifyRequest.requestedScopes = requestedScopes;\n\n if (otpVerification.email) {\n return apiClient.verifyEmailVerification({\n emailVerificationVerifyRequest: verifyRequest,\n environmentId: core.environmentId,\n });\n }\n\n return apiClient.verifySmsVerification({\n environmentId: core.environmentId,\n smsVerificationVerifyRequest: verifyRequest,\n });\n};\n","import type { TokenScope, VerifyResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport type { OTPVerification } from '../otp.types';\nimport { verifyOTPForUserSignIn } from './verifyOTPForUserSignIn';\nimport { verifyOTPForUserUpdate } from './verifyOTPForUserUpdate';\n\nexport type VerifyOTPParams = {\n otpVerification: OTPVerification;\n requestedScopes?: TokenScope[];\n verificationToken: string;\n};\n\n/**\n * Verifies a one-time password (OTP) for user authentication or updates.\n *\n * This function validates the OTP code provided by the user and completes\n * the verification process for either sign-in or account updates.\n *\n * @param params.otpVerification - The OTP verification object containing verification details.\n * @param params.verificationToken - The token received from the OTP verification process.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verify response object upon successful verification.\n * @instrumented\n * @redact-params\n */\nexport const verifyOTP = async (\n { otpVerification, verificationToken, requestedScopes }: VerifyOTPParams,\n client = getDefaultClient()\n): Promise<VerifyResponse> => {\n let response: VerifyResponse;\n if (client.user) {\n response = await verifyOTPForUserUpdate(\n {\n otpVerification,\n requestedScopes,\n verificationToken,\n },\n client\n );\n } else {\n response = await verifyOTPForUserSignIn(\n { otpVerification, verificationToken },\n client\n );\n }\n\n updateAuthFromVerifyResponse({ response }, client);\n\n return response;\n};\n","import type {\n ChainEnum,\n SwapQuoteRequestOrderEnum,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { SwapQuoteOrder, SwapQuoteResponse } from '../swap.types';\n\nexport type GetSwapQuoteParams = {\n from: {\n /* Source wallet address */\n address: string;\n /**\n * Source token amount, including all decimals (e.g. 1000000 for 1 USDC (6 decimals))\n * Mutually exclusive with `to.amount`\n */\n amount?: string;\n /* Source chain (e.g. 'EVM', 'SOL', 'SUI') */\n chain: Chain;\n /* Source network id (e.g. 1 for Ethereum, 137 for Polygon) */\n networkId: string;\n /* Source token address. Use zero address for EVM and SOL native tokens. */\n tokenAddress: string;\n };\n /**\n * The price impact threshold above which routes are hidden.\n * As an example, one should specify 0.15 (15%) to hide routes with more than 15% price impact.\n */\n maxPriceImpact?: number;\n /**\n * Which kind of route should be preferred\n *\n * FASTEST: This sorting criterion prioritizes routes with the shortest estimated execution time.\n * Users who value speed and want their transactions to be completed as quickly as possible should choose the fastest routes.\n *\n * CHEAPEST: This criterion focuses on minimizing the cost of the transaction, whether in token amount or USD amount (USD amount minus gas cost).\n * Users looking for the most economical option should choose the cheapest routes.\n *\n */\n order?: SwapQuoteOrder;\n /* The maximum allowed slippage for the transaction as a decimal value. 0.005 represents 0.5%. */\n slippage?: number;\n to: {\n /* Destination wallet address */\n address: string;\n /**\n * Destination token amount, including all decimals (e.g. 1000000 for 1 USDC (6 decimals))\n * Mutually exclusive with `from.amount`\n */\n amount?: string;\n /* Destination chain (e.g. 'EVM', 'SOL', 'SUI') */\n chain: Chain;\n /* Destination network id (e.g. 1 for Ethereum, 137 for Polygon) */\n networkId: string;\n /* Destination token address. Use zero address for EVM and SOL native tokens. */\n tokenAddress: string;\n };\n};\n\n/**\n * Gets a swap quote\n *\n * @param params GetSwapQuoteParams - The parameters for the swap quote.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The swap quote details. Use the `signingPayload` field to get the transaction data for the wallet to sign.\n * @not-instrumented\n */\nexport const getSwapQuote = async (\n params: GetSwapQuoteParams,\n client = getDefaultClient()\n): Promise<SwapQuoteResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n if (!params.from.amount && !params.to.amount) {\n throw new InvalidParamError('Either from.amount or to.amount is required');\n }\n\n if (params.from.amount && params.to.amount) {\n throw new InvalidParamError(\n 'Only one of from.amount or to.amount is allowed'\n );\n }\n\n const response = await apiClient.swapQuote({\n environmentId: core.environmentId,\n swapQuoteRequest: {\n from: {\n ...params.from,\n chainId: params.from.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.from.chain as ChainEnum,\n },\n maxPriceImpact: params.maxPriceImpact,\n order: params.order as SwapQuoteRequestOrderEnum,\n slippage: params.slippage,\n to: {\n ...params.to,\n chainId: params.to.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.to.chain as ChainEnum,\n },\n },\n });\n return response;\n};\n","import type {\n ChainEnum,\n SwapStatusRequestChain,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { TokenSwapError } from '../../../errors/TokenSwapError';\nimport { createApiClient } from '../../apiClient';\nimport type { Chain } from '../../chain';\nimport type { SwapStatusResponse } from '../swap.types';\n\nexport type GetSwapStatusParams = {\n from?: {\n chain: Chain;\n networkId: string;\n };\n to?: {\n chain: Chain;\n networkId: string;\n };\n txHash: string;\n};\n\n/**\n * Gets the status of a swap\n *\n * @param params GetSwapStatusParams - The parameters for the swap status.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The swap status.\n * @not-instrumented\n */\nexport const getSwapStatus = async (\n params: GetSwapStatusParams,\n client = getDefaultClient()\n): Promise<SwapStatusResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n let from: SwapStatusRequestChain | undefined;\n\n if (params.from) {\n from = {\n chainId: params.from.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.from.chain as ChainEnum,\n };\n }\n\n let to: SwapStatusRequestChain | undefined;\n if (params.to) {\n to = {\n chainId: params.to.networkId,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.to.chain as ChainEnum,\n };\n }\n try {\n const response = await apiClient.swapStatus({\n environmentId: core.environmentId,\n swapStatusRequest: {\n from,\n to,\n txHash: params.txHash,\n },\n });\n\n return {\n status: response.status,\n substatus: response.substatus,\n };\n } catch (error) {\n throw new TokenSwapError({\n message: 'Failed to get swap status',\n originalError: error,\n });\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\n\n/**\n * Deletes the current user's account permanently.\n *\n * This function performs a hard delete of the user account. Upon successful deletion,\n * the user will be automatically logged out and all authentication data will be cleared.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the user account is successfully deleted.\n * @instrumented\n */\nexport const deleteUser = async (\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({ includeMfaToken: true }, client);\n\n await apiClient.hardDeleteUser({\n environmentId: core.environmentId,\n });\n\n await logoutWithReason({ reason: 'user-deleted' }, client);\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { isPendingRecoveryCodesAcknowledgment } from '../../mfa/isPendingRecoveryCodesAcknowledgment';\nimport { isUserMissingMfaAuth } from '../../mfa/isUserMissingMfaAuth';\n\n/**\n * Checks if the user has completed all onboarding requirements.\n *\n * This function verifies whether a user has fulfilled all necessary requirements\n * including KYC fields (Know Your Customer information) and MFA setup\n * (Multi-Factor Authentication including recovery codes acknowledgment).\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if onboarding is complete (no pending requirements), false if there are pending requirements.\n * @not-instrumented\n */\nexport const isUserOnboardingComplete = (client = getDefaultClient()) => {\n const user = client.user;\n\n assertDefined(user, 'User not logged in');\n\n const hasMissingKycFields = Boolean(user.missingFields?.length);\n const hasPendingMfaAuth = isUserMissingMfaAuth(client);\n const hasPendingRecoveryCodes = isPendingRecoveryCodesAcknowledgment(client);\n\n const userOnboardingComplete = !hasMissingKycFields && !hasPendingMfaAuth && !hasPendingRecoveryCodes;\n\n return userOnboardingComplete;\n};\n","/**\n * OAuth scopes that must be granted on the user's Google account in order\n * for the keyshare backup upload to Google Drive to succeed.\n *\n * Exported so host apps can pre-flight check or display these in their own\n * UX. Kept as a `readonly` tuple to discourage mutation.\n */\nexport const GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES = [\n 'https://www.googleapis.com/auth/drive.appdata',\n 'https://www.googleapis.com/auth/drive.file',\n] as const;\n\n/**\n * Stable phrase the WaaS layer includes in Google Drive 401 / scope-insufficient\n * upload failure messages. Match by `.includes(...)` rather than equality\n * because the iframe message-handler fallback path rewraps the original error\n * as `new Error(String(response.error))`, which prefixes the message with\n * \"Error: \". The phrase remains unique to the auth/scope case across all the\n * Drive failure reasons (rate-limit, storage-full, 5xx, network all use\n * distinct prefixes), so message-only matching is sufficient to discriminate.\n */\nexport const ACCESS_DENIED_PHRASE = 'Google Drive access denied';\n","import { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../constants';\n\n/**\n * Returns the Google OAuth scopes from `GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES`\n * that are NOT present in `grantedScopes`. An empty array means all required\n * scopes have been granted.\n *\n * @param grantedScopes - Scopes the user has granted to their Google account.\n * @returns The subset of required scopes that are still missing.\n * @not-instrumented\n */\nexport const findMissingGoogleDriveBackupScopes = (\n grantedScopes: readonly string[]\n): string[] =>\n GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES.filter(\n (required) => !grantedScopes.includes(required)\n );\n","import type { UserOauthAccessTokenResponse } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../../client/types';\nimport { createApiClient } from '../../../../apiClient';\n\nexport type FetchGoogleDriveOauthAccessParams = {\n oauthAccountId: string;\n};\n\n/**\n * Fetches the user's stored Google OAuth access token together with the\n * scopes that were granted when the token was issued.\n *\n * Internal to the Google Drive backup readiness check — not exported as a\n * public API. The returned `scopes` array can be empty for legacy tokens\n * captured before the API began tracking granted scopes.\n *\n * @param params.oauthAccountId - The verified-credential id of the linked\n * Google account (see `findGoogleOauthAccountId`).\n * @param client - The Dynamic client instance.\n * @returns The OAuth access token and granted scopes.\n * @not-instrumented\n */\nexport const fetchGoogleDriveOauthAccess = async (\n { oauthAccountId }: FetchGoogleDriveOauthAccessParams,\n client: DynamicClient\n): Promise<UserOauthAccessTokenResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n return apiClient.getEndUserOauthAccessToken({\n environmentId: core.environmentId,\n oauthAccountId,\n });\n};\n","import {\n type JwtVerifiedCredential,\n JwtVerifiedCredentialFormatEnum,\n ProviderEnum,\n} from '@dynamic-labs/sdk-api-core';\n\n/**\n * Returns the verified-credential `id` (UUID of the user_oauth_accounts row)\n * for the user's linked Google account, or `undefined` if no Google account\n * is linked.\n *\n * The `getEndUserOauthAccessToken` API path parameter expects this UUID, NOT\n * the third-party `oauthAccountId` (Google's numeric profile ID) — those are\n * stored in the same credential under different fields.\n *\n * @param credentials - The user's verified credentials, typically from\n * `client.user?.verifiedCredentials`.\n * @returns The credential id of the linked Google oauth account, or\n * `undefined`.\n * @not-instrumented\n */\nexport const findGoogleOauthAccountId = (\n credentials: readonly JwtVerifiedCredential[] | undefined\n): string | undefined =>\n credentials?.find(\n (cred) =>\n cred.format === JwtVerifiedCredentialFormatEnum.Oauth &&\n cred.oauthProvider === ProviderEnum.Google\n )?.id;\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../constants';\nimport { findMissingGoogleDriveBackupScopes } from '../findMissingGoogleDriveBackupScopes';\nimport type { GoogleDriveBackupReadiness } from '../googleDrive.types';\nimport { fetchGoogleDriveOauthAccess } from '../utils/fetchGoogleDriveOauthAccess';\nimport { findGoogleOauthAccountId } from '../utils/findGoogleOauthAccountId';\n\n/**\n * Pre-flight readiness check for backing up MPC keyshares to Google Drive.\n *\n * Call this before initiating the keyshare backup ceremony. When the result\n * is `'needs-access'`, have the user re-link their Google account so the\n * required Drive scopes are granted, then call this again before retrying\n * the backup. This avoids spending an MPC reshare ceremony on a backup that\n * will predictably fail.\n *\n * Status values:\n * - `'ready'`: stored scopes include both required Drive scopes; backup\n * should succeed (barring transient errors).\n * - `'needs-access'`: backup likely won't succeed without user intervention.\n * Three sub-cases, distinguished by `missingScopes`:\n * - No Google account linked → `missingScopes` is the full required set.\n * - Some scopes granted but not all → `missingScopes` lists the gap.\n * - Legacy token captured before scope tracking shipped (`scopes: []` from\n * the API) → `missingScopes` is empty. Forcing a fresh consent will\n * populate the scopes column for subsequent calls.\n *\n * Failures of the underlying access-token fetch propagate as Promise\n * rejections — the caller is expected to surface or retry them.\n *\n * Pair with `isInsufficientGoogleDriveScopesError` to detect post-flight\n * scope failures (e.g. for the legacy \"unknown scopes\" case where pre-flight\n * cannot prove failure).\n *\n * @param [client] - The Dynamic client instance. Only required when using\n * multiple Dynamic clients.\n * @returns The readiness result.\n * @instrumented\n */\nexport const getGoogleDriveBackupReadiness = async (\n client = getDefaultClient()\n): Promise<GoogleDriveBackupReadiness> => {\n const { user } = client;\n\n const oauthAccountId = findGoogleOauthAccountId(user?.verifiedCredentials);\n\n if (!oauthAccountId) {\n // No Google credential linked — every required scope is effectively\n // missing, so populate the full set so callers can render their\n // \"we need access to ...\" UX without checking the empty case.\n return {\n missingScopes: GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES,\n status: 'needs-access',\n };\n }\n\n const { accessToken, scopes } = await fetchGoogleDriveOauthAccess(\n { oauthAccountId },\n client\n );\n\n if (scopes.length === 0) {\n // Legacy token captured before scope tracking shipped — we can't\n // confirm the upload will work, so surface as needs-access (with empty\n // missingScopes to differentiate from the explicit-missing case).\n // Forcing a fresh consent populates the scopes column for next time.\n return {\n accessToken,\n missingScopes: [],\n status: 'needs-access',\n };\n }\n\n const missing = findMissingGoogleDriveBackupScopes(scopes);\n\n if (missing.length === 0) {\n return {\n accessToken,\n missingScopes: [],\n status: 'ready',\n };\n }\n\n return {\n accessToken,\n missingScopes: missing,\n status: 'needs-access',\n };\n};\n","import { findMissingGoogleDriveBackupScopes } from '../findMissingGoogleDriveBackupScopes';\n\n/**\n * Returns whether `grantedScopes` covers every Google OAuth scope required\n * to upload a keyshare backup to Google Drive.\n *\n * @param grantedScopes - Scopes the user has granted to their Google account.\n * @returns `true` when every required scope is granted, otherwise `false`.\n * @not-instrumented\n */\nexport const hasAllGoogleDriveBackupScopes = (\n grantedScopes: readonly string[]\n): boolean => findMissingGoogleDriveBackupScopes(grantedScopes).length === 0;\n","import { ACCESS_DENIED_PHRASE } from '../constants';\n\n/**\n * Type-guard for Google Drive backup failures caused by missing or\n * insufficient OAuth scopes (or otherwise denied access).\n *\n * Recover by having the user re-link their Google account and retrying the\n * backup once the granted scopes include\n * `GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES`.\n *\n * @param err - The unknown value to check.\n * @returns `true` when `err` is an `Error` whose message indicates Google\n * Drive access was denied.\n * @not-instrumented\n */\nexport const isInsufficientGoogleDriveScopesError = (\n err: unknown\n): err is Error =>\n err instanceof Error && err.message.includes(ACCESS_DENIED_PHRASE);\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\nimport { WalletAccountNotSelectedError } from './../../../errors/WalletAccountNotSelectedError';\n\ntype AssertWalletAccountSigningAvailabilityParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Asserts that a wallet account is available and ready for signing operations.\n *\n * This function verifies that the specified wallet account is currently\n * connected and selected in the wallet app, ensuring it can perform signing operations.\n *\n * If the wallet account is not available, the user might need to reconnect it or\n * change the account in their wallet app to make it active.\n *\n * @param params.walletAccount - The wallet account to verify signing availability for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves if the wallet is available for signing.\n * @throws WalletAccountNotSelectedError If the wallet account is not currently selected.\n * @not-instrumented\n */\nexport const assertWalletAccountSigningAvailability = async (\n { walletAccount }: AssertWalletAccountSigningAvailabilityParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { addresses } = await walletProvider.getConnectedAddresses();\n\n if (addresses.length > 0 && !addresses.includes(walletAccount.address)) {\n throw new WalletAccountNotSelectedError({\n expectedAddress: walletAccount.address,\n selectedAddress: addresses[0],\n });\n }\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { ConfirmTransactionParams } from '../walletProvider/walletProvider.types';\n\n/**\n * Waits for a transaction to be confirmed on-chain.\n *\n * Delegates to the wallet provider's `confirmTransaction` implementation,\n * which polls the appropriate chain API until the transaction is included\n * in a block or the maximum wait time is exceeded.\n *\n * @param params.walletAccount - The wallet account that submitted the transaction.\n * @param params.transactionHash - The transaction hash to wait for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the transaction is confirmed.\n * @throws If the wallet provider does not support the confirmTransaction method.\n * @instrumented\n */\nexport const confirmTransaction = async (\n { walletAccount, transactionHash }: ConfirmTransactionParams,\n client = getDefaultClient()\n): Promise<void> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'confirmTransaction');\n\n await walletProvider.confirmTransaction({ transactionHash, walletAccount });\n};\n","import type { WalletAddressWithType } from '../../walletAccount/walletAccount.types';\nimport type { WalletProviderConnectResult } from '../../walletProvider/walletProvider.types';\n\n/** @not-instrumented */\nexport const getAddressesWithTypesFromConnectionResult = (\n connectionResult: WalletProviderConnectResult\n): WalletAddressWithType[] => {\n return connectionResult.addresses.filter(\n (address): address is WalletAddressWithType =>\n !!address.address && !!address.type\n );\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport { reconcileWalletAccountsAgainstClient } from '../reconcileWalletAccountsAgainstClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { formatWalletAccountId } from '../utils/formatWalletAccountId';\nimport { getAddressesWithTypesFromConnectionResult } from '../utils/getAddressesWithTypesFromConnectionResult';\nimport type { WalletAccount } from '../walletAccount';\nimport { NoAddressFoundError } from './../../../errors/NoAddressFoundError';\n\ntype ConnectWithWalletProviderParams = {\n addToDynamicWalletAccounts?: boolean;\n hardwareWalletVendor?: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Connects to a wallet provider and returns the connected wallet account.\n *\n * Note: This function will not verify the wallet account, use the verifyWalletAccount function to do that\n * or connectAndVerifyWithWalletProvider to do that in a single step.\n * @see verifyWalletAccount\n * @see connectAndVerifyWithWalletProvider\n *\n * @param params.walletProviderKey - The unique key identifying the wallet provider to connect to (e.g. 'metamaskevm', 'phantomsol').\n * @param [params.addToDynamicWalletAccounts] - Whether to add the connected wallet account to the user's wallet accounts. Defaults to true.\n * @param [params.hardwareWalletVendor] - The hardware wallet vendor, if connecting via a hardware wallet (e.g. 'ledger').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the connected wallet account.\n * @throws NoAddressFoundError If the request to connect was successful but no address is connected to your app.\n * @instrumented\n */\nexport const connectWithWalletProvider = async (\n {\n walletProviderKey,\n addToDynamicWalletAccounts = true,\n hardwareWalletVendor,\n }: ConnectWithWalletProviderParams,\n client = getDefaultClient()\n): Promise<WalletAccount> => {\n const walletProvider = getWalletProviderByKey(\n {\n walletProviderKey,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'connect');\n\n const { addresses } = await walletProvider.connect();\n\n // We only materialize the first connected address to stay consistent with\n // the dynamic-auth pattern — simpler, and there's no real demand for\n // multi-address-per-provider connections at the moment.\n const mainAddress = addresses?.length ? addresses[0].address : null;\n\n /**\n * This error is thrown in case the wallet has no addresses connected\n * to the dapp. Then the error is thrown so the consumer can instruct the\n * user on the next steps.\n */\n if (!mainAddress) {\n throw new NoAddressFoundError();\n }\n\n const walletAccount: WalletAccount = {\n address: mainAddress,\n addressesWithTypes: getAddressesWithTypesFromConnectionResult({\n addresses,\n }),\n chain: walletProvider.chain,\n hardwareWalletVendor,\n id: formatWalletAccountId({\n address: mainAddress,\n chain: walletProvider.chain,\n walletProviderKey,\n }),\n lastSelectedAt: null,\n verifiedCredentialId: null,\n walletProviderKey,\n };\n\n const [reconciledWalletAccount] = reconcileWalletAccountsAgainstClient(\n {\n addToDynamicWalletAccounts,\n walletAccounts: [walletAccount],\n walletProviderKey,\n },\n client\n );\n\n return reconciledWalletAccount;\n};\n","import type { HardwareWalletVendor } from '../hardwareWallet.types';\n\ntype FormatSignatureForHardwareWalletParams = {\n hardwareWalletVendor: HardwareWalletVendor;\n signature: string;\n};\n\n/**\n * Wraps a raw signature in the JSON format expected by the backend for hardware wallet verification.\n *\n * @param params.hardwareWalletVendor - The hardware wallet vendor that produced the signature.\n * @param params.signature - The raw signature string to wrap.\n * @returns The signature wrapped in `{ signedTransaction: { data } }` JSON format.\n * @not-instrumented\n */\nexport const formatSignatureForHardwareWallet = ({\n signature,\n hardwareWalletVendor: _,\n}: FormatSignatureForHardwareWalletParams): string =>\n JSON.stringify({\n signedTransaction: {\n data: signature,\n },\n });\n","import type { Chain } from '../../../chain';\nimport type { WalletProvider } from '../../../wallets/walletProvider/walletProvider.types';\n\n/** @not-instrumented */\nexport const getChainIdForAccountVerification = async ({\n walletProvider,\n}: {\n walletProvider: WalletProvider;\n}) => {\n // for some chains, we don't need to specify a chain id for account verification because it's\n // not required and it might break the message signature in some wallets (e.g. Trust Wallet SOL)\n const chainsThatDontNeedChainId: Chain[] = ['BTC', 'SOL', 'SUI'];\n\n if (chainsThatDontNeedChainId.includes(walletProvider.chain)) {\n return undefined;\n }\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n if (networkId) {\n return networkId;\n }\n\n // default to ethereum mainnet\n if (walletProvider.chain === 'EVM') {\n return '1';\n }\n\n return undefined;\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport type { DynamicClient } from '../../../../client/types';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport { getAppMetadata } from '../../../../utils/getAppMetadata';\nimport { getNonce } from '../../../../utils/getNonce';\nimport { CHAINS_INFO_MAP } from '../../constants';\nimport type { WalletAccount } from '../../walletAccount';\nimport { formatSignInMessage } from '../formatSignInMessage';\nimport { getChainIdForAccountVerification } from '../getChainIdForAccountVerification';\nimport { getWalletProviderFromWalletAccount } from '../getWalletProviderFromWalletAccount';\nimport { createSignInMessageStatement } from './createSignInMessageStatement';\n\ntype GetSignInMessageParams = {\n nonce?: string;\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getSignInMessage = async (\n { nonce: nonceOverride, walletAccount }: GetSignInMessageParams,\n client: DynamicClient\n) => {\n const core = getCore(client);\n const { appUniversalLink } = getAppMetadata(client);\n\n assertDefined(appUniversalLink, 'Universal link is not set');\n\n const url = new URL(appUniversalLink);\n const domain = url.host;\n\n const nonce = nonceOverride ?? (await getNonce(client));\n\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n // for starknet, the message to sign needs to be a JSON object with the domain and nonce\n if (walletProvider.chain === 'STARK') {\n /**\n * Starknet requires the strings to be 31 chars long\n * Nonce - we need to keep full size for nonce verification on the backend (the backend shortens it to 31 chars)\n * Domain - we need to shorten the domain to 31 chars\n */\n return JSON.stringify({\n domain: domain.substring(0, 31),\n nonce,\n });\n }\n\n const statement = createSignInMessageStatement(client);\n\n const messageToSign = await formatSignInMessage({\n address: walletAccount.address,\n blockchainName: CHAINS_INFO_MAP[walletProvider.chain].blockchainName,\n chainId: await getChainIdForAccountVerification({ walletProvider }),\n domain,\n issuedAt: new Date().toISOString(),\n nonce,\n requestId: core.environmentId,\n statement,\n uri: url.toString(),\n });\n\n return messageToSign;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getSignInMessage } from '../utils/getSignInMessage';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype ProveWalletAccountOwnershipParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Proves ownership of a wallet account by signing a verification message.\n *\n * This function generates a sign-in message and requires the user to sign it\n * with their wallet's private key, proving they control the wallet address.\n *\n * @param params.walletAccount - The wallet account to prove ownership of.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the message and signature.\n * @instrumented\n */\nexport const proveWalletAccountOwnership = async (\n { walletAccount }: ProveWalletAccountOwnershipParams,\n client = getDefaultClient()\n): Promise<{\n messageToSign: string;\n signature: string;\n}> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'signMessage');\n\n const messageToSign = await getSignInMessage(\n { nonce: walletProvider.getConnectProofNonce?.(), walletAccount },\n client\n );\n\n const { signature } = await walletProvider.signMessage({\n message: messageToSign,\n walletAccount,\n });\n\n return { messageToSign, signature };\n};\n","import type { Chain } from '../../../chain';\nimport { normalizeAddress } from '../normalizeAddress';\n\nexport type IsSameAddressOptions = {\n /** The chain used to normalize both addresses before comparison. */\n chain: Chain;\n\n /** The first address to compare. */\n left: string;\n\n /** The second address to compare. */\n right: string;\n};\n\n/** @not-instrumented */\nexport const isSameAddress = ({ chain, left, right }: IsSameAddressOptions) =>\n normalizeAddress({ address: left, chain }) ===\n normalizeAddress({ address: right, chain });\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { getWalletAccounts } from '../getWalletAccounts';\nimport { formatSignatureForHardwareWallet } from '../hardwareWallet/formatSignatureForHardwareWallet';\nimport { proveWalletAccountOwnership } from '../proveWalletAccountOwnership';\nimport { removeUnverifiedWalletAccount } from '../unverifiedWalletAccounts/removeUnverifiedWalletAccount';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport { isSameAddress } from '../utils/isSameAddress';\nimport { verifyMessageSignatureOwnership } from '../verifyMessageSignatureOwnership';\nimport type { WalletAccount } from '../walletAccount';\nimport { updateWalletProviderKeysForVerifiedCredentials } from '../walletProvider/walletProviderKeyMap/updateWalletProviderKeysForVerifiedCredentials';\nimport { WalletAccountAlreadyVerifiedError } from './../../../errors/WalletAccountAlreadyVerifiedError';\n\ntype VerifyWalletAccountForSignInOrTransferParams = {\n isTransfer: boolean;\n requestedScopes?: TokenScope[];\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const verifyWalletAccountForSignInOrTransfer = async (\n {\n walletAccount,\n isTransfer,\n requestedScopes,\n }: VerifyWalletAccountForSignInOrTransferParams,\n client: DynamicClient\n): Promise<WalletAccount> => {\n if (walletAccount.verifiedCredentialId) {\n throw new WalletAccountAlreadyVerifiedError(walletAccount.address);\n }\n\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { messageToSign, signature } = await proveWalletAccountOwnership(\n {\n walletAccount,\n },\n client\n );\n\n const formattedSignature = walletAccount.hardwareWalletVendor\n ? formatSignatureForHardwareWallet({\n hardwareWalletVendor: walletAccount.hardwareWalletVendor,\n signature,\n })\n : signature;\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const response = await verifyMessageSignatureOwnership(\n {\n addressesWithTypes: walletAccount.addressesWithTypes,\n chain: walletAccount.chain,\n isTransfer,\n messageToSign,\n networkId,\n requestedScopes,\n signature: formattedSignature,\n walletAddress: walletAccount.address,\n walletDisplayName: walletProvider.metadata.displayName,\n walletProviderType: walletProvider.walletProviderType,\n },\n client\n );\n\n const walletVerifiedCredential = response.user?.verifiedCredentials.find(\n (verifiedCredential) =>\n isSameAddress({\n chain: walletAccount.chain,\n left: verifiedCredential.address ?? '',\n right: walletAccount.address,\n })\n );\n\n assertDefined(\n walletVerifiedCredential,\n `After verifying, still unable to find verified wallet credential for wallet account ${walletAccount.address} on chain ${walletAccount.chain}`\n );\n\n updateWalletProviderKeysForVerifiedCredentials(\n {\n keysToUpdate: {\n [walletVerifiedCredential.id]: walletProvider.key,\n },\n },\n client\n );\n\n /**\n * Adds the user with the new wallet verified credential\n * This will add the new verified wallet account to the client`s state\n */\n updateAuthFromVerifyResponse({ response }, client);\n\n /**\n * Remove the now verified wallet account from the unverified wallet accounts\n */\n removeUnverifiedWalletAccount(\n { unverifiedWalletAccount: walletAccount },\n client\n );\n\n const verifiedWalletAccount = getWalletAccounts(client).find(({ address }) =>\n isSameAddress({\n chain: walletAccount.chain,\n left: address,\n right: walletAccount.address,\n })\n );\n\n assertDefined(\n verifiedWalletAccount,\n `Unable to find wallet account ${walletAccount.address} on chain ${walletAccount.chain} for verified credential ${walletVerifiedCredential.id}`\n );\n\n return verifiedWalletAccount;\n};\n","import type { TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { verifyWalletAccountForSignInOrTransfer } from '../verifyWalletAccountForSignInOrTransfer';\nimport type { WalletAccount } from '../walletAccount';\n\ntype VerifyWalletAccountParams = {\n requestedScopes?: TokenScope[];\n walletAccount: WalletAccount;\n};\n\n/**\n * Verifies ownership of a wallet account and adds it to the user's profile.\n *\n * This function requires the user to sign a message to prove wallet ownership,\n * then sets the wallet account as verified.\n *\n * @param params.walletAccount - The wallet account to verify ownership of.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the verified wallet account.\n * @throws WalletAccountAlreadyVerifiedError If the wallet is already verified.\n * @throws WalletAlreadyLinkedToAnotherUserError If the wallet is linked to another user.\n * @instrumented\n */\nexport const verifyWalletAccount = async (\n { walletAccount, requestedScopes }: VerifyWalletAccountParams,\n client = getDefaultClient()\n): Promise<WalletAccount> => {\n return verifyWalletAccountForSignInOrTransfer(\n {\n isTransfer: false,\n requestedScopes,\n walletAccount,\n },\n client\n );\n};\n","import { WalletProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport type { WalletProviderData } from '../walletProvider.types';\n\ntype IsDeeplinkWalletProviderParams = {\n walletProvider: WalletProviderData;\n};\n\n/**\n * Returns true if the wallet provider uses the deep link protocol (e.g. Phantom redirect on mobile).\n * @not-instrumented\n */\nexport const isDeeplinkWalletProvider = ({\n walletProvider,\n}: IsDeeplinkWalletProviderParams): boolean =>\n walletProvider.walletProviderType === WalletProviderEnum.DeepLink;\n","import { AuthModeEnum } from '@dynamic-labs/sdk-api-core';\n\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { DeeplinkConnectAndVerifyUnsupportedError } from '../../../errors/DeeplinkConnectAndVerifyUnsupportedError';\nimport { isMobile } from '../../../utils/isMobile';\nimport { createVisit } from '../../auth/createVisit';\nimport { connectWithWalletProvider } from '../connectWithWalletProvider';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet/hardwareWallet.types';\nimport { verifyWalletAccount } from '../verifyWalletAccount';\nimport { isDeeplinkWalletProvider } from '../walletProvider/isDeeplinkWalletProvider';\n\ntype ConnectAndVerifyWithWalletProviderParams = {\n hardwareWalletVendor?: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Connects to a wallet provider and verifies ownership through message signing.\n *\n * This function combines wallet connection and verification in a single step,\n * requiring the user to sign a message to prove wallet ownership before\n * the wallet account is added to their profile.\n *\n * @throws {DeeplinkConnectAndVerifyUnsupportedError} On mobile with deep link\n * wallet providers (e.g. Phantom redirect). This function triggers two sequential\n * deeplinks — one to connect and another to sign for verification. iOS will not\n * honor the second deeplink because it is no longer tied to a user gesture.\n * Android may handle sequential deeplinks differently, but this guard applies to\n * all mobile platforms to ensure a stable experience and prevent production-only\n * errors. Use `connectWithWalletProvider` first and then invoke\n * `verifyWalletAccount` separately from a new user gesture (e.g. a \"Verify\n * Ownership\" button).\n *\n * @param params.walletProviderKey - The unique key identifying the wallet provider to connect to.\n * @param [params.hardwareWalletVendor] - The hardware wallet vendor, if connecting via a hardware wallet (e.g. 'ledger').\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the connected and verified wallet account.\n * @instrumented\n */\nexport const connectAndVerifyWithWalletProvider = async (\n { walletProviderKey, hardwareWalletVendor }: ConnectAndVerifyWithWalletProviderParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n if (isMobile() && isDeeplinkWalletProvider({ walletProvider })) {\n throw new DeeplinkConnectAndVerifyUnsupportedError({ walletProviderKey });\n }\n\n const walletAccount = await connectWithWalletProvider(\n { addToDynamicWalletAccounts: false, hardwareWalletVendor, walletProviderKey },\n client\n );\n\n await verifyWalletAccount({ walletAccount }, client);\n\n /*\n * send information to backend to kick off background jobs\n * this is an async work, but does not need to be awaited\n */\n void createVisit({ authMode: AuthModeEnum.AndSign, walletAccount }, client);\n\n return walletAccount;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { hasWalletProviderConnectMethod } from '../hasWalletProviderConnectMethod';\nimport { getWalletProviders } from '../getWalletProviders';\nimport type { WalletProviderData } from '../walletProvider';\n\n/**\n * Retrieves data for all available wallet providers that can be used for connection.\n *\n * This function returns metadata about wallet providers that users can\n * connect to, like MetaMask, Phantom, etc.\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of wallet provider data including chain, keys, and metadata.\n * @not-instrumented\n */\nexport const getAvailableWalletProvidersData = (\n client = getDefaultClient()\n): WalletProviderData[] => {\n const allWalletProviders = getWalletProviders(client);\n\n const filteredWalletProviders = allWalletProviders.filter((walletProvider) =>\n hasWalletProviderConnectMethod({ walletProvider })\n );\n\n return filteredWalletProviders.map((walletProvider) => ({\n chain: walletProvider.chain,\n groupKey: walletProvider.groupKey,\n key: walletProvider.key,\n metadata: walletProvider.metadata,\n walletProviderType: walletProvider.walletProviderType,\n }));\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\n\ntype GetConnectedAddressesParams = {\n walletProviderKey: string;\n};\n\n/**\n * Retrieves all connected addresses for a specific wallet provider.\n *\n * This function returns the list of wallet addresses that are currently\n * connected and available through the specified wallet provider.\n *\n * @param params.walletProviderKey - The unique key of the wallet provider to query.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns An array of connected wallet addresses.\n * @not-instrumented\n */\nexport const getConnectedAddresses = (\n { walletProviderKey }: GetConnectedAddressesParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n return walletProvider.getConnectedAddresses();\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertDefined } from '../../../utils/assertDefined';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { getWalletAccounts } from '../getWalletAccounts';\nimport { getVerifiedCredentialForWalletAccount } from '../utils/getVerifiedCredentialForWalletAccount';\n\ntype GetOwnerWalletAccountForSmartWalletAccountParams = {\n smartWalletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getOwnerWalletAccountForSmartWalletAccount = (\n { smartWalletAccount }: GetOwnerWalletAccountForSmartWalletAccountParams,\n client = getDefaultClient()\n): WalletAccount | undefined => {\n const smartWalletVerifiedCredential = getVerifiedCredentialForWalletAccount(\n { walletAccount: smartWalletAccount },\n client\n );\n\n assertDefined(\n smartWalletVerifiedCredential?.signerRefId,\n 'Invalid smart wallet account'\n );\n\n return getWalletAccounts(client).find(\n (walletAccount) =>\n walletAccount.verifiedCredentialId ===\n smartWalletVerifiedCredential.signerRefId\n );\n};\n","import type { WalletAccount, WalletAddressType } from '../walletAccount';\n\ntype GetWalletAccountAddressByTypeParams = {\n type: WalletAddressType;\n walletAccount: WalletAccount;\n};\n\n/** @not-instrumented */\nexport const getWalletAccountAddressByType = ({\n type,\n walletAccount,\n}: GetWalletAccountAddressByTypeParams) => {\n return walletAccount.addressesWithTypes?.find(\n (address) => address.type === type\n )?.address;\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../getWalletProviderByKey';\nimport type { WalletProviderData } from '../walletProvider';\n\ntype GetWalletProviderDataByKeyParams = {\n walletProviderKey: string;\n};\n\n/**\n * Retrieves data for a specific wallet provider that can be used for display or connection.\n *\n * @param params.walletProviderKey - The key of the wallet provider to retrieve data for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The data for the wallet provider.\n * @not-instrumented\n */\nexport const getWalletProviderDataByKey = (\n { walletProviderKey }: GetWalletProviderDataByKeyParams,\n client = getDefaultClient()\n): WalletProviderData => {\n const { chain, groupKey, key, metadata, walletProviderType } =\n getWalletProviderByKey({ walletProviderKey }, client);\n\n return { chain, groupKey, key, metadata, walletProviderType };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { getWalletAccounts } from '../getWalletAccounts';\n\n/**\n * Checks whether the session has at least one connected wallet account.\n *\n * Both verified and unverified wallet accounts count as connected. This is a\n * single building block for a custom signed-in check — combine it with whatever\n * else your app considers \"signed in\" (e.g. `client.user`, completed onboarding,\n * a required embedded wallet, …).\n *\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if the session has at least one wallet account, false otherwise.\n * @not-instrumented\n */\nexport const isAnyWalletAccountConnected = (\n client = getDefaultClient()\n): boolean => getWalletAccounts(client).length > 0;\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { HardwareWalletVendor } from '../hardwareWallet.types';\n\ntype CanConnectWithHardwareWalletParams = {\n hardwareWalletVendor: HardwareWalletVendor;\n walletProviderKey: string;\n};\n\n/**\n * Checks whether a wallet provider supports connecting with a specific hardware wallet vendor.\n *\n * @param params.walletProviderKey - The key of the wallet provider to check.\n * @param params.hardwareWalletVendor - The hardware wallet vendor to check for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns Whether the wallet provider supports the specified hardware wallet vendor.\n * @not-instrumented\n */\nexport const canConnectWithHardwareWallet = (\n {\n walletProviderKey,\n hardwareWalletVendor,\n }: CanConnectWithHardwareWalletParams,\n client = getDefaultClient()\n): boolean => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey },\n client\n );\n\n return (\n walletProvider.metadata.supportedHardwareWalletVendors?.includes(\n hardwareWalletVendor\n ) ?? false\n );\n};\n","import type { WalletAccount } from '../../walletAccount';\n\ntype IsHardwareWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks whether a wallet account was connected via a hardware wallet.\n *\n * @param params.walletAccount - The wallet account to check.\n * @returns Whether the wallet account has a hardware wallet vendor set.\n * @not-instrumented\n */\nexport const isHardwareWalletAccount = ({\n walletAccount,\n}: IsHardwareWalletAccountParams): boolean =>\n walletAccount.hardwareWalletVendor !== undefined;\n","import type { WalletAccount } from '../walletAccount';\n\ntype isWalletAccountVerifiedParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks if a wallet account has been verified by a user.\n *\n * @param walletAccount - The wallet account to check.\n * @returns True if the wallet account has been verified, false otherwise.\n * @not-instrumented\n */\nexport const isWalletAccountVerified = ({\n walletAccount,\n}: isWalletAccountVerifiedParams) => {\n return walletAccount.verifiedCredentialId !== null;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { NetworkAddingUnavailableError } from '../../../../errors/NetworkAddingUnavailableError';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\nimport type { NetworkData } from '../networkProvider/networkProvider.types';\n\ntype AddNetworkParams = {\n networkData: NetworkData;\n walletAccount: WalletAccount;\n};\n\n/**\n * Adds a network to the wallet provider.\n *\n * This function requests that the wallet provider add a network\n * to its list of available networks.\n *\n * @param params.networkData - The network configuration data to add to the wallet.\n * @param params.walletAccount - The wallet account to add the network for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the network addition is complete.\n * @throws NetworkAddingUnavailableError If the wallet provider doesn't support adding networks.\n * @instrumented\n */\nexport const addNetwork = async (\n { networkData, walletAccount }: AddNetworkParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n if (walletProvider.addNetwork === undefined) {\n throw new NetworkAddingUnavailableError({\n extraMessages: [\n `Wallet provider ${walletAccount.walletProviderKey} does not have addNetwork method`,\n ],\n originalError: null,\n walletProviderKey: walletAccount.walletProviderKey,\n });\n }\n\n return walletProvider.addNetwork({ networkData });\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getNetworksData } from '../getNetworksData';\n\ntype GetActiveNetworkDataParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Retrieves the network configuration data for the currently active network.\n *\n * This function returns detailed network information including RPC URLs,\n * native currency details, and block explorer URLs for the network that\n * the wallet account is currently connected to.\n *\n * @param params.walletAccount - The wallet account to get network data for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the network data, or undefined if not found.\n * @not-instrumented\n */\nexport const getActiveNetworkData = async (\n { walletAccount }: GetActiveNetworkDataParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const networksData = getNetworksData(client);\n\n const activeNetworkData = networksData.find(\n (data) =>\n data.networkId === networkId && data.chain === walletProvider.chain\n );\n\n return { networkData: activeNetworkData };\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype GetActiveNetworkIdParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * This function returns the network identifier that this wallet account's provider is currently connected to.\n *\n * @param params.walletAccount - The wallet account to get the network ID for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the active network ID for the wallet account.\n * @not-instrumented\n */\nexport const getActiveNetworkId = (\n { walletAccount }: GetActiveNetworkIdParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n return walletProvider.getActiveNetworkId();\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderFromWalletAccount } from '../../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getNetworkProviderFromNetworkId } from '../getNetworkProviderFromNetworkId';\n\ntype GetNativeBalanceParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Retrieves the native token balance for a wallet account on its active\n * network. Reads directly from the chain's network provider (RPC), not\n * the Dynamic API.\n *\n * Use this when you only need the user's gas / native-currency balance\n * (ETH, SOL, BTC, etc.). For token balances, use\n * {@link getTokenBalances}; for a multi-chain portfolio snapshot, use\n * {@link getMultichainTokenBalances}.\n *\n * @param params.walletAccount - The wallet account to get the balance for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the balance as a string or null.\n * @not-instrumented\n */\nexport const getNativeBalance = async (\n { walletAccount }: GetNativeBalanceParams,\n client = getDefaultClient()\n): Promise<{ balance: string | null }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n const { networkId } = await walletProvider.getActiveNetworkId();\n\n const networkProvider = getNetworkProviderFromNetworkId(\n { chain: walletProvider.chain, networkId },\n client\n );\n\n return networkProvider.getBalance({ address: walletAccount.address });\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getNativeBalance } from '../getNativeBalance/getNativeBalance';\n\ntype GetBalanceParams = Parameters<typeof getNativeBalance>[0];\n\n/**\n * @deprecated Use {@link getNativeBalance} instead. Renamed so its name\n * states what it returns (native gas balance) and is no longer confusable\n * with the token-balance fetchers (`getTokenBalances` /\n * `getMultichainTokenBalances`).\n *\n * @not-instrumented\n */\n// Wrapper, not an `export { … as … }` alias: TS does not surface a\n// deprecation tag on a re-export line, so the tag would never warn consumers.\nexport const getBalance = (\n params: GetBalanceParams,\n client = getDefaultClient()\n): ReturnType<typeof getNativeBalance> => getNativeBalance(params, client);\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { assertDefined } from '../../../../utils/assertDefined';\nimport type { Chain } from '../../../chain';\nimport { getNetworkProviderFromNetworkId } from '../getNetworkProviderFromNetworkId';\n\ntype GetBalanceForAddressParams = {\n address: string;\n chain: Chain;\n networkId: string;\n};\n\n/**\n * Retrieves the native token balance for a specific address on a given network.\n *\n * This function queries the balance directly for any address without requiring\n * a connected wallet account, useful for checking balances of external addresses.\n *\n * @param params.address - The wallet address to check the balance for.\n * @param params.chain - The chain (e.g., 'EVM', 'SOL').\n * @param params.networkId - The specific network ID within the chain.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the balance as a string or null.\n * @not-instrumented\n */\nexport const getBalanceForAddress = async (\n { address, chain, networkId }: GetBalanceForAddressParams,\n client = getDefaultClient()\n): Promise<{ balance: string | null }> => {\n const networkProvider = getNetworkProviderFromNetworkId(\n { chain, networkId },\n client\n );\n\n assertDefined(\n networkProvider,\n `No network found for chain ${chain} and network id ${networkId}. Please ensure you've enabled this network in the Dashboard.`\n );\n\n return networkProvider.getBalance({ address });\n};\n","import type {\n ChainEnum,\n WalletTransactionsResponse,\n} from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport type { Chain } from '../../../chain/chain.types';\n\nexport type GetTransactionHistoryParams = {\n address: string;\n chain: Chain;\n limit?: number;\n networkId: number;\n offset?: string;\n tokenAddress?: string;\n};\n\nexport type GetTransactionHistoryResponse = WalletTransactionsResponse;\n\n/**\n * Retrieves the transaction history for a given wallet address, chain and network.\n *\n * This function fetches the transaction history for a specified wallet address and chain,\n * returning a list of transactions associated with that address along with nextOffset for pagination.\n *\n * @param params.address - The wallet address to query transactions for.\n * @param params.chain - The chain to query transactions for.\n * @param [params.limit] - The maximum number of transactions to return.\n * @param params.networkId - The network ID to query transactions for.\n * @param [params.offset] - The offset to use for pagination.\n * @param [params.tokenAddress] - Optional token contract address (EVM) or SPL mint address (Solana) to filter transaction history by token.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the transaction history along with nextOffset for the given wallet address and chain.\n * @not-instrumented\n */\nexport const getTransactionHistory = async (\n params: GetTransactionHistoryParams,\n client = getDefaultClient()\n): Promise<WalletTransactionsResponse> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.getWalletTransactions({\n address: params.address,\n // eslint-disable-next-line custom-rules/ban-chain-enum\n chainName: params.chain as ChainEnum,\n environmentId: core.environmentId,\n limit: params.limit,\n networkId: params.networkId,\n offset: params.offset,\n tokenAddress: params.tokenAddress,\n });\n\n return response;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype IsProgrammaticNetworkSwitchAvailableParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Checks if programmatic network switching is available for a wallet account.\n *\n * This function determines whether the wallet provider supports automatic\n * network switching without requiring the user to manually switch networks on their wallet app.\n *\n * @param params.walletAccount - The wallet account to check network switching support for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns True if programmatic network switching is available, false otherwise.\n * @not-instrumented\n */\nexport const isProgrammaticNetworkSwitchAvailable = (\n { walletAccount }: IsProgrammaticNetworkSwitchAvailableParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n return walletProvider.switchActiveNetwork !== undefined;\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport { NetworkSwitchingUnavailableError } from '../../../../errors/NetworkSwitchingUnavailableError';\nimport { getWalletProviderByKey } from '../../getWalletProviderByKey';\nimport type { WalletAccount } from '../../walletAccount';\n\ntype SwitchActiveNetworkParams = {\n networkId: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Switches the active network for a wallet account.\n *\n * This function programmatically changes the network\n * that the wallet is currently connected to.\n *\n * @param params.networkId - The identifier of the network to switch to. Should match the networkId of the network data.\n * @param params.walletAccount - The wallet account to switch networks for.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the network switch is complete.\n * @throws NetworkSwitchingUnavailableError If the wallet provider doesn't support network switching.\n * @instrumented\n */\nexport const switchActiveNetwork = async (\n { networkId, walletAccount }: SwitchActiveNetworkParams,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey(\n { walletProviderKey: walletAccount.walletProviderKey },\n client\n );\n\n if (walletProvider.switchActiveNetwork === undefined) {\n throw new NetworkSwitchingUnavailableError({\n extraMessages: [\n `Wallet provider ${walletAccount.walletProviderKey} does not have switchActiveNetwork method`,\n ],\n originalError: null,\n walletProviderKey: walletAccount.walletProviderKey,\n });\n }\n\n return walletProvider.switchActiveNetwork({ networkId });\n};\n","import { getCore } from '../../../../client/core/getCore';\nimport { getDefaultClient } from '../../../../client/defaultClient';\nimport { createApiClient } from '../../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../../auth/updateAuthFromVerifyResponse';\nimport { setUnverifiedWalletAccounts } from '../../unverifiedWalletAccounts/setUnverifiedWalletAccounts';\nimport type { WalletAccount } from '../../walletAccount';\nimport { getPrimaryWalletAccount } from './../getPrimaryWalletAccount';\n\ntype SelectPrimaryWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Make the wallet account provided as the primary wallet account.\n * @instrumented\n */\nexport const selectPrimaryWalletAccount = async (\n { walletAccount }: SelectPrimaryWalletAccountParams,\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n\n const currentPrimaryWalletAccount = getPrimaryWalletAccount(client);\n\n if (currentPrimaryWalletAccount?.id === walletAccount.id) {\n return;\n }\n\n if (walletAccount.verifiedCredentialId) {\n const apiClient = createApiClient({}, client);\n\n const response = await apiClient.selectUserWallet({\n environmentId: core.environmentId,\n userWalletSelectionRequest: {\n walletId: walletAccount.verifiedCredentialId,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n } else {\n const updatedWalletAccount = {\n ...walletAccount,\n lastSelectedAt: new Date(),\n };\n\n setUnverifiedWalletAccounts(\n {\n unverifiedWalletAccountsToUpdate: [updatedWalletAccount],\n },\n client\n );\n }\n};\n","import type { DynamicClient } from '../../../client/types';\nimport { NoWalletProviderFoundError } from '../../../errors/NoWalletProviderFoundError';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype DisconnectWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * This function disconnects the specified wallet account with the wallet provider.\n *\n * The wallet account is not removed from the user's profile or from dynamic's state,\n * it is only responsible for terminating the connection with the wallet provider.\n * @not-instrumented\n */\nexport const disconnectWalletAccount = async (\n { walletAccount }: DisconnectWalletAccountParams,\n client: DynamicClient\n): Promise<void> => {\n try {\n const walletProvider = getWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n await walletProvider.disconnectWalletAccount?.({ walletAccount });\n } catch (error) {\n // If there is no wallet provider, we don't need to do anything\n // as the wallet account is not connected. It's fine to ignore this error.\n if (error instanceof NoWalletProviderFoundError) {\n return;\n }\n\n throw error;\n }\n};\n","import { getCore } from '../../../client/core/getCore';\nimport { getDefaultClient } from '../../../client/defaultClient';\nimport { createApiClient } from '../../apiClient';\nimport { updateAuthFromVerifyResponse } from '../../auth/updateAuthFromVerifyResponse';\nimport { disconnectWalletAccount } from '../disconnectWalletAccount';\nimport { removeUnverifiedWalletAccount } from '../unverifiedWalletAccounts/removeUnverifiedWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype RemoveWalletAccountParams = {\n walletAccount: WalletAccount;\n};\n\n/**\n * Removes a wallet account from the current session or user (if authenticated).\n *\n * This function both disconnects and removes the specified wallet account,\n * updating local state and server records (if there is an authenticated user).\n * For verified wallets, it will unlink them from the user's account.\n *\n * @param params.walletAccount - The wallet account to remove.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves when the wallet account is successfully removed.\n * @instrumented\n */\nexport const removeWalletAccount = async (\n { walletAccount }: RemoveWalletAccountParams,\n client = getDefaultClient()\n): Promise<void> => {\n const core = getCore(client);\n const apiClient = createApiClient({}, client);\n\n await disconnectWalletAccount({ walletAccount }, client);\n\n if (!walletAccount.verifiedCredentialId) {\n removeUnverifiedWalletAccount(\n { unverifiedWalletAccount: walletAccount },\n client\n );\n\n return;\n }\n\n const response = await apiClient.verifyUnlink({\n environmentId: core.environmentId,\n verifyUnlinkRequest: {\n walletId: walletAccount.verifiedCredentialId,\n },\n });\n\n updateAuthFromVerifyResponse({ response }, client);\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { WalletAccount } from '../walletAccount';\n\ntype SignMessageParams = {\n message: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Signs a message using the specified wallet account.\n *\n * This function uses the wallet's private key to cryptographically sign\n * the provided message.\n *\n * @param params.walletAccount - The wallet account to use for signing.\n * @param params.message - The message to sign.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the signature.\n * @instrumented\n */\nexport const signMessage = async (\n { walletAccount, message }: SignMessageParams,\n client = getDefaultClient()\n): Promise<{ signature: string }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'signMessage');\n\n const { signature } = await walletProvider.signMessage({\n message,\n walletAccount,\n });\n\n return { signature };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { assertWalletProviderMethodDefined } from '../utils/assertWalletProviderMethodDefined';\nimport { getWalletProviderFromWalletAccount } from '../utils/getWalletProviderFromWalletAccount';\nimport type { TransferAmountParams } from '../walletProvider/walletProvider.types';\n\n/**\n * Transfers an amount of currency from the wallet account to a recipient.\n *\n * Supports native token transfers and, where supported by the chain,\n * fungible/token transfers via the optional `token` parameter.\n *\n * @param params.walletAccount - The wallet account to transfer from.\n * @param params.amount - The amount to transfer as a decimal string (e.g. \"1.5\").\n * @param params.recipient - The recipient address.\n * @param params.token - Optional token info for non-native transfers.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to an object containing the transaction hash.\n * @throws If the wallet provider does not support the transfer amount method.\n * @instrumented\n */\nexport const transferAmount = async (\n { walletAccount, amount, recipient, token }: TransferAmountParams,\n client = getDefaultClient()\n): Promise<{ transactionHash: string }> => {\n const walletProvider = getWalletProviderFromWalletAccount(\n {\n walletAccount,\n },\n client\n );\n\n assertWalletProviderMethodDefined(walletProvider, 'transferAmount');\n\n const { transactionHash } = await walletProvider.transferAmount({\n amount,\n recipient,\n token,\n walletAccount,\n });\n\n return { transactionHash };\n};\n","import { getDefaultClient } from '../../../client/defaultClient';\nimport { connectWithWalletProvider } from '../connectWithWalletProvider';\nimport { verifyWalletAccountForSignInOrTransfer } from '../verifyWalletAccountForSignInOrTransfer';\n\ntype TransferWalletAccountParams = {\n walletProviderKey: string;\n};\n\n/**\n * Transfer a wallet account to the current user's account.\n *\n * This function requires the user to sign a message to prove wallet ownership,\n * then transfers the wallet account to the current user's account.\n *\n * @param params.walletProviderKey - The key of the wallet provider of the wallet account to transfer.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A promise that resolves to the transferred wallet account.\n * @instrumented\n */\nexport const transferWalletAccount = async (\n { walletProviderKey }: TransferWalletAccountParams,\n client = getDefaultClient()\n) => {\n const walletAccount = await connectWithWalletProvider(\n { addToDynamicWalletAccounts: false, walletProviderKey },\n client\n );\n\n return verifyWalletAccountForSignInOrTransfer(\n {\n isTransfer: true,\n walletAccount,\n },\n client\n );\n};\n","import { getDefaultClient } from '../../../../client/defaultClient';\nimport type { Chain } from '../../../chain';\nimport { getWalletAccounts } from '../../getWalletAccounts';\n\ntype GetWalletAccountFromAddressParams = {\n address: string;\n chain: Chain;\n};\n\n/**\n * Finds a wallet account by address and blockchain.\n *\n * This function searches through the current session's wallet accounts\n * to find one matching the specified address and chain.\n *\n * @param params.address - The wallet address to search for.\n * @param params.chain - The blockchain the wallet belongs to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns The matching wallet account, or undefined if not found.\n * @not-instrumented\n */\nexport const getWalletAccountFromAddress = (\n { address, chain }: GetWalletAccountFromAddressParams,\n client = getDefaultClient()\n) => {\n const walletAccounts = getWalletAccounts(client);\n\n return walletAccounts.find(\n (walletAccount) =>\n walletAccount.address === address && walletAccount.chain === chain\n );\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../../getWalletProviderByKey';\nimport { assertWalletProviderMethodDefined } from '../../../utils/assertWalletProviderMethodDefined';\nimport type { WalletProviderEvents } from '../walletProviderEvents.types';\n\ntype OffWalletProviderEventParams<\n E extends Extract<keyof WalletProviderEvents, string>\n> = {\n callback: WalletProviderEvents[E];\n event: E;\n walletProviderKey: string;\n};\n\n/**\n * Removes a listener from a wallet provider event.\n * You can alternatively use the returned function from `onWalletProviderEvent` instead of using this function.\n *\n * @param params.callback - The callback function to remove. This should be the same function that was passed to the `onWalletProviderEvent` function.\n * @see onWalletProviderEvent\n * @param params.event - The event name to remove the listener from.\n * @param params.walletProviderKey - The unique key identifying the wallet provider to remove the listener from.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @not-instrumented\n */\nexport const offWalletProviderEvent = <\n E extends Extract<keyof WalletProviderEvents, string>\n>(\n { callback, event, walletProviderKey }: OffWalletProviderEventParams<E>,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n assertWalletProviderMethodDefined(walletProvider, 'events');\n\n // We use any here because typescript is messing up the type inference\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.off(event, callback as any);\n};\n","import { getDefaultClient } from '../../../../../client/defaultClient';\nimport { getWalletProviderByKey } from '../../../getWalletProviderByKey';\nimport { assertWalletProviderMethodDefined } from '../../../utils/assertWalletProviderMethodDefined';\nimport type { WalletProviderEvents } from '../walletProviderEvents.types';\n\nexport type OnWalletProviderEventParams<\n E extends Extract<keyof WalletProviderEvents, string>\n> = {\n callback: WalletProviderEvents[E];\n event: E;\n walletProviderKey: string;\n};\n\n/**\n * Listens to a wallet provider event.\n *\n * @param params.callback - The callback function to execute when the event is fired.\n * @param params.event - The event name to listen for.\n * @param params.walletProviderKey - The unique key identifying the wallet provider to listen to.\n * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.\n * @returns A function that can be called to remove the listener.\n * @not-instrumented\n */\nexport const onWalletProviderEvent = <\n E extends Extract<keyof WalletProviderEvents, string>\n>(\n { callback, event, walletProviderKey }: OnWalletProviderEventParams<E>,\n client = getDefaultClient()\n) => {\n const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);\n\n assertWalletProviderMethodDefined(walletProvider, 'events');\n\n // We use any here because typescript is messing up the type inference\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.on(event, callback as any);\n\n return () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n walletProvider.events.off(event, callback as any);\n };\n};\n","type ParseUserAgentParams = {\n userAgent: string;\n};\n\ntype ParsedUserAgent = {\n displayText: string;\n type: 'mobile' | 'desktop';\n};\n\nconst browserMatchers = [\n { name: 'Edge', pattern: /Edg(e|A|iOS)?\\// },\n { name: 'Opera', pattern: /OPR\\/|Opera/ },\n { name: 'Samsung Browser', pattern: /SamsungBrowser/ },\n { name: 'Firefox', pattern: /Firefox/ },\n { name: 'Safari', pattern: /^(?!.*(?:Chrome|Chromium|CriOS)).*Safari/ },\n { name: 'Chrome', pattern: /Chrome|CriOS/ },\n] as const;\n\nconst mobileOsNames = new Set(['iPhone', 'iPad', 'Android']);\n\nconst osMatchers = [\n { name: 'iPhone', pattern: /iPhone/ },\n { name: 'iPad', pattern: /iPad/ },\n { name: 'Android', pattern: /Android/ },\n { name: 'Windows', pattern: /Windows/ },\n { name: 'macOS', pattern: /Macintosh|Mac OS X/ },\n { name: 'Linux', pattern: /Linux/ },\n { name: 'ChromeOS', pattern: /CrOS/ },\n] as const;\n\n/** @not-instrumented */\nexport const parseUserAgent = ({\n userAgent,\n}: ParseUserAgentParams): ParsedUserAgent | null => {\n if (!userAgent?.trim()) {\n return null;\n }\n\n const browser = browserMatchers.find(({ pattern }) =>\n pattern.test(userAgent),\n )?.name;\n\n const os = osMatchers.find(({ pattern }) => pattern.test(userAgent))?.name;\n\n if (!browser && !os) {\n return null;\n }\n\n const isMobile = os ? mobileOsNames.has(os) : false;\n\n const displayText =\n browser && os ? `${browser} on ${os}` : (browser ?? os ?? '');\n\n return {\n displayText,\n type: isMobile ? 'mobile' : 'desktop',\n };\n};\n","/* eslint-disable import/no-unassigned-import */\n\nimport { assertPackageVersion } from '@dynamic-labs-sdk/assert-package-version';\n\nimport {\n name as packageName,\n version as packageVersion,\n} from '../../package.json';\nassertPackageVersion(packageName, packageVersion);\n\n// Import the modules states so that they are available in the global scope.\nimport '../modules/auth/state';\nimport '../modules/captcha/state';\nimport '../modules/initializeClient/state';\nimport '../modules/mfa/state';\nimport '../modules/projectSettings/state';\nimport '../modules/sessionKeys/state';\nimport '../modules/wallets/unverifiedWalletAccounts/state';\nimport '../modules/wallets/walletProvider/walletProviderKeyMap/state';\nimport '../utils/getNonce/state';\n\n// Import the event types for the modules so that they are available in the global scope.\nimport '../modules/auth/events';\nimport '../modules/deviceRegistration/events';\nimport '../modules/mfa/events';\nimport '../modules/state/raiseStateEvents/events';\nimport '../modules/wallets/walletAccount/events';\nimport '../modules/wallets/walletProviderRegistry/events';\n\nexport { appendConnectionUriToDeeplink } from '../utils/appendConnectionUriToDeeplink/appendConnectionUriToDeeplink';\nexport { MFAAction } from '@dynamic-labs/sdk-api-core';\nexport type {\n CreateMfaToken,\n DeviceRegistrationResponse,\n TokenScope,\n UserPasskey,\n VerifyResponse,\n} from '@dynamic-labs/sdk-api-core';\nexport type { DynamicCoreConfig } from '../client/core/types';\nexport { createDynamicClient } from '../client/createDynamicClient';\nexport { getDefaultClient } from '../client/defaultClient';\nexport type { DynamicClient, DynamicClientConfig } from '../client/types';\nexport { BaseError, type BaseErrorParameters } from '../errors/base';\nexport { CheckoutSessionTokenMissingError } from '../errors/CheckoutSessionTokenMissingError';\nexport { ClientAlreadyInitializedError } from '../errors/ClientAlreadyInitializedError';\nexport { DeeplinkConnectAndVerifyUnsupportedError } from '../errors/DeeplinkConnectAndVerifyUnsupportedError';\nexport { FeeEstimationFailedError } from '../errors/FeeEstimationFailedError';\nexport { InvalidDeviceRegistrationRedirectError } from '../errors/InvalidDeviceRegistrationRedirectError';\nexport { InvalidExternalAuthError } from '../errors/InvalidExternalAuthError';\nexport { InvalidParamError } from '../errors/InvalidParamError';\nexport { InvalidRedirectStorageStateError } from '../errors/InvalidRedirectStorageStateError';\nexport { InvalidSocialCallbackOriginError } from '../errors/InvalidSocialCallbackOriginError';\nexport { UserCancelledSocialPopUpError } from '../errors/UserCancelledSocialPopUpError';\nexport { LinkCredentialError } from '../errors/LinkCredentialError';\nexport { MfaInvalidOtpError } from '../errors/MfaInvalidOtpError';\nexport { MfaRateLimitedError } from '../errors/MfaRateLimitedError';\nexport { MissingRedirectStorageStateError } from '../errors/MissingRedirectStorageStateError';\nexport { MissingSocialUrlParamError } from '../errors/MissingSocialUrlParamError';\nexport { MissingUserVerificationError } from '../errors/MissingUserVerificationError';\nexport { NetworkAddingUnavailableError } from '../errors/NetworkAddingUnavailableError';\nexport { NetworkNotAddedError } from '../errors/NetworkNotAddedError';\nexport { NetworkSwitchingUnavailableError } from '../errors/NetworkSwitchingUnavailableError';\nexport { NoAddressFoundError } from '../errors/NoAddressFoundError';\nexport { NoNetworkProvidersError } from '../errors/NoNetworkProvidersError';\nexport { NoPasskeyCredentialsFoundError } from '../errors/NoPasskeyCredentialsFoundError';\nexport { NoSmartWalletAccountSignerFoundError } from '../errors/NoSmartWalletAccountSignerFoundError';\nexport { NotWaasWalletAccountError } from '../errors/NotWaasWalletAccountError';\nexport { NoWebAuthNSupportError } from '../errors/NoWebAuthNSupportError';\nexport { SandboxMaximumThresholdReachedError } from '../errors/SandboxMaximumThresholdReachedError';\nexport { SimulationFailedError } from '../errors/SimulationFailedError';\nexport { TokenSwapError } from '../errors/TokenSwapError';\nexport { UnauthorizedError } from '../errors/UnauthorizedError';\nexport { UnavailableInServerSideError } from '../errors/UnavailableInServerSideError';\nexport { UnrecognizedNetworkError } from '../errors/UnrecognizedNetworkError';\nexport { UserNotAuthenticatedError } from '../errors/UserNotAuthenticatedError';\nexport { UserRejectedError } from '../errors/UserRejectedError';\nexport { WalletAccountAlreadyVerifiedError } from '../errors/WalletAccountAlreadyVerifiedError';\nexport { WalletAccountNotSelectedError } from '../errors/WalletAccountNotSelectedError';\nexport { WalletAlreadyLinkedToAnotherUserError } from '../errors/WalletAlreadyLinkedToAnotherUserError';\nexport { WalletProviderMethodUnavailableError } from '../errors/WalletProviderMethodUnavailableError';\nexport { checkStepUpAuth } from '../modules/auth/checkStepUpAuth';\nexport type { LogoutEventMetadata } from '../modules/auth/events';\nexport { requestExternalAuthElevatedToken } from '../modules/auth/externalAuth/requestExternalAuthElevatedToken';\nexport { signInWithExternalJwt } from '../modules/auth/externalAuth/signInWithExternalJwt';\nexport { getElevatedAccessToken } from '../modules/auth/getElevatedAccessToken';\nexport { isSignedIn } from '../modules/auth/isSignedIn';\nexport { logout } from '../modules/auth/logout';\nexport type { LogoutReason } from '../modules/auth/logoutReason';\nexport { deletePasskey } from '../modules/auth/passkeys/deletePasskey';\nexport { getPasskeys } from '../modules/auth/passkeys/getPasskeys';\nexport { registerPasskey } from '../modules/auth/passkeys/registerPasskey';\nexport { signInWithPasskey } from '../modules/auth/passkeys/signInWithPasskey';\nexport { getUserSocialAccounts } from '../modules/auth/social/getUserSocialAccounts';\nexport { signInWithSocialRedirect } from '../modules/auth/social/oauth/signInWithSocialRedirect';\nexport { signInWithSocialPopUp } from '../modules/auth/social/oauth/signInWithSocialPopUp';\nexport { detectSocialRedirectUrl } from '../modules/auth/social/oauth/detectSocialRedirectUrl';\nexport { completeSocialRedirect } from '../modules/auth/social/oauth/completeSocialRedirect';\nexport { authenticateWithSocial } from '../modules/auth/social/oauth/authenticateWithSocial';\nexport { completeSocialAuthentication } from '../modules/auth/social/oauth/completeSocialAuthentication';\nexport { detectOAuthRedirect } from '../modules/auth/social/oauth/detectOAuthRedirect';\nexport { unlinkSocialAccount } from '../modules/auth/social/oauth/unlinkSocialAccount';\nexport type {\n SocialAccount,\n SocialProvider,\n} from '../modules/auth/social/social.types';\nexport {\n getTokenBalances,\n type GetTokenBalancesParams,\n} from '../modules/balances/getTokenBalances';\nexport {\n getMultichainTokenBalances,\n type GetMultichainTokenBalancesParams,\n} from '../modules/balances/getMultichainTokenBalances';\nexport {\n getBalances,\n type GetBalancesParams,\n} from '../modules/balances/getBalances';\nexport {\n getMultichainBalances,\n type GetMultichainBalancesParams,\n} from '../modules/balances/getMultichainBalances';\nexport { isCaptchaRequired } from '../modules/captcha/isCaptchaRequired';\nexport { setCaptchaToken } from '../modules/captcha/setCaptchaToken';\nexport type { Chain } from '../modules/chain';\nexport { attachCheckoutTransactionSource } from '../modules/checkout/attachCheckoutTransactionSource';\nexport type { AttachCheckoutTransactionSourceParams } from '../modules/checkout/attachCheckoutTransactionSource';\nexport { broadcastCheckoutTransaction } from '../modules/checkout/broadcastCheckoutTransaction';\nexport type { BroadcastCheckoutTransactionParams } from '../modules/checkout/broadcastCheckoutTransaction';\nexport { cancelCheckoutTransaction } from '../modules/checkout/cancelCheckoutTransaction';\nexport type { CancelCheckoutTransactionParams } from '../modules/checkout/cancelCheckoutTransaction';\nexport type {\n CheckoutExecutionState,\n CheckoutFailure,\n CheckoutFeeBreakdown,\n CheckoutRiskState,\n CheckoutSettlementData,\n CheckoutSettlementState,\n CheckoutSourceType,\n CheckoutSupportedExchangeProvider,\n CheckoutTransaction,\n CheckoutTransactionCreateResponse,\n CheckoutTransactionQuote,\n} from '../modules/checkout/checkout.types';\nexport { createCheckoutTransaction } from '../modules/checkout/createCheckoutTransaction';\nexport type { CreateCheckoutTransactionParams } from '../modules/checkout/createCheckoutTransaction';\nexport type {\n CheckoutTransactionExecutionStateChangedEvent,\n CheckoutTransactionSettlementStateChangedEvent,\n} from '../modules/checkout/events';\nexport { getCheckoutTransaction } from '../modules/checkout/getCheckoutTransaction';\nexport type { GetCheckoutTransactionParams } from '../modules/checkout/getCheckoutTransaction';\nexport { getCheckoutTransactionQuote } from '../modules/checkout/getCheckoutTransactionQuote';\nexport type { GetCheckoutTransactionQuoteParams } from '../modules/checkout/getCheckoutTransactionQuote';\nexport { prepareCheckoutTransaction } from '../modules/checkout/prepareCheckoutTransaction';\nexport type { PrepareCheckoutTransactionParams } from '../modules/checkout/prepareCheckoutTransaction';\nexport { submitCheckoutTransaction } from '../modules/checkout/submitCheckoutTransaction';\nexport type { SubmitCheckoutTransactionParams } from '../modules/checkout/submitCheckoutTransaction';\nexport { trackCheckoutTransaction } from '../modules/checkout/trackCheckoutTransaction';\nexport type { TrackCheckoutTransactionParams } from '../modules/checkout/trackCheckoutTransaction';\nexport { requiresConversion } from '../modules/checkout/utils/requiresConversion';\nexport type { RequiresConversionParams } from '../modules/checkout/utils/requiresConversion';\nexport { offEvent, onceEvent, onEvent } from '../modules/clientEvents';\nexport type {\n DynamicEvents,\n OffEventParams,\n OnceEventParams,\n OnEventParams,\n} from '../modules/clientEvents/clientEvents.types';\nexport { completeDeviceRegistration } from '../modules/deviceRegistration/completeDeviceRegistration';\nexport { detectDeviceRegistrationRedirect } from '../modules/deviceRegistration/detectDeviceRegistrationRedirect';\nexport { getDeviceRegistrationTokenFromUrl } from '../modules/deviceRegistration/getDeviceRegistrationTokenFromUrl';\nexport { getRegisteredDevices } from '../modules/deviceRegistration/getRegisteredDevices';\nexport { isDeviceRegistrationRequired } from '../modules/deviceRegistration/isDeviceRegistrationRequired';\nexport { revokeAllRegisteredDevices } from '../modules/deviceRegistration/revokeAllRegisteredDevices';\nexport { revokeRegisteredDevice } from '../modules/deviceRegistration/revokeRegisteredDevice';\nexport { hasExtension } from '../modules/extension/hasExtension';\nexport { addCoinbaseOnrampOrderEventListener } from '../modules/funding/coinbase/addCoinbaseOnrampOrderEventListener';\nexport type {\n CoinbaseCreateOnrampOrderRequest,\n CoinbaseOnrampFeeType,\n CoinbaseOnrampGetBuyUrlRequest,\n CoinbaseOnrampGetBuyUrlResponse,\n CoinbaseOnrampMissingVerificationErrorCode,\n CoinbaseOnrampOrderPaymentLinkType,\n CoinbaseOnrampOrderPaymentMethod,\n CoinbaseOnrampOrderResponse,\n CoinbaseOnrampOrderStatus,\n FieldMissingVerificationForCoinbaseOnramp,\n} from '../modules/funding/coinbase/coinbase.types';\nexport { createCoinbaseOnrampOrder } from '../modules/funding/coinbase/createCoinbaseOnrampOrder';\nexport { getCoinbaseBuyUrl } from '../modules/funding/coinbase/getCoinbaseBuyUrl';\nexport { getMissingVerificationForCoinbaseOnrampOrder } from '../modules/funding/coinbase/getMissingVerificationForCoinbaseOnrampOrder';\nexport { createCryptoDotComPayment } from '../modules/funding/cryptoDotCom/createCryptoDotComPayment';\nexport type {\n CryptoDotComPaymentCreateRequest,\n CryptoDotComPaymentResponse,\n} from '../modules/funding/cryptoDotCom/cryptoDotCom.types';\nexport { getMoonPayCurrencies } from '../modules/funding/moonpay/getMoonPayCurrencies';\nexport { getMoonPayUrl } from '../modules/funding/moonpay/getMoonPayUrl';\nexport type {\n GetMoonPayCurrenciesParams,\n GetMoonPayUrlParams,\n MoonPayCurrency,\n} from '../modules/funding/moonpay/moonpay.types';\nexport {\n createKrakenExchangeTransfer,\n type KrakenTransferRequest,\n} from '../modules/funding/kraken/createKrakenExchangeTransfer';\nexport {\n getKrakenAccounts,\n type GetKrakenAccountsParams,\n} from '../modules/funding/kraken/getKrakenAccounts';\nexport { getKrakenWhitelistedAddresses } from '../modules/funding/kraken/getKrakenWhitelistedAddresses';\nexport type {\n ExchangeTransferResponse,\n KrakenAccount,\n TransferDestinationResponse,\n} from '../modules/funding/kraken/kraken.types';\nexport { initializeClient } from '../modules/initializeClient';\nexport type { DynamicInitStatus } from '../modules/initializeClient/state';\nexport { waitForClientInitialized } from '../modules/initializeClient/waitForClientInitialized';\nexport { setInstrumentationEnabled } from '../modules/instrumentation/setInstrumentationEnabled/setInstrumentationEnabled';\nexport { getWalletConnectCatalog } from '../modules/legacyWalletBook/getWalletConnectCatalog';\nexport type {\n WalletConnectCatalog,\n WalletConnectCatalogDeepLinks,\n WalletConnectCatalogGroup,\n WalletConnectCatalogWallet,\n} from '../modules/legacyWalletBook/getWalletConnectCatalog';\nexport { excludeInstalledFromCatalog } from '../modules/legacyWalletBook/excludeInstalledFromCatalog';\nexport { getWalletConnectCatalogWalletByWalletProviderKey } from '../modules/legacyWalletBook/getWalletConnectCatalogWalletByWalletProviderKey';\nexport { getInstallationLinkForCurrentPlatform } from '../modules/walletOptionsCatalogue/getInstallationLinkForCurrentPlatform';\nexport { getWalletOptionsCatalogue } from '../modules/walletOptionsCatalogue/getWalletOptionsCatalogue/getWalletOptionsCatalogue';\nexport type {\n GetWalletOptionsCatalogueParams,\n InAppBrowserConnectionOption,\n InstallationUrls,\n UriDeeplinkConnectionOption,\n WalletConnectionOption,\n WalletOption,\n WalletOptionOrdering,\n WalletOptionsCatalogue,\n WithWalletProviderConnectionOption,\n WithWalletProviderSource,\n} from '../modules/walletOptionsCatalogue/walletOptionsCatalogue.types';\nexport { matchWalletProvidersToCatalogGroup } from '../modules/legacyWalletBook/matchWalletProvidersToCatalogGroup';\nexport { acknowledgeRecoveryCodes } from '../modules/mfa/acknowledgeRecoveryCodes';\nexport { authenticateMfaRecoveryCode } from '../modules/mfa/authenticateMfaRecoveryCode';\nexport { authenticatePasskeyMFA } from '../modules/mfa/authenticatePasskeyMFA';\nexport { authenticateTotpMfaDevice } from '../modules/mfa/authenticateTotpMfaDevice';\nexport { consumeMfaToken } from '../modules/mfa/consumeMfaToken';\nexport { createNewMfaRecoveryCodes } from '../modules/mfa/createNewMfaRecoveryCodes';\nexport { deleteMfaDevice } from '../modules/mfa/deleteMfaDevice';\nexport { getMfaDevices } from '../modules/mfa/getMfaDevices';\nexport { getMfaMethods } from '../modules/mfa/getMfaMethods';\nexport { getMfaRecoveryCodes } from '../modules/mfa/getMfaRecoveryCodes';\nexport { isMfaRequiredForAction } from '../modules/mfa/isMfaRequiredForAction';\nexport { isPendingRecoveryCodesAcknowledgment } from '../modules/mfa/isPendingRecoveryCodesAcknowledgment';\nexport { isUserMissingMfaAuth } from '../modules/mfa/isUserMissingMfaAuth';\nexport type { MFADevice } from '../modules/mfa/mfa.types';\nexport { registerTotpMfaDevice } from '../modules/mfa/registerTotpMfaDevice';\nexport { setDefaultMfaDevice } from '../modules/mfa/setDefaultMfaDevice';\nexport type { OTPVerification } from '../modules/otp/otp.types';\nexport { sendEmailOTP } from '../modules/otp/sendEmailOTP';\nexport { sendSmsOTP } from '../modules/otp/sendSmsOTP';\nexport {\n supportedCountries,\n type CountryCode,\n} from '../modules/otp/sendSmsOTP/supportedCountries';\nexport { verifyOTP } from '../modules/otp/verifyOTP';\nexport { fetchProjectSettings } from '../modules/projectSettings/fetchProjectSettings';\nexport type {\n BlockaidValidation,\n SimulationResult,\n TransactionFeeData,\n} from '../modules/simulation/simulation.types';\nexport { executeSwapTransaction } from '../modules/swap/executeSwapTransaction';\nexport type { ExecuteSwapTransactionParams } from '../modules/swap/executeSwapTransaction';\nexport { getSwapQuote } from '../modules/swap/getSwapQuote';\nexport type { GetSwapQuoteParams } from '../modules/swap/getSwapQuote';\nexport { getSwapStatus } from '../modules/swap/getSwapStatus';\nexport type { GetSwapStatusParams } from '../modules/swap/getSwapStatus';\nexport type {\n SwapQuoteOrder,\n SwapQuoteResponse,\n SwapStatus,\n SwapStatusResponse,\n SwapSubstatus,\n SwapSubstatusDone,\n SwapSubstatusFailed,\n SwapSubstatusPending,\n SwapTransactionSigningPayload,\n} from '../modules/swap/swap.types';\nexport { deleteUser } from '../modules/user/deleteUser';\nexport { isUserOnboardingComplete } from '../modules/user/isUserOnboardingComplete';\nexport { refreshAuth } from '../modules/user/refreshAuth';\nexport { refreshUser } from '../modules/user/refreshUser';\nexport { updateUser } from '../modules/user/updateUser';\nexport type { UpdateUserFields } from '../modules/user/user.types';\nexport { GOOGLE_DRIVE_BACKUP_REQUIRED_SCOPES } from '../modules/walletBackup/googleDrive/constants';\nexport { findMissingGoogleDriveBackupScopes } from '../modules/walletBackup/googleDrive/findMissingGoogleDriveBackupScopes';\nexport { getGoogleDriveBackupReadiness } from '../modules/walletBackup/googleDrive/getGoogleDriveBackupReadiness';\nexport type {\n GoogleDriveBackupReadiness,\n GoogleDriveBackupReadinessStatus,\n} from '../modules/walletBackup/googleDrive/googleDrive.types';\nexport { hasAllGoogleDriveBackupScopes } from '../modules/walletBackup/googleDrive/hasAllGoogleDriveBackupScopes';\nexport { isInsufficientGoogleDriveScopesError } from '../modules/walletBackup/googleDrive/isInsufficientGoogleDriveScopesError';\nexport { assertWalletAccountSigningAvailability } from '../modules/wallets/assertWalletAccountSigningAvailability';\nexport { confirmTransaction } from '../modules/wallets/confirmTransaction';\nexport { connectAndVerifyWithWalletProvider } from '../modules/wallets/connectAndVerifyWithWalletProvider';\nexport { connectWithWalletProvider } from '../modules/wallets/connectWithWalletProvider';\nexport { getAvailableWalletProvidersData } from '../modules/wallets/getAvailableWalletProvidersData';\nexport { getConnectedAddresses } from '../modules/wallets/getConnectedAddresses';\nexport { getOwnerWalletAccountForSmartWalletAccount } from '../modules/wallets/getOwnerWalletAccountForSmartWalletAccount';\nexport { getWalletAccountAddressByType } from '../modules/wallets/getWalletAccountAddressByType';\nexport { getWalletAccounts } from '../modules/wallets/getWalletAccounts';\nexport { getWalletProviderDataByKey } from '../modules/wallets/getWalletProviderDataByKey';\nexport { isAnyWalletAccountConnected } from '../modules/wallets/isAnyWalletAccountConnected';\nexport { canConnectWithHardwareWallet } from '../modules/wallets/hardwareWallet/canConnectWithHardwareWallet';\nexport type { HardwareWalletVendor } from '../modules/wallets/hardwareWallet/hardwareWallet.types';\nexport { isHardwareWalletAccount } from '../modules/wallets/hardwareWallet/isHardwareWalletAccount';\nexport { isWalletAccountVerified } from '../modules/wallets/isWalletAccountVerified';\nexport { addNetwork } from '../modules/wallets/networks/addNetwork';\nexport { getActiveNetworkData } from '../modules/wallets/networks/getActiveNetworkData';\nexport { getActiveNetworkId } from '../modules/wallets/networks/getActiveNetworkId';\nexport { getNativeBalance } from '../modules/wallets/networks/getNativeBalance';\nexport { getBalance } from '../modules/wallets/networks/getBalance';\nexport { getBalanceForAddress } from '../modules/wallets/networks/getBalanceForAddress';\nexport { getNetworksData } from '../modules/wallets/networks/getNetworksData';\nexport {\n getTransactionHistory,\n type GetTransactionHistoryParams,\n type GetTransactionHistoryResponse,\n} from '../modules/wallets/networks/getTransactionHistory';\nexport { isProgrammaticNetworkSwitchAvailable } from '../modules/wallets/networks/isProgrammaticNetworkSwitchAvailable';\nexport type { NetworkProvider } from '../modules/wallets/networks/networkProvider';\nexport type { NetworkData } from '../modules/wallets/networks/networkProvider/networkProvider.types';\nexport { switchActiveNetwork } from '../modules/wallets/networks/switchActiveNetwork';\nexport { getPrimaryWalletAccount } from '../modules/wallets/primaryWalletAccount/getPrimaryWalletAccount';\nexport { selectPrimaryWalletAccount } from '../modules/wallets/primaryWalletAccount/selectPrimaryWalletAccount';\nexport { proveWalletAccountOwnership } from '../modules/wallets/proveWalletAccountOwnership';\nexport { removeWalletAccount } from '../modules/wallets/removeWalletAccount';\nexport { signMessage } from '../modules/wallets/signMessage';\nexport { transferAmount } from '../modules/wallets/transferAmount';\nexport { transferWalletAccount } from '../modules/wallets/transferWalletAccount';\nexport { assertWalletProviderMethodDefined } from '../modules/wallets/utils/assertWalletProviderMethodDefined';\nexport { getWalletAccountFromAddress } from '../modules/wallets/utils/getWalletAccountFromAddress';\nexport { verifyWalletAccount } from '../modules/wallets/verifyWalletAccount';\nexport type {\n WalletAccount,\n WalletAddressType,\n} from '../modules/wallets/walletAccount';\nexport type {\n ConfirmTransactionParams,\n TransferAmountParams,\n WalletProviderData,\n WalletProviderMetadata,\n} from '../modules/wallets/walletProvider';\nexport type { WalletProviderUriConnectionResult } from '../modules/wallets/walletProviderUriConnection.types';\nexport { offWalletProviderEvent } from '../modules/wallets/walletProvider/events/offWalletProviderEvent';\nexport { onWalletProviderEvent } from '../modules/wallets/walletProvider/events/onWalletProviderEvent';\nexport type { OnWalletProviderEventParams } from '../modules/wallets/walletProvider/events/onWalletProviderEvent/onWalletProviderEvent';\nexport type { WalletProviderEvents } from '../modules/wallets/walletProvider/events/walletProviderEvents.types';\nexport { isDeeplinkWalletProvider } from '../modules/wallets/walletProvider/isDeeplinkWalletProvider';\nexport type { DeviceSigner } from '../services/deviceSigner';\nexport { isMobile } from '../utils/isMobile';\nexport { parseUserAgent } from '../utils/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AA;GACjC;;EAEF,eAAgB,KAAA;EACjB,CAAA;;;;;;;;;;;;;;;;;;;;;;AC+MD,MAAaC,qBAAuC;CAClD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MAAM;EACP;CACD,IAAI;EACF,MAAM;EACN,MA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