@dynamic-labs-sdk/client 1.24.0 → 1.25.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 (113) hide show
  1. package/dist/core.cjs +6 -7
  2. package/dist/core.cjs.map +1 -1
  3. package/dist/core.esm.js +5 -6
  4. package/dist/core.esm.js.map +1 -1
  5. package/dist/core.native.esm.js +5 -5
  6. package/dist/exports/waas.d.ts +1 -0
  7. package/dist/exports/waas.d.ts.map +1 -1
  8. package/dist/{getNetworkProviderFromNetworkId-R8IKGc6s.native.esm.js → getNetworkProviderFromNetworkId-CN0fhJMJ.native.esm.js} +3 -2
  9. package/dist/{getNetworkProviderFromNetworkId-R8IKGc6s.native.esm.js.map → getNetworkProviderFromNetworkId-CN0fhJMJ.native.esm.js.map} +1 -1
  10. package/dist/{getNetworkProviderFromNetworkId-CZjFA5G8.cjs → getNetworkProviderFromNetworkId-CtXKqsri.cjs} +2 -2
  11. package/dist/{getNetworkProviderFromNetworkId-CZjFA5G8.cjs.map → getNetworkProviderFromNetworkId-CtXKqsri.cjs.map} +1 -1
  12. package/dist/{getNetworkProviderFromNetworkId-CjdC5HjA.esm.js → getNetworkProviderFromNetworkId-DCvqxwoP.esm.js} +2 -2
  13. package/dist/{getNetworkProviderFromNetworkId-CjdC5HjA.esm.js.map → getNetworkProviderFromNetworkId-DCvqxwoP.esm.js.map} +1 -1
  14. package/dist/{getSignedSessionId-BYR70F5w.esm.js → getSignedSessionId-B3aCjPhf.native.esm.js} +12 -3
  15. package/dist/{getSignedSessionId-B6Eqmue0.native.esm.js.map → getSignedSessionId-B3aCjPhf.native.esm.js.map} +1 -1
  16. package/dist/{getSignedSessionId-B6Eqmue0.native.esm.js → getSignedSessionId-BmL1vPnC.esm.js} +3 -3
  17. package/dist/getSignedSessionId-BmL1vPnC.esm.js.map +1 -0
  18. package/dist/{getSignedSessionId-BpUNqL9z.cjs → getSignedSessionId-DIn697B6.cjs} +17 -2
  19. package/dist/getSignedSessionId-DIn697B6.cjs.map +1 -0
  20. package/dist/{getWalletProviderByKey-BVVFLnfy.esm.js → getWalletProviderByKey-Dm7Ey9SI.esm.js} +2 -2
  21. package/dist/{getWalletProviderByKey-BVVFLnfy.esm.js.map → getWalletProviderByKey-Dm7Ey9SI.esm.js.map} +1 -1
  22. package/dist/{getWalletProviderByKey-D2ElEmJR.cjs → getWalletProviderByKey-DtcD_nPD.cjs} +2 -2
  23. package/dist/{getWalletProviderByKey-D2ElEmJR.cjs.map → getWalletProviderByKey-DtcD_nPD.cjs.map} +1 -1
  24. package/dist/{getWalletProviderByKey-CqdhcE7y.native.esm.js → getWalletProviderByKey-Pg1oNi-G.native.esm.js} +2 -2
  25. package/dist/{getWalletProviderByKey-CqdhcE7y.native.esm.js.map → getWalletProviderByKey-Pg1oNi-G.native.esm.js.map} +1 -1
  26. package/dist/index.cjs +14 -10
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.esm.js +14 -10
  29. package/dist/index.esm.js.map +1 -1
  30. package/dist/index.native.esm.js +18 -21
  31. package/dist/index.native.esm.js.map +1 -1
  32. package/dist/{isDynamicWaasEnabled-yo_LqzH5.native.esm.js → isDynamicWaasEnabled-B75AeGiP.native.esm.js} +2 -2
  33. package/dist/{isDynamicWaasEnabled-yo_LqzH5.native.esm.js.map → isDynamicWaasEnabled-B75AeGiP.native.esm.js.map} +1 -1
  34. package/dist/{isDynamicWaasEnabled-Ck0VFh7Z.esm.js → isDynamicWaasEnabled-BC2gR0R1.esm.js} +2 -2
  35. package/dist/{isDynamicWaasEnabled-Ck0VFh7Z.esm.js.map → isDynamicWaasEnabled-BC2gR0R1.esm.js.map} +1 -1
  36. package/dist/{isDynamicWaasEnabled-B7_FiTkx.cjs → isDynamicWaasEnabled-BWvSMhAP.cjs} +2 -2
  37. package/dist/{isDynamicWaasEnabled-B7_FiTkx.cjs.map → isDynamicWaasEnabled-BWvSMhAP.cjs.map} +1 -1
  38. package/dist/{isMfaRequiredForAction-B3FO4Zbn.cjs → isMfaRequiredForAction-Dr44C3-l.cjs} +2 -2
  39. package/dist/{isMfaRequiredForAction-B3FO4Zbn.cjs.map → isMfaRequiredForAction-Dr44C3-l.cjs.map} +1 -1
  40. package/dist/{isMfaRequiredForAction-Zi7_K00W.native.esm.js → isMfaRequiredForAction-WmEokgKF.native.esm.js} +32 -3
  41. package/dist/isMfaRequiredForAction-WmEokgKF.native.esm.js.map +1 -0
  42. package/dist/{isMfaRequiredForAction-CnO4g-V0.esm.js → isMfaRequiredForAction-ncRFYLGn.esm.js} +2 -2
  43. package/dist/{isMfaRequiredForAction-CnO4g-V0.esm.js.map → isMfaRequiredForAction-ncRFYLGn.esm.js.map} +1 -1
  44. package/dist/{isUserOnboardingComplete-DZk1nVHO.esm.js → isUserOnboardingComplete-B-J8O4KB.esm.js} +3 -3
  45. package/dist/{isUserOnboardingComplete-DZk1nVHO.esm.js.map → isUserOnboardingComplete-B-J8O4KB.esm.js.map} +1 -1
  46. package/dist/{isUserOnboardingComplete-Dnx30meW.cjs → isUserOnboardingComplete-B9vzjs71.cjs} +3 -3
  47. package/dist/{isUserOnboardingComplete-Dnx30meW.cjs.map → isUserOnboardingComplete-B9vzjs71.cjs.map} +1 -1
  48. package/dist/{isUserOnboardingComplete-DcRl6Q1f.native.esm.js → isUserOnboardingComplete-G6Hf8p_v.native.esm.js} +3 -3
  49. package/dist/{isUserOnboardingComplete-DcRl6Q1f.native.esm.js.map → isUserOnboardingComplete-G6Hf8p_v.native.esm.js.map} +1 -1
  50. package/dist/{migrateFromFireblocks-CdSxWZav.cjs → migrateFromFireblocks-MbP1ajwI.cjs} +3 -54
  51. package/dist/migrateFromFireblocks-MbP1ajwI.cjs.map +1 -0
  52. package/dist/{migrateFromFireblocks-nkmSeZrn.esm.js → migrateFromFireblocks-fY2IrQgU.esm.js} +4 -43
  53. package/dist/migrateFromFireblocks-fY2IrQgU.esm.js.map +1 -0
  54. package/dist/migrateFromFireblocks-kFz_kyA5.native.esm.js +65 -0
  55. package/dist/migrateFromFireblocks-kFz_kyA5.native.esm.js.map +1 -0
  56. package/dist/modules/waas/businessAccounts/addBusinessAccountMember/addBusinessAccountMember.d.ts.map +1 -1
  57. package/dist/modules/waas/businessAccounts/addBusinessAccountSigner/addBusinessAccountSigner.d.ts.map +1 -1
  58. package/dist/modules/waas/businessAccounts/addWalletToBusinessAccount/addWalletToBusinessAccount.d.ts.map +1 -1
  59. package/dist/modules/waas/businessAccounts/createBusinessAccount/createBusinessAccount.d.ts +2 -1
  60. package/dist/modules/waas/businessAccounts/createBusinessAccount/createBusinessAccount.d.ts.map +1 -1
  61. package/dist/modules/waas/businessAccounts/getBusinessAccount/getBusinessAccount.d.ts +2 -1
  62. package/dist/modules/waas/businessAccounts/getBusinessAccount/getBusinessAccount.d.ts.map +1 -1
  63. package/dist/modules/waas/businessAccounts/listBusinessAccounts/listBusinessAccounts.d.ts +2 -1
  64. package/dist/modules/waas/businessAccounts/listBusinessAccounts/listBusinessAccounts.d.ts.map +1 -1
  65. package/dist/modules/waas/businessAccounts/removeBusinessAccountMember/removeBusinessAccountMember.d.ts.map +1 -1
  66. package/dist/modules/waas/businessAccounts/removeBusinessAccountSigner/removeBusinessAccountSigner.d.ts.map +1 -1
  67. package/dist/modules/waas/businessAccounts/removeBusinessAccountWallet/index.d.ts +2 -0
  68. package/dist/modules/waas/businessAccounts/removeBusinessAccountWallet/index.d.ts.map +1 -0
  69. package/dist/modules/waas/businessAccounts/removeBusinessAccountWallet/removeBusinessAccountWallet.d.ts +32 -0
  70. package/dist/modules/waas/businessAccounts/removeBusinessAccountWallet/removeBusinessAccountWallet.d.ts.map +1 -0
  71. package/dist/modules/waas/businessAccounts/transferBusinessAccountOwnership/transferBusinessAccountOwnership.d.ts.map +1 -1
  72. package/dist/modules/waas/businessAccounts/updateBusinessAccountMemberRole/updateBusinessAccountMemberRole.d.ts.map +1 -1
  73. package/dist/modules/waas/createWaasClient/createWaasClient.d.ts.map +1 -1
  74. package/dist/modules/waas/createWaasProvider/createWaasProvider.d.ts.map +1 -1
  75. package/dist/services/openDeeplink/{createWebDeeplinkOpener/createWebDeeplinkOpener.d.ts → createDeeplinkOpener/createDeeplinkOpener.d.ts} +6 -2
  76. package/dist/services/openDeeplink/createDeeplinkOpener/createDeeplinkOpener.d.ts.map +1 -0
  77. package/dist/services/openDeeplink/createDeeplinkOpener/index.d.ts +2 -0
  78. package/dist/services/openDeeplink/createDeeplinkOpener/index.d.ts.map +1 -0
  79. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  80. package/dist/{updateAuthFromVerifyResponse-BSORoVT0.cjs → updateAuthFromVerifyResponse-D9kFrAkK.cjs} +3 -3
  81. package/dist/{updateAuthFromVerifyResponse-BSORoVT0.cjs.map → updateAuthFromVerifyResponse-D9kFrAkK.cjs.map} +1 -1
  82. package/dist/{NativeModuleNotLinkedError-CJy_4-6r.native.esm.js → updateAuthFromVerifyResponse-WlGmt2v0.native.esm.js} +4 -33
  83. package/dist/updateAuthFromVerifyResponse-WlGmt2v0.native.esm.js.map +1 -0
  84. package/dist/{updateAuthFromVerifyResponse-D0Tt9-Z-.esm.js → updateAuthFromVerifyResponse-ZzU46s0t.esm.js} +3 -3
  85. package/dist/{updateAuthFromVerifyResponse-D0Tt9-Z-.esm.js.map → updateAuthFromVerifyResponse-ZzU46s0t.esm.js.map} +1 -1
  86. package/dist/waas.cjs +60 -33
  87. package/dist/waas.cjs.map +1 -1
  88. package/dist/waas.esm.js +61 -35
  89. package/dist/waas.esm.js.map +1 -1
  90. package/dist/waas.native.esm.js +61 -34
  91. package/dist/waas.native.esm.js.map +1 -1
  92. package/dist/waasCore.cjs +55 -12
  93. package/dist/waasCore.cjs.map +1 -1
  94. package/dist/waasCore.esm.js +51 -8
  95. package/dist/waasCore.esm.js.map +1 -1
  96. package/dist/waasCore.native.esm.js +267 -7
  97. package/dist/waasCore.native.esm.js.map +1 -1
  98. package/package.json +3 -3
  99. package/dist/NativeModuleNotLinkedError-CJy_4-6r.native.esm.js.map +0 -1
  100. package/dist/consumeMfaTokenIfRequiredForAction-B6nFE5IO.cjs +0 -17
  101. package/dist/consumeMfaTokenIfRequiredForAction-B6nFE5IO.cjs.map +0 -1
  102. package/dist/consumeMfaTokenIfRequiredForAction-DXTH4qki.esm.js +0 -12
  103. package/dist/consumeMfaTokenIfRequiredForAction-DXTH4qki.esm.js.map +0 -1
  104. package/dist/getSignedSessionId-BYR70F5w.esm.js.map +0 -1
  105. package/dist/getSignedSessionId-BpUNqL9z.cjs.map +0 -1
  106. package/dist/isMfaRequiredForAction-Zi7_K00W.native.esm.js.map +0 -1
  107. package/dist/migrateFromFireblocks-COEK_Acn.native.esm.js +0 -321
  108. package/dist/migrateFromFireblocks-COEK_Acn.native.esm.js.map +0 -1
  109. package/dist/migrateFromFireblocks-CdSxWZav.cjs.map +0 -1
  110. package/dist/migrateFromFireblocks-nkmSeZrn.esm.js.map +0 -1
  111. package/dist/services/openDeeplink/createWebDeeplinkOpener/createWebDeeplinkOpener.d.ts.map +0 -1
  112. package/dist/services/openDeeplink/createWebDeeplinkOpener/index.d.ts +0 -2
  113. package/dist/services/openDeeplink/createWebDeeplinkOpener/index.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"waasCore.esm.js","names":["_waasClient: DynamicWalletClient | undefined","_waasClientSessionId: string | undefined","getWaasClient: WaasProvider['getWaasClient']","backupKeySharesToGoogleDrive: WaasProvider['backupKeySharesToGoogleDrive']","createWalletAccount: WaasProvider['createWalletAccount']","delegateKeyShares: WaasProvider['delegateKeyShares']","exportClientKeyshares: WaasProvider['exportClientKeyshares']","exportPrivateKey: WaasProvider['exportPrivateKey']","restoreUserShareForWalletAccount: WaasProvider['restoreUserShareForWalletAccount']","importPrivateKey: WaasProvider['importPrivateKey']","migrateFromFireblocks: WaasProvider['migrateFromFireblocks']","refreshWalletAccountShares: WaasProvider['refreshWalletAccountShares']","reshareToNewSignerShareSet: WaasProvider['reshareToNewSignerShareSet']","revokeDelegation: WaasProvider['revokeDelegation']","setWaasWalletAccountPassword: WaasProvider['setWaasWalletAccountPassword']","signRawMessage: WaasProvider['signRawMessage']","destroy: WaasProvider['destroy']","updatePassword: WaasProvider['updatePassword']","signMessage: WaasProvider['signMessage']","signSerializedTransaction: WaasProvider['signSerializedTransaction']","getWalletRecoveryState: WaasProvider['getWalletRecoveryState']","unlockWallet: WaasProvider['unlockWallet']","migrateFromFireblocks","packageName","packageVersion"],"sources":["../src/utils/createTranslateRejection/createTranslateRejection.ts","../src/modules/auth/getActionAuthorizationTokens/getActionAuthorizationTokens.ts","../src/modules/waas/createWaasProvider/isWaasLoadExhaustionError.ts","../src/modules/waas/createWaasProvider/createWaasProvider.ts","../src/modules/waas/exportWaasPrivateKeyToContainer/exportWaasPrivateKeyToContainer.ts","../src/modules/waas/getAllUserWaasAddressesForChain/getAllUserWaasAddressesForChain.ts","../src/exports/waasCore.ts"],"sourcesContent":["export type CreateTranslateRejectionParams<TMatched> = {\n /**\n * Builds the error thrown in place of a matched rejection.\n */\n mapTo: (error: TMatched) => Error;\n /**\n * Type guard selecting which rejections to translate. Anything it does not\n * match is rethrown untouched, so callers only translate the errors they\n * own. Narrowing to `TMatched` lets {@link CreateTranslateRejectionParams.mapTo}\n * receive a typed error without a cast.\n */\n match: (error: unknown) => error is TMatched;\n};\n\n/**\n * Builds a reusable decorator, bound once to a `match`/`mapTo` pair, that wraps\n * any async function so a matching rejection is rethrown as `mapTo(error)`\n * while every other rejection — and every resolved value — passes through\n * untouched. Unmatched errors are rethrown by reference, so the decorator can\n * never swallow or reshape an error it was not asked to translate.\n *\n * Binding `match`/`mapTo` up front keeps the generic wrapping machinery here\n * instead of at the call site: consumers get a plain `(fn) => wrappedFn`\n * decorator they can apply to many functions of differing signatures, each of\n * which keeps its own argument and return types.\n *\n * @notInstrumented\n */\nexport const createTranslateRejection =\n <TMatched>({ match, mapTo }: CreateTranslateRejectionParams<TMatched>) =>\n <TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => Promise<TReturn>) =>\n async (...args: TArgs): Promise<TReturn> => {\n try {\n return await fn(...args);\n } catch (error) {\n if (match(error)) {\n throw mapTo(error);\n }\n throw error;\n }\n };\n","import type { MFAAction, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport { consumeMfaTokenIfRequiredForAction } from '../../mfa/consumeMfaTokenIfRequiredForAction';\nimport { getElevatedAccessToken } from '../getElevatedAccessToken';\n\ntype GetActionAuthorizationTokensParams = {\n mfaAction: MFAAction;\n scope: TokenScope;\n};\n\ntype ActionAuthorizationTokens = {\n elevatedAccessToken: string | undefined;\n mfaToken: string | undefined;\n};\n\n/**\n * Resolves the tokens that authorize a verification-gated wallet action.\n *\n * An elevated access token for `scope` is the current proof of verification, so\n * it takes precedence: when one has been banked, the legacy per-action MFA token\n * is left untouched. Demanding both would break every user who has a verified\n * MFA method, because satisfying the challenge with `requestedScopes` mints an\n * elevated access token and no MFA token -- leaving nothing for\n * `consumeMfaTokenIfRequiredForAction` to consume, which then throws.\n *\n * @param params.mfaAction - The action whose legacy MFA requirement to evaluate.\n * @param params.scope - The scope of the elevated access token that authorizes the action.\n * @param client - The Dynamic client instance.\n * @returns The elevated access token, or the legacy MFA token when no elevated token exists.\n * @notInstrumented\n */\nexport const getActionAuthorizationTokens = async (\n { mfaAction, scope }: GetActionAuthorizationTokensParams,\n client: DynamicClient\n): Promise<ActionAuthorizationTokens> => {\n const elevatedAccessToken = getElevatedAccessToken({ scope }, client);\n\n if (elevatedAccessToken) {\n return { elevatedAccessToken, mfaToken: undefined };\n }\n\n const mfaToken = await consumeMfaTokenIfRequiredForAction(\n { mfaAction },\n client\n );\n\n return { elevatedAccessToken: undefined, mfaToken };\n};\n","/**\n * Exact message prefix of the rejection thrown by\n * `@dynamic-labs-wallet/browser-wallet-client` when the secure container load\n * exhausts all retry attempts. The upstream library throws a plain `Error`\n * with no code, so message matching is the only detection mechanism available;\n * the dependency is pinned to an exact version and the spec pins this string\n * so drift is caught at upgrade time.\n */\nconst UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX =\n 'Failed to load iframe after all retry attempts';\n\n/**\n * True when `error` is the upstream \"load retry attempts exhausted\" rejection\n * from the embedded (WaaS) wallet's secure container load. Narrows to `Error`\n * so the matched value can be forwarded as a typed error cause without a cast,\n * and guards `instanceof Error` before reading `.message` so a non-`Error`\n * rejection never throws during detection.\n *\n * @notInstrumented\n */\nexport const isWaasLoadExhaustionError = (error: unknown): error is Error =>\n error instanceof Error &&\n error.message.startsWith(UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX);\n","import {\n type BitcoinConfig,\n type DynamicWalletClient,\n ThresholdSignatureScheme,\n WalletOperation,\n} from '@dynamic-labs-wallet/browser-wallet-client';\nimport { MFAAction, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { WaasLoadFailedError } from '../../../errors/WaasLoadFailedError';\nimport { WaasOnboardingIncompleteError } from '../../../errors/WaasOnboardingIncompleteError';\nimport { createTranslateRejection } from '../../../utils/createTranslateRejection';\nimport { getActionAuthorizationTokens } from '../../auth/getActionAuthorizationTokens';\nimport type { Chain } from '../../chain';\nimport { consumeMfaTokenIfRequiredForAction } from '../../mfa/consumeMfaTokenIfRequiredForAction';\nimport { getSignedSessionId } from '../../sessionKeys/getSignedSessionId';\nimport { isUserOnboardingComplete } from '../../user/isUserOnboardingComplete';\nimport { createWaasClient } from '../createWaasClient';\nimport { getWaasChainNameFromChain } from '../getWaasChainNameFromChain';\nimport type { WaasProvider } from '../waas.types';\nimport { isWaasLoadExhaustionError } from './isWaasLoadExhaustionError';\n\nconst RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH = 64;\n\ntype CreateWaasProviderParams = {\n chain: Chain;\n sdkClient: DynamicClient;\n};\n\n/** @notInstrumented */\nexport const createWaasProvider = ({\n sdkClient,\n chain,\n}: CreateWaasProviderParams): WaasProvider => {\n const logger = getCore(sdkClient).logger;\n\n let _waasClient: DynamicWalletClient | undefined;\n // The session the cached client was built against. A step-up reauth mints a\n // NEW session (new sessionId + token); see the rebuild guard below.\n let _waasClientSessionId: string | undefined;\n\n // Drops the cached client only when it still points at `client`. Guarding on\n // identity matters because a step-up reauth can mint a new session and rebuild\n // a healthy client (via the session-change reset in getWaasClient) while an\n // older client's initialize()/operation is still failing in flight. Clearing\n // in that case would orphan the healthy replacement, since nothing would\n // release its upstream shared-container reference. _waasClientSessionId is\n // cleared alongside to keep the pair consistent.\n const resetClientIfCurrent = (client: DynamicWalletClient): void => {\n if (_waasClient === client) {\n _waasClient = undefined;\n _waasClientSessionId = undefined;\n }\n };\n\n // because the waas client needs the authToken to be set, we can only create it\n // the first time it's needed, which is after the user has logged in\n const getWaasClient: WaasProvider['getWaasClient'] = async () => {\n // After a step-up reauthentication a new session is minted. In header auth\n // mode (native webview) the iframe has no cookie jar to fall back on, so a\n // client cached against the previous session keeps presenting the stale\n // token — its next backend call (createRooms/users) 401s and trips the\n // iframe's onUnauthorized → forced logout. Drop the cached client when the\n // session changes so it rebuilds + re-initializes with the fresh token and\n // signed session id. Key shares stay in storage (only client auth resets);\n // routine token refresh keeps the same sessionId, so it does not rebuild.\n const currentSessionId = getCore(sdkClient).state.get().user?.sessionId;\n if (_waasClient && currentSessionId !== _waasClientSessionId) {\n _waasClient = undefined;\n }\n\n if (!_waasClient) {\n // Chokepoint: don't build + initialize the iframe client until onboarding\n // is complete. The iframe's init-time room-cache pre-warm fires\n // `createRooms` using the token captured at construction — before any\n // per-operation token resync exists to correct it. Built while the token\n // is still pre-`user:basic` (MFA / KYC / recovery codes / device\n // registration pending), that pre-warm 401s and trips the iframe's\n // onUnauthorized → forced-logout. This is the single gateway to\n // createWaasClient (web and native), so it covers every WaaS caller.\n if (!isUserOnboardingComplete(sdkClient)) {\n throw new WaasOnboardingIncompleteError();\n }\n\n const builtClient = createWaasClient(\n { chainName: getWaasChainNameFromChain(chain) },\n sdkClient\n );\n _waasClient = builtClient;\n _waasClientSessionId = currentSessionId;\n try {\n await builtClient.initialize();\n } catch (error) {\n // A failed load (e.g. iframe retry exhaustion) leaves an unusable,\n // never-initialized client cached. Drop it so the next getWaasClient()\n // rebuilds and re-initializes — the fresh load cycle WaasLoadFailedError\n // documents — instead of returning the dead client for the rest of the\n // session. Identity-guarded (see resetClientIfCurrent).\n resetClientIfCurrent(builtClient);\n throw error;\n }\n }\n // Read the shared var, not the locally-built client: if a concurrent\n // session-change rebuilt a fresh client while this initialize() was pending,\n // the caller should get that current healthy client, not this now-superseded\n // instance built against the old session.\n return _waasClient;\n };\n\n // Runs an operation against an already-fetched client and, if it fails because\n // the container's load was exhausted mid-flight (the client built and\n // initialized fine, then its iframe died — e.g. tab backgrounding, relogin —\n // and its own recovery could not reload), drops the cached client so the next\n // operation rebuilds and re-initializes. This covers the post-initialization\n // path that getWaasClient's own load-failure reset cannot see, so the\n // fresh-load cycle WaasLoadFailedError documents holds for every operation,\n // not just the first load. Identity-guarded (see resetClientIfCurrent).\n const discardClientOnLoadFailure = async <TReturn>({\n waasClient,\n operation,\n }: {\n operation: () => Promise<TReturn>;\n waasClient: DynamicWalletClient;\n }): Promise<TReturn> => {\n try {\n return await operation();\n } catch (error) {\n if (isWaasLoadExhaustionError(error)) {\n resetClientIfCurrent(waasClient);\n }\n throw error;\n }\n };\n\n const backupKeySharesToGoogleDrive: WaasProvider['backupKeySharesToGoogleDrive'] =\n async ({ googleDriveAccessToken, password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.backupKeySharesToGoogleDrive({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n googleDriveAccessToken,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const createWalletAccount: WaasProvider['createWalletAccount'] = async (\n args = {}\n ) => {\n logger.debug('[createWaasProvider] createWalletAccount', {\n bitcoinConfig: args.bitcoinConfig,\n thresholdSignatureScheme: args.thresholdSignatureScheme,\n });\n\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n const waasWallet = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.createWalletAccount({\n authToken: sdkClient.token ?? undefined,\n bitcoinConfig: args.bitcoinConfig as BitcoinConfig | undefined,\n businessAccountId: args.businessAccountId,\n password: args.password,\n signedSessionId,\n thresholdSignatureScheme:\n args.thresholdSignatureScheme ??\n ThresholdSignatureScheme.TWO_OF_TWO,\n }),\n waasClient,\n });\n\n return waasWallet;\n };\n\n const delegateKeyShares: WaasProvider['delegateKeyShares'] = async ({\n initialSignerRules,\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.delegateKeyShares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n initialSignerRules,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const exportClientKeyshares: WaasProvider['exportClientKeyshares'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.exportClientKeyshares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const exportPrivateKey: WaasProvider['exportPrivateKey'] = async ({\n container,\n displayContainer,\n walletAccount,\n password,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n // Forwards whichever token proves the export was verified: the elevated\n // wallet:export token banked by step-up, or the legacy per-action MFA token.\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasExport, scope: TokenScope.Walletexport },\n sdkClient\n );\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.exportPrivateKey({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n // Exactly one display surface is forwarded: `container` (a\n // WaasSDKContainer, e.g. a React Native visible WebView) or\n // `displayContainer` (a DOM element, web). The upstream client enforces\n // the \"exactly one\" invariant and renders the key inside the surface's\n // own sandboxed document — it never crosses back to the host.\n container,\n displayContainer,\n elevatedAccessToken,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const restoreUserShareForWalletAccount: WaasProvider['restoreUserShareForWalletAccount'] =\n async ({ walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.getWallet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n signedSessionId,\n walletOperation: WalletOperation.SIGN_MESSAGE,\n }),\n waasClient,\n });\n };\n\n const importPrivateKey: WaasProvider['importPrivateKey'] = async ({\n privateKey,\n thresholdSignatureScheme = ThresholdSignatureScheme.TWO_OF_TWO,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const walletClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n walletClient.importPrivateKey({\n authToken: sdkClient.token ?? undefined,\n privateKey,\n signedSessionId,\n thresholdSignatureScheme,\n }),\n waasClient: walletClient,\n });\n };\n\n const migrateFromFireblocks: WaasProvider['migrateFromFireblocks'] = async ({\n coinTypes,\n deviceId,\n expectedAddresses,\n jwt,\n password,\n storage,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const walletClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n walletClient.migrateFromFireblocks({\n authToken: sdkClient.token ?? undefined,\n fireblocks: {\n deviceId,\n expectedAddresses,\n jwt,\n ncwStorage: storage,\n walletPassword: password,\n ...(coinTypes ? { coinTypes } : {}),\n },\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n };\n\n const refreshWalletAccountShares: WaasProvider['refreshWalletAccountShares'] =\n async ({ password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const walletClient = await getWaasClient();\n\n const mfaToken = await consumeMfaTokenIfRequiredForAction(\n { mfaAction: MFAAction.WalletWaasRefresh },\n sdkClient\n );\n\n return discardClientOnLoadFailure({\n operation: () =>\n walletClient.refreshWalletAccountShares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n };\n\n const reshareToNewSignerShareSet: WaasProvider['reshareToNewSignerShareSet'] =\n async ({\n businessAccountId,\n password,\n signerType,\n targetSignerIdentity,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.reshareToNewSignerShareSet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n businessAccountId,\n password,\n signedSessionId,\n // Public API uses a string union; the client expects the core enum\n // (identical values). Cast at this single boundary.\n signerType: signerType as Parameters<\n typeof waasClient.reshareToNewSignerShareSet\n >[0]['signerType'],\n targetSignerIdentity,\n }),\n waasClient,\n });\n };\n\n const revokeDelegation: WaasProvider['revokeDelegation'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.revokeDelegation({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const setWaasWalletAccountPassword: WaasProvider['setWaasWalletAccountPassword'] =\n async ({ password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.setPassword({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n newPassword: password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const signRawMessage: WaasProvider['signRawMessage'] = async ({\n message,\n password,\n walletAccount,\n }) => {\n if (message.length !== RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH) {\n throw new InvalidParamError(\n `Message must be ${RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH} characters long`\n );\n }\n\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const walletClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n walletClient.signRawMessage({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n elevatedAccessToken,\n message,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n\n return { signature };\n };\n\n const destroy: WaasProvider['destroy'] = async (args) => {\n if (!_waasClient) {\n return;\n }\n\n const waasClient = await getWaasClient();\n // When a session token expires, we preserve key shares in storage instead\n // of clearing them. Customers with short-lived sessions (minutes) were\n // hitting excessive server-side share recovery on every re-login, which\n // also forced users to re-enter their wallet password since the unlocked\n // share only lives for the duration of the session.\n //\n // This is safe because the waas-sdk separately fingerprints the user\n // (sub + environment_id) and clears all storage if a different user logs\n // in. On explicit user-initiated logout, shares are always cleared for\n // security.\n if (args?.reason !== 'token-expired') {\n await waasClient.cleanup();\n }\n _waasClient = undefined;\n };\n\n const updatePassword: WaasProvider['updatePassword'] = async ({\n walletAccount,\n currentPassword,\n newPassword,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.updatePassword({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n existingPassword: currentPassword,\n newPassword,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const signMessage: WaasProvider['signMessage'] = async ({\n message,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.signMessage({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n elevatedAccessToken,\n message,\n mfaToken,\n signedSessionId,\n }),\n waasClient,\n });\n\n return { signature };\n };\n\n const signSerializedTransaction: WaasProvider['signSerializedTransaction'] =\n async ({ chainId, serializedTransaction, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const { elevatedAccessToken, mfaToken } =\n await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.signTransaction({\n authToken: sdkClient.token ?? undefined,\n chainId,\n elevatedAccessToken,\n mfaToken,\n senderAddress: walletAccount.address,\n signedSessionId,\n transaction: serializedTransaction,\n }),\n waasClient,\n });\n\n return { signature };\n };\n\n const getWalletRecoveryState: WaasProvider['getWalletRecoveryState'] =\n async ({ walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.getWalletRecoveryState({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const unlockWallet: WaasProvider['unlockWallet'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.unlockWallet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n // Every operation is wrapped so an exhausted container load surfaces as a\n // typed WaasLoadFailedError no matter which call triggers it — the initial\n // load or a mid-operation recovery. Wrapped at the operation itself (rather\n // than a separate whole-provider pass) so the translation is visible right\n // where the provider is assembled.\n const translateLoadFailure = createTranslateRejection({\n mapTo: (error) => new WaasLoadFailedError({ cause: error }),\n match: isWaasLoadExhaustionError,\n });\n\n const provider: WaasProvider = {\n backupKeySharesToGoogleDrive: translateLoadFailure(\n backupKeySharesToGoogleDrive\n ),\n createWalletAccount: translateLoadFailure(createWalletAccount),\n delegateKeyShares: translateLoadFailure(delegateKeyShares),\n destroy: translateLoadFailure(destroy),\n exportClientKeyshares: translateLoadFailure(exportClientKeyshares),\n exportPrivateKey: translateLoadFailure(exportPrivateKey),\n getWaasClient: translateLoadFailure(getWaasClient),\n getWalletRecoveryState: translateLoadFailure(getWalletRecoveryState),\n importPrivateKey: translateLoadFailure(importPrivateKey),\n migrateFromFireblocks: translateLoadFailure(migrateFromFireblocks),\n refreshWalletAccountShares: translateLoadFailure(\n refreshWalletAccountShares\n ),\n reshareToNewSignerShareSet: translateLoadFailure(\n reshareToNewSignerShareSet\n ),\n restoreUserShareForWalletAccount: translateLoadFailure(\n restoreUserShareForWalletAccount\n ),\n revokeDelegation: translateLoadFailure(revokeDelegation),\n setWaasWalletAccountPassword: translateLoadFailure(\n setWaasWalletAccountPassword\n ),\n signMessage: translateLoadFailure(signMessage),\n signRawMessage: translateLoadFailure(signRawMessage),\n signSerializedTransaction: translateLoadFailure(signSerializedTransaction),\n unlockWallet: translateLoadFailure(unlockWallet),\n updatePassword: translateLoadFailure(updatePassword),\n };\n\n return provider;\n};\n","import type { WaasSDKContainer } from '@dynamic-labs-wallet/core';\n\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { getWaasWalletProviderFromWalletAccount } from '../getWaasWalletProviderFromWalletAccount';\n\ntype ExportWaasPrivateKeyToContainerParams = {\n container: WaasSDKContainer;\n password?: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Exports the private key for a WaaS wallet account into a caller-provided\n * {@link WaasSDKContainer} (e.g. a visible React Native WebView) instead of a\n * DOM element.\n *\n * This is the container-based counterpart to `exportWaasPrivateKey` (which\n * injects an iframe into a DOM `displayContainer` on web). The export ceremony\n * runs — and the private key is rendered — entirely inside the container's own\n * sandboxed document; the key is never exposed to the host JS layer. The caller\n * owns the container's lifecycle and must call `container.destroy()` when the\n * display is dismissed.\n *\n * @param params.walletAccount - The WaaS wallet account to export the private key from.\n * @param params.container - The container that hosts the secure key display.\n * @param [params.password] - Optional password to decrypt the private key.\n * @param client - The Dynamic client instance. This is an internal API (exposed\n * only via `@dynamic-labs-sdk/client/waas/core`), so the client is passed\n * explicitly rather than defaulted — callers resolve it (e.g. via\n * `getDefaultClient()`) and thread it in.\n * @returns A promise that resolves when the private key export is complete.\n * @notInstrumented\n */\nexport const exportWaasPrivateKeyToContainer = async (\n { container, password, walletAccount }: ExportWaasPrivateKeyToContainerParams,\n client: DynamicClient\n) => {\n const provider = getWaasWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n return provider.exportPrivateKey({\n container,\n password,\n walletAccount,\n });\n};\n","import { WalletProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { getChainFromVerifiedCredentialChain } from '../../../utils/getChainFromVerifiedCredentialChain';\nimport type { Chain } from '../../chain';\nimport { DYNAMIC_WAAS_METADATA } from '../constants';\n\ntype GetAllUserWaasAddressesForChainParams = {\n chain: Chain;\n};\n\n/** @notInstrumented */\nexport const getAllUserWaasAddressesForChain = (\n { chain }: GetAllUserWaasAddressesForChainParams,\n client: DynamicClient\n): string[] => {\n if (!client.user) {\n return [];\n }\n\n const waasWalletCredentials =\n client.user.verifiedCredentials.filter(\n (credential) =>\n credential.walletProvider === WalletProviderEnum.EmbeddedWallet &&\n credential.walletName\n ?.toLowerCase()\n .startsWith(DYNAMIC_WAAS_METADATA.normalizedWalletName) &&\n credential.address &&\n credential.chain &&\n getChainFromVerifiedCredentialChain(credential.chain) === chain\n ) ?? [];\n\n const waasAddresses: string[] = waasWalletCredentials.map(\n // casting because we're already filtering out credentials without an address\n (credential) => credential.address as string\n );\n\n return waasAddresses;\n};\n","import { 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\nexport type {\n BitcoinNetwork,\n DynamicWalletClient,\n MigrateFromFireblocksResponse,\n ThresholdSignatureScheme,\n} from '@dynamic-labs-wallet/browser-wallet-client';\nexport type { WaasSDKContainer } from '@dynamic-labs-wallet/core';\nexport { DYNAMIC_WAAS_METADATA } from '../modules/waas/constants';\nexport { createWaasClient } from '../modules/waas/createWaasClient';\nexport { createWaasProvider } from '../modules/waas/createWaasProvider';\nexport { exportWaasPrivateKeyToContainer } from '../modules/waas/exportWaasPrivateKeyToContainer';\nexport { getAllUserWaasAddressesForChain } from '../modules/waas/getAllUserWaasAddressesForChain';\nexport { getWaasChainNameFromChain } from '../modules/waas/getWaasChainNameFromChain';\nexport { migrateFromFireblocks } from '../modules/waas/migrateFromFireblocks';\nexport { preconnectWaasIframe } from '../modules/waas/preconnectWaasIframe';\nexport type {\n WaasProvider,\n WaasWalletProvider,\n} from '../modules/waas/waas.types';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,4BACA,EAAE,OAAO,aACe,OACnC,OAAO,GAAG,SAAkC;AAC1C,KAAI;AACF,SAAO,MAAM,GAAG,GAAG,KAAK;UACjB,OAAO;AACd,MAAI,MAAM,MAA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AAQ;EACtC,uBAAuB,qBAAqB,sBAAsB;EAClE,kBAAkB,qBAAqB,iBAAiB;EACxD,eAAe,qBAAqB,cAAc;EAClD,wBAAwB,qBAAqB,uBAAuB;EACpE,kBAAkB,qBAAqB,iBAAiB;EACxD,uBAAuB,qBAAqBC,wBAAsB;EAClE,4BAA4B,qBAC1B,2BACD;EACD,4BAA4B,qBAC1B,2BACD;EACD,kCAAkC,qBAChC,iCACD;EACD,kBAAkB,qBAAqB,iBAAiB;EACxD,8BAA8B,qBAC5B,6BACD;EACD,aAAa,qBAAqB,YAAY;EAC9C,gBAAgB,qBAAqB,eAAe;EACpD,2BAA2B,qBAAqB,0BAA0B;EAC1E,cAAc,qBAAqB,aAAa;EAChD,gBAAgB,qBAAqB,eAAe;EACrD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/mBH,MAAa,kCAAkC,OAC7C,EAAE,WAAW,UAAU,iBACvB,WACG;AAMH,QALiB,uCACf,EAAE,eAAe,EACjB,OACD,CAEe,iBAAiB;EAC/B;EACA;EACA;EACD,CAAC;;;;;;ACnCJ,MAAa,mCACX,EAAE,SACF,WACa;AACb,KAAI,CAAC,OAAO,KACV,QAAO,EAAE;AAoBX,SAhBE,OAAO,KAAK,oBAAoB,QAC7B,eACC,WAAW,mBAAmB,mBAAmB,kBACjD,WAAW,YACP,aAAa,CACd,WAAW,sBAAsB,qBAAqB,IACzD,WAAW,WACX,WAAW,SACX,oCAAoC,WAAW,MAAM,KAAK,MAC7D,IAAI,EAAE,EAE6C,KAEnD,eAAe,WAAW,QAC5B;;;;;AC7BH,qBAAqBC,MAAaC,QAAe"}
1
+ {"version":3,"file":"waasCore.esm.js","names":["createWaasClient: CreateWaasClient","logoutWithReason","_waasClient: DynamicWalletClient | undefined","_waasClientSessionId: string | undefined","getWaasClient: WaasProvider['getWaasClient']","backupKeySharesToGoogleDrive: WaasProvider['backupKeySharesToGoogleDrive']","createWalletAccount: WaasProvider['createWalletAccount']","delegateKeyShares: WaasProvider['delegateKeyShares']","exportClientKeyshares: WaasProvider['exportClientKeyshares']","exportPrivateKey: WaasProvider['exportPrivateKey']","restoreUserShareForWalletAccount: WaasProvider['restoreUserShareForWalletAccount']","importPrivateKey: WaasProvider['importPrivateKey']","migrateFromFireblocks: WaasProvider['migrateFromFireblocks']","refreshWalletAccountShares: WaasProvider['refreshWalletAccountShares']","reshareToNewSignerShareSet: WaasProvider['reshareToNewSignerShareSet']","revokeDelegation: WaasProvider['revokeDelegation']","setWaasWalletAccountPassword: WaasProvider['setWaasWalletAccountPassword']","signRawMessage: WaasProvider['signRawMessage']","destroy: WaasProvider['destroy']","updatePassword: WaasProvider['updatePassword']","signMessage: WaasProvider['signMessage']","signSerializedTransaction: WaasProvider['signSerializedTransaction']","getWalletRecoveryState: WaasProvider['getWalletRecoveryState']","unlockWallet: WaasProvider['unlockWallet']","migrateFromFireblocks","packageName","packageVersion"],"sources":["../src/modules/waas/createWaasClient/createWaasClient.ts","../src/utils/createTranslateRejection/createTranslateRejection.ts","../src/modules/auth/getActionAuthorizationTokens/getActionAuthorizationTokens.ts","../src/modules/waas/getWaasChainNameFromChain/getWaasChainNameFromChain.ts","../src/modules/waas/createWaasProvider/isWaasLoadExhaustionError.ts","../src/modules/waas/createWaasProvider/createWaasProvider.ts","../src/modules/waas/exportWaasPrivateKeyToContainer/exportWaasPrivateKeyToContainer.ts","../src/modules/waas/getAllUserWaasAddressesForChain/getAllUserWaasAddressesForChain.ts","../src/exports/waasCore.ts"],"sourcesContent":["import type { AuthMode } from '@dynamic-labs-wallet/browser-wallet-client';\nimport { DynamicWalletClient } from '@dynamic-labs-wallet/browser-wallet-client';\n\nimport { getCore } from '../../../client/core/getCore';\nimport { CLIENT_SDK_NAME } from '../../apiClient/constants';\nimport { logoutWithReason } from '../../auth/logoutWithReason';\nimport { isCookieEnabled } from '../../projectSettings/isCookieEnabled';\nimport { getSignedSessionId } from '../../sessionKeys/getSignedSessionId';\nimport type { CreateWaasClient } from './createWaasClient.types';\nimport {\n DEFAULT_WAAS_BASE_API_URL,\n DEFAULT_WAAS_BASE_MPC_RELAY_API_URL,\n} from '../constants';\n\n/** @notInstrumented */\nexport const createWaasClient: CreateWaasClient = ({ chainName }, client) => {\n const core = getCore(client);\n\n const additionalTrustedOrigins = core.waas?.additionalTrustedOrigins;\n\n const baseClientKeysharesRelayApiUrl =\n client.projectSettings?.sdk.waas?.customKeyshareRelayBaseUrl;\n\n // Capture the session at construction time so the onUnauthorized guard can\n // ignore notifications that arrive after a step-up reauth mints a new session.\n // A client built against session S1 should never force-logout session S2.\n const sessionIdAtCreation = core.state.get().user?.sessionId;\n\n return new DynamicWalletClient(\n {\n authMode: (isCookieEnabled(client) ? 'cookie' : 'header') as AuthMode,\n authToken: client.token || '',\n baseApiUrl: (core.apiBaseUrl || DEFAULT_WAAS_BASE_API_URL).replace(\n '/api/v0',\n ''\n ),\n baseMPCRelayApiUrl:\n client.projectSettings?.sdk.waas?.relayUrl ||\n DEFAULT_WAAS_BASE_MPC_RELAY_API_URL,\n chainName,\n // Opt into the SDK self-driving eager key-share recovery on auth-token\n // arrival, so the client no longer restores shares itself on login.\n eagerlyRecoverKeyShares: true,\n environmentId: core.environmentId,\n sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`,\n ...(additionalTrustedOrigins == undefined\n ? {}\n : { additionalTrustedOrigins }),\n ...(baseClientKeysharesRelayApiUrl == undefined\n ? {}\n : { baseClientKeysharesRelayApiUrl }),\n ...(core.waas?.loadTimeoutMs == undefined\n ? {}\n : { iframeLoadTimeout: core.waas.loadTimeoutMs }),\n ...(core.waas?.maxLoadRetries == undefined\n ? {}\n : { maxRetryAttempts: core.waas.maxLoadRetries }),\n },\n {\n // Lets the iframe mint a fresh signed session id over the reverse channel,\n // which the SDK's eager key-share recovery needs.\n getSignedSessionId: () =>\n getSignedSessionId(client).then(({ signature }) => signature),\n // When the WaaS iframe's own backend call returns 401 (e.g. a forcibly\n // revoked token), the iframe notifies the host via the reverse channel\n // and this fires — log the user out. Mirrors the session-expiry\n // middleware that covers the SDK's own direct API 401s.\n //\n // Guard: after a step-up reauth the session rotates. A client built\n // against the previous session will receive this notification but must\n // not force-logout the new session — ignore if the session has changed.\n onUnauthorized: () => {\n const currentSessionId = core.state.get().user?.sessionId;\n if (currentSessionId !== sessionIdAtCreation) {\n return;\n }\n void logoutWithReason(\n { reason: 'session-refresh-unauthorized' },\n client\n ).catch((error) => {\n core.logger.error(\n 'Failed to log out after WaaS unauthorized response',\n error\n );\n });\n },\n }\n );\n};\n","export type CreateTranslateRejectionParams<TMatched> = {\n /**\n * Builds the error thrown in place of a matched rejection.\n */\n mapTo: (error: TMatched) => Error;\n /**\n * Type guard selecting which rejections to translate. Anything it does not\n * match is rethrown untouched, so callers only translate the errors they\n * own. Narrowing to `TMatched` lets {@link CreateTranslateRejectionParams.mapTo}\n * receive a typed error without a cast.\n */\n match: (error: unknown) => error is TMatched;\n};\n\n/**\n * Builds a reusable decorator, bound once to a `match`/`mapTo` pair, that wraps\n * any async function so a matching rejection is rethrown as `mapTo(error)`\n * while every other rejection — and every resolved value — passes through\n * untouched. Unmatched errors are rethrown by reference, so the decorator can\n * never swallow or reshape an error it was not asked to translate.\n *\n * Binding `match`/`mapTo` up front keeps the generic wrapping machinery here\n * instead of at the call site: consumers get a plain `(fn) => wrappedFn`\n * decorator they can apply to many functions of differing signatures, each of\n * which keeps its own argument and return types.\n *\n * @notInstrumented\n */\nexport const createTranslateRejection =\n <TMatched>({ match, mapTo }: CreateTranslateRejectionParams<TMatched>) =>\n <TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => Promise<TReturn>) =>\n async (...args: TArgs): Promise<TReturn> => {\n try {\n return await fn(...args);\n } catch (error) {\n if (match(error)) {\n throw mapTo(error);\n }\n throw error;\n }\n };\n","import type { MFAAction, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport { consumeMfaTokenIfRequiredForAction } from '../../mfa/consumeMfaTokenIfRequiredForAction';\nimport { getElevatedAccessToken } from '../getElevatedAccessToken';\n\ntype GetActionAuthorizationTokensParams = {\n mfaAction: MFAAction;\n scope: TokenScope;\n};\n\ntype ActionAuthorizationTokens = {\n elevatedAccessToken: string | undefined;\n mfaToken: string | undefined;\n};\n\n/**\n * Resolves the tokens that authorize a verification-gated wallet action.\n *\n * An elevated access token for `scope` is the current proof of verification, so\n * it takes precedence: when one has been banked, the legacy per-action MFA token\n * is left untouched. Demanding both would break every user who has a verified\n * MFA method, because satisfying the challenge with `requestedScopes` mints an\n * elevated access token and no MFA token -- leaving nothing for\n * `consumeMfaTokenIfRequiredForAction` to consume, which then throws.\n *\n * @param params.mfaAction - The action whose legacy MFA requirement to evaluate.\n * @param params.scope - The scope of the elevated access token that authorizes the action.\n * @param client - The Dynamic client instance.\n * @returns The elevated access token, or the legacy MFA token when no elevated token exists.\n * @notInstrumented\n */\nexport const getActionAuthorizationTokens = async (\n { mfaAction, scope }: GetActionAuthorizationTokensParams,\n client: DynamicClient\n): Promise<ActionAuthorizationTokens> => {\n const elevatedAccessToken = getElevatedAccessToken({ scope }, client);\n\n if (elevatedAccessToken) {\n return { elevatedAccessToken, mfaToken: undefined };\n }\n\n const mfaToken = await consumeMfaTokenIfRequiredForAction(\n { mfaAction },\n client\n );\n\n return { elevatedAccessToken: undefined, mfaToken };\n};\n","import type { Chain } from '../../chain';\nimport { CHAINS_INFO_MAP } from '../../wallets/constants';\n\n/** @notInstrumented */\n// eslint-disable-next-line custom-rules/require-single-object-param\nexport const getWaasChainNameFromChain = (chain: Chain): string => {\n return CHAINS_INFO_MAP[chain].waasChainNameOverride || chain;\n};\n","/**\n * Exact message prefix of the rejection thrown by\n * `@dynamic-labs-wallet/browser-wallet-client` when the secure container load\n * exhausts all retry attempts. The upstream library throws a plain `Error`\n * with no code, so message matching is the only detection mechanism available;\n * the dependency is pinned to an exact version and the spec pins this string\n * so drift is caught at upgrade time.\n */\nconst UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX =\n 'Failed to load iframe after all retry attempts';\n\n/**\n * True when `error` is the upstream \"load retry attempts exhausted\" rejection\n * from the embedded (WaaS) wallet's secure container load. Narrows to `Error`\n * so the matched value can be forwarded as a typed error cause without a cast,\n * and guards `instanceof Error` before reading `.message` so a non-`Error`\n * rejection never throws during detection.\n *\n * @notInstrumented\n */\nexport const isWaasLoadExhaustionError = (error: unknown): error is Error =>\n error instanceof Error &&\n error.message.startsWith(UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX);\n","import {\n type BitcoinConfig,\n type DynamicWalletClient,\n ThresholdSignatureScheme,\n WalletOperation,\n} from '@dynamic-labs-wallet/browser-wallet-client';\nimport { MFAAction, TokenScope } from '@dynamic-labs/sdk-api-core';\n\nimport { getCore } from '../../../client/core/getCore';\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport { InvalidParamError } from '../../../errors/InvalidParamError';\nimport { WaasLoadFailedError } from '../../../errors/WaasLoadFailedError';\nimport { WaasOnboardingIncompleteError } from '../../../errors/WaasOnboardingIncompleteError';\nimport { createTranslateRejection } from '../../../utils/createTranslateRejection';\nimport { getActionAuthorizationTokens } from '../../auth/getActionAuthorizationTokens';\nimport type { Chain } from '../../chain';\nimport { consumeMfaTokenIfRequiredForAction } from '../../mfa/consumeMfaTokenIfRequiredForAction';\nimport { getSignedSessionId } from '../../sessionKeys/getSignedSessionId';\nimport { isUserOnboardingComplete } from '../../user/isUserOnboardingComplete';\nimport { createWaasClient } from '../createWaasClient';\nimport { getWaasChainNameFromChain } from '../getWaasChainNameFromChain';\nimport type { WaasProvider } from '../waas.types';\nimport { isWaasLoadExhaustionError } from './isWaasLoadExhaustionError';\n\nconst RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH = 64;\n\ntype CreateWaasProviderParams = {\n chain: Chain;\n sdkClient: DynamicClient;\n};\n\n/** @notInstrumented */\nexport const createWaasProvider = ({\n sdkClient,\n chain,\n}: CreateWaasProviderParams): WaasProvider => {\n const logger = getCore(sdkClient).logger;\n\n let _waasClient: DynamicWalletClient | undefined;\n // The session the cached client was built against. A step-up reauth mints a\n // NEW session (new sessionId + token); see the rebuild guard below.\n let _waasClientSessionId: string | undefined;\n\n // Drops the cached client only when it still points at `client`. Guarding on\n // identity matters because a step-up reauth can mint a new session and rebuild\n // a healthy client (via the session-change reset in getWaasClient) while an\n // older client's initialize()/operation is still failing in flight. Clearing\n // in that case would orphan the healthy replacement, since nothing would\n // release its upstream shared-container reference. _waasClientSessionId is\n // cleared alongside to keep the pair consistent.\n const resetClientIfCurrent = (client: DynamicWalletClient): void => {\n if (_waasClient === client) {\n _waasClient = undefined;\n _waasClientSessionId = undefined;\n }\n };\n\n // because the waas client needs the authToken to be set, we can only create it\n // the first time it's needed, which is after the user has logged in\n const getWaasClient: WaasProvider['getWaasClient'] = async () => {\n // After a step-up reauthentication a new session is minted. In header auth\n // mode (native webview) the iframe has no cookie jar to fall back on, so a\n // client cached against the previous session keeps presenting the stale\n // token — its next backend call (createRooms/users) 401s and trips the\n // iframe's onUnauthorized → forced logout. Drop the cached client when the\n // session changes so it rebuilds + re-initializes with the fresh token and\n // signed session id. Key shares stay in storage (only client auth resets);\n // routine token refresh keeps the same sessionId, so it does not rebuild.\n const currentSessionId = getCore(sdkClient).state.get().user?.sessionId;\n if (_waasClient && currentSessionId !== _waasClientSessionId) {\n _waasClient = undefined;\n }\n\n if (!_waasClient) {\n // Chokepoint: don't build + initialize the iframe client until onboarding\n // is complete. The iframe's init-time room-cache pre-warm fires\n // `createRooms` using the token captured at construction — before any\n // per-operation token resync exists to correct it. Built while the token\n // is still pre-`user:basic` (MFA / KYC / recovery codes / device\n // registration pending), that pre-warm 401s and trips the iframe's\n // onUnauthorized → forced-logout. This is the single gateway to\n // createWaasClient (web and native), so it covers every WaaS caller.\n if (!isUserOnboardingComplete(sdkClient)) {\n throw new WaasOnboardingIncompleteError();\n }\n\n const builtClient = createWaasClient(\n { chainName: getWaasChainNameFromChain(chain) },\n sdkClient\n );\n _waasClient = builtClient;\n _waasClientSessionId = currentSessionId;\n try {\n await builtClient.initialize();\n } catch (error) {\n // A failed load (e.g. iframe retry exhaustion) leaves an unusable,\n // never-initialized client cached. Drop it so the next getWaasClient()\n // rebuilds and re-initializes — the fresh load cycle WaasLoadFailedError\n // documents — instead of returning the dead client for the rest of the\n // session. Identity-guarded (see resetClientIfCurrent).\n resetClientIfCurrent(builtClient);\n throw error;\n }\n }\n // Read the shared var, not the locally-built client: if a concurrent\n // session-change rebuilt a fresh client while this initialize() was pending,\n // the caller should get that current healthy client, not this now-superseded\n // instance built against the old session.\n return _waasClient;\n };\n\n // Runs an operation against an already-fetched client and, if it fails because\n // the container's load was exhausted mid-flight (the client built and\n // initialized fine, then its iframe died — e.g. tab backgrounding, relogin —\n // and its own recovery could not reload), drops the cached client so the next\n // operation rebuilds and re-initializes. This covers the post-initialization\n // path that getWaasClient's own load-failure reset cannot see, so the\n // fresh-load cycle WaasLoadFailedError documents holds for every operation,\n // not just the first load. Identity-guarded (see resetClientIfCurrent).\n const discardClientOnLoadFailure = async <TReturn>({\n waasClient,\n operation,\n }: {\n operation: () => Promise<TReturn>;\n waasClient: DynamicWalletClient;\n }): Promise<TReturn> => {\n try {\n return await operation();\n } catch (error) {\n if (isWaasLoadExhaustionError(error)) {\n resetClientIfCurrent(waasClient);\n }\n throw error;\n }\n };\n\n const backupKeySharesToGoogleDrive: WaasProvider['backupKeySharesToGoogleDrive'] =\n async ({ googleDriveAccessToken, password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.backupKeySharesToGoogleDrive({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n googleDriveAccessToken,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const createWalletAccount: WaasProvider['createWalletAccount'] = async (\n args = {}\n ) => {\n logger.debug('[createWaasProvider] createWalletAccount', {\n bitcoinConfig: args.bitcoinConfig,\n thresholdSignatureScheme: args.thresholdSignatureScheme,\n });\n\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n const waasWallet = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.createWalletAccount({\n authToken: sdkClient.token ?? undefined,\n bitcoinConfig: args.bitcoinConfig as BitcoinConfig | undefined,\n businessAccountId: args.businessAccountId,\n password: args.password,\n signedSessionId,\n thresholdSignatureScheme:\n args.thresholdSignatureScheme ??\n ThresholdSignatureScheme.TWO_OF_TWO,\n }),\n waasClient,\n });\n\n return waasWallet;\n };\n\n const delegateKeyShares: WaasProvider['delegateKeyShares'] = async ({\n initialSignerRules,\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.delegateKeyShares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n initialSignerRules,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const exportClientKeyshares: WaasProvider['exportClientKeyshares'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.exportClientKeyshares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const exportPrivateKey: WaasProvider['exportPrivateKey'] = async ({\n container,\n displayContainer,\n walletAccount,\n password,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n // Forwards whichever token proves the export was verified: the elevated\n // wallet:export token banked by step-up, or the legacy per-action MFA token.\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasExport, scope: TokenScope.Walletexport },\n sdkClient\n );\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.exportPrivateKey({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n // Exactly one display surface is forwarded: `container` (a\n // WaasSDKContainer, e.g. a React Native visible WebView) or\n // `displayContainer` (a DOM element, web). The upstream client enforces\n // the \"exactly one\" invariant and renders the key inside the surface's\n // own sandboxed document — it never crosses back to the host.\n container,\n displayContainer,\n elevatedAccessToken,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const restoreUserShareForWalletAccount: WaasProvider['restoreUserShareForWalletAccount'] =\n async ({ walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n waasClient.getWallet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n signedSessionId,\n walletOperation: WalletOperation.SIGN_MESSAGE,\n }),\n waasClient,\n });\n };\n\n const importPrivateKey: WaasProvider['importPrivateKey'] = async ({\n privateKey,\n thresholdSignatureScheme = ThresholdSignatureScheme.TWO_OF_TWO,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const walletClient = await getWaasClient();\n\n await discardClientOnLoadFailure({\n operation: () =>\n walletClient.importPrivateKey({\n authToken: sdkClient.token ?? undefined,\n privateKey,\n signedSessionId,\n thresholdSignatureScheme,\n }),\n waasClient: walletClient,\n });\n };\n\n const migrateFromFireblocks: WaasProvider['migrateFromFireblocks'] = async ({\n coinTypes,\n deviceId,\n expectedAddresses,\n jwt,\n password,\n storage,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const walletClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n walletClient.migrateFromFireblocks({\n authToken: sdkClient.token ?? undefined,\n fireblocks: {\n deviceId,\n expectedAddresses,\n jwt,\n ncwStorage: storage,\n walletPassword: password,\n ...(coinTypes ? { coinTypes } : {}),\n },\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n };\n\n const refreshWalletAccountShares: WaasProvider['refreshWalletAccountShares'] =\n async ({ password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const walletClient = await getWaasClient();\n\n const mfaToken = await consumeMfaTokenIfRequiredForAction(\n { mfaAction: MFAAction.WalletWaasRefresh },\n sdkClient\n );\n\n return discardClientOnLoadFailure({\n operation: () =>\n walletClient.refreshWalletAccountShares({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n };\n\n const reshareToNewSignerShareSet: WaasProvider['reshareToNewSignerShareSet'] =\n async ({\n businessAccountId,\n password,\n signerType,\n targetSignerIdentity,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n const { elevatedAccessToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasReshare, scope: TokenScope.BusinessAccountsigneradd },\n sdkClient\n );\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.reshareToNewSignerShareSet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n businessAccountId,\n elevatedAccessToken,\n password,\n signedSessionId,\n // Public API uses a string union; the client expects the core enum\n // (identical values). Cast at this single boundary.\n signerType: signerType as Parameters<\n typeof waasClient.reshareToNewSignerShareSet\n >[0]['signerType'],\n targetSignerIdentity,\n }),\n waasClient,\n });\n };\n\n const revokeDelegation: WaasProvider['revokeDelegation'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.revokeDelegation({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const setWaasWalletAccountPassword: WaasProvider['setWaasWalletAccountPassword'] =\n async ({ password, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.setPassword({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n newPassword: password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const signRawMessage: WaasProvider['signRawMessage'] = async ({\n message,\n password,\n walletAccount,\n }) => {\n if (message.length !== RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH) {\n throw new InvalidParamError(\n `Message must be ${RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH} characters long`\n );\n }\n\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const walletClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n walletClient.signRawMessage({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n elevatedAccessToken,\n message,\n mfaToken,\n password,\n signedSessionId,\n }),\n waasClient: walletClient,\n });\n\n return { signature };\n };\n\n const destroy: WaasProvider['destroy'] = async (args) => {\n if (!_waasClient) {\n return;\n }\n\n const waasClient = await getWaasClient();\n // When a session token expires, we preserve key shares in storage instead\n // of clearing them. Customers with short-lived sessions (minutes) were\n // hitting excessive server-side share recovery on every re-login, which\n // also forced users to re-enter their wallet password since the unlocked\n // share only lives for the duration of the session.\n //\n // This is safe because the waas-sdk separately fingerprints the user\n // (sub + environment_id) and clears all storage if a different user logs\n // in. On explicit user-initiated logout, shares are always cleared for\n // security.\n if (args?.reason !== 'token-expired') {\n await waasClient.cleanup();\n }\n _waasClient = undefined;\n };\n\n const updatePassword: WaasProvider['updatePassword'] = async ({\n walletAccount,\n currentPassword,\n newPassword,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.updatePassword({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n existingPassword: currentPassword,\n newPassword,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const signMessage: WaasProvider['signMessage'] = async ({\n message,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const { elevatedAccessToken, mfaToken } = await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.signMessage({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n elevatedAccessToken,\n message,\n mfaToken,\n signedSessionId,\n }),\n waasClient,\n });\n\n return { signature };\n };\n\n const signSerializedTransaction: WaasProvider['signSerializedTransaction'] =\n async ({ chainId, serializedTransaction, walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const { elevatedAccessToken, mfaToken } =\n await getActionAuthorizationTokens(\n { mfaAction: MFAAction.WalletWaasSign, scope: TokenScope.Walletsign },\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n const signature = await discardClientOnLoadFailure({\n operation: () =>\n waasClient.signTransaction({\n authToken: sdkClient.token ?? undefined,\n chainId,\n elevatedAccessToken,\n mfaToken,\n senderAddress: walletAccount.address,\n signedSessionId,\n transaction: serializedTransaction,\n }),\n waasClient,\n });\n\n return { signature };\n };\n\n const getWalletRecoveryState: WaasProvider['getWalletRecoveryState'] =\n async ({ walletAccount }) => {\n const { signature: signedSessionId } = await getSignedSessionId(\n sdkClient\n );\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.getWalletRecoveryState({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n const unlockWallet: WaasProvider['unlockWallet'] = async ({\n password,\n walletAccount,\n }) => {\n const { signature: signedSessionId } = await getSignedSessionId(sdkClient);\n\n const waasClient = await getWaasClient();\n\n return discardClientOnLoadFailure({\n operation: () =>\n waasClient.unlockWallet({\n accountAddress: walletAccount.address,\n authToken: sdkClient.token ?? undefined,\n password,\n signedSessionId,\n }),\n waasClient,\n });\n };\n\n // Every operation is wrapped so an exhausted container load surfaces as a\n // typed WaasLoadFailedError no matter which call triggers it — the initial\n // load or a mid-operation recovery. Wrapped at the operation itself (rather\n // than a separate whole-provider pass) so the translation is visible right\n // where the provider is assembled.\n const translateLoadFailure = createTranslateRejection({\n mapTo: (error) => new WaasLoadFailedError({ cause: error }),\n match: isWaasLoadExhaustionError,\n });\n\n const provider: WaasProvider = {\n backupKeySharesToGoogleDrive: translateLoadFailure(\n backupKeySharesToGoogleDrive\n ),\n createWalletAccount: translateLoadFailure(createWalletAccount),\n delegateKeyShares: translateLoadFailure(delegateKeyShares),\n destroy: translateLoadFailure(destroy),\n exportClientKeyshares: translateLoadFailure(exportClientKeyshares),\n exportPrivateKey: translateLoadFailure(exportPrivateKey),\n getWaasClient: translateLoadFailure(getWaasClient),\n getWalletRecoveryState: translateLoadFailure(getWalletRecoveryState),\n importPrivateKey: translateLoadFailure(importPrivateKey),\n migrateFromFireblocks: translateLoadFailure(migrateFromFireblocks),\n refreshWalletAccountShares: translateLoadFailure(\n refreshWalletAccountShares\n ),\n reshareToNewSignerShareSet: translateLoadFailure(\n reshareToNewSignerShareSet\n ),\n restoreUserShareForWalletAccount: translateLoadFailure(\n restoreUserShareForWalletAccount\n ),\n revokeDelegation: translateLoadFailure(revokeDelegation),\n setWaasWalletAccountPassword: translateLoadFailure(\n setWaasWalletAccountPassword\n ),\n signMessage: translateLoadFailure(signMessage),\n signRawMessage: translateLoadFailure(signRawMessage),\n signSerializedTransaction: translateLoadFailure(signSerializedTransaction),\n unlockWallet: translateLoadFailure(unlockWallet),\n updatePassword: translateLoadFailure(updatePassword),\n };\n\n return provider;\n};\n","import type { WaasSDKContainer } from '@dynamic-labs-wallet/core';\n\nimport type { DynamicClient } from '../../../client/types/DynamicClient';\nimport type { WalletAccount } from '../../wallets/walletAccount';\nimport { getWaasWalletProviderFromWalletAccount } from '../getWaasWalletProviderFromWalletAccount';\n\ntype ExportWaasPrivateKeyToContainerParams = {\n container: WaasSDKContainer;\n password?: string;\n walletAccount: WalletAccount;\n};\n\n/**\n * Exports the private key for a WaaS wallet account into a caller-provided\n * {@link WaasSDKContainer} (e.g. a visible React Native WebView) instead of a\n * DOM element.\n *\n * This is the container-based counterpart to `exportWaasPrivateKey` (which\n * injects an iframe into a DOM `displayContainer` on web). The export ceremony\n * runs — and the private key is rendered — entirely inside the container's own\n * sandboxed document; the key is never exposed to the host JS layer. The caller\n * owns the container's lifecycle and must call `container.destroy()` when the\n * display is dismissed.\n *\n * @param params.walletAccount - The WaaS wallet account to export the private key from.\n * @param params.container - The container that hosts the secure key display.\n * @param [params.password] - Optional password to decrypt the private key.\n * @param client - The Dynamic client instance. This is an internal API (exposed\n * only via `@dynamic-labs-sdk/client/waas/core`), so the client is passed\n * explicitly rather than defaulted — callers resolve it (e.g. via\n * `getDefaultClient()`) and thread it in.\n * @returns A promise that resolves when the private key export is complete.\n * @notInstrumented\n */\nexport const exportWaasPrivateKeyToContainer = async (\n { container, password, walletAccount }: ExportWaasPrivateKeyToContainerParams,\n client: DynamicClient\n) => {\n const provider = getWaasWalletProviderFromWalletAccount(\n { walletAccount },\n client\n );\n\n return provider.exportPrivateKey({\n container,\n password,\n walletAccount,\n });\n};\n","import { WalletProviderEnum } from '@dynamic-labs/sdk-api-core';\n\nimport type { DynamicClient } from '../../../client/types';\nimport { getChainFromVerifiedCredentialChain } from '../../../utils/getChainFromVerifiedCredentialChain';\nimport type { Chain } from '../../chain';\nimport { DYNAMIC_WAAS_METADATA } from '../constants';\n\ntype GetAllUserWaasAddressesForChainParams = {\n chain: Chain;\n};\n\n/** @notInstrumented */\nexport const getAllUserWaasAddressesForChain = (\n { chain }: GetAllUserWaasAddressesForChainParams,\n client: DynamicClient\n): string[] => {\n if (!client.user) {\n return [];\n }\n\n const waasWalletCredentials =\n client.user.verifiedCredentials.filter(\n (credential) =>\n credential.walletProvider === WalletProviderEnum.EmbeddedWallet &&\n credential.walletName\n ?.toLowerCase()\n .startsWith(DYNAMIC_WAAS_METADATA.normalizedWalletName) &&\n credential.address &&\n credential.chain &&\n getChainFromVerifiedCredentialChain(credential.chain) === chain\n ) ?? [];\n\n const waasAddresses: string[] = waasWalletCredentials.map(\n // casting because we're already filtering out credentials without an address\n (credential) => credential.address as string\n );\n\n return waasAddresses;\n};\n","import { 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\nexport type {\n BitcoinNetwork,\n DynamicWalletClient,\n MigrateFromFireblocksResponse,\n ThresholdSignatureScheme,\n} from '@dynamic-labs-wallet/browser-wallet-client';\nexport type { WaasSDKContainer } from '@dynamic-labs-wallet/core';\nexport { DYNAMIC_WAAS_METADATA } from '../modules/waas/constants';\nexport { createWaasClient } from '../modules/waas/createWaasClient';\nexport { createWaasProvider } from '../modules/waas/createWaasProvider';\nexport { exportWaasPrivateKeyToContainer } from '../modules/waas/exportWaasPrivateKeyToContainer';\nexport { getAllUserWaasAddressesForChain } from '../modules/waas/getAllUserWaasAddressesForChain';\nexport { getWaasChainNameFromChain } from '../modules/waas/getWaasChainNameFromChain';\nexport { migrateFromFireblocks } from '../modules/waas/migrateFromFireblocks';\nexport { preconnectWaasIframe } from '../modules/waas/preconnectWaasIframe';\nexport type {\n WaasProvider,\n WaasWalletProvider,\n} from '../modules/waas/waas.types';\n"],"mappings":";;;;;;;;;;;;AAeA,MAAaA,oBAAsC,EAAE,aAAa,WAAW;CAC3E,MAAM,OAAO,QAAQ,OAAO;CAE5B,MAAM,2BAA2B,KAAK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Q;EACtC,uBAAuB,qBAAqB,sBAAsB;EAClE,kBAAkB,qBAAqB,iBAAiB;EACxD,eAAe,qBAAqB,cAAc;EAClD,wBAAwB,qBAAqB,uBAAuB;EACpE,kBAAkB,qBAAqB,iBAAiB;EACxD,uBAAuB,qBAAqBC,wBAAsB;EAClE,4BAA4B,qBAC1B,2BACD;EACD,4BAA4B,qBAC1B,2BACD;EACD,kCAAkC,qBAChC,iCACD;EACD,kBAAkB,qBAAqB,iBAAiB;EACxD,8BAA8B,qBAC5B,6BACD;EACD,aAAa,qBAAqB,YAAY;EAC9C,gBAAgB,qBAAqB,eAAe;EACpD,2BAA2B,qBAAqB,0BAA0B;EAC1E,cAAc,qBAAqB,aAAa;EAChD,gBAAgB,qBAAqB,eAAe;EACrD;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrnBH,MAAa,kCAAkC,OAC7C,EAAE,WAAW,UAAU,iBACvB,WACG;AAMH,QALiB,uCACf,EAAE,eAAe,EACjB,OACD,CAEe,iBAAiB;EAC/B;EACA;EACA;EACD,CAAC;;;;;;ACnCJ,MAAa,mCACX,EAAE,SACF,WACa;AACb,KAAI,CAAC,OAAO,KACV,QAAO,EAAE;AAoBX,SAhBE,OAAO,KAAK,oBAAoB,QAC7B,eACC,WAAW,mBAAmB,mBAAmB,kBACjD,WAAW,YACP,aAAa,CACd,WAAW,sBAAsB,qBAAqB,IACzD,WAAW,WACX,WAAW,SACX,oCAAoC,WAAW,MAAM,KAAK,MAC7D,IAAI,EAAE,EAE6C,KAEnD,eAAe,WAAW,QAC5B;;;;;AC7BH,qBAAqBC,MAAaC,QAAe"}
@@ -1,13 +1,261 @@
1
- import { Ct as name, M as getChainFromVerifiedCredentialChain, St as getCore, a as InvalidParamError, f as DYNAMIC_WAAS_METADATA, mt as getElevatedAccessToken, wt as version } from "./NativeModuleNotLinkedError-CJy_4-6r.native.esm.js";
2
- import "./isDynamicWaasEnabled-yo_LqzH5.native.esm.js";
3
- import { a as WaasOnboardingIncompleteError, i as preconnectWaasIframe, o as WaasLoadFailedError, t as isUserOnboardingComplete } from "./isUserOnboardingComplete-DcRl6Q1f.native.esm.js";
4
- import "./isMfaRequiredForAction-Zi7_K00W.native.esm.js";
5
- import { n as consumeMfaTokenIfRequiredForAction, t as getSignedSessionId } from "./getSignedSessionId-B6Eqmue0.native.esm.js";
6
- import { i as getWaasWalletProviderFromWalletAccount, n as getWaasChainNameFromChain, r as createWaasClient, t as migrateFromFireblocks } from "./migrateFromFireblocks-COEK_Acn.native.esm.js";
1
+ import { Ct as version, M as CHAINS_INFO_MAP, St as name, at as CLIENT_SDK_NAME, bt as BaseError, d as DYNAMIC_WAAS_METADATA, i as InvalidParamError, j as getChainFromVerifiedCredentialChain, l as DEFAULT_WAAS_BASE_API_URL, pt as getElevatedAccessToken, u as DEFAULT_WAAS_BASE_MPC_RELAY_API_URL, ut as isCookieEnabled, xt as getCore } from "./updateAuthFromVerifyResponse-WlGmt2v0.native.esm.js";
2
+ import "./isDynamicWaasEnabled-B75AeGiP.native.esm.js";
3
+ import { i as NativeModuleNotLinkedError } from "./isMfaRequiredForAction-WmEokgKF.native.esm.js";
4
+ import { a as WaasOnboardingIncompleteError, i as preconnectWaasIframe, o as WaasLoadFailedError, t as isUserOnboardingComplete } from "./isUserOnboardingComplete-G6Hf8p_v.native.esm.js";
5
+ import { n as consumeMfaTokenIfRequiredForAction, t as getSignedSessionId } from "./getSignedSessionId-B3aCjPhf.native.esm.js";
6
+ import { n as getWaasWalletProviderFromWalletAccount, t as migrateFromFireblocks } from "./migrateFromFireblocks-kFz_kyA5.native.esm.js";
7
7
  import { assertPackageVersion } from "@dynamic-labs-sdk/assert-package-version";
8
8
  import { MFAAction, TokenScope, WalletProviderEnum } from "@dynamic-labs/sdk-api-core";
9
- import { ThresholdSignatureScheme, WalletOperation } from "@dynamic-labs-wallet/browser-wallet-client";
9
+ import { ACCESSIBLE, getGenericPassword, resetGenericPassword, setGenericPassword } from "react-native-keychain";
10
+ import { NativeEventEmitter, TurboModuleRegistry } from "react-native";
11
+ import { DynamicWalletClient, ThresholdSignatureScheme, WalletOperation } from "@dynamic-labs-wallet/browser-wallet-client";
10
12
 
13
+ //#region src/errors/CorruptedKeyShareError.ts
14
+ /**
15
+ * Thrown when a persisted client key share cannot be parsed back into its
16
+ * structured form (e.g. a partially-written or corrupted keychain entry).
17
+ *
18
+ * Surfaced as a typed error rather than swallowed so callers can distinguish
19
+ * "no key share stored" (empty result) from "key share exists but is
20
+ * unreadable" — the latter must never be silently treated as the former,
21
+ * which could trigger an unintended re-keygen that overwrites recoverable
22
+ * material.
23
+ */
24
+ var CorruptedKeyShareError = class extends BaseError {
25
+ constructor({ cause = null } = {}) {
26
+ super({
27
+ cause,
28
+ code: "corrupted_key_share_error",
29
+ details: "The stored client key share could not be parsed. The secure storage entry may be partially written or corrupted.",
30
+ docsUrl: null,
31
+ name: "CorruptedKeyShareError",
32
+ shortMessage: "Stored client key share is corrupted and cannot be read."
33
+ });
34
+ }
35
+ };
36
+
37
+ //#endregion
38
+ //#region src/turboModules/NativeDynamicWebView.ts
39
+ var NativeDynamicWebView_default = TurboModuleRegistry.get("DynamicClientWebView");
40
+
41
+ //#endregion
42
+ //#region src/errors/WebViewLoadFailedError.ts
43
+ /**
44
+ * Thrown when `DynamicWebView.open()` (via the WaaS transport provider)
45
+ * fails to establish a usable load. Inspect `reason` to distinguish the
46
+ * failure mode; `statusCode` and `underlyingError` provide structured
47
+ * metadata for the cases that have it.
48
+ */
49
+ var WebViewLoadFailedError = class extends BaseError {
50
+ reason;
51
+ statusCode;
52
+ underlyingError;
53
+ constructor({ reason, shortMessage, cause = null, statusCode, underlyingError }) {
54
+ super({
55
+ cause,
56
+ code: "webview_load_failed_error",
57
+ details: underlyingError,
58
+ docsUrl: null,
59
+ name: "WebViewLoadFailedError",
60
+ shortMessage
61
+ });
62
+ this.reason = reason;
63
+ this.statusCode = statusCode;
64
+ this.underlyingError = underlyingError;
65
+ }
66
+ };
67
+
68
+ //#endregion
69
+ //#region src/modules/waas/createWaasClient/translateNativeOpenError.ts
70
+ const REASON_BY_NATIVE_CODE = {
71
+ webview_cancelled: "cancelled",
72
+ webview_content_process_terminated: "content_process_terminated",
73
+ webview_http_error: "http_error",
74
+ webview_instance_busy: "instance_busy",
75
+ webview_invalid_url: "invalid_url",
76
+ webview_navigation_failed: "navigation_failed",
77
+ webview_no_host_view: "no_host_view",
78
+ webview_unsupported: "unsupported"
79
+ };
80
+ /**
81
+ * Translates a native `DynamicWebView.open()` rejection into a typed
82
+ * `WebViewLoadFailedError`. Maps the native RCT reject code to the JS-level
83
+ * `WebViewLoadFailureReason` discriminator (falling back to
84
+ * `navigation_failed` for unrecognized codes) and carries through the
85
+ * structured `statusCode` / `underlyingError` metadata.
86
+ *
87
+ * The `reason` it produces is the contract `createWaasSDKContainer` branches
88
+ * on — notably `emitError` swallows `cancelled` because that code is only ever
89
+ * produced by our own `close()` teardown (verified on both the iOS and Android
90
+ * native sides). Keep `REASON_BY_NATIVE_CODE` in sync with the native reject
91
+ * codes so that branching stays correct.
92
+ *
93
+ * @notInstrumented
94
+ */
95
+ const translateNativeOpenError = (err) => {
96
+ const rejection = err ?? {};
97
+ const isNativeRejectionCode = (code) => code != void 0 && code in REASON_BY_NATIVE_CODE;
98
+ const reason = isNativeRejectionCode(rejection.code) ? REASON_BY_NATIVE_CODE[rejection.code] : "navigation_failed";
99
+ return new WebViewLoadFailedError({
100
+ cause: err instanceof Error ? err : null,
101
+ reason,
102
+ shortMessage: rejection.message ?? `DynamicWebView open failed (${reason}).`,
103
+ statusCode: rejection.userInfo?.DynamicWebViewStatusCode,
104
+ underlyingError: rejection.userInfo?.DynamicWebViewUnderlying
105
+ });
106
+ };
107
+
108
+ //#endregion
109
+ //#region src/modules/waas/createWaasClient/createNativeWaasSDKContainer.native.ts
110
+ const NATIVE_MODULE_NAME = "DynamicClientWebView";
111
+ const MESSAGE_EVENT_NAME = "dynamicBridgeMessage";
112
+ const generateInstanceId = () => `${Date.now().toString(36)}-${crypto.randomUUID()}`;
113
+ /**
114
+ * Creates a React Native `WaasSDKContainer` backed by a hidden, headless native
115
+ * WebView (WKWebView on iOS, `android.webkit.WebView` on Android) hosted by the
116
+ * `DynamicClientWebView` TurboModule. Each invocation returns an isolated
117
+ * container with its own instance ID, native WebView, and message routing.
118
+ *
119
+ * Used for MPC operations (signing, key-share management) where there is
120
+ * nothing for the user to see. The VISIBLE private-key export display is no
121
+ * longer a native overlay — it is rendered by the `ExportPrivateKey` component
122
+ * (`@dynamic-labs-sdk/react-native-embedded-wallet-export`) on top of
123
+ * `react-native-webview`, so it scrolls and positions like any RN view.
124
+ *
125
+ * @notInstrumented
126
+ */
127
+ const createNativeWaasSDKContainer = () => {
128
+ if (!NativeDynamicWebView_default) throw new NativeModuleNotLinkedError({ moduleName: NATIVE_MODULE_NAME });
129
+ const nativeModule = NativeDynamicWebView_default;
130
+ const instanceId = generateInstanceId();
131
+ const emitter = new NativeEventEmitter(nativeModule);
132
+ const messageHandlers = [];
133
+ const errorHandlers = [];
134
+ let subscription = null;
135
+ let destroyed = false;
136
+ const emitError = (err) => {
137
+ if (destroyed) return;
138
+ const translated = translateNativeOpenError(err);
139
+ if (translated.reason === "cancelled") return;
140
+ for (const handler of errorHandlers) handler(translated);
141
+ };
142
+ return {
143
+ destroy() {
144
+ if (destroyed) return;
145
+ destroyed = true;
146
+ subscription?.remove();
147
+ subscription = null;
148
+ messageHandlers.length = 0;
149
+ errorHandlers.length = 0;
150
+ nativeModule.close(instanceId);
151
+ },
152
+ isAlive: () => !destroyed,
153
+ onError(handler) {
154
+ errorHandlers.push(handler);
155
+ return () => {
156
+ const index = errorHandlers.indexOf(handler);
157
+ if (index !== -1) errorHandlers.splice(index, 1);
158
+ };
159
+ },
160
+ onMessage(handler) {
161
+ messageHandlers.push(handler);
162
+ subscription ??= emitter.addListener(MESSAGE_EVENT_NAME, (payload) => {
163
+ if (payload.instanceId !== instanceId) return;
164
+ for (const fn of messageHandlers) fn(payload.data);
165
+ });
166
+ return () => {
167
+ const index = messageHandlers.indexOf(handler);
168
+ if (index !== -1) messageHandlers.splice(index, 1);
169
+ if (messageHandlers.length === 0) {
170
+ subscription?.remove();
171
+ subscription = null;
172
+ }
173
+ };
174
+ },
175
+ sendMessage(data) {
176
+ nativeModule.sendMessage(instanceId, data);
177
+ },
178
+ async setUrl(url) {
179
+ nativeModule.open(instanceId, url).catch(emitError);
180
+ }
181
+ };
182
+ };
183
+
184
+ //#endregion
185
+ //#region src/modules/waas/createWaasClient/createWaasSDKContainer.native.ts
186
+ /**
187
+ * Creates a React Native `WaasSDKContainer` backed by a hidden, headless native
188
+ * WebView (WKWebView on iOS, `android.webkit.WebView` on Android) hosted by the
189
+ * `DynamicClientWebView` TurboModule. Used for MPC operations (signing, key-share
190
+ * management) where there is nothing for the user to see.
191
+ *
192
+ * For the private-key export display — where the hosted page must render the
193
+ * key for the user — use the `ExportPrivateKey` component from
194
+ * `@dynamic-labs-sdk/react-native-embedded-wallet-export`, which renders the
195
+ * key inside a `react-native-webview` instead of a native overlay.
196
+ *
197
+ * @notInstrumented
198
+ */
199
+ const createWaasSDKContainer = () => createNativeWaasSDKContainer();
200
+
201
+ //#endregion
202
+ //#region src/modules/waas/createWaasClient/createWaasClient.native.ts
203
+ /**
204
+ * Keychain security options for the client key share. The share is wallet
205
+ * key material that cannot be re-derived locally, so the options are pinned
206
+ * explicitly rather than inherited from `react-native-keychain` defaults
207
+ * (which vary across versions and platforms).
208
+ *
209
+ * `WHEN_UNLOCKED_THIS_DEVICE_ONLY` keeps the share readable only while the
210
+ * device is unlocked, excludes it from iCloud Keychain sync, and prevents it
211
+ * migrating to a new device on encrypted-backup restore. It deliberately does
212
+ * NOT set `accessControl` (e.g. biometry) — reads must not surface a Face ID /
213
+ * passcode prompt, since the share is read on routine wallet operations.
214
+ */
215
+ const KEY_SHARE_KEYCHAIN_OPTIONS = { accessible: ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY };
216
+ /** @notInstrumented */
217
+ const createWaasClient = ({ chainName }, client) => {
218
+ const core = getCore(client);
219
+ const additionalTrustedOrigins = core.waas?.additionalTrustedOrigins;
220
+ const getKeyShareService = (accountAddress) => `${core.environmentId}:${accountAddress}`;
221
+ return new DynamicWalletClient({
222
+ authMode: isCookieEnabled(client) ? "cookie" : "header",
223
+ authToken: client.token || "",
224
+ baseApiUrl: (core.apiBaseUrl || DEFAULT_WAAS_BASE_API_URL).replace("/api/v0", ""),
225
+ baseMPCRelayApiUrl: client.projectSettings?.sdk.waas?.relayUrl || DEFAULT_WAAS_BASE_MPC_RELAY_API_URL,
226
+ chainName,
227
+ environmentId: core.environmentId,
228
+ hostOrigin: core.metadata?.universalLink,
229
+ sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`,
230
+ ...additionalTrustedOrigins == void 0 ? {} : { additionalTrustedOrigins },
231
+ ...core.waas?.loadTimeoutMs == void 0 ? {} : { iframeLoadTimeout: core.waas.loadTimeoutMs },
232
+ ...core.waas?.maxLoadRetries == void 0 ? {} : { maxRetryAttempts: core.waas.maxLoadRetries }
233
+ }, {
234
+ createWaasSDKContainer,
235
+ secureStorage: {
236
+ getClientKeyShare: async (accountAddress) => {
237
+ const result = await getGenericPassword({ service: getKeyShareService(accountAddress) });
238
+ if (!result) return [];
239
+ try {
240
+ return JSON.parse(result.password);
241
+ } catch (cause) {
242
+ throw new CorruptedKeyShareError({ cause: cause instanceof Error ? cause : null });
243
+ }
244
+ },
245
+ removeClientKeyShare: async (accountAddress) => {
246
+ await resetGenericPassword({ service: getKeyShareService(accountAddress) });
247
+ },
248
+ setClientKeyShare: async (accountAddress, shares) => {
249
+ await setGenericPassword(accountAddress, JSON.stringify(shares), {
250
+ ...KEY_SHARE_KEYCHAIN_OPTIONS,
251
+ service: getKeyShareService(accountAddress)
252
+ });
253
+ }
254
+ }
255
+ });
256
+ };
257
+
258
+ //#endregion
11
259
  //#region src/utils/createTranslateRejection/createTranslateRejection.ts
12
260
  /**
13
261
  * Builds a reusable decorator, bound once to a `match`/`mapTo` pair, that wraps
@@ -62,6 +310,13 @@ const getActionAuthorizationTokens = async ({ mfaAction, scope }, client) => {
62
310
  };
63
311
  };
64
312
 
313
+ //#endregion
314
+ //#region src/modules/waas/getWaasChainNameFromChain/getWaasChainNameFromChain.ts
315
+ /** @notInstrumented */
316
+ const getWaasChainNameFromChain = (chain) => {
317
+ return CHAINS_INFO_MAP[chain].waasChainNameOverride || chain;
318
+ };
319
+
65
320
  //#endregion
66
321
  //#region src/modules/waas/createWaasProvider/isWaasLoadExhaustionError.ts
67
322
  /**
@@ -267,11 +522,16 @@ const createWaasProvider = ({ sdkClient, chain }) => {
267
522
  const reshareToNewSignerShareSet = async ({ businessAccountId, password, signerType, targetSignerIdentity, walletAccount }) => {
268
523
  const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
269
524
  const waasClient = await getWaasClient();
525
+ const { elevatedAccessToken } = await getActionAuthorizationTokens({
526
+ mfaAction: MFAAction.WalletWaasReshare,
527
+ scope: TokenScope.BusinessAccountsigneradd
528
+ }, sdkClient);
270
529
  return discardClientOnLoadFailure({
271
530
  operation: () => waasClient.reshareToNewSignerShareSet({
272
531
  accountAddress: walletAccount.address,
273
532
  authToken: sdkClient.token ?? void 0,
274
533
  businessAccountId,
534
+ elevatedAccessToken,
275
535
  password,
276
536
  signedSessionId,
277
537
  signerType,