@seams/wallet 0.28.0 → 0.29.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 (350) hide show
  1. package/README.md +29 -4
  2. package/dist/.build-inputs.sha256 +1 -1
  3. package/dist/esm/SeamsWeb/publicApi/createPublicApi.js +11 -0
  4. package/dist/esm/SeamsWeb/publicApi/near.js +3 -0
  5. package/dist/esm/SeamsWeb/publicApi/ownerNearOperation.js +175 -0
  6. package/dist/esm/SeamsWeb/walletIframe/client/nearCommands.js +4 -0
  7. package/dist/esm/SeamsWeb/walletIframe/client/ownerNearOperation.js +67 -0
  8. package/dist/esm/SeamsWeb/walletIframe/client/progress/on-events-progress-bus.js +27 -17
  9. package/dist/esm/SeamsWeb/walletIframe/client/router.js +30 -7
  10. package/dist/esm/SeamsWeb/walletIframe/client/sessionCommands.js +4 -0
  11. package/dist/esm/SeamsWeb/walletIframe/host/walletMutationGuard.js +5 -0
  12. package/dist/esm/SeamsWeb/walletIframe/shared/exactSessionState.js +15 -1
  13. package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +1 -1
  14. package/dist/esm/SeamsWeb/walletIframe/shared/ownerNearOperation.js +152 -0
  15. package/dist/esm/core/accountData/near/accountProjection.js +1 -1
  16. package/dist/esm/core/indexedDB/seamsWalletDB/repositories.js +4 -3
  17. package/dist/esm/core/rpcClients/relayer/walletRegistration.js +1 -1
  18. package/dist/esm/core/signingEngine/flows/registration/accountLifecycle.js +1 -1
  19. package/dist/esm/core/signingEngine/flows/shared/signingConfirmation.js +1 -1
  20. package/dist/esm/core/signingEngine/flows/signEvmFamily/signEvmFamily.js +1 -1
  21. package/dist/esm/core/signingEngine/flows/signEvmFamily/signingFlow.js +1 -1
  22. package/dist/esm/core/signingEngine/flows/signNear/shared/ed25519YaoNormalSigning.js +2 -2
  23. package/dist/esm/core/signingEngine/flows/signNear/signDelegate.js +2 -2
  24. package/dist/esm/core/signingEngine/flows/signNear/signNear.js +3 -8
  25. package/dist/esm/core/signingEngine/flows/signNear/signNep413.js +1 -1
  26. package/dist/esm/core/signingEngine/flows/signNear/signTransactions.js +3 -4
  27. package/dist/esm/core/signingEngine/session/identity/exactSigningLaneIdentity.js +1 -1
  28. package/dist/esm/index.js +3 -2
  29. package/dist/esm/react/boundWallet.js +24 -0
  30. package/dist/esm/react/context/useLoginStateRefresher.js +1 -0
  31. package/dist/esm/react/hooks/useAccountInput.js +1 -1
  32. package/dist/esm/react/hooks/useOwnerNearOperation.js +10 -0
  33. package/dist/esm/react/index.js +3 -2
  34. package/dist/esm/sdk/{ConfirmationDrawer-MJoE0AAo.js → ConfirmationDrawer-BRnd5SEf.js} +1 -1
  35. package/dist/esm/sdk/NonceCoordinator-CNXYrOoy.js +1 -0
  36. package/dist/{public/sdk/SeamsWordmark-DwvPx2UA.js → esm/sdk/SeamsWordmark-CeEi2RlU.js} +1 -1
  37. package/dist/esm/sdk/accountLifecycle-B5a9SCM7.js +1 -0
  38. package/dist/esm/sdk/{adapters-C-g_hkkZ.js → adapters-B2k8y0MB.js} +1 -1
  39. package/dist/{public/sdk/appearance-token-vars-01eH9pgA.js → esm/sdk/appearance-token-vars-DkF3EBbF.js} +1 -1
  40. package/dist/esm/sdk/authorization-gVWwKwav.js +1 -0
  41. package/dist/esm/sdk/clientSessionPersistenceState-BxpITYM_.js +1 -0
  42. package/dist/esm/sdk/{collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js → collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js} +1 -1
  43. package/dist/esm/sdk/{commitQueue-CYruPlkm.js → commitQueue-C1wkey4q.js} +1 -1
  44. package/dist/esm/sdk/confirm-ui-Dx6c4-Rk.js +2 -0
  45. package/dist/{public/sdk/device-linking-DiCNt3iA.js → esm/sdk/device-linking-_o3_fgiG.js} +1 -1
  46. package/dist/esm/sdk/{deviceLinkApproval-x3WkiYrd.js → deviceLinkApproval-CObsEWBa.js} +1 -1
  47. package/dist/esm/sdk/{display-D0EPmU4w.js → display-CUWg48tD.js} +1 -1
  48. package/dist/{public/sdk/ecdsaCapabilityManifest-DAJEVjlP.js → esm/sdk/ecdsaCapabilityManifest--1Ztngfx.js} +1 -1
  49. package/dist/{public/sdk/ecdsaDerivationClientWasm-AYOJgTJm.js → esm/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js} +1 -1
  50. package/dist/esm/sdk/ecdsaDerivationExport-BUUUGc6o.js +1 -0
  51. package/dist/esm/sdk/{ecdsaWalletRecords-WLyq414E.js → ecdsaWalletRecords-CKaXfsVu.js} +1 -1
  52. package/dist/esm/sdk/ed25519OperationFingerprint-Dev4P6Og.js +1 -0
  53. package/dist/{public/sdk/emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js → esm/sdk/emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js} +1 -1
  54. package/dist/esm/sdk/{enrichDisplayModelWithAbi-O6Mw4i2E.js → enrichDisplayModelWithAbi-JeAcpa7r.js} +1 -1
  55. package/dist/esm/sdk/{evmCryptoWasm-BUPb4hBH.js → evmCryptoWasm-CeH6Qeaa.js} +1 -1
  56. package/dist/esm/sdk/{export-viewer-host-BSTfHhau.js → export-viewer-host-O0OV1Oou.js} +1 -1
  57. package/dist/esm/sdk/exportKeypairOperation-DkqY9Bpf.js +1 -0
  58. package/dist/esm/sdk/host-BeE2dIU4.js +1 -0
  59. package/dist/{public/sdk/icons-BlMXolHv.js → esm/sdk/icons-pSZJ5Xrm.js} +1 -1
  60. package/dist/esm/sdk/indexedDB-CA4tGqkr.js +1 -0
  61. package/dist/esm/sdk/{intentDigest-HvRsBQ1z.js → intentDigest-gM3r4SVX.js} +1 -1
  62. package/dist/esm/sdk/{lanes-BU-fGqY4.js → lanes-vBKm6yBJ.js} +1 -1
  63. package/dist/esm/sdk/{localOnly-Xs89Xajm.js → localOnly-U_MucUAe.js} +1 -1
  64. package/dist/{public/sdk/mountExportPrivateKeySurface-CsUEKeum.js → esm/sdk/mountExportPrivateKeySurface-C2-fnvP6.js} +1 -1
  65. package/dist/{public/sdk/mountRecoveryCodeBackupSurface-kFLo5zLk.js → esm/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js} +1 -1
  66. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-CnbgQfZc.js +1 -0
  67. package/dist/esm/sdk/{nonceLaneKeys-BF_UpvIy.js → nonceLaneKeys-DtBpxubF.js} +1 -1
  68. package/dist/esm/sdk/{normalization-Df9fZWJC.js → normalization-DmfGvZ_3.js} +1 -1
  69. package/dist/esm/sdk/ownerNearOperation-DjNDxW3_.js +1 -0
  70. package/dist/{public/sdk/pendingWalletRecoveryCodeBackup-B-R_U34I.js → esm/sdk/pendingWalletRecoveryCodeBackup-DXFrQmO5.js} +1 -1
  71. package/dist/esm/sdk/{presignaturePool-BbvqRWYw.js → presignaturePool-Dq4RhzXn.js} +1 -1
  72. package/dist/{public/sdk/recovery-entrypoint-DJbMDC_m.js → esm/sdk/recovery-entrypoint-s9OoKBcl.js} +1 -1
  73. package/dist/esm/sdk/registration-CTtTocyo.js +1 -0
  74. package/dist/esm/sdk/{registration-C2fb9kRQ.js → registration-D3p7muCc.js} +1 -1
  75. package/dist/esm/sdk/{registrationAccounts-4r74gX1l.js → registrationAccounts-Bso0ntMs.js} +1 -1
  76. package/dist/esm/sdk/{registrationIntent-Do1tD1V7.js → registrationIntent-C1-Kyx_-.js} +1 -1
  77. package/dist/{public/sdk/registrationSignerPlan-DK2b3N_p.js → esm/sdk/registrationSignerPlan-CeMidFme.js} +1 -1
  78. package/dist/{public/sdk/requireStepUpAuth-COqCGb1i.js → esm/sdk/requireStepUpAuth-iVo6h_U-.js} +1 -1
  79. package/dist/esm/sdk/resealedEnvelopeResult-DXDo-72P.js +1 -0
  80. package/dist/{public/sdk/routerAbNormalSigning-D-UZmCBS.js → esm/sdk/routerAbNormalSigning-DVFFkNhJ.js} +1 -1
  81. package/dist/esm/sdk/runtime-auth-Dsmw_dUA.js +1 -0
  82. package/dist/esm/sdk/runtime-device-link-qmYvGep9.js +1 -0
  83. package/dist/esm/sdk/runtime-ecdsa-tempo-Zh95TuLV.js +1 -0
  84. package/dist/esm/sdk/runtime-email-otp-CnLuW4H1.js +1 -0
  85. package/dist/esm/sdk/runtime-export-m8lvrXtw.js +1 -0
  86. package/dist/esm/sdk/runtime-near-BiXzXXhH.js +1 -0
  87. package/dist/esm/sdk/runtime-preferences-DlKHDIjb.js +1 -0
  88. package/dist/esm/sdk/runtime-recovery-C6lS71Jp.js +1 -0
  89. package/dist/esm/sdk/{runtime-recovery-codes-si1fGktB.js → runtime-recovery-codes-B033ake_.js} +1 -1
  90. package/dist/esm/sdk/runtimeContext-RNS2E5wy.js +7 -0
  91. package/dist/{public/sdk/secp256k1-CE7-q9Sn.js → esm/sdk/secp256k1-DPeaOjM0.js} +1 -1
  92. package/dist/esm/sdk/signEvmFamily-Cksw3RpU.js +1 -0
  93. package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js → signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js} +1 -1
  94. package/dist/esm/sdk/{signEvmWithUiConfirm-CGrLtMV6.js → signEvmWithUiConfirm-B14zYdwE.js} +1 -1
  95. package/dist/esm/sdk/signNear-D0rFEYP1.js +1 -0
  96. package/dist/esm/sdk/{signatureUses-kSrUHSSH.js → signatureUses-BLOoPRsb.js} +1 -1
  97. package/dist/{public/sdk/signingFlow-BcetvUeS.js → esm/sdk/signingFlow-Bd1X0e-1.js} +2 -2
  98. package/dist/{public/sdk/signingQueue-dMFOFOP5.js → esm/sdk/signingQueue-DoUBeaCv.js} +1 -1
  99. package/dist/esm/sdk/{thresholdEcdsa-CqR1fFA-.js → thresholdEcdsa-BxfOZmiR.js} +1 -1
  100. package/dist/esm/sdk/{trace--mRP2OQc.js → trace-BnhLKxcu.js} +1 -1
  101. package/dist/esm/sdk/{transaction-activity-DCzHGg3b.js → transaction-activity-BXSxMp1E.js} +1 -1
  102. package/dist/{public/sdk/transactionState-29T9xfvL.js → esm/sdk/transactionState-G_FPe-U8.js} +1 -1
  103. package/dist/esm/sdk/{types-f7dyj5N6.js → types-A-w1cYlJ.js} +1 -1
  104. package/dist/esm/sdk/{unlockedEd25519ExportRootCapability-yzxQjIFd.js → unlockedEd25519ExportRootCapability-5F1egCSv.js} +1 -1
  105. package/dist/esm/sdk/voiceid-host.js +1 -1
  106. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  107. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  108. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  109. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  110. package/dist/esm/sdk/{wallet-recovery-BZB2Vu3X.js → wallet-recovery-DXdm68_Q.js} +1 -1
  111. package/dist/{public/sdk/walletAuthMethodRecord-DLBB5fez.js → esm/sdk/walletAuthMethodRecord-BW-XV4fv.js} +1 -1
  112. package/dist/{public/sdk/walletAuthority-BTGAuOi8.js → esm/sdk/walletAuthority-DbGaSw7D.js} +1 -1
  113. package/dist/esm/sdk/{walletCapabilityBindings-D5YYB7nN.js → walletCapabilityBindings-mPx-6_r-.js} +1 -1
  114. package/dist/{public/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js → esm/sdk/walletCustodyEcdsaContinuity-BnyL1Ryu.js} +1 -1
  115. package/dist/{public/sdk/walletOwnershipGeneration-CgjCtPrV.js → esm/sdk/walletOwnershipGeneration-BZc6UKqX.js} +1 -1
  116. package/dist/esm/sdk/walletRecoveryAdminProof-DdwikrW3.js +1 -0
  117. package/dist/esm/sdk/walletRecoveryCommit-DbAoiJp5.js +1 -0
  118. package/dist/esm/sdk/{walletSessionAuthorizationStore-B9Vwkshr.js → walletSessionAuthorizationStore-BivTUoKY.js} +1 -1
  119. package/dist/esm/sdk/{webauthnP256-BsQQPurm.js → webauthnP256-BGHikiNl.js} +1 -1
  120. package/dist/esm/shared-ts/src/auth/externalAuth.js +2 -2
  121. package/dist/esm/shared-ts/src/utils/index.js +2 -2
  122. package/dist/esm/voiceid-host.js +1 -1
  123. package/dist/public/headers.manifest.json +1 -1
  124. package/dist/public/sdk/{ConfirmationDrawer-MJoE0AAo.js → ConfirmationDrawer-BRnd5SEf.js} +1 -1
  125. package/dist/public/sdk/NonceCoordinator-CNXYrOoy.js +1 -0
  126. package/dist/{esm/sdk/SeamsWordmark-DwvPx2UA.js → public/sdk/SeamsWordmark-CeEi2RlU.js} +1 -1
  127. package/dist/public/sdk/accountLifecycle-B5a9SCM7.js +1 -0
  128. package/dist/public/sdk/{adapters-C-g_hkkZ.js → adapters-B2k8y0MB.js} +1 -1
  129. package/dist/{esm/sdk/appearance-token-vars-01eH9pgA.js → public/sdk/appearance-token-vars-DkF3EBbF.js} +1 -1
  130. package/dist/public/sdk/authorization-gVWwKwav.js +1 -0
  131. package/dist/public/sdk/clientSessionPersistenceState-BxpITYM_.js +1 -0
  132. package/dist/public/sdk/{collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js → collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js} +1 -1
  133. package/dist/public/sdk/{commitQueue-CYruPlkm.js → commitQueue-C1wkey4q.js} +1 -1
  134. package/dist/public/sdk/confirm-ui-Dx6c4-Rk.js +2 -0
  135. package/dist/{esm/sdk/device-linking-DiCNt3iA.js → public/sdk/device-linking-_o3_fgiG.js} +1 -1
  136. package/dist/public/sdk/{deviceLinkApproval-x3WkiYrd.js → deviceLinkApproval-CObsEWBa.js} +1 -1
  137. package/dist/public/sdk/{display-D0EPmU4w.js → display-CUWg48tD.js} +1 -1
  138. package/dist/{esm/sdk/ecdsaCapabilityManifest-DAJEVjlP.js → public/sdk/ecdsaCapabilityManifest--1Ztngfx.js} +1 -1
  139. package/dist/{esm/sdk/ecdsaDerivationClientWasm-AYOJgTJm.js → public/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js} +1 -1
  140. package/dist/public/sdk/ecdsaDerivationExport-BUUUGc6o.js +1 -0
  141. package/dist/public/sdk/{ecdsaWalletRecords-WLyq414E.js → ecdsaWalletRecords-CKaXfsVu.js} +1 -1
  142. package/dist/public/sdk/ed25519OperationFingerprint-Dev4P6Og.js +1 -0
  143. package/dist/{esm/sdk/emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js → public/sdk/emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js} +1 -1
  144. package/dist/public/sdk/{enrichDisplayModelWithAbi-O6Mw4i2E.js → enrichDisplayModelWithAbi-JeAcpa7r.js} +1 -1
  145. package/dist/public/sdk/{evmCryptoWasm-BUPb4hBH.js → evmCryptoWasm-CeH6Qeaa.js} +1 -1
  146. package/dist/public/sdk/{export-viewer-host-BSTfHhau.js → export-viewer-host-O0OV1Oou.js} +1 -1
  147. package/dist/public/sdk/exportKeypairOperation-DkqY9Bpf.js +1 -0
  148. package/dist/public/sdk/host-BeE2dIU4.js +1 -0
  149. package/dist/{esm/sdk/icons-BlMXolHv.js → public/sdk/icons-pSZJ5Xrm.js} +1 -1
  150. package/dist/public/sdk/indexedDB-CA4tGqkr.js +1 -0
  151. package/dist/public/sdk/{intentDigest-HvRsBQ1z.js → intentDigest-gM3r4SVX.js} +1 -1
  152. package/dist/public/sdk/{lanes-BU-fGqY4.js → lanes-vBKm6yBJ.js} +1 -1
  153. package/dist/public/sdk/{localOnly-Xs89Xajm.js → localOnly-U_MucUAe.js} +1 -1
  154. package/dist/{esm/sdk/mountExportPrivateKeySurface-CsUEKeum.js → public/sdk/mountExportPrivateKeySurface-C2-fnvP6.js} +1 -1
  155. package/dist/{esm/sdk/mountRecoveryCodeBackupSurface-kFLo5zLk.js → public/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js} +1 -1
  156. package/dist/public/sdk/nearEd25519YaoSigningPreparation-CnbgQfZc.js +1 -0
  157. package/dist/public/sdk/{nonceLaneKeys-BF_UpvIy.js → nonceLaneKeys-DtBpxubF.js} +1 -1
  158. package/dist/public/sdk/{normalization-Df9fZWJC.js → normalization-DmfGvZ_3.js} +1 -1
  159. package/dist/public/sdk/ownerNearOperation-DjNDxW3_.js +1 -0
  160. package/dist/{esm/sdk/pendingWalletRecoveryCodeBackup-B-R_U34I.js → public/sdk/pendingWalletRecoveryCodeBackup-DXFrQmO5.js} +1 -1
  161. package/dist/public/sdk/{presignaturePool-BbvqRWYw.js → presignaturePool-Dq4RhzXn.js} +1 -1
  162. package/dist/{esm/sdk/recovery-entrypoint-DJbMDC_m.js → public/sdk/recovery-entrypoint-s9OoKBcl.js} +1 -1
  163. package/dist/public/sdk/registration-CTtTocyo.js +1 -0
  164. package/dist/public/sdk/{registration-C2fb9kRQ.js → registration-D3p7muCc.js} +1 -1
  165. package/dist/public/sdk/{registrationAccounts-4r74gX1l.js → registrationAccounts-Bso0ntMs.js} +1 -1
  166. package/dist/public/sdk/{registrationIntent-Do1tD1V7.js → registrationIntent-C1-Kyx_-.js} +1 -1
  167. package/dist/{esm/sdk/registrationSignerPlan-DK2b3N_p.js → public/sdk/registrationSignerPlan-CeMidFme.js} +1 -1
  168. package/dist/{esm/sdk/requireStepUpAuth-COqCGb1i.js → public/sdk/requireStepUpAuth-iVo6h_U-.js} +1 -1
  169. package/dist/public/sdk/resealedEnvelopeResult-DXDo-72P.js +1 -0
  170. package/dist/{esm/sdk/routerAbNormalSigning-D-UZmCBS.js → public/sdk/routerAbNormalSigning-DVFFkNhJ.js} +1 -1
  171. package/dist/public/sdk/runtime-auth-Dsmw_dUA.js +1 -0
  172. package/dist/public/sdk/runtime-device-link-qmYvGep9.js +1 -0
  173. package/dist/public/sdk/runtime-ecdsa-tempo-Zh95TuLV.js +1 -0
  174. package/dist/public/sdk/runtime-email-otp-CnLuW4H1.js +1 -0
  175. package/dist/public/sdk/runtime-export-m8lvrXtw.js +1 -0
  176. package/dist/public/sdk/runtime-near-BiXzXXhH.js +1 -0
  177. package/dist/public/sdk/runtime-preferences-DlKHDIjb.js +1 -0
  178. package/dist/public/sdk/runtime-recovery-C6lS71Jp.js +1 -0
  179. package/dist/public/sdk/{runtime-recovery-codes-si1fGktB.js → runtime-recovery-codes-B033ake_.js} +1 -1
  180. package/dist/public/sdk/runtimeContext-RNS2E5wy.js +7 -0
  181. package/dist/{esm/sdk/secp256k1-CE7-q9Sn.js → public/sdk/secp256k1-DPeaOjM0.js} +1 -1
  182. package/dist/public/sdk/signEvmFamily-Cksw3RpU.js +1 -0
  183. package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js → signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js} +1 -1
  184. package/dist/public/sdk/{signEvmWithUiConfirm-CGrLtMV6.js → signEvmWithUiConfirm-B14zYdwE.js} +1 -1
  185. package/dist/public/sdk/signNear-D0rFEYP1.js +1 -0
  186. package/dist/public/sdk/{signatureUses-kSrUHSSH.js → signatureUses-BLOoPRsb.js} +1 -1
  187. package/dist/{esm/sdk/signingFlow-BcetvUeS.js → public/sdk/signingFlow-Bd1X0e-1.js} +2 -2
  188. package/dist/{esm/sdk/signingQueue-dMFOFOP5.js → public/sdk/signingQueue-DoUBeaCv.js} +1 -1
  189. package/dist/public/sdk/{thresholdEcdsa-CqR1fFA-.js → thresholdEcdsa-BxfOZmiR.js} +1 -1
  190. package/dist/public/sdk/{trace--mRP2OQc.js → trace-BnhLKxcu.js} +1 -1
  191. package/dist/public/sdk/{transaction-activity-DCzHGg3b.js → transaction-activity-BXSxMp1E.js} +1 -1
  192. package/dist/{esm/sdk/transactionState-29T9xfvL.js → public/sdk/transactionState-G_FPe-U8.js} +1 -1
  193. package/dist/public/sdk/{types-f7dyj5N6.js → types-A-w1cYlJ.js} +1 -1
  194. package/dist/public/sdk/{unlockedEd25519ExportRootCapability-yzxQjIFd.js → unlockedEd25519ExportRootCapability-5F1egCSv.js} +1 -1
  195. package/dist/public/sdk/voiceid-host.js +1 -1
  196. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  197. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  198. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  199. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  200. package/dist/public/sdk/{wallet-recovery-BZB2Vu3X.js → wallet-recovery-DXdm68_Q.js} +1 -1
  201. package/dist/{esm/sdk/walletAuthMethodRecord-DLBB5fez.js → public/sdk/walletAuthMethodRecord-BW-XV4fv.js} +1 -1
  202. package/dist/{esm/sdk/walletAuthority-BTGAuOi8.js → public/sdk/walletAuthority-DbGaSw7D.js} +1 -1
  203. package/dist/public/sdk/{walletCapabilityBindings-D5YYB7nN.js → walletCapabilityBindings-mPx-6_r-.js} +1 -1
  204. package/dist/{esm/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js → public/sdk/walletCustodyEcdsaContinuity-BnyL1Ryu.js} +1 -1
  205. package/dist/{esm/sdk/walletOwnershipGeneration-CgjCtPrV.js → public/sdk/walletOwnershipGeneration-BZc6UKqX.js} +1 -1
  206. package/dist/public/sdk/walletRecoveryAdminProof-DdwikrW3.js +1 -0
  207. package/dist/public/sdk/walletRecoveryCommit-DbAoiJp5.js +1 -0
  208. package/dist/public/sdk/{walletSessionAuthorizationStore-B9Vwkshr.js → walletSessionAuthorizationStore-BivTUoKY.js} +1 -1
  209. package/dist/public/sdk/{webauthnP256-BsQQPurm.js → webauthnP256-BGHikiNl.js} +1 -1
  210. package/dist/public/wallet-assets.manifest.json +258 -258
  211. package/dist/public/wallet-service/index.html +4 -4
  212. package/dist/types/shared-ts/src/auth/externalAuth.d.ts +51 -8
  213. package/dist/types/shared-ts/src/authorization/index.d.ts +1 -1
  214. package/dist/types/shared-ts/src/authorization/walletOwnerOperation.d.ts +10 -0
  215. package/dist/types/shared-ts/src/utils/registrationEstablishedSession.d.ts +4 -0
  216. package/dist/types/shared-ts/src/utils/registrationIntent.d.ts +2 -0
  217. package/dist/types/shared-ts/src/utils/walletManagementProtocol.d.ts +1 -1
  218. package/dist/types/wallet/src/SeamsWeb/operations/registration/pendingRegistrationRecovery.d.ts +1 -0
  219. package/dist/types/wallet/src/SeamsWeb/operations/registration/registration.d.ts +1 -0
  220. package/dist/types/wallet/src/SeamsWeb/operations/registration/registrationPasskeyMaterial.d.ts +24 -0
  221. package/dist/types/wallet/src/SeamsWeb/publicApi/auth.d.ts +1 -1
  222. package/dist/types/wallet/src/SeamsWeb/publicApi/createPublicApi.d.ts +1 -0
  223. package/dist/types/wallet/src/SeamsWeb/publicApi/nearCommands.d.ts +2 -0
  224. package/dist/types/wallet/src/SeamsWeb/publicApi/ownerNearOperation.d.ts +58 -0
  225. package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +14 -6
  226. package/dist/types/wallet/src/SeamsWeb/signingSurface/BrowserSigningSurface.d.ts +57 -56
  227. package/dist/types/wallet/src/SeamsWeb/signingSurface/nearOwnerOperation.d.ts +16 -0
  228. package/dist/types/wallet/src/SeamsWeb/signingSurface/nearPasskeyOperationMaterial.d.ts +72 -0
  229. package/dist/types/wallet/src/SeamsWeb/signingSurface/types.d.ts +3 -0
  230. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/ownerNearOperation.d.ts +25 -0
  231. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +4 -1
  232. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/WalletHostRuntime.d.ts +5 -1
  233. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/createNearCommands.d.ts +2 -1
  234. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/createSessionCommands.d.ts +6 -2
  235. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/externalAuth.d.ts +10 -8
  236. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/externalOwnerApproval.d.ts +24 -0
  237. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ownerNearOperation.d.ts +12 -0
  238. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/requestRouter.d.ts +2 -2
  239. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/exactSessionState.d.ts +8 -0
  240. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +17 -7
  241. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/ownerNearOperation.d.ts +51 -0
  242. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/registrationSetup.d.ts +1 -0
  243. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/repositories.d.ts +4 -0
  244. package/dist/types/wallet/src/core/rpcClients/near/NearClient.d.ts +4 -0
  245. package/dist/types/wallet/src/core/rpcClients/relayer/walletRecoveryRotate.d.ts +2 -2
  246. package/dist/types/wallet/src/core/rpcClients/relayer/walletRegistration.d.ts +1 -0
  247. package/dist/types/wallet/src/core/signingEngine/session/passkey/ed25519YaoLocalMaterial.d.ts +21 -0
  248. package/dist/types/wallet/src/core/types/seams.d.ts +7 -0
  249. package/dist/types/wallet/src/index.d.ts +2 -0
  250. package/dist/types/wallet/src/react/boundWallet.d.ts +21 -1
  251. package/dist/types/wallet/src/react/hooks/useOwnerNearOperation.d.ts +4 -0
  252. package/dist/types/wallet/src/react/index.d.ts +3 -0
  253. package/package.json +1 -1
  254. package/dist/esm/sdk/NonceCoordinator-3YhmDTS5.js +0 -1
  255. package/dist/esm/sdk/accountLifecycle-6DHYWf0v.js +0 -1
  256. package/dist/esm/sdk/clientSessionPersistenceState-BCkJAYSz.js +0 -1
  257. package/dist/esm/sdk/confirm-ui-em0vkd2m.js +0 -2
  258. package/dist/esm/sdk/ecdsaDerivationExport-DJKOzDbS.js +0 -1
  259. package/dist/esm/sdk/exportKeypairOperation-CjST_NUK.js +0 -1
  260. package/dist/esm/sdk/host-C51z-AxP.js +0 -1
  261. package/dist/esm/sdk/indexedDB-C4SDsyOG.js +0 -1
  262. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +0 -1
  263. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +0 -1
  264. package/dist/esm/sdk/registration-Byl4l4yZ.js +0 -1
  265. package/dist/esm/sdk/resealedEnvelopeResult-CLW00Vbw.js +0 -1
  266. package/dist/esm/sdk/runtime-auth-ufbVur2p.js +0 -1
  267. package/dist/esm/sdk/runtime-device-link-CagI2Q62.js +0 -1
  268. package/dist/esm/sdk/runtime-ecdsa-tempo-Rctxr0yM.js +0 -1
  269. package/dist/esm/sdk/runtime-email-otp-BQtcG-LF.js +0 -1
  270. package/dist/esm/sdk/runtime-export-wTeEaqlk.js +0 -1
  271. package/dist/esm/sdk/runtime-near-59yU_3ud.js +0 -1
  272. package/dist/esm/sdk/runtime-preferences-B9qLHX8W.js +0 -1
  273. package/dist/esm/sdk/runtime-recovery-DNyzdMBj.js +0 -1
  274. package/dist/esm/sdk/runtimeContext-ByeM6Z4Z.js +0 -6
  275. package/dist/esm/sdk/sessionObservationRevision-ihBwjS3y.js +0 -1
  276. package/dist/esm/sdk/signEvmFamily-BY5jlZEG.js +0 -1
  277. package/dist/esm/sdk/signNear-DMpJFkwF.js +0 -1
  278. package/dist/esm/sdk/signer-worker-BNodGJKY.js +0 -1
  279. package/dist/esm/sdk/walletRecoveryAdminProof-B4Ic07jY.js +0 -1
  280. package/dist/esm/sdk/walletRecoveryCommit-Cc2LAkCS.js +0 -1
  281. package/dist/public/sdk/NonceCoordinator-3YhmDTS5.js +0 -1
  282. package/dist/public/sdk/accountLifecycle-6DHYWf0v.js +0 -1
  283. package/dist/public/sdk/clientSessionPersistenceState-BCkJAYSz.js +0 -1
  284. package/dist/public/sdk/confirm-ui-em0vkd2m.js +0 -2
  285. package/dist/public/sdk/ecdsaDerivationExport-DJKOzDbS.js +0 -1
  286. package/dist/public/sdk/exportKeypairOperation-CjST_NUK.js +0 -1
  287. package/dist/public/sdk/host-C51z-AxP.js +0 -1
  288. package/dist/public/sdk/indexedDB-C4SDsyOG.js +0 -1
  289. package/dist/public/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +0 -1
  290. package/dist/public/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +0 -1
  291. package/dist/public/sdk/registration-Byl4l4yZ.js +0 -1
  292. package/dist/public/sdk/resealedEnvelopeResult-CLW00Vbw.js +0 -1
  293. package/dist/public/sdk/runtime-auth-ufbVur2p.js +0 -1
  294. package/dist/public/sdk/runtime-device-link-CagI2Q62.js +0 -1
  295. package/dist/public/sdk/runtime-ecdsa-tempo-Rctxr0yM.js +0 -1
  296. package/dist/public/sdk/runtime-email-otp-BQtcG-LF.js +0 -1
  297. package/dist/public/sdk/runtime-export-wTeEaqlk.js +0 -1
  298. package/dist/public/sdk/runtime-near-59yU_3ud.js +0 -1
  299. package/dist/public/sdk/runtime-preferences-B9qLHX8W.js +0 -1
  300. package/dist/public/sdk/runtime-recovery-DNyzdMBj.js +0 -1
  301. package/dist/public/sdk/runtimeContext-ByeM6Z4Z.js +0 -6
  302. package/dist/public/sdk/sessionObservationRevision-ihBwjS3y.js +0 -1
  303. package/dist/public/sdk/signEvmFamily-BY5jlZEG.js +0 -1
  304. package/dist/public/sdk/signNear-DMpJFkwF.js +0 -1
  305. package/dist/public/sdk/signer-worker-BNodGJKY.js +0 -1
  306. package/dist/public/sdk/walletRecoveryAdminProof-B4Ic07jY.js +0 -1
  307. package/dist/public/sdk/walletRecoveryCommit-Cc2LAkCS.js +0 -1
  308. package/dist/types/shared-ts/src/authorization/walletCustodyOperation.d.ts +0 -10
  309. /package/dist/{public/sdk/accountIds-CW2BP-d9.js → esm/sdk/accountIds-DGWFzEnw.js} +0 -0
  310. /package/dist/{public/sdk/actions-DrtSTGus.js → esm/sdk/actions-7SvZZut1.js} +0 -0
  311. /package/dist/{public/sdk/authenticatorOptions-WCDKYRux.js → esm/sdk/authenticatorOptions-B4q62CLs.js} +0 -0
  312. /package/dist/{public/sdk/confirmTypes-BvVtQs-M.js → esm/sdk/confirmTypes-DmEPoxys.js} +0 -0
  313. /package/dist/{public/sdk/csp-stylesheet-DUSqfXvZ.js → esm/sdk/csp-stylesheet-5LU6VGKK.js} +0 -0
  314. /package/dist/{public/sdk/digestEncoding-CqNXPZY9.js → esm/sdk/digestEncoding-34kXJoJr.js} +0 -0
  315. /package/dist/{public/sdk/ecdsaChainTarget-Bm5X4k-V.js → esm/sdk/ecdsaChainTarget-BoRVQtjQ.js} +0 -0
  316. /package/dist/{public/sdk/executeWorkerOperation-C9FOCCR7.js → esm/sdk/executeWorkerOperation-CAYSt0NA.js} +0 -0
  317. /package/dist/{public/sdk/helpers-Dubwo5uK.js → esm/sdk/helpers-B7c1zc7h.js} +0 -0
  318. /package/dist/{public/sdk/jsonRpc-BVDv1wfm.js → esm/sdk/jsonRpc-DGzeiNSa.js} +0 -0
  319. /package/dist/{public/sdk/keccak-mS0Mejjx.js → esm/sdk/keccak-DGHI1G6t.js} +0 -0
  320. /package/dist/{public/sdk/keyMaterialEnvelope-Dm2ZEilb.js → esm/sdk/keyMaterialEnvelope-Czkks9Ki.js} +0 -0
  321. /package/dist/{public/sdk/presignatures-BCeq56DG.js → esm/sdk/presignatures-CkhuZ0YQ.js} +0 -0
  322. /package/dist/{public/sdk/profileAccountProjection-C5sNt-s2.js → esm/sdk/profileAccountProjection-dvLchPBo.js} +0 -0
  323. /package/dist/{public/sdk/registrationAuthMethodInput-BR1WVbK3.js → esm/sdk/registrationAuthMethodInput-C4o7yFBJ.js} +0 -0
  324. /package/dist/{public/sdk/sdkSentEvents-DjOlKtdW.js → esm/sdk/sdkSentEvents-BFwv3mBw.js} +0 -0
  325. /package/dist/{public/sdk/signerDomain-BAsLT3XN.js → esm/sdk/signerDomain-D-EUTlLK.js} +0 -0
  326. /package/dist/{public/sdk/signerSlot-D2RZnb27.js → esm/sdk/signerSlot-BlijMq8C.js} +0 -0
  327. /package/dist/{public/sdk/surface-measurement-reporter-DXsvq401.js → esm/sdk/surface-measurement-reporter-DJ_dQhBV.js} +0 -0
  328. /package/dist/{public/sdk/walletCustodyOperation-DimzAbCB.js → esm/sdk/walletOwnerOperation-CScYv2K6.js} +0 -0
  329. /package/dist/{public/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js → esm/sdk/walletSessionAuthorizationStatus-GhcGvDCX.js} +0 -0
  330. /package/dist/{esm/sdk/accountIds-CW2BP-d9.js → public/sdk/accountIds-DGWFzEnw.js} +0 -0
  331. /package/dist/{esm/sdk/actions-DrtSTGus.js → public/sdk/actions-7SvZZut1.js} +0 -0
  332. /package/dist/{esm/sdk/authenticatorOptions-WCDKYRux.js → public/sdk/authenticatorOptions-B4q62CLs.js} +0 -0
  333. /package/dist/{esm/sdk/confirmTypes-BvVtQs-M.js → public/sdk/confirmTypes-DmEPoxys.js} +0 -0
  334. /package/dist/{esm/sdk/csp-stylesheet-DUSqfXvZ.js → public/sdk/csp-stylesheet-5LU6VGKK.js} +0 -0
  335. /package/dist/{esm/sdk/digestEncoding-CqNXPZY9.js → public/sdk/digestEncoding-34kXJoJr.js} +0 -0
  336. /package/dist/{esm/sdk/ecdsaChainTarget-Bm5X4k-V.js → public/sdk/ecdsaChainTarget-BoRVQtjQ.js} +0 -0
  337. /package/dist/{esm/sdk/executeWorkerOperation-C9FOCCR7.js → public/sdk/executeWorkerOperation-CAYSt0NA.js} +0 -0
  338. /package/dist/{esm/sdk/helpers-Dubwo5uK.js → public/sdk/helpers-B7c1zc7h.js} +0 -0
  339. /package/dist/{esm/sdk/jsonRpc-BVDv1wfm.js → public/sdk/jsonRpc-DGzeiNSa.js} +0 -0
  340. /package/dist/{esm/sdk/keccak-mS0Mejjx.js → public/sdk/keccak-DGHI1G6t.js} +0 -0
  341. /package/dist/{esm/sdk/keyMaterialEnvelope-Dm2ZEilb.js → public/sdk/keyMaterialEnvelope-Czkks9Ki.js} +0 -0
  342. /package/dist/{esm/sdk/presignatures-BCeq56DG.js → public/sdk/presignatures-CkhuZ0YQ.js} +0 -0
  343. /package/dist/{esm/sdk/profileAccountProjection-C5sNt-s2.js → public/sdk/profileAccountProjection-dvLchPBo.js} +0 -0
  344. /package/dist/{esm/sdk/registrationAuthMethodInput-BR1WVbK3.js → public/sdk/registrationAuthMethodInput-C4o7yFBJ.js} +0 -0
  345. /package/dist/{esm/sdk/sdkSentEvents-DjOlKtdW.js → public/sdk/sdkSentEvents-BFwv3mBw.js} +0 -0
  346. /package/dist/{esm/sdk/signerDomain-BAsLT3XN.js → public/sdk/signerDomain-D-EUTlLK.js} +0 -0
  347. /package/dist/{esm/sdk/signerSlot-D2RZnb27.js → public/sdk/signerSlot-BlijMq8C.js} +0 -0
  348. /package/dist/{esm/sdk/surface-measurement-reporter-DXsvq401.js → public/sdk/surface-measurement-reporter-DJ_dQhBV.js} +0 -0
  349. /package/dist/{esm/sdk/walletCustodyOperation-DimzAbCB.js → public/sdk/walletOwnerOperation-CScYv2K6.js} +0 -0
  350. /package/dist/{esm/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js → public/sdk/walletSessionAuthorizationStatus-GhcGvDCX.js} +0 -0
@@ -1 +0,0 @@
1
- import{h as e,v as t}from"./digests-BIaE0DMd.js";import{t as n}from"./errors-BJBDbwHk.js";import{o as r,t as i}from"./accountIds-CW2BP-d9.js";import{r as a}from"./types-f7dyj5N6.js";import{_ as o,a as s,b as c,d as l,f as u,g as d,h as f,i as p,m,n as ee,o as h,r as g,t as _,u as v,v as y,x as b,y as x}from"./nonceLaneKeys-BF_UpvIy.js";function te(e,t){let n=S(e,t);if(n.ok)return n.state;throw k(n.current,n.transition)}function S(e,t){switch(t){case`release`:return ne(e);case`expire`:return re(e);case`mark_signed`:return ie(e);case`broadcast_accepted`:return ae(e);case`broadcast_rejected`:return oe(e);case`finalize`:return se(e);case`drop`:return ce(e);case`replace`:return C(e);case`reconcile`:return w(e);default:return D(t)}}function ne(e){switch(e){case b.Released:return T(e);case b.Reserved:return T(b.Released);default:return E(e,`release`)}}function re(e){switch(e){case b.Reserved:return T(b.Expired);case b.Signed:return T(b.SignedLeaseExpired);case b.Expired:case b.SignedLeaseExpired:return T(e);default:return E(e,`expire`)}}function ie(e){switch(e){case b.Reserved:case b.Signed:return T(b.Signed);default:return E(e,`mark_signed`)}}function ae(e){switch(e){case b.Signed:case b.BroadcastAccepted:return T(b.BroadcastAccepted);default:return E(e,`broadcast_accepted`)}}function oe(e){switch(e){case b.Signed:case b.BroadcastRejected:return T(b.BroadcastRejected);default:return E(e,`broadcast_rejected`)}}function se(e){switch(e){case b.BroadcastAccepted:case b.Finalized:return T(b.Finalized);default:return E(e,`finalize`)}}function ce(e){switch(e){case b.BroadcastAccepted:case b.Dropped:return T(b.Dropped);default:return E(e,`drop`)}}function C(e){switch(e){case b.BroadcastAccepted:case b.Replaced:return T(b.Replaced);default:return E(e,`replace`)}}function w(e){switch(e){case b.Released:case b.Expired:case b.SignedLeaseExpired:case b.BroadcastRejected:case b.Dropped:case b.Replaced:case b.Reconciled:return T(b.Reconciled);default:return E(e,`reconcile`)}}function T(e){return{ok:!0,state:e}}function E(e,t){return{ok:!1,current:e,transition:t,reason:`illegal_transition`}}function D(e){throw Error(`[NonceCoordinator] unhandled nonce lease transition: ${String(e)}`)}function O(e){return e===b.Reserved||e===b.Signed}function le(e){return e===b.Reserved||e===b.Signed||e===b.BroadcastAccepted}function ue(e){return e===b.Reserved||e===b.Signed||e===b.BroadcastAccepted}function de(e,t){return e.state===c.BroadcastAccepted?!0:(e.state===c.Reserved||e.state===c.Signed)&&e.expiresAtMs>t}function k(e,t){return Error(`[NonceCoordinator] illegal nonce lease transition: ${e} -> ${t}`)}function A(e,t){let n=String(e||``).trim();if(!n)throw Error(`[NonceCoordinator] ${t} is required`);return n}function j(e,t){try{if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e))return BigInt(e);let t=String(e||``).trim();if(/^\d+$/.test(t))return BigInt(t)}catch{}throw Error(`[NonceCoordinator] invalid ${t}`)}function M(e,t){let n=Math.floor(Number(e));return Number.isFinite(n)&&n>0?n:t}function N(e,t){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``)||t}function P(...e){return e.length===0?0n:e.reduce((e,t)=>e>t?e:t)}function F(e,t){return e<t?e:t}function fe(){return{chainNonce:null,nextCandidate:null,inFlight:new Map,lastRefreshMs:null,inflightRefresh:null}}function pe(e,t){let n=e.get(t);if(n)return n;let r=fe();return e.set(t,r),r}function me(e){let t=String(e.lane.subjectId||``).trim();if(!t)return;let n=e.accountLaneKeys.get(t);if(!n){e.accountLaneKeys.set(t,new Set([e.laneKey]));return}n.add(e.laneKey)}async function he(e){let{state:t}=e;if(t.inflightRefresh)return await t.inflightRefresh;let n=(async()=>{let n=await e.fetchChainNonce(e.lane),r=n>=0n?n:0n,i=await e.readActiveLeaseNonces({chainNextNonce:r,lane:e.lane}),a=0n;for(let e of i){let t=BigInt(e);t>a&&(a=t)}let o=0n,s=new Map;for(let[e,n]of t.inFlight.entries())n.nonce<r||(s.set(e,n),n.nonce>o&&(o=n.nonce));return t.inFlight=s,t.nextCandidate=P(0n,r,(i.size>0||s.size>0)&&t.nextCandidate||0n,a>0n?a+1n:0n,o>0n?o+1n:0n),t.chainNonce=r,t.lastRefreshMs=e.nowMs,r})();t.inflightRefresh=n;try{return await n}finally{t.inflightRefresh===n&&(t.inflightRefresh=null)}}async function ge(e){return e.state.nextCandidate==null||e.state.lastRefreshMs==null||e.state.inFlight.size>0?!0:(await e.readActiveLeaseNonces({lane:e.lane})).size>0?!1:e.nowMs-e.state.lastRefreshMs>=e.refreshTtlMs}async function _e(e){if(await e.removeCoordinationLease(e.lease),!e.state)return;let t=e.lease.nonce;e.state.inFlight.delete(t.toString()),!((await e.readActiveLeaseNonces({excludeLeaseId:e.lease.leaseId,lane:e.lease.lane})).size>0)&&e.state.inFlight.size===0&&(e.state.lastRefreshMs=null)}async function ve(e){let t=e.lease.nonce,n=ye(e.txHash);e.state.inFlight.set(t.toString(),{nonce:t,txHash:n,status:`accepted`,acceptedAtMs:e.nowMs,updatedAtMs:e.nowMs});let r=t+1n;(e.state.nextCandidate==null||e.state.nextCandidate<r)&&(e.state.nextCandidate=r),await e.persistCoordinationLease(e.lease,{state:c.BroadcastAccepted,txHash:n},e.nowMs+e.staleInFlightThresholdMs)}function ye(e){let t=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(t))throw Error(`[NonceCoordinator] EVM broadcast acceptance requires txHash`);return t}async function be(e){let t=e.lease.nonce;e.state.inFlight.delete(t.toString());let n=t+1n;e.state.chainNonce=e.state.chainNonce==null?n:P(e.state.chainNonce,n),(e.state.nextCandidate==null||e.state.nextCandidate<n)&&(e.state.nextCandidate=n),e.state.lastRefreshMs=e.nowMs,await e.removeCoordinationLease(e.lease)}async function xe(e){let t=e.lease.nonce;if(e.outcome.reason===m.Dropped)e.state.inFlight.delete(t.toString()),(e.state.chainNonce==null||e.state.chainNonce<=t)&&(e.state.nextCandidate=e.state.nextCandidate==null?t:F(e.state.nextCandidate,t));else{let n=e.state.inFlight.get(t.toString());e.state.inFlight.set(t.toString(),{nonce:t,...e.outcome.txHash?{txHash:e.outcome.txHash}:n?.txHash?{txHash:n.txHash}:{},status:`replaced`,acceptedAtMs:n?.acceptedAtMs??e.nowMs,updatedAtMs:e.nowMs})}e.state.lastRefreshMs=null,await e.removeCoordinationLease(e.lease)}async function Se(e){let t=await e.refreshFromChain(e.lane,e.state),n=Array.from(e.state.inFlight.values()).map(e=>e.nonce).sort((e,t)=>e<t?-1:e>t?1:0),r=Ce({state:e.state,nowMs:e.nowMs,staleInFlightThresholdMs:e.staleInFlightThresholdMs});return{chainNextNonce:t,unresolvedInFlightNonces:n,blocked:!!r,...r?{blockedNonce:r.blockedNonce}:{}}}function Ce(e){let{state:t}=e;if(t.inFlight.size===0||t.chainNonce==null)return null;let n=null,r=null;for(let e of t.inFlight.values())(n==null||e.nonce<n)&&(n=e.nonce,r=e.updatedAtMs);if(n==null||r==null||t.chainNonce>n)return null;let i=Math.max(0,e.nowMs-r);return i<e.staleInFlightThresholdMs?null:{blockedNonce:n,ageMs:i}}function we(e){let t=Error(`[NonceCoordinator] nonce lane blocked on ${l(e.lane)} (nonce=${e.blockedNonce.toString()}) for ${e.ageMs}ms; reconcile or replace/dropped report required`);return t.code=`nonce_lane_blocked`,t.retryable=!0,t.details={chain:e.lane.chainTarget.kind,networkKey:l(e.lane),chainId:e.lane.chainTarget.chainId,blockedNonce:e.blockedNonce.toString(),ageMs:e.ageMs},t}function I(e){let t=String(e?.nextNonce??e?.accessKeyInfo?.nonce??`0`).trim();if(!t)return 0n;try{return BigInt(t)}catch{return 0n}}function Te(e){let t={walletId:String(e.walletId||``).trim(),nearAccountId:String(e.nearAccountId||``).trim(),nearPublicKeyStr:String(e.nearPublicKeyStr||``).trim()};if(!e.accessKeyAvailable&&r(t.nearAccountId))return{kind:`implicit_unfunded`,...t};let n={...t,nonce:I(e.transactionContext),accessKeyNonce:String(e.transactionContext?.accessKeyInfo?.nonce??``).trim(),nextNonce:String(e.transactionContext?.nextNonce??``).trim(),txBlockHeight:String(e.transactionContext?.txBlockHeight??``).trim(),txBlockHash:String(e.transactionContext?.txBlockHash??``).trim()};return r(t.nearAccountId)?{kind:`access_key_available`,...n}:{kind:`sponsored_named_ready`,...n}}function L(e){switch(e.lifecycle.kind){case`uninitialized`:return null;case`access_key_bound`:case`access_key_lookup_pending`:case`implicit_unfunded`:case`lookup_failed`:return e.lifecycle.subject;default:return Ne(e.lifecycle)}}function R(e){let t=L(e);if(!t)throw Error(`[NonceCoordinator] NEAR access key is not initialized`);return t}function z(e){return V(e.lifecycle)?.transactionContext??null}function B(e){return z(e)!==null}function Ee(e){return Ae(e)!==null}function De(e){return L(e)?.nearAccountId??null}function Oe(e){return L(e)?.publicKey??null}function V(e){switch(e.kind){case`uninitialized`:case`implicit_unfunded`:case`lookup_failed`:return null;case`access_key_bound`:return e.context.kind===`ready`?e.context:null;case`access_key_lookup_pending`:return e.previousContext.kind===`ready`?e.previousContext:null;default:return Ne(e)}}function ke(e){return V(e)??{kind:`missing`}}function Ae(e){switch(e.lifecycle.kind){case`access_key_lookup_pending`:return e.lifecycle.promise;case`uninitialized`:case`access_key_bound`:case`implicit_unfunded`:case`lookup_failed`:return null;default:return Ne(e.lifecycle)}}function H(e){let t=V(e.state.lifecycle);e.state.lifecycle={kind:`access_key_bound`,subject:e.subject,context:{kind:`ready`,transactionContext:e.transactionContext,lastNonceUpdateMs:e.updateNonce?e.nowMs:t?.lastNonceUpdateMs??e.nowMs,lastBlockHeightUpdateMs:e.updateBlock?e.nowMs:t?.lastBlockHeightUpdateMs??e.nowMs}}}function je(e){e.state.lifecycle={kind:`access_key_lookup_pending`,subject:e.subject,previousContext:ke(e.state.lifecycle),promise:e.promise}}function Me(e){e.state.lifecycle={kind:`implicit_unfunded`,subject:e.subject,readiness:{kind:`implicit_unfunded`,walletId:e.subject.walletId,nearAccountId:e.subject.nearAccountId,nearPublicKeyStr:e.subject.publicKey}}}function U(e){e.state.lifecycle={kind:`lookup_failed`,subject:e.subject,readiness:{kind:`account_lookup_failed`,walletId:e.subject.walletId,nearAccountId:e.subject.nearAccountId,nearPublicKeyStr:e.subject.publicKey,message:e.message}}}function Ne(e){throw Error(`[NonceCoordinator] unhandled NEAR nonce lane lifecycle: ${String(e)}`)}function Pe(){return{lifecycle:{kind:`uninitialized`},inflightId:0,refreshTimer:null,prefetchTimer:null,reservedNonces:new Set,lastReservedNonce:null,inFlight:new Map}}function W(e){e.refreshTimer&&=(clearTimeout(e.refreshTimer),null)}function Fe(e){e.prefetchTimer&&=(clearTimeout(e.prefetchTimer),null)}function G(e){let t=L(e);e.lifecycle=t?{kind:`access_key_bound`,subject:t,context:{kind:`missing`}}:{kind:`uninitialized`},e.reservedNonces.clear(),e.lastReservedNonce=null,e.inFlight.clear(),W(e),Fe(e)}function Ie(e){e.lifecycle={kind:`uninitialized`},G(e)}function Le(e){let t=A(e.nearAccountId,`nearAccountId`),n=A(e.publicKey,`publicKey`),r=A(e.walletId,`walletId`);if(!r)throw Error(`[NonceCoordinator] NEAR access key walletId is required`);let i={walletId:r,nearAccountId:t,publicKey:n},a=L(e.state);a?.walletId===r&&a.nearAccountId===t&&a.publicKey===n||(e.state.lifecycle={kind:`access_key_bound`,subject:i,context:{kind:`missing`}},G(e.state))}function Re(e){Le({state:e.state,walletId:e.walletId,nearAccountId:e.nearAccountId,publicKey:e.publicKey}),H({state:e.state,subject:R(e.state),transactionContext:e.transactionContext,nowMs:e.nowMs,updateNonce:!0,updateBlock:!0})}async function ze(e){let t=z(e.state);if(!t)throw Error(`NEAR transaction context not available - call fetchNearContext() first`);let n=Math.max(0,Math.floor(Number(e.countInput||0)));if(n<=0)return[];let r=v(e.lane),i=await e.readActiveLeaseNonces(r,{lane:e.lane}),a=0n;for(let e of i){let t=BigInt(e);t>a&&(a=t)}let o=P(e.state.lastReservedNonce?BigInt(e.state.lastReservedNonce)+1n:0n,BigInt(t.nextNonce),a>0n?a+1n:0n),s=[],c=o;for(let t=0;t<n;t+=1){for(;e.state.reservedNonces.has(c.toString())||i.has(c.toString());)c+=1n;let t=c.toString();s.push(t),c+=1n}for(let t of s)e.state.reservedNonces.add(t);return e.state.lastReservedNonce=s[s.length-1]||e.state.lastReservedNonce,s}function Be(e){let t=null;for(let n of e)try{let e=BigInt(n);(t===null||e>t)&&(t=e)}catch{}return t===null?null:t.toString()}function Ve(e,t){e.reservedNonces.delete(String(t))&&(e.lastReservedNonce=Be(e.reservedNonces))}async function He(e){let t=BigInt(e.lease.nonce);e.state.inFlight.set(t.toString(),{nonce:t,txHash:e.txHash,acceptedAtMs:e.nowMs,updatedAtMs:e.nowMs}),await e.persistCoordinationLease(e.lease,{state:c.BroadcastAccepted,txHash:e.txHash})}async function Ue(e){Le({state:e.state,walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,publicKey:e.lane.publicKey});let t=await e.nearClient.viewAccessKey(e.lane.nearAccountId,e.lane.publicKey);if(!q(t))throw Error(`Access key not found or invalid for account ${e.lane.nearAccountId}`);let n=J(t),r=BigInt(n.nonce),i=r+1n,a=[];for(let t of e.activeLeases){let n=BigInt(t.nonce),i=e.state.inFlight.get(n.toString());if(n>r){i&&a.push(n);continue}if(!i?.txHash)continue;let o=await K({nearClient:e.nearClient,txHash:i.txHash,accountId:e.lane.nearAccountId});if(o===`finalized`){e.transitionLease({lease:t,transition:`finalize`,reason:`near_tx_status_finalized`,txHash:i.txHash}),await e.removeCoordinationLease(t),e.state.inFlight.delete(n.toString()),Ve(e.state,n.toString());continue}if(o===`missing`){e.transitionLease({lease:t,transition:`drop`,reason:d.NonceAdvancedHashMissing,txHash:i.txHash}),await e.removeCoordinationLease(t),e.state.inFlight.delete(n.toString()),Ve(e.state,n.toString());continue}a.push(n)}let o=z(e.state),s=P(i,o?.nextNonce?BigInt(o.nextNonce):0n,e.state.lastReservedNonce?BigInt(e.state.lastReservedNonce)+1n:0n);if(H({state:e.state,subject:{walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,publicKey:e.lane.publicKey},transactionContext:{...o||{nearPublicKeyStr:e.lane.publicKey,txBlockHeight:`0`,txBlockHash:``},accessKeyInfo:n,nextNonce:s.toString()},nowMs:e.now(),updateNonce:!0,updateBlock:!1}),e.state.reservedNonces.size>0){let t=We(r,e.state.reservedNonces);e.state.reservedNonces=t.set,e.state.lastReservedNonce=t.lastReserved}return{chainNextNonce:i,unresolvedInFlightNonces:a.sort((e,t)=>e<t?-1:e>t?1:0),blocked:!1}}async function K(e){try{return await e.nearClient.txStatus(e.txHash,e.accountId),`finalized`}catch(e){let t=n(e);return/unknown transaction|does not exist|not found|not found in storage/i.test(t)?`missing`:`unknown`}}function We(e,t){let n=new Set,r=null;for(let i of t)try{let t=BigInt(i);if(t<=e)continue;n.add(i),(r===null||t>r)&&(r=t)}catch{}return{set:n,lastReserved:r===null?null:r.toString()}}function Ge(e){let t=String(e||``).toLowerCase();return t.includes(`does not exist while viewing`)||t.includes(`access key not found`)||t.includes(`unknown public key`)||t.includes(`unknown_account`)||t.includes(`unknown account`)||t.includes(`unknown_access_key`)||t.includes(`does not exist`)||t.includes(`doesn't exist`)}var Ke=class extends Error{code=`near_implicit_account_unfunded`;nearAccountId;readiness;constructor(e){super(`NEAR account ${e.nearAccountId} needs funding before direct NEAR signing.`),this.name=`NearImplicitAccountFundingRequiredError`,this.nearAccountId=e.nearAccountId,this.readiness=Te({walletId:e.walletId,nearAccountId:e.nearAccountId,nearPublicKeyStr:e.nearPublicKeyStr,accessKeyAvailable:!1})}},qe=class extends Error{code=`near_account_lookup_failed`;nearAccountId;readiness;constructor(e){super(e.message||`NEAR account ${e.nearAccountId} access key lookup failed.`),this.name=`NearAccountLookupFailedError`,this.nearAccountId=e.nearAccountId,this.readiness={kind:`account_lookup_failed`,walletId:e.walletId,nearAccountId:e.nearAccountId,nearPublicKeyStr:e.nearPublicKeyStr,message:this.message}}};async function Je(e){let{state:t}=e,i=Ae(t);if(i&&!e.force)return i;let a=R(t),o=++t.inflightId,s=(async()=>{try{let i=e.now(),s=V(t.lifecycle),c=s?.transactionContext??null,l=e.force||!s||i-s.lastNonceUpdateMs>=e.nonceFreshnessThresholdMs,u=e.force||!s||i-s.lastBlockHeightUpdateMs>=e.blockFreshnessThresholdMs,d=c?.accessKeyInfo,f=c?.txBlockHeight,p=c?.txBlockHash,m=l||!d,ee=u||!f||!p,h=d??null,g=null,_=null,v=null,y=[];if(m&&y.push((async()=>{try{h=await e.nearClient.viewAccessKey(a.nearAccountId,a.publicKey)}catch(e){let t=n(e);if(Ge(t)){if(r(a.nearAccountId)){_=new Ke({walletId:a.walletId,nearAccountId:a.nearAccountId,nearPublicKeyStr:a.publicKey});return}_=new qe({walletId:a.walletId,nearAccountId:a.nearAccountId,nearPublicKeyStr:a.publicKey,message:t});return}_=e}})()),ee&&y.push((async()=>{try{g=await e.nearClient.viewBlock({finality:`final`})}catch(e){v=e}})()),y.length>0&&await Promise.all(y),_)throw _ instanceof Ke?Me({state:t,subject:a}):_ instanceof qe&&U({state:t,subject:a,message:_.message}),_;if(v)throw v;if(m&&(d=q(h)?J(h):c?.accessKeyInfo||$e()),ee){if(!Y(g))throw Error(`[NonceCoordinator] failed to fetch NEAR block info`);f=String(g.header.height),p=g.header.hash}let b=P(d?.nonce===void 0?0n:BigInt(d.nonce)+1n,c?.nextNonce?BigInt(c.nextNonce):0n,t.lastReservedNonce?BigInt(t.lastReservedNonce)+1n:0n,1n),x={nearPublicKeyStr:a.publicKey,accessKeyInfo:d,nextNonce:b.toString(),txBlockHeight:f,txBlockHash:p};return et(L(t),a)&&o===t.inflightId&&H({state:t,subject:a,transactionContext:x,nowMs:e.now(),updateNonce:m,updateBlock:ee}),x}finally{if(o===t.inflightId){let e=L(t);t.lifecycle.kind===`access_key_lookup_pending`&&et(e,a)&&(t.lifecycle={kind:`access_key_bound`,subject:a,context:t.lifecycle.previousContext})}}})();return je({state:t,subject:a,promise:s}),s}async function Ye(e){let{state:t}=e,r=R(t);try{let n=await e.nearClient.viewAccessKey(r.nearAccountId,r.publicKey);if(!q(n))throw Error(`Access key not found or invalid for account ${r.nearAccountId}`);let i=J(n),a=BigInt(i.nonce),o=BigInt(e.actualNonce),s=z(t),c=P(a+1n,o+1n,s?.nextNonce?BigInt(s.nextNonce):0n,t.lastReservedNonce?BigInt(t.lastReservedNonce)+1n:0n);if(H({state:t,subject:r,transactionContext:s?{...s,accessKeyInfo:i,nextNonce:c.toString()}:{nearPublicKeyStr:r.publicKey,accessKeyInfo:i,nextNonce:c.toString(),txBlockHeight:`0`,txBlockHash:``},nowMs:e.now(),updateNonce:!0,updateBlock:!1}),t.inFlight.delete(e.actualNonce),Ve(t,e.actualNonce),t.reservedNonces.size>0){let e=We(a,t.reservedNonces);t.reservedNonces=e.set,t.lastReservedNonce=e.lastReserved}}catch(i){if(Ge(n(i))){let n=BigInt(e.actualNonce),i=z(t),a=P(n+1n,i?.nextNonce?BigInt(i.nextNonce):0n,t.lastReservedNonce?BigInt(t.lastReservedNonce)+1n:0n);H({state:t,subject:r,transactionContext:i?{...i,nextNonce:a.toString()}:{nearPublicKeyStr:r.publicKey,accessKeyInfo:$e(),txBlockHeight:`0`,txBlockHash:``,nextNonce:a.toString()},nowMs:e.now(),updateNonce:!0,updateBlock:!1})}}}async function Xe(e){let{state:t}=e,n=R(t),r=await e.nearClient.viewAccessKey(n.nearAccountId,n.publicKey);if(!q(r))throw Error(`Access key not found or invalid for account ${n.nearAccountId}`);let i=J(r),a=BigInt(i.nonce),o=P(a+1n,t.lastReservedNonce?BigInt(t.lastReservedNonce)+1n:0n,1n),s=z(t);if(H({state:t,subject:n,transactionContext:s?{...s,accessKeyInfo:i,nextNonce:o.toString()}:{nearPublicKeyStr:n.publicKey,accessKeyInfo:i,nextNonce:o.toString(),txBlockHeight:`0`,txBlockHash:``},nowMs:e.now(),updateNonce:!0,updateBlock:!1}),t.reservedNonces.size>0){let e=We(a,t.reservedNonces);t.reservedNonces=e.set,t.lastReservedNonce=e.lastReserved}}function Ze(e){let t=V(e.state.lifecycle);return!t||e.nowMs-t.lastBlockHeightUpdateMs>=e.blockFreshnessThresholdMs||!t}function q(t){if(!e(t))return!1;try{return j(t.nonce,`near access-key nonce`),!0}catch{return!1}}function J(e){let n=e;return{nonce:j(n.nonce,`near access-key nonce`),permission:Qe(n.permission),block_hash:t(n.block_hash)?n.block_hash:``,block_height:typeof n.block_height==`number`?n.block_height:0}}function Qe(n){if(n===`FullAccess`||!e(n))return`FullAccess`;let r=n.FunctionCall;if(!e(r))return`FullAccess`;let i=Array.isArray(r.method_names)?r.method_names.filter(t):[];return{FunctionCall:{allowance:t(r.allowance)?r.allowance:``,receiver_id:t(r.receiver_id)?r.receiver_id:``,method_names:i}}}function Y(e){let t=e;if(!t||typeof t!=`object`)return!1;let n=t.header;return!!n&&typeof n.hash==`string`&&n.height!==void 0}function $e(){return{nonce:0n,permission:`FullAccess`,block_height:0,block_hash:``}}function et(e,t){return e?.walletId===t.walletId&&e.nearAccountId===t.nearAccountId&&e.publicKey===t.publicKey}function tt(e){let t=e.lane,n=e.fallback||y.InRuntimeLock,r=t?l(t):String(e.networkKey||``).trim(),i=t?u(t):String(e.accountId||``).trim(),a=t?.family||e.laneFamily,o=[e.reason,a||``,r,i,n].join(`|`);if(e.observed.has(o))return null;let s={reason:e.reason,...a?{laneFamily:a}:{},...r?{networkKey:r}:{},...i?{accountId:i}:{},fallback:n};return e.observed.set(o,s),{...t?{lane:t}:{},degradation:s}}function nt(e){let t=[v(e.lane),e.reason].join(`|`),n=e.alerts.get(t),r=n&&e.nowMs-n.firstSeenAtMs<=e.windowMs?{count:n.count+1,firstSeenAtMs:n.firstSeenAtMs,lastSeenAtMs:e.nowMs}:{count:1,firstSeenAtMs:e.nowMs,lastSeenAtMs:e.nowMs};return e.alerts.set(t,r),r.count<e.threshold?null:{alert:{kind:`repeated_dropped_or_replaced`,severity:`warning`,lane:e.lane,reason:e.reason,count:r.count,windowMs:e.windowMs,firstSeenAtMs:r.firstSeenAtMs,lastSeenAtMs:r.lastSeenAtMs},warning:{chainTarget:e.lane.chainTarget,networkKey:l(e.lane),chainId:e.lane.chainTarget.chainId,sender:e.lane.sender,nonceKey:e.lane.nonceKey?.toString(),subjectId:e.lane.subjectId,reason:e.reason,count:r.count,windowMs:e.windowMs}}}function X(){let e={};for(let t of f)e[t]=0;return e}function rt(e,t){let n=(t.lease?.lane?u(t.lease.lane):``)||(t.lane?u(t.lane):``)||t.accountId,r=(t,r)=>{e.push({...n?{accountId:n}:{},kind:t,reason:r})};if(t.event===x.LeaseDropped){r(m.Dropped,m.Dropped);return}if(t.event===x.LeaseReplaced){r(m.Replaced,m.Replaced);return}if(t.event===x.LaneReconciled){r(`reconciled`,N(t.reason,`manual`));return}if(t.event===x.LeaseReleased){r(`released`,N(t.reason,`unspecified`));return}if(t.event===x.LeaseExpired){r(`expired`,N(t.reason,`lease_ttl_elapsed`));return}t.event===x.LeaseBroadcastRejected&&r(b.BroadcastRejected,b.BroadcastRejected)}function it(e,t){let n={droppedCount:0,replacedCount:0,reconciledCount:0,releasedCount:0,expiredCount:0,broadcastRejectedCount:0,releaseReasons:{},reconcileReasons:{},expiryReasons:{}};for(let r of e)if(!(t&&r.accountId!==t)){if(r.kind===m.Dropped){n.droppedCount+=1;continue}if(r.kind===m.Replaced){n.replacedCount+=1;continue}if(r.kind===`broadcast_rejected`){n.broadcastRejectedCount+=1;continue}if(r.kind===`reconciled`){n.reconciledCount+=1,n.reconcileReasons[r.reason]=(n.reconcileReasons[r.reason]||0)+1;continue}if(r.kind===`released`){n.releasedCount+=1,n.releaseReasons[r.reason]=(n.releaseReasons[r.reason]||0)+1;continue}r.kind===`expired`&&(n.expiredCount+=1,n.expiryReasons[r.reason]=(n.expiryReasons[r.reason]||0)+1)}return n}function at(e){let t=e.options?.accountId?String(e.options.accountId).trim():``,n=X(),r=new Map,i=new Set,a=0,o=0,s=0,c=0;for(let l of e.leases){if(t&&u(l.lane)!==t)continue;a+=1,n[l.state]+=1;let d=v(l.lane),f=Math.max(0,e.nowMs-l.reservedAtMs);o=Math.max(o,f),O(l.state)&&(s=Math.max(s,f),l.expiresAtMs<=e.nowMs&&(c+=1,i.add(d)));let p=r.get(d)||{lane:l.lane,leaseCount:0,states:{}};p.leaseCount+=1,p.states[l.state]=(p.states[l.state]||0)+1,r.set(d,p)}let d={atMs:e.nowMs,...t?{accountId:t}:{},leaseCount:a,laneCount:r.size,oldestLeaseAgeMs:o,oldestInFlightLeaseAgeMs:s,staleInFlightLeaseCount:c,staleInFlightLaneCount:i.size,reservedLeaseCount:n[b.Reserved],signedLeaseCount:n[b.Signed],broadcastAcceptedLeaseCount:n[b.BroadcastAccepted],droppedLeaseCount:n[b.Dropped],replacedLeaseCount:n[b.Replaced],reconciledLeaseCount:n[b.Reconciled],releasedLeaseCount:n[b.Released],outcomes:it(e.outcomeMetricEvents,t)},f=De(e.nearState),p=Oe(e.nearState);return{leaseCount:a,leasesByState:n,laneCount:r.size,metrics:d,coordinationWarnings:Array.from(e.observedCoordinationDegradations).filter(e=>!t||!e.accountId||e.accountId===t),lanes:Array.from(r.values()).map(e=>({family:e.lane.family,accountId:u(e.lane),networkKey:l(e.lane),...e.lane.family===`evm`?{chain:e.lane.chainTarget.kind,chainId:e.lane.chainTarget.chainId}:{},leaseCount:e.leaseCount,states:{...e.states}})),near:{...f?{activeAccountId:f}:{},...p?{activePublicKey:p}:{},hasContext:B(e.nearState),reservedNonceCount:e.nearState.reservedNonces.size,...e.nearState.lastReservedNonce?{lastReservedNonce:e.nearState.lastReservedNonce}:{}}}}function Z(e,t){let n=e.trim();if(!n)throw Error(`[NonceCoordinator][near] ${t} is required`);return n}function ot(e){let t=e?.find(e=>String(e.network||``).startsWith(`near-`));return String(t?.network||`near`)}function st(e){return{family:`near`,networkKey:ot(e.chains),walletId:Z(e.walletId,`walletId`),nearAccountId:i(e.nearAccountId),publicKey:Z(e.nearPublicKeyStr,`nearPublicKeyStr`)}}const ct=2e4;async function lt(e,t){try{let n=await e.viewAccessKey(t.nearAccountId,t.publicKey);if(q(n))return{kind:`observed`,nonce:BigInt(n.nonce)}}catch{}return{kind:`unavailable`}}function ut(t){let n=new Map,r=new Map,i=new Map,l=new Map,d=[],f=new Map,S=t.now||Date.now,ne=M(t.leaseTtlMs,12e4),re=M(t.signedLeaseTtlMs,3e4),ie=M(t.evmRefreshTtlMs,5e3),ae=M(t.evmStaleInFlightThresholdMs,45e3),oe=M(t.droppedReplacedAlertThreshold,3),se=M(t.droppedReplacedAlertWindowMs,3e5),ce=t.sameOriginLock===void 0?gt():t.sameOriginLock,C=t.nonceLaneCoordinationStore??null,w=t.nonceLaneCoordinationStore!==void 0,T=s(),E=new Map,D=e=>{rt(d,e);try{t.onTrace?.(e)}catch{}},O=(e,t)=>{let n=tt({observed:E,reason:e,...t});n&&(D({event:x.CoordinationDegraded,...n}),console.warn(`[NonceCoordinator] nonce coordination degraded`,n.degradation))},k=e=>({leaseId:A(e.leaseId,`leaseId`),operationId:a.signingOperation(e.operationId),operationFingerprint:a.signingOperationFingerprint(e.operationFingerprint)}),j=e=>{let t=A(e.leaseId,`leaseId`),r=n.get(t);if(!r)throw Error(`[NonceCoordinator] nonce lease not found`);return ee(r,e.operationId,e.operationFingerprint),r},N=e=>{let t=e.lease.state,n=te(t,e.transition);e.lease.state=n;let r=e.expiresAtMs;typeof r==`number`&&Number.isSafeInteger(r)&&(e.lease.expiresAtMs=r),D({event:e.event,lease:e.lease,previousState:t,nextState:n,...e.reason?{reason:e.reason}:{},...e.txHash?{txHash:e.txHash}:{}})},P=(e,t)=>{te(e.state,t)},F=e=>pe(r,e),fe=(e,t)=>{me({accountLaneKeys:i,lane:e,laneKey:t})},ye=async(e,t)=>{if(!C)return w&&O(o.IndexedDBUnavailable,{lane:t}),[];try{await C.pruneExpired(S())}catch{O(o.DurableStoreError,{lane:t})}try{return await C.readLane(e)}catch{return O(o.DurableStoreError,{lane:t}),[]}},I=async(e,t)=>{let r=new Set;for(let i of n.values()){if(t?.excludeLeaseId&&i.leaseId===t.excludeLeaseId||!Q(i)||v(i.lane)!==e||!le(i.state))continue;let n=i.nonce;t?.chainNextNonce!=null&&n<t.chainNextNonce||r.add(n.toString())}for(let n of await ye(e,t?.lane))n.record.family===`evm`&&(t?.excludeLeaseId&&n.record.leaseId===t.excludeLeaseId||de(n.record,S())&&(t?.chainNextNonce!=null&&n.nonce<t.chainNextNonce||r.add(n.nonce.toString())));return r},Te=async(e,t)=>{let r=new Set;for(let i of n.values()){if(t?.excludeLeaseId&&i.leaseId===t.excludeLeaseId||!$(i)||v(i.lane)!==e||!ue(i.state))continue;let n=BigInt(i.nonce);t?.chainNextNonce!=null&&n<t.chainNextNonce||r.add(n.toString())}for(let n of await ye(e,t?.lane))n.record.family===`near`&&(t?.excludeLeaseId&&n.record.leaseId===t.excludeLeaseId||de(n.record,S())&&(t?.chainNextNonce!=null&&n.nonce<t.chainNextNonce||r.add(n.nonce.toString())));return r},R=async(e,t,n=e.expiresAtMs)=>{let r=C;if(!r){w&&O(o.IndexedDBUnavailable,{lane:e.lane});return}Q(e)?await z(r,pt({lease:e,lifecycle:t,expiresAtMs:n,updatedAtMs:S(),runtimeId:T}),e.lane):$(e)?await z(r,mt({lease:e,lifecycle:t,expiresAtMs:n,updatedAtMs:S(),runtimeId:T}),e.lane):ft(e)},z=async(e,t,n)=>{try{await e.upsert(t)}catch{O(o.DurableStoreError,{lane:n})}},B=async e=>{if(C)try{await C.remove({laneKey:v(e.lane),leaseId:e.leaseId})}catch{O(o.DurableStoreError,{lane:e.lane})}},De=async(e,n)=>{let r=v(e);return await he({lane:e,state:n,nowMs:S(),fetchChainNonce:async e=>await t.evmNonceBackend.fetchChainNonce(h(e)),readActiveLeaseNonces:async e=>await I(r,e)})},V=async(e,t,n)=>await ge({state:t,lane:n,nowMs:S(),refreshTtlMs:ie,readActiveLeaseNonces:async t=>await I(e,t)}),ke=async e=>{await Z(e.lane);let t=v(e.lane),r=F(t);fe(e.lane,t),await V(t,r,e.lane)&&await De(e.lane,r);let i=Ce({state:r,nowMs:S(),staleInFlightThresholdMs:ae});if(i)throw we({lane:e.lane,blockedNonce:i.blockedNonce,ageMs:i.ageMs});let a=r.chainNonce??r.nextCandidate??0n,o=await I(t,{lane:e.lane});for(;o.has(a.toString())||r.inFlight.has(a.toString());)a+=1n;r.nextCandidate=a+1n;let s=S(),l={leaseId:p({operationId:e.operation.operationId,chain:e.lane.chainTarget.kind,nonce:a}),lane:e.lane,operationId:e.operation.operationId,operationFingerprint:e.operation.operationFingerprint,nonce:a,state:b.Reserved,reservedAtMs:s,expiresAtMs:s+ne};return n.set(l.leaseId,l),await R(l,{state:c.Reserved}),D({event:x.LeaseReserved,lease:l}),{...l}},Ae=async e=>{let t=v(e.lane);await _e({lease:e,state:r.get(t),removeCoordinationLease:B,readActiveLeaseNonces:async e=>await I(t,e)})},H=async(e,t)=>{await ve({lease:e,state:F(v(e.lane)),txHash:t,nowMs:S(),staleInFlightThresholdMs:ae,persistCoordinationLease:R})},je=async e=>{await be({lease:e,state:F(v(e.lane)),nowMs:S(),removeCoordinationLease:B})},Me=async(e,t)=>{await xe({lease:e,state:F(v(e.lane)),outcome:t,nowMs:S(),removeCoordinationLease:B})},U=async e=>{let t=v(e),n=F(t);return fe(e,t),await Se({lane:e,state:n,nowMs:S(),staleInFlightThresholdMs:ae,refreshFromChain:De})},Ne=e=>{let t=nt({alerts:l,lane:e.lane,reason:e.reason,nowMs:S(),threshold:oe,windowMs:se});t&&(D({event:x.LaneAlert,lane:e.lane,alert:t.alert}),console.warn(`[NonceCoordinator] repeated EVM-family dropped/replaced nonce outcomes`,t.warning))},W=Pe(),G=()=>{Ie(W)},Be=e=>{let n=e||t.nearClient;if(!n)throw Error(`[NonceCoordinator] NEAR client is not configured`);return n},K=e=>{Le({state:W,...e})},We=async(e,t)=>await ze({state:W,lane:e,countInput:t,readActiveLeaseNonces:Te}),Ge=e=>{Ve(W,e)},Ke=async(e,t=!1)=>await Je({state:W,nearClient:e,force:t,now:S,nonceFreshnessThresholdMs:5e3,blockFreshnessThresholdMs:ct}),qe=async e=>(K({walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,publicKey:e.lane.publicKey}),{...await Ke(Be(e.nearClient),e.force===!0)}),q=async(e,t)=>{await Ye({state:W,nearClient:e,actualNonce:t,now:S})},J=async e=>{await Xe({state:W,nearClient:e,now:S})},Qe=async e=>{let t=v(e);return await Ue({lane:e,state:W,nearClient:Be(),now:S,activeLeases:Array.from(n.values()).filter(e=>e.lane.family===`near`&&v(e.lane)===t&&e.state===b.BroadcastAccepted),removeCoordinationLease:B,transitionLease:({lease:e,transition:t,reason:n,txHash:r})=>{N({lease:e,transition:t,event:t===`finalize`?x.LeaseFinalized:x.LeaseDropped,reason:n,...r?{txHash:r}:{}})}})},Y=async e=>{if(Q(e)){await Ae(e);return}Ge(String(e.nonce)),await B(e)},$e=async e=>{await Y(e),e.lane.family===`evm`&&(await U(e.lane),D({event:x.LaneReconciled,lane:e.lane}))},et=async(e,t)=>{let n=f.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>void 0).then(()=>i);f.set(e,a),await n.catch(()=>void 0);try{return await t()}finally{r(),f.get(e)===a&&f.delete(e)}},X=async(t,n)=>{let r=v(t),i=async()=>await et(r,n),a=`nonce-coordinator:${r}`;if(ce)return await ce.withLock(a,i);if(C?.withLock){let n=null,r=async()=>{try{return await i()}catch(e){throw n=e,e}};try{return await C.withLock({lockKey:a,ownerId:T,ttlMs:5e3,waitTimeoutMs:3e3},r)}catch(r){throw n===r||O((e(r)?String(r.code||``):``)===o.DurableLockTimeout?o.DurableLockTimeout:o.DurableStoreError,{lane:t,fallback:y.None}),r}}return w&&O(o.WebLocksUnavailable,{lane:t}),await i()},it=async(e,t)=>{if(e.expiresAtMs>t||e.state!==b.Reserved&&e.state!==b.Signed)return null;let n=e.state;return e.state===b.Signed?await $e(e):await Y(e),N({lease:e,transition:`expire`,event:x.LeaseExpired,reason:n===b.Signed?`signed_lease_ttl_elapsed`:`lease_ttl_elapsed`}),{...e}},Z=async e=>{let t=S(),r=v(e),i=[];for(let e of Array.from(n.values())){if(v(e.lane)!==r)continue;let n=await it(e,t);n&&i.push(n)}return i},ot=async e=>{let t=e?.walletId?String(e.walletId).trim():``,r=new Map;for(let e of Array.from(n.values()))t&&u(e.lane)!==t||r.set(v(e.lane),e.lane);let i=[];for(let e of r.values())i.push(...await X(e,async()=>Z(e)));return i},st=async e=>{if(!C){w&&O(o.IndexedDBUnavailable);return}let n=[];try{n=await C.readAllForRecovery(e)}catch{O(o.DurableStoreError);return}let r=new Map;for(let e of n){if(!e.ok){e.leaseId&&await C.remove({laneKey:e.laneKey,leaseId:e.leaseId}),O(e.degradation.reason,{accountId:e.degradation.accountId,networkKey:e.degradation.networkKey,laneFamily:e.degradation.laneFamily,fallback:e.degradation.fallback});continue}let{record:n,lane:i,canonicalLaneKey:a,nonce:s}=e.parsed;await X(i,async()=>{if(n.laneKey!==a){await C.remove({laneKey:n.laneKey,leaseId:n.leaseId}),O(o.MalformedDurableRecord,{accountId:u(i),networkKey:n.networkKey,laneFamily:n.family,fallback:y.None});return}let e=n.expiresAtMs<=S();if(e&&n.state!==c.BroadcastAccepted){await C.remove({laneKey:n.laneKey,leaseId:n.leaseId}),n.family===`evm`&&await U(i).catch(()=>null),D({event:x.LaneReconciled,lane:i,reason:`startup_recovery_expired_lease`});return}if(n.family===`evm`){let r=i,a=F(n.laneKey),o=null;if(n.state===c.BroadcastAccepted){let e=dt(n.txHash);if(a.inFlight.set(n.nonce.toString(),{nonce:s,txHash:e,status:`accepted`,acceptedAtMs:n.reservedAtMs,updatedAtMs:n.updatedAtMs}),o=await t.evmNonceBackend.fetchBroadcastTransactionStatus({...h(r),txHash:e}).catch(()=>null),o?.kind===`finalized`){a.inFlight.delete(n.nonce.toString()),await C.remove({laneKey:n.laneKey,leaseId:n.leaseId}),await U(r).catch(()=>null),D({event:x.LaneReconciled,lane:r,reason:`startup_recovery_finalized_transaction`,txHash:n.txHash});return}}let l=await U(r).catch(()=>null),u=!!l&&l.chainNextNonce>s,d=n.state===c.BroadcastAccepted&&o?.kind===`missing`&&e;(u||d)&&(a.inFlight.delete(n.nonce.toString()),await C.remove({laneKey:n.laneKey,leaseId:n.leaseId})),D({event:x.LaneReconciled,lane:r,reason:d?`startup_recovery_dropped_transaction`:`startup_recovery`,...d&&n.state===c.BroadcastAccepted?{txHash:n.txHash}:{}});return}if(n.family===`near`&&t.nearClient)try{let e=r.get(a);e||(e=await lt(t.nearClient,n),r.set(a,e)),e.kind===`observed`&&e.nonce>=s&&await C.remove({laneKey:n.laneKey,leaseId:n.leaseId})}catch{}})}},ut=async e=>{await Z(e.lane);let t=Math.max(1,Math.floor(Number(e.count||1))),r=await We(e.lane,t);if(r.length!==t)throw Error(`[NonceCoordinator] NEAR nonce reservation returned an incomplete batch`);let i=S(),a=g({operationId:e.operation.operationId,chain:`near`,firstNonce:r[0],count:t}),o=r.map((t,n)=>({leaseId:p({operationId:e.operation.operationId,chain:`near`,nonce:t}),lane:e.lane,operationId:e.operation.operationId,operationFingerprint:e.operation.operationFingerprint,nonce:t,state:b.Reserved,reservedAtMs:i,expiresAtMs:i+ne,batchId:a,txIndex:n}));for(let e of o)n.set(e.leaseId,e),await R(e,{state:c.Reserved}),D({event:x.LeaseReserved,lease:e});return o.map(e=>({...e}))},ht=e=>{let t=e?.accountId?String(e.accountId).trim():``,r=at({options:e,leases:n.values(),nearState:W,observedCoordinationDegradations:E.values(),outcomeMetricEvents:d,nowMs:S()});return e?.emitMetrics&&D({event:x.Metrics,metrics:r.metrics,...t?{accountId:t}:{}}),r};return{async reserve(e){if(e.lane.family===`near`){let t=e.lane;return await X(t,async()=>(await ut({lane:t,operation:e.operation,count:1}))[0])}let t=e.lane;return await X(t,async()=>await ke({lane:t,operation:e.operation}))},async reserveBatch(e){return await X(e.lane,async()=>await ut(e))},async reserveNearContext(e){return await X(e.lane,async()=>{K({walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,publicKey:e.lane.publicKey});let t={...e.fetchContext?await e.fetchContext():await qe({lane:e.lane,nearClient:e.nearClient,force:e.force!==!1})};Re({state:W,walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,publicKey:e.lane.publicKey,transactionContext:t,nowMs:S()});let n=await ut({lane:e.lane,operation:e.operation,count:e.count});return n[0]&&(t.nextNonce=String(n[0].nonce)),{context:t,leases:n}})},initializeNearAccessKey:K,getActiveNearPublicKey(){return Oe(W)},async fetchNearContext(e){return await X(e.lane,async()=>qe(e))},async prefetchNearContext(e){if(e?.kind===`access_key_subject`&&K({walletId:e.walletId,nearAccountId:e.nearAccountId,publicKey:e.publicKey}),!L(W))return;Fe(W);let t=Be(e?.nearClient);W.prefetchTimer=setTimeout(()=>{W.prefetchTimer=null,!Ee(W)&&Ze({state:W,nowMs:S(),blockFreshnessThresholdMs:ct})&&Ke(t).catch(()=>void 0)},400)},clearNearAccessKey(){G();for(let[e,t]of n.entries())t.lane.family===`near`&&n.delete(e)},async markSigned(e){let t=k(e);return await X(j(t).lane,async()=>{let n=j(t),r=S()+re;N({lease:n,transition:`mark_signed`,event:x.LeaseSigned,expiresAtMs:r,...e.signedTxHash?{txHash:e.signedTxHash}:{}}),await R(n,{state:c.Signed},r)})},async markBroadcastAccepted(e){let t=k(e);return await X(j(t).lane,async()=>{let n=j(t);P(n,`broadcast_accepted`),Q(n)?await H(n,String(e.txHash)):$(n)?await He({lease:n,state:W,txHash:String(e.txHash),nowMs:S(),persistCoordinationLease:R}):ft(n),N({lease:n,transition:`broadcast_accepted`,event:x.LeaseBroadcastAccepted,txHash:String(e.txHash)})})},async markBroadcastRejected(e){let n=k(e);return await X(j(n).lane,async()=>{let r=j(n);if(P(r,`broadcast_rejected`),await Y(r),$(r)&&t.nearClient)try{await J(t.nearClient)}catch{}N({lease:r,transition:`broadcast_rejected`,event:x.LeaseBroadcastRejected,reason:e.error instanceof Error?e.error.message:String(e.error||``)})})},async markFinalized(e){let n=k(e);return await X(j(n).lane,async()=>{let r=j(n);P(r,`finalize`),Q(r)?await je(r):$(r)?(t.nearClient?await q(t.nearClient,String(r.nonce)):await Y(r),await B(r)):ft(r),N({lease:r,transition:`finalize`,event:x.LeaseFinalized,...e.txHash?{txHash:String(e.txHash)}:{}})})},async markDroppedOrReplaced(e){let t=k(e),n=j(t);return _(n),await X(n.lane,async()=>{let n=j(t);_(n),P(n,e.reason===m.Replaced?`replace`:`drop`),await Me(n,{reason:e.reason,...e.txHash?{txHash:String(e.txHash)}:{}}),N({lease:n,transition:e.reason===m.Replaced?`replace`:`drop`,event:e.reason===m.Replaced?x.LeaseReplaced:x.LeaseDropped,reason:e.reason,...e.txHash?{txHash:String(e.txHash)}:{}}),Ne({lane:n.lane,reason:e.reason})})},async release(e){let t=k(e);return await X(j(t).lane,async()=>{let n=j(t);P(n,`release`),await Y(n),N({lease:n,transition:`release`,event:x.LeaseReleased,reason:e.reason})})},async expireLeases(e){return await ot(e)},async recoverDurableLeases(e){await st(e)},async reconcile(e){return await X(e.lane,async()=>{let t=e.lane.family===`evm`?await U(e.lane):await Qe(e.lane);return D({event:x.LaneReconciled,lane:e.lane}),t})},clearForWallet(e){let t=String(e||``).trim();if(!t)return;C?.clearForWallet(t).catch(()=>O(o.DurableStoreError));let a=i.get(t);if(a){for(let e of a)r.delete(e);i.delete(t)}L(W)?.walletId===t&&G();for(let[e,r]of n.entries())u(r.lane)===t&&n.delete(e);D({event:x.LanesCleared,accountId:t,reason:`clear_for_account`})},clearAll(){r.clear(),i.clear(),l.clear(),C?.clearAll().catch(()=>O(o.DurableStoreError)),G(),n.clear(),f.clear(),D({event:x.LanesCleared,reason:`clear_all`})},getDiagnostics(e){return ht(e)}}}function dt(e){let t=e.trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(t))throw Error(`[NonceCoordinator] recovered EVM broadcast record has invalid txHash`);return t}function Q(e){return e.lane.family===`evm`}function $(e){return e.lane.family===`near`}function ft(e){throw Error(`Unexpected nonce lease variant: ${String(e)}`)}function pt(e){let t=e.lease,n={v:1,laneKey:v(t.lane),leaseId:t.leaseId,networkKey:l(t.lane),nonce:t.nonce,operationId:String(t.operationId),operationFingerprint:String(t.operationFingerprint),reservedAtMs:t.reservedAtMs,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs,runtimeId:e.runtimeId,family:`evm`,chainTarget:t.lane.chainTarget,accountId:t.lane.subjectId,sender:t.lane.sender,...t.lane.nonceKey==null?{}:{nonceKey:t.lane.nonceKey},...ht(t)};switch(e.lifecycle.state){case c.Reserved:case c.Signed:return{...n,state:e.lifecycle.state};case c.BroadcastAccepted:return{...n,state:c.BroadcastAccepted,txHash:dt(e.lifecycle.txHash)}}}function mt(e){let t=e.lease,n={v:1,laneKey:v(t.lane),leaseId:t.leaseId,networkKey:l(t.lane),nonce:BigInt(t.nonce),operationId:String(t.operationId),operationFingerprint:String(t.operationFingerprint),reservedAtMs:t.reservedAtMs,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs,runtimeId:e.runtimeId,family:`near`,walletId:t.lane.walletId,nearAccountId:t.lane.nearAccountId,publicKey:t.lane.publicKey,...ht(t)};switch(e.lifecycle.state){case c.Reserved:case c.Signed:return{...n,state:e.lifecycle.state};case c.BroadcastAccepted:return{...n,state:c.BroadcastAccepted,txHash:e.lifecycle.txHash}}}function ht(e){return{...e.batchId?{batchId:e.batchId}:{},...Number.isSafeInteger(e.txIndex)?{txIndex:e.txIndex}:{}}}function gt(){let e=globalThis.navigator?.locks;return typeof e?.request==`function`?{async withLock(t,n){return await e.request(t,{mode:`exclusive`},n)}}:null}export{st as n,ut as t};
@@ -1 +0,0 @@
1
- import{V as e}from"./domainIds-t1lp25yU.js";import{i as t}from"./digests-BIaE0DMd.js";import{i as n,r}from"./base64-BmKR3UqU.js";import{i,n as a,r as o}from"./signerDomain-BAsLT3XN.js";import{c as s,o as c}from"./ecdsaChainTarget-Bm5X4k-V.js";import{s as l,t as u}from"./normalization-Df9fZWJC.js";import{a as d,i as f,t as p}from"./keyMaterialEnvelope-Dm2ZEilb.js";import{d as m,n as h,t as g}from"./accountIds-CW2BP-d9.js";import{i as _,t as v}from"./signerSlot-D2RZnb27.js";import{t as y}from"./registrationSignerPlan-DK2b3N_p.js";import{a as b,i as x,n as ee,o as S,r as C,t as te}from"./profileAccountProjection-C5sNt-s2.js";function ne(e){return e===a.emailOtp?a.emailOtp:e===a.passkey?a.passkey:null}function re(t){if(t.authMethod===a.emailOtp){let n=e(t.metadata.email||``);if(n)return n}return t.walletId}async function w(t,n,r){let i=g(n),a=u(i);if(!a)return null;let o=await C(t,{accountRefs:b(i).map(e=>({chainIdKey:e,accountAddress:a})),signerSlot:r});if(!o)return null;let s=o.selectedSigner.metadata||{},c=typeof s.passkeyCredentialRawId==`string`?s.passkeyCredentialRawId:o.selectedSigner.signerId,l=typeof s.passkeyCredentialId==`string`?s.passkeyCredentialId:o.profile.passkeyCredential?.id||c,d=typeof s.operationalPublicKey==`string`?s.operationalPublicKey:``,f=e(s.nearEd25519SigningKeyId||``);if(!f)return null;let p=e(s.walletId||``);if(!p)return null;let m=ne(o.selectedSigner.signerAuthMethod);return{walletId:p,nearAccountId:i,loginDisplayName:re({walletId:p,authMethod:m,metadata:s}),signerSlot:o.selectedSigner.signerSlot,version:2,registeredAt:o.profile.createdAt,lastLogin:o.profile.updatedAt,lastUpdated:o.profile.updatedAt,operationalPublicKey:d,nearEd25519SigningKeyId:f,passkeyCredential:{id:l,rawId:c},authMethod:m,preferences:o.profile.preferences}}async function ie(e){let t=await te(e,{chainIdKeys:[`near:testnet`,`near:mainnet`]});if(!t?.chainAccount?.accountAddress)return null;let n;try{n=g(t.chainAccount.accountAddress)}catch{return null}return{nearAccountId:n,profileId:t.profileId,signerSlot:t.signerSlot}}async function ae(e){let t=await ie(e).catch(()=>null);return t?w(e,t.nearAccountId,t.signerSlot):null}async function oe(t){let[n,r]=await Promise.all([t.listChainAccountsByChain(`near:testnet`),t.listChainAccountsByChain(`near:mainnet`)]),i=new Set;for(let t of[...n,...r]){let n=e(t.accountAddress||``);if(n)try{i.add(g(n))}catch{}}let a=[],s=new Set;for(let e of i){let n=await C(t,{accountRefs:b(e).map(t=>({chainIdKey:t,accountAddress:u(e)}))}).catch(()=>null);if(!n)continue;let r=n.activeSigners.filter(e=>e.signerKind===o.thresholdEd25519&&ne(e.signerAuthMethod)).slice().sort((e,t)=>e.signerSlot-t.signerSlot);for(let n of r){let r=Number(n.signerSlot);if(!Number.isSafeInteger(r)||r<1)continue;let i=`${String(e)}:${r}`;if(s.has(i))continue;s.add(i);let o=await w(t,e,r).catch(()=>null);o&&a.push(o)}}return a}const T=`wallet_custody_ed25519_active_client_v1`,E=`chacha20poly1305-hkdf-sha256-wallet-custody-seed-v1`;function D(e){for(let[t,n]of[[`walletId`,e.walletId],[`nearAccountId`,e.nearAccountId],[`nearEd25519SigningKeyId`,e.nearEd25519SigningKeyId],[`signingWorkerId`,e.signingWorkerId],[`applicationBindingDigestB64u`,e.applicationBindingDigestB64u],[`signingWorkerVerifyingShareB64u`,e.signingWorkerVerifyingShareB64u],[`stateEpoch`,e.stateEpoch]])if(!String(n||``).trim())throw Error(`Wallet custody Ed25519 material binding requires ${t}`);if(e.participantIds.length!==2)throw Error(`Wallet custody Ed25519 material binding requires exactly two participants`)}function O(e){let{binding:t,sealed:n,target:i}=e;D(t);let a=r(t.registeredPublicKeyB64u);if(a.length!==32)throw Error(`Wallet custody Ed25519 material requires a 32-byte registered public key`);if(!n.ciphertextB64u||!n.nonceB64u)throw Error(`Wallet custody Ed25519 material requires its sealed ciphertext and nonce`);return{profileId:i.profileId,signerSlot:t.signerSlot,chainIdKey:i.chainIdKey,accountAddress:i.accountAddress,keyKind:T,algorithm:`ed25519`,publicKey:`ed25519:${m(a)}`,signerId:t.nearEd25519SigningKeyId,payload:{binding:t},payloadEnvelope:{encVersion:1,alg:E,nonce:n.nonceB64u,ciphertext:n.ciphertextB64u,aad:p({profileId:i.profileId,signerSlot:t.signerSlot,chainIdKey:i.chainIdKey,accountAddress:i.accountAddress,keyKind:T,schemaVersion:1,signerId:t.nearEd25519SigningKeyId})},timestamp:Date.now(),schemaVersion:1}}const k=`threshold-ecdsa`,A={signerAuthMethod:a.passkey,signerSource:i.passkeyRegistration},j={signerAuthMethod:a.emailOtp,signerSource:i.emailOtpRegistration};function M(e,t){let n=String(e||``).trim();if(!n)throw Error(`SeamsWalletDB: ${t} is required`);let i=r(n);if(i.length===0)throw Error(`SeamsWalletDB: ${t} decoded to empty credential public key`);return i}async function N(e,t){let n=g(t),r=await ee(e.accountStore,x(n)).catch(()=>null);if(!r?.profileId)return null;let i=d(r.profileId);return i.ok?{profileId:i.value}:null}async function se(e,t){let n=g(t.nearAccountId),r=Number(t.signerSlot);if(!Number.isSafeInteger(r)||r<1)throw Error(`SeamsWalletDB: storeUserData requires an exact signerSlot`);let c=r,l=s(t.walletId),d=f(n),p=S(n,t.preferences?.useNetwork),m=u(n),h=String(t.passkeyCredential?.rawId||``).trim()||`signer-${c}`;await e.accountStore.upsertProfile({profileId:d,defaultSignerSlot:c,passkeyCredential:t.passkeyCredential,...t.preferences?{preferences:t.preferences}:{}});let _=await e.accountStore.getAccountSigner({chainIdKey:p,accountAddress:m,signerId:h}).catch(()=>null),v=await e.accountStore.activateAccountSigner({account:{profileId:d,chainIdKey:p,accountAddress:m,accountModel:`near-native`},signer:{signerId:h,signerType:`threshold`,signerKind:o.thresholdEd25519,signerAuthMethod:a.passkey,signerSource:i.passkeyRegistration,metadata:{..._?.metadata||{},walletId:String(l),nearAccountId:String(n),nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,operationalPublicKey:t.operationalPublicKey,passkeyCredentialId:t.passkeyCredential?.id,passkeyCredentialRawId:t.passkeyCredential?.rawId}},activationPolicy:{mode:`allocate_next_free`},preferredSlot:c,mutation:{routeThroughOutbox:!1}});v.signerSlot!==c&&await e.accountStore.upsertProfile({profileId:d,defaultSignerSlot:v.signerSlot,passkeyCredential:t.passkeyCredential,...t.preferences?{preferences:t.preferences}:{}}),await e.accountStore.setLastProfileStateForProfile(d,v.signerSlot)}function ce(e){return oe(e.accountStore)}function le(e,t,n){return w(e.accountStore,t,n)}function ue(e){return ae(e.accountStore)}function de(e,t,n){return{nearAccountId:t,signerSlot:n??e.signerSlot,credentialId:e.credentialId,credentialPublicKey:e.credentialPublicKey,transports:e.transports,name:e.name,registered:e.registered,syncedAt:e.syncedAt}}function fe(e){if(e.signerAuthMethod!==a.passkey)return null;let t=String(e.metadata?.walletId||``).trim(),n=String(e.metadata?.passkeyCredentialRawId||``).trim();return!t||!n?null:{walletId:t,credentialId:n,signerSlot:e.signerSlot}}async function pe(e,t){let n=(await e.accountStore.listAccountSigners({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,status:`active`})).map(fe).filter(e=>e!==null),r=new Map;for(let e of n){let t=r.get(e.walletId);t?t.push(e):r.set(e.walletId,[e])}let i=[];for(let[n,a]of r.entries()){let r=await e.accountStore.listProfileAuthenticators(n);for(let e of a){let n=r.find(t=>t.credentialId===e.credentialId);n&&i.push(de(n,t.nearAccountId,e.signerSlot))}}return i}async function P(e,t){let n=g(t),r=await ee(e.accountStore,x(n)).catch(()=>null);return r?.accountRef?await pe(e,{nearAccountId:n,chainIdKey:r.accountRef.chainIdKey,accountAddress:r.accountRef.accountAddress}):[]}async function me(e,t,n){let r=Number(n);if(!Number.isSafeInteger(r)||r<1)throw Error(`SeamsWalletDB: signerSlot must be an integer >= 1`);let i=String(t||``).trim();if(!i)throw Error(`SeamsWalletDB: selected wallet id is required`);let a=await e.accountStore.getProfile(i).catch(()=>null);if(!a?.profileId)throw Error(`SeamsWalletDB: Missing profile for wallet ${i}`);await e.accountStore.setLastProfileStateForProfile(a.profileId,r)}function he(e){try{return s(e)}catch{return null}}function ge(e){if(typeof e!=`string`)return null;try{return g(e)}catch{return null}}function _e(e){if(typeof e!=`string`||!e.trim())return null;try{return _(e)}catch{return null}}async function ve(e,t){let n=null;try{n=await C(e.accountStore,{accountRefs:x(t.nearAccountId),signerSlot:t.signerSlot})}catch{n=null}if(!n)throw Error(`Authenticated wallet activation requires an exact NEAR signer projection`);let r=d(n.context.profileId);if(!r.ok)throw Error(r.message);let i=n.selectedSigner,a=i.metadata||{},s=he(a.walletId),c=ge(a.nearAccountId),l=_e(a.nearEd25519SigningKeyId),u=typeof a.operationalPublicKey==`string`?a.operationalPublicKey.trim():``;if(i.signerKind!==o.thresholdEd25519||i.signerSlot!==t.signerSlot||s!==t.walletId||c!==t.nearAccountId||!l||!u)throw Error(`Authenticated wallet activation requires an exact wallet signer binding`);return{kind:`authenticated_near_ed25519_wallet_profile_binding`,walletId:s,nearProjectionProfileId:r.value,nearAccountId:c,nearEd25519SigningKeyId:l,signerSlot:i.signerSlot,operationalPublicKey:u}}async function ye(e,t){return(await e.accountStore.getProfile(String(t)))?.nearProvisioning??null}async function be(e,t){let n=String(t.walletId||``).trim();if(!n)throw Error(`SeamsWalletDB: walletId is required`);let r=Date.now(),i=t.status===`near_ready`?{status:`near_ready`,updatedAtMs:r,nearAccountId:t.nearAccountId}:t.status===`near_failed_retryable`?{status:`near_failed_retryable`,updatedAtMs:r,error:t.errorCode,errorCode:t.errorCode}:{status:t.status,updatedAtMs:r};await e.accountStore.upsertProfile({profileId:n,nearProvisioning:i})}async function xe(e,t){let n=g(t.nearAccountId),r=s(t.walletId),i=v(t.signerSlot);if(!i)throw Error(`Authenticated wallet activation requires an exact signerSlot`);let a=await ve(e,{walletId:r,nearAccountId:n,signerSlot:i});await e.accountStore.setLastProfileStateForProfile(a.nearProjectionProfileId,a.signerSlot),e.userPreferencesManager.setCurrentWallet(a.walletId),await e.userPreferencesManager.reloadUserSettings().catch(()=>void 0),e.nonceCoordinator.initializeNearAccessKey({walletId:a.walletId,nearAccountId:a.nearAccountId,publicKey:a.operationalPublicKey}),t.nearClient&&e.nonceCoordinator.prefetchNearContext({kind:`initialized_state`,nearClient:t.nearClient}).catch(e=>console.debug(`Nonce prefetch after authentication state initialization failed (non-fatal):`,e))}async function Se(e,t){let n=Number(t.signerSlot);if(!Number.isSafeInteger(n)||n<1)throw Error(`SeamsWalletDB: authenticator signerSlot must be an integer >= 1`);let r={...t,nearAccountId:g(t.nearAccountId),signerSlot:n},i=await N(e,r.nearAccountId);if(!i?.profileId)throw Error(`SeamsWalletDB: Missing profile/account mapping for NEAR account ${r.nearAccountId}`);await e.accountStore.upsertProfileAuthenticator({profileId:i.profileId,signerSlot:r.signerSlot,credentialId:r.credentialId,credentialPublicKey:r.credentialPublicKey,transports:r.transports,name:r.name,registered:r.registered,syncedAt:r.syncedAt})}function Ce(e){let t=String(e).trim();return h(t)||t.split(`.`)[0]||``}function F(e){let t=Date.now();return{version:`wallet_auth_method_v1`,kind:`passkey`,status:`active`,localStatus:`synced`,walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialId,credentialPublicKeyB64u:n(e.credentialPublicKey),counter:0,createdAtMs:t,updatedAtMs:t}}async function I(e){let n=String(e.walletId||``).trim(),r=String(e.email||``).trim().toLowerCase(),i=String(e.registrationAuthorityId||``).trim();if(!n||!r||!i)throw Error(`SeamsWalletDB: Email OTP auth method requires walletId, email, and registrationAuthorityId`);let a=await t(r);if(String(e.authority.walletId)!==n||e.authority.verifier.emailHashHex!==a)throw Error(`SeamsWalletDB: Email OTP auth method authority does not match wallet or email`);let o=Date.now();return{version:`wallet_auth_method_v1`,kind:`email_otp`,status:`active`,localStatus:`synced`,walletId:e.walletId,emailHashHex:a,registrationAuthorityId:i,authority:e.authority,createdAtMs:o,updatedAtMs:o}}async function we(e,t){let n=g(t),r=await N(e,n);r?.profileId&&await e.accountStore.deleteProfileData(r.profileId,{eventAccountId:n})}async function Te(e,t){return(await P(e,g(t))).length>0}function Ee(e){let t=e.activation.signer.metadata||{},n=e.activation.signer.signerKind,r=n===o.thresholdEcdsa?X(t.thresholdEcdsaPublicKeyB64u,`ECDSA key material publicKey`):X(t.operationalPublicKey,`Ed25519 key material publicKey`),i={profileId:X(e.activation.account.profileId,`profileId`),signerSlot:e.signerSlot,chainIdKey:X(e.activation.account.chainIdKey,`chainIdKey`),accountAddress:X(e.activation.account.accountAddress,`accountAddress`),signerId:X(e.activation.signer.signerId,`signerId`),keyKind:`threshold_share_v1`,algorithm:n===o.thresholdEcdsa?`secp256k1`:`ed25519`,publicKey:r,timestamp:e.timestamp,schemaVersion:1};return n===o.thresholdEd25519&&(i.payload={walletId:X(t.walletId,`walletId`),nearAccountId:X(t.nearAccountId,`nearAccountId`),nearEd25519SigningKeyId:X(t.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),relayerKeyId:X(t.relayerKeyId,`relayerKeyId`),keyVersion:X(t.keyVersion,`keyVersion`)}),i}function De(e){switch(e.mode.kind){case`fresh_registration`:return{mode:`fail_if_occupied`,signerSlot:e.signerSlot};case`wallet_recovery_replacement`:return{mode:`replace_slot`,signerSlot:e.signerSlot,replacedSignerKind:o.thresholdEd25519,revocationReason:`wallet_recovery_replacement`}}}function Oe(e){switch(e.mode.kind){case`fresh_registration`:return{mode:`allocate_next_free`};case`wallet_recovery_replacement`:return{mode:`replace_profile_chain_kind`,signerSlot:e.signerSlot,replacedSignerKind:o.thresholdEcdsa,revocationReason:`wallet_recovery_replacement`}}}function L(e){let t=Number(e.signerSlot);if(!Number.isSafeInteger(t)||t<1)throw Error(`SeamsWalletDB: wallet signerSlot must be an integer >= 1`);let n=String(e.walletId||``).trim();if(!n)throw Error(`SeamsWalletDB: walletId is required`);let r=g(e.nearAccountId),i=String(e.nearEd25519SigningKeyId||``).trim();if(!i)throw Error(`SeamsWalletDB: nearEd25519SigningKeyId is required`);return{signerSlot:t,walletId:n,nearAccountId:r,nearEd25519SigningKeyId:i}}function R(e,t,n){return{walletId:e.walletId,nearAccountId:String(e.nearAccountId),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,operationalPublicKey:t.operationalPublicKey,relayerKeyId:t.relayerKeyId,keyVersion:t.keyVersion,...n,...t.participantIds?{participantIds:t.participantIds}:{},...t.clientParticipantId==null?{}:{clientParticipantId:t.clientParticipantId},...t.relayerParticipantId==null?{}:{relayerParticipantId:t.relayerParticipantId}}}function z(e){let t=X(e.operationalPublicKey,`Ed25519 signerId`),{signerSlot:n,walletId:r,nearAccountId:i}=e.identity,a=r=>({input:{account:r,signer:{signerId:t,signerType:`threshold`,signerKind:o.thresholdEd25519,signerAuthMethod:e.source.signerAuthMethod,signerSource:e.source.signerSource,metadata:e.metadata},activationPolicy:e.activationPolicy,preferredSlot:n,mutation:{routeThroughOutbox:!1}},signerSlot:n});return[a({profileId:r,chainIdKey:`wallet`,accountAddress:r,accountModel:`wallet`}),a({profileId:e.nearProfileId,chainIdKey:S(i),accountAddress:u(i),accountModel:`near-native`})]}function B(e){let t=e.map(e=>e.input),n=Date.now();return{signerActivations:t,keyMaterials:e.map(e=>Ee({activation:e.input,signerSlot:e.signerSlot,timestamp:n}))}}function V(e,t,n,r){return t.kind===`near_ed25519_and_evm_family_ecdsa`?Q({walletId:e,walletKeys:t.walletKeys},n,r).signerActivations:[]}function H(e,t){return{chainTarget:e.chainTarget,targetKey:e.targetKey,signerSlot:t.signerSlot,signerId:e.signerId}}function ke(e,t,n){let r=String(e.credential.rawId||``).trim();if(!r)throw Error(`SeamsWalletDB: registration credential rawId is required`);let i=e.participantIds===void 0?void 0:Z(e.participantIds);return U({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,rpId:e.rpId,signerSlot:e.signerSlot,operationalPublicKey:e.operationalPublicKey,relayerKeyId:e.relayerKeyId,keyVersion:e.keyVersion,participantIds:i,clientParticipantId:e.clientParticipantId,relayerParticipantId:e.relayerParticipantId,credentialFacts:{credentialId:r,credentialDisplayId:e.credential.id,credentialPublicKey:M(e.credentialPublicKeyB64u,`credentialPublicKeyB64u`),transports:e.credential.response?.transports??[]}},t,n)}function U(e,t,n){let r=e.credentialFacts.credentialId,i=L(e),{signerSlot:a,walletId:o,nearAccountId:s}=i,c={id:e.credentialFacts.credentialDisplayId,rawId:r},l=new Date().toISOString(),u=f(s),{signerActivations:d,keyMaterials:p}=B([...z({identity:i,nearProfileId:u,operationalPublicKey:e.operationalPublicKey,source:A,metadata:R(i,e,{passkeyCredentialId:e.credentialFacts.credentialDisplayId,passkeyCredentialRawId:r}),activationPolicy:De({mode:t,signerSlot:a})}),...V(e.walletId,n,A,t)]);return{profiles:[o,u].map(e=>({profileId:e,defaultSignerSlot:a,passkeyCredential:c})),initialAuthMethod:F({walletId:e.walletId,rpId:e.rpId,credentialId:r,credentialPublicKey:e.credentialFacts.credentialPublicKey}),authenticators:[o,u].map(t=>({profileId:t,signerSlot:a,credentialId:r,credentialPublicKey:e.credentialFacts.credentialPublicKey,transports:[...e.credentialFacts.transports],name:`Passkey for ${Ce(s)}`,registered:l,syncedAt:l})),signerActivations:d,keyMaterials:p,lastProfileState:{profileId:o,activeSignerSlot:a}}}function Ae(e,t){let n=e.signerActivations[1];if(!n)throw Error(`SeamsWalletDB: wallet Ed25519 registration batch did not complete`);let r=[];for(let n=0;n<t.length;n+=1){let i=t[n],a=e.signerActivations[n+2];if(!i||!a)throw Error(`SeamsWalletDB: mixed wallet ECDSA registration batch did not complete`);r.push(H(i,a))}return{signerSlot:n.signerSlot,storedSigners:r}}function je(e){return W(ke(e,{kind:`fresh_registration`},{kind:`near_ed25519_only`}),e,e.participantIds,[e.custodyMaterial])}function Me(e){let t=String(e.credentialIdB64u||``).trim();if(!t)throw Error(`SeamsWalletDB: registration credential projection id is required`);return W(U({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,rpId:e.rpId,signerSlot:e.signerSlot,operationalPublicKey:e.operationalPublicKey,relayerKeyId:e.relayerKeyId,keyVersion:e.keyVersion,participantIds:e.participantIds,credentialFacts:{credentialId:t,credentialDisplayId:t,credentialPublicKey:M(e.credentialPublicKeyB64u,`credentialPublicKeyB64u`),transports:[...e.transports]}},{kind:`fresh_registration`},{kind:`near_ed25519_only`}),e,e.participantIds,[e.custodyMaterial])}function W(e,t,n,r){let i=g(t.nearAccountId),a=r.map(e=>{let r=e.binding;if(r.walletId!==String(t.walletId)||r.nearAccountId!==String(i)||r.nearEd25519SigningKeyId!==String(t.nearEd25519SigningKeyId)||r.signerSlot!==Number(t.signerSlot)||r.participantIds[0]!==n[0]||r.participantIds[1]!==n[1])throw Error(`Wallet custody Ed25519 material does not match registration identity`);return O({target:{profileId:String(f(i)),chainIdKey:S(i),accountAddress:u(i)},binding:r,sealed:e.sealed})}),o=e.lastProfileState;if(!o)throw Error(`Wallet Ed25519 registration publication requires last profile state`);return{profiles:e.profiles,initialAuthMethod:e.initialAuthMethod,authenticators:e.authenticators,signerActivations:e.signerActivations,keyMaterials:[...e.keyMaterials,...a],lastProfileState:{profileId:o.profileId,activeSignerSlot:o.activeSignerSlot,scope:o.scope??null}}}function G(e){let t=e[0];if(!t)throw Error(`SeamsWalletDB: threshold ECDSA walletKeys are required`);return[t,...e.slice(1)]}function Ne(e){switch(e){case`email_otp`:return j;case`passkey`:return A;default:return Pe(e)}}function Pe(e){throw Error(`Unsupported wallet ECDSA registration kind: ${String(e)}`)}async function K(e,t){let{signerActivations:n,keyMaterials:r}=B(Q({walletId:e.walletId,walletKeys:e.walletKeys},Ne(e.kind),t).signerActivations);switch(e.kind){case`passkey`:{let t=X(e.credentialIdB64u,`credentialIdB64u`),i=M(e.credentialPublicKeyB64u,`credentialPublicKeyB64u`),a=new Date().toISOString();return{profiles:[{profileId:e.walletId,defaultSignerSlot:1,passkeyCredential:{id:t,rawId:t}}],initialAuthMethod:F({walletId:e.walletId,rpId:e.rpId,credentialId:t,credentialPublicKey:i}),authenticators:[{profileId:e.walletId,signerSlot:1,credentialId:t,credentialPublicKey:i,transports:[...e.transports],name:`Passkey for wallet`,registered:a,syncedAt:a}],signerActivations:n,keyMaterials:r,lastProfileState:{profileId:e.walletId,activeSignerSlot:1,scope:null}}}case`email_otp`:return{profiles:[{profileId:e.walletId,defaultSignerSlot:1}],initialAuthMethod:await I({walletId:e.walletId,email:e.email,registrationAuthorityId:e.registrationAuthorityId,authority:e.authority}),authenticators:[],signerActivations:n,keyMaterials:r,lastProfileState:{profileId:e.walletId,activeSignerSlot:1,scope:null}}}}function q(e){return K(e,{kind:`fresh_registration`})}async function Fe(e){let t=X(e.credentialIdB64u,`credentialIdB64u`);return e.kind===`near_ed25519`?W(U({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,rpId:e.rpId,signerSlot:e.signerSlot,operationalPublicKey:e.operationalPublicKey,relayerKeyId:e.relayerKeyId,keyVersion:y,participantIds:Z(e.participantIds),credentialFacts:{credentialId:t,credentialDisplayId:t,credentialPublicKey:M(e.credentialPublicKeyB64u,`credentialPublicKeyB64u`),transports:e.transports}},{kind:`wallet_recovery_replacement`},e.walletKeys.length>0?{kind:`near_ed25519_and_evm_family_ecdsa`,walletKeys:e.walletKeys}:{kind:`near_ed25519_only`}),e,Z(e.participantIds),e.custodyMaterials):await K({kind:`passkey`,walletId:e.walletId,rpId:e.rpId,credentialIdB64u:t,credentialPublicKeyB64u:e.credentialPublicKeyB64u,transports:e.transports,walletKeys:G(e.walletKeys)},{kind:`wallet_recovery_replacement`})}async function Ie(e){return e.kind===`near_ed25519`?W(await Y({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,email:e.email,registrationAuthorityId:e.registrationAuthorityId,authority:e.authority,signerSlot:e.signerSlot,operationalPublicKey:e.operationalPublicKey,relayerKeyId:e.relayerKeyId,keyVersion:y,participantIds:Z(e.participantIds)},e.walletKeys.length>0?{kind:`near_ed25519_and_evm_family_ecdsa`,walletKeys:e.walletKeys}:{kind:`near_ed25519_only`},{kind:`wallet_recovery_replacement`}),e,Z(e.participantIds),e.custodyMaterials):await K({kind:`email_otp`,walletId:e.walletId,email:e.email,registrationAuthorityId:e.registrationAuthorityId,authority:e.authority,walletKeys:G(e.walletKeys)},{kind:`wallet_recovery_replacement`})}async function J(e,t,n,r){let i=ke(t,n,r);return Ae(await e.accountStore.persistWalletRegistrationFinalize(i),V(t.walletId,r,A))}async function Le(e,t){return{signerSlot:(await J(e,t,{kind:`fresh_registration`},{kind:`near_ed25519_only`})).signerSlot}}async function Re(e,t){return await J(e,t,{kind:`fresh_registration`},{kind:`near_ed25519_and_evm_family_ecdsa`,walletKeys:t.walletKeys})}async function ze(e,t){return{signerSlot:(await J(e,t,{kind:`wallet_recovery_replacement`},{kind:`near_ed25519_only`})).signerSlot}}async function Y(e,t,n={kind:`fresh_registration`}){let r=L(e),{signerSlot:i,walletId:a,nearAccountId:o}=r,s=f(o),{signerActivations:c,keyMaterials:l}=B([...z({identity:r,nearProfileId:s,operationalPublicKey:e.operationalPublicKey,source:j,metadata:R(r,e,{email:String(e.email||``).trim().toLowerCase(),registrationAuthorityId:String(e.registrationAuthorityId||``).trim()}),activationPolicy:De({mode:n,signerSlot:i})}),...V(e.walletId,t,j,n)]);return{profiles:[a,s].map(e=>({profileId:e,defaultSignerSlot:i})),initialAuthMethod:await I({walletId:e.walletId,email:e.email,registrationAuthorityId:e.registrationAuthorityId,authority:e.authority}),authenticators:[],signerActivations:c,keyMaterials:l,lastProfileState:{profileId:a,activeSignerSlot:i}}}async function Be(e,t,n){let r=await Y(t,n),i=await e.accountStore.persistWalletRegistrationFinalize(r),a=V(t.walletId,n,j),o=i.signerActivations[1];if(!o)throw Error(`SeamsWalletDB: wallet Email OTP Ed25519 registration batch did not complete`);let s=[];for(let e=0;e<a.length;e+=1){let t=a[e],n=i.signerActivations[e+2];if(!t||!n)throw Error(`SeamsWalletDB: mixed wallet Email OTP ECDSA registration batch did not complete`);s.push(H(t,n))}return{signerSlot:o.signerSlot,storedSigners:s}}async function Ve(e){return W(await Y(e,{kind:`near_ed25519_only`}),e,e.participantIds,[e.custodyMaterial])}async function He(e,t){return{signerSlot:(await Be(e,t,{kind:`near_ed25519_only`})).signerSlot}}async function Ue(e,t){return Be(e,t,{kind:`near_ed25519_and_evm_family_ecdsa`,walletKeys:t.walletKeys})}async function We(e,t){let n=String(t.auth.credential.rawId||t.auth.credential.id||``).trim();if(!n)throw Error(`SeamsWalletDB: add-signer credential id is required`);let r=L(t),{signerSlot:i,walletId:a,nearAccountId:o}=r,s={id:t.auth.credential.id,rawId:n},c=f(o),{signerActivations:l,keyMaterials:u}=B(z({identity:r,nearProfileId:c,operationalPublicKey:t.operationalPublicKey,source:A,metadata:R(r,t,{passkeyCredentialId:t.auth.credential.id,passkeyCredentialRawId:n}),activationPolicy:{mode:`fail_if_occupied`,signerSlot:i}})),d=await e.accountStore.persistWalletSignerFinalize({profiles:[a,c].map(e=>({profileId:e,defaultSignerSlot:i,passkeyCredential:s})),signerActivations:l,keyMaterials:u,lastProfileState:{profileId:a,activeSignerSlot:i}}),p=d.signerActivations[1];if(!p)throw Error(`SeamsWalletDB: wallet Ed25519 signer batch did not complete`);return{signerSlot:p.signerSlot,rollbackReceipt:d.rollbackReceipt}}async function Ge(e,t){await e.accountStore.rollbackWalletSignerFinalize(t)}function X(e,t){let n=String(e||``).trim();if(!n)throw Error(`SeamsWalletDB: ${t} is required`);return n}function Z(e){if(e.length!==2||e.some(e=>!Number.isSafeInteger(e)||e<1))throw Error(`SeamsWalletDB: Ed25519 participantIds must contain two positive integers`);return[e[0],e[1]]}function Ke(e){if(!Array.isArray(e)||e.length!==2||e[0]!==1||e[1]!==2)throw Error(`SeamsWalletDB: threshold ECDSA participantIds must be [1, 2]`);return[1,2]}function Q(e,t=A,n={kind:`fresh_registration`}){let r=X(e.walletId,`walletId`);if(!Array.isArray(e.walletKeys)||e.walletKeys.length===0)throw Error(`SeamsWalletDB: threshold ECDSA walletKeys are required`);let i=[];for(let a of e.walletKeys){if(a.keyScope!==`evm-family`)throw Error(`SeamsWalletDB: threshold ECDSA wallet keyScope must be evm-family`);let e=X(a.walletId,`wallet key walletId`);if(e!==r)throw Error(`SeamsWalletDB: threshold ECDSA wallet key walletId mismatch`);let s=X(a.keyHandle,`wallet key keyHandle`),d=X(a.ecdsaThresholdKeyId,`wallet key ecdsaThresholdKeyId`),f=X(a.signingRootId,`wallet key signingRootId`),p=X(a.signingRootVersion,`wallet key signingRootVersion`),m=X(a.relayerKeyId,`wallet key relayerKeyId`),h=X(a.thresholdEcdsaPublicKeyB64u,`wallet key thresholdEcdsaPublicKeyB64u`),g=Ke(a.participantIds),_=u(a.thresholdOwnerAddress);if(!_)throw Error(`SeamsWalletDB: wallet key thresholdOwnerAddress is required`);let v=l(a.chainTarget),y=c(a.chainTarget);i.push({chainTarget:a.chainTarget,targetKey:y,signerId:_,signerSlot:1,input:{account:{profileId:e,chainIdKey:v,accountAddress:_,accountModel:k},signer:{signerId:_,signerType:`threshold`,signerKind:o.thresholdEcdsa,signerAuthMethod:t.signerAuthMethod,signerSource:t.signerSource,metadata:{accountModel:k,accountAddress:_,ownerAddress:_,thresholdOwnerAddress:_,keyScope:a.keyScope,keyHandle:s,walletId:e,ecdsaThresholdKeyId:d,signingRootId:f,signingRootVersion:p,relayerKeyId:m,relayerVerifyingShareB64u:X(a.relayerVerifyingShareB64u,`wallet key relayerVerifyingShareB64u`),publicCapability:a.publicCapability,roleLocalMaterialRef:a.roleLocalMaterialRef,ecdsaRoleLocalPublicFacts:a.ecdsaRoleLocalPublicFacts,thresholdEcdsaPublicKeyB64u:h,participantIds:g,chainTarget:a.chainTarget,targetMembership:{targetKey:y,chainTarget:a.chainTarget},sharedEvmFamilyKey:{walletId:e,keyScope:a.keyScope,keyHandle:s,ecdsaThresholdKeyId:d,signingRootId:f,signingRootVersion:p,participantIds:g,thresholdOwnerAddress:_,thresholdEcdsaPublicKeyB64u:h},chainId:a.chainTarget.chainId}},activationPolicy:Oe({mode:n,signerSlot:1}),preferredSlot:1,mutation:{routeThroughOutbox:!1}}})}return{walletId:r,signerActivations:i}}function $(e,t){return e.accountStore.persistWalletSignerFinalize({profiles:[{profileId:t.walletId}],...B(t.signerActivations)})}async function qe(e,t){let n=Q(t),r=await $(e,n);return{storedSigners:n.signerActivations.map((e,t)=>{let n=r.signerActivations[t];if(!n)throw Error(`SeamsWalletDB: wallet ECDSA signer batch did not complete`);return H(e,n)})}}async function Je(e,t){let n=Q(t,A,{kind:`wallet_recovery_replacement`}),r=await $(e,n);return{storedSigners:n.signerActivations.map((e,t)=>{let n=r.signerActivations[t];if(!n)throw Error(`SeamsWalletDB: wallet recovery ECDSA signer batch did not complete`);return H(e,n)})}}async function Ye(e,t){let n=Q(t,j),r=await $(e,n);return{storedSigners:n.signerActivations.map((e,t)=>{let n=r.signerActivations[t];if(!n)throw Error(`SeamsWalletDB: wallet Email OTP ECDSA signer batch did not complete`);return H(e,n)})}}async function Xe(e,t){let n=String(t.credential.rawId||``).trim();if(!n)throw Error(`SeamsWalletDB: registration credential rawId is required`);let r=Q({walletId:t.walletId,walletKeys:t.walletKeys}),i=await q({kind:`passkey`,walletId:t.walletId,rpId:t.rpId,credentialIdB64u:n,credentialPublicKeyB64u:t.credentialPublicKeyB64u,transports:t.credential.response?.transports??[],walletKeys:G(t.walletKeys)}),a=await e.accountStore.persistWalletRegistrationFinalize(i);return{storedSigners:r.signerActivations.map((e,t)=>{let n=a.signerActivations[t];if(!n)throw Error(`SeamsWalletDB: wallet ECDSA registration batch did not complete`);return H(e,n)})}}async function Ze(e,t){let n=Q({walletId:t.walletId,walletKeys:t.walletKeys},j),r=await q({kind:`email_otp`,walletId:t.walletId,email:t.email,registrationAuthorityId:t.registrationAuthorityId,authority:t.authority,walletKeys:G(t.walletKeys)}),i=await e.accountStore.persistWalletRegistrationFinalize(r);return{storedSigners:n.signerActivations.map((e,t)=>{let n=i.signerActivations[t];if(!n)throw Error(`SeamsWalletDB: wallet Email OTP ECDSA registration batch did not complete`);return H(e,n)})}}export{Re as A,qe as C,Ye as D,Ze as E,ie as F,w as I,T as M,D as N,He as O,O as P,Je as S,Le as T,Ge as _,ue as a,Se as b,Te as c,Me as d,je as f,we as g,Fe as h,ce as i,E as j,Ue as k,P as l,Ie as m,Xe as n,le as o,Ve as p,We as r,ye as s,xe as t,q as u,me as v,ze as w,se as x,be as y};
@@ -1 +0,0 @@
1
- import{F as e,i as t}from"./domainIds-t1lp25yU.js";import{c as n,o as r}from"./ecdsaChainTarget-Bm5X4k-V.js";import{t as i}from"./accountIds-CW2BP-d9.js";import{ut as a}from"./digestEncoding-CqNXPZY9.js";import{i as o,t as s}from"./signerSlot-D2RZnb27.js";import{T as c,g as l}from"./emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js";import{c as u,s as d}from"./types-f7dyj5N6.js";import{a as f,k as p}from"./nearEd25519YaoSigningPreparation-DHNk0F8e.js";function m(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?null:t.toString(10).padStart(20,`0`)}function h(e,t){if(e.length===0)return{kind:`no_current_lane`,unusableFacts:[]};let n=_(e,t),r=v(n,t);if(r.length)return{kind:`conflicting_key_material`,conflicts:r};if(n.length!==1)return{kind:`ambiguous_material`,candidates:e};let i=n[0];return i?g(i,t.supersession):{kind:`no_current_lane`,unusableFacts:[]}}function g(e,t){let n=e.facts.filter(t.isOperationUsable);if(n.length===0)return{kind:`no_current_lane`,unusableFacts:e.facts};let r=y(n,t);return r.kind===`ambiguous`?{kind:`ambiguous_material`,candidates:r.candidates}:{kind:`selected`,selectedFact:r.fact,supersededFacts:e.facts.filter(e=>e!==r.fact)}}function _(e,t){let n=new Map;for(let r of e){let e=t.groupKey(r),i=t.groupKeyString(e),a=n.get(i);n.set(i,a?{groupKey:a.groupKey,facts:[...a.facts,r]}:{groupKey:e,facts:[r]})}return[...n.values()]}function v(e,t){return e.flatMap(e=>t.groupConflicts(e.facts))}function y(e,t){let n=e[0];if(n===void 0)return{kind:`ambiguous`,candidates:[]};let r=n;for(let n of e.slice(1)){let e=b(r,n,t);switch(e.kind){case`left`:break;case`right`:r=n;break;case`ambiguous`:return{kind:`ambiguous`,candidates:e.candidates};default:return e}}return{kind:`selected`,fact:r}}function b(e,t,n){let r=x(e,t,n);if(r.kind!==`equal`)return r;let i=S(e,t,n);if(i.kind!==`equal`)return i;let a=n.tieBreak(e,t);switch(a){case 1:return{kind:`left`};case-1:return{kind:`right`};case 0:return{kind:`ambiguous`,candidates:[e,t]};default:return a}}function x(e,t,n){let r=n.generation(e),i=n.generation(t);return!r||!i?{kind:`ambiguous`,candidates:[e,t]}:r>i?{kind:`left`}:i>r?{kind:`right`}:{kind:`equal`}}function S(e,t,n){let r=n.exactness(e);return r===n.exactness(t)?{kind:`equal`}:r===`exact_target`?{kind:`left`}:{kind:`right`}}function C(e){return{kind:`ed25519_durable_material`,authMethod:e.authMethod,materialActivation:e.materialActivation}}function w(e){return[e.activationId,e.capability,e.materialOwner,e.keyBinding,e.lifecycleBinding,e.signingWorker].map(e=>encodeURIComponent(String(e))).join(`:`)}function T(e){let t={source:e.source,runtime:e.runtime,key:e.key,materialActivation:e.materialActivation,publicFacts:e.publicFacts,curve:`ecdsa`,chainTarget:e.chainTarget,state:e.state,authorizationState:e.authorizationState};if(e.auth.kind===`passkey`){if(!e.resolvedKey)throw Error(`active Wallet Authority passkey lane is missing its resolved ECDSA key`);return{...t,auth:e.auth,resolvedKey:e.resolvedKey}}return{...t,auth:e.auth}}function ee(e){let t=e.authorization;return t?e.remainingUses===t.runtime.remainingUses&&e.expiresAtMs===t.runtime.expiresAtMs:!0}function E(e){return e.auth.kind}function D(e){return u(e.auth)}function O(e){let t=e.ed25519Restore;if(e.authMethod===`passkey`){if(!t.credentialIdB64u)return null;try{return{kind:`passkey`,rpId:c(t.rpId),credentialIdB64u:t.credentialIdB64u}}catch{return null}}return t.providerSubjectId?{kind:`email_otp`,providerSubjectId:t.providerSubjectId}:null}function k(e){let{authorization:t}=e;if(String(t.session.walletId)!==e.walletId||t.selectedAuthMethod.kind!==e.auth.kind||t.operationCredential.walletSessionId.length===0||t.session.quotaId.length===0||!f({session:t.session,materialActivation:e.materialActivation}))return!1;switch(e.auth.kind){case`passkey`:if(t.selectedAuthMethod.kind!==`passkey`||String(t.selectedAuthMethod.rpId)!==String(e.auth.rpId)||t.selectedAuthMethod.credentialIdB64u!==e.auth.credentialIdB64u)return!1;break;case`email_otp`:if(t.selectedAuthMethod.kind!==`email_otp`||t.selectedFactorAuthority.factor.kind!==`email_otp`||t.selectedFactorAuthority.factor.providerUserId!==e.auth.providerSubjectId)return!1;break;case`voiceid`:if(t.selectedAuthMethod.kind!==`voiceid`||t.selectedAuthMethod.walletAuthMethodId!==e.auth.walletAuthMethodId||t.selectedAuthMethod.deviceKeyId!==e.auth.deviceKeyId)return!1;break;default:return e.auth,!1}return!!(e.ownerScope&&d(e.auth)===d(e.ownerScope.auth))}function te(e,t,r){if(e.curve!==`ed25519`)return null;let a=String(e.thresholdSessionIds.ed25519||``).trim(),c=String(e.walletId||``).trim(),l=e.ed25519Restore,u=s(l.signerSlot),d=O(e);if(!a||!c||u===null||!d)return null;let f=Math.floor(Number(e.expiresAtMs)||0),p=Math.max(0,Math.floor(Number(e.remainingUses)||0)),m=f>0&&f<=Date.now()?`expired`:p===0?`exhausted`:`restorable`,h=t&&k({authorization:t,auth:d,walletId:c,materialActivation:l.materialActivation,ownerScope:r})?t:null;try{let t={auth:d,curve:`ed25519`,chain:`near`,materialActivation:l.materialActivation,walletId:n(c),nearAccountId:i(l.nearAccountId),nearEd25519SigningKeyId:o(l.nearEd25519SigningKeyId),signerSlot:u,source:`durable_sealed_record`,thresholdSessionId:a,remainingUses:p,...f>0?{expiresAtMs:f}:{},updatedAtMs:Math.floor(Number(e.updatedAtMs)||0),...P(e)?{policyHint:P(e)}:{}};return h?{...t,state:m,authorizationState:`authorized`,authorization:h}:{...t,state:`deferred`,authorizationState:`authorization_required`}}catch{return null}}function ne(e){return e.auth.kind===`email_otp`}function re(e,t,r){let a=String(e.walletId||``).trim(),o=String(e.nearAccountId||``).trim(),s=String(e.thresholdSessionId||``).trim();if(!a||!o||!s)return null;let c=t&&k({authorization:t,auth:e.auth,walletId:a,materialActivation:e.materialActivation,ownerScope:r})?t:null;try{let t={auth:e.auth,curve:`ed25519`,chain:`near`,materialActivation:e.materialActivation,walletId:n(a),nearAccountId:i(o),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,thresholdSessionId:s,source:`public_capability_reference`};if(!c)return{...t,state:`deferred`,authorizationState:`authorization_required`};let r=Math.floor(Number(c.status.expiresAtMs)||0),l=ne(e)?e:null,u=l?Math.min(l.expiresAtMs,r):r,d=u>0&&u<=Date.now()?`expired`:`ready`;return{...t,state:d,authorizationState:`authorized`,authorization:c,remainingUses:c.status.remainingUses,...u>0?{expiresAtMs:u}:{}}}catch{return null}}function A(e){if(e.state===`missing`)return!1;if(e.curve!==`ecdsa`){let t=String(e.thresholdSessionId||``).trim();return e.thresholdSessionId!==t||!t?!1:e.authorizationState===`authorization_required`?e.state===`deferred`:!(!e.authorization.operationCredential.walletSessionId||!e.authorization.session.quotaId||e.authorization.status.remainingUses<=0||e.authorization.status.expiresAtMs<=Date.now())}return e.source===`active_wallet_authority`&&(e.state!==`deferred`||e.authorizationState!==`authorization_required`||e.runtime.kind!==`active_wallet_authority_ecdsa_runtime_v1`||String(e.runtime.walletId)!==String(e.key.walletId)||!t(e.runtime.materialActivation,e.materialActivation)||e.runtime.publicFacts!==e.publicFacts)||!(e.key&&String(e.key.walletId||``).trim()&&String(e.key.ecdsaThresholdKeyId||``).trim()&&String(e.key.signingRootId||``).trim()&&String(e.key.signingRootVersion||``).trim()&&Array.isArray(e.key.participantIds)&&e.key.participantIds.length>0&&String(e.key.thresholdOwnerAddress||``).trim()&&`publicFacts`in e&&e.publicFacts&&e.publicFacts.keyHandle&&String(e.publicFacts.publicKeyB64u||``).trim()&&Array.isArray(e.publicFacts.participantIds)&&e.publicFacts.participantIds.length>0&&String(e.publicFacts.thresholdOwnerAddress||``).trim())||e.source===`canonical_capability`&&!ee(e)?!1:u(e.auth)===`passkey`?e.resolvedKey?.kind===`resolved_evm_family_ecdsa_key`&&e.resolvedKey.authBinding.kind===`passkey_ecdsa_auth_binding`&&String(e.resolvedKey.walletId)===String(e.key.walletId)&&e.resolvedKey.publicFacts===e.publicFacts:!(`resolvedKey`in e)}function j(e){return e===`missing`?null:e}function ie(e){return e||`unknown`}function ae(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function oe(e){let t=Math.max(0,Math.floor(Number(e)));return Number.isFinite(t)?t:null}function se(e){if(!A(e.lane)||e.lane.curve!==`ed25519`)return null;let t=j(e.lane.state);if(!t)return null;let n={kind:`lane_candidate`,walletId:e.lane.walletId,nearAccountId:e.lane.nearAccountId,nearEd25519SigningKeyId:e.lane.nearEd25519SigningKeyId,signerSlot:e.lane.signerSlot,materialActivation:e.lane.materialActivation,auth:e.lane.auth,curve:`ed25519`,chain:`near`,thresholdSessionId:e.lane.thresholdSessionId,state:t,remainingUses:oe(e.lane.remainingUses),expiresAtMs:ae(e.lane.expiresAtMs),updatedAtMs:ae(e.lane.updatedAtMs),source:ie(e.lane.source)};return e.lane.authorizationState===`authorization_required`?{...n,authorizationState:`authorization_required`,state:`deferred`}:{...n,authorizationState:`authorized`,authorization:e.lane.authorization}}function ce(e){if(!A(e.lane)||e.lane.curve!==`ecdsa`)return null;let t=j(e.lane.state);if(!t)return null;let r=u(e.lane.auth),i={kind:`lane_candidate`,walletId:n(e.walletId),auth:e.lane.auth,authMethod:r,curve:`ecdsa`,chain:e.lane.chainTarget.kind,key:e.lane.key,materialActivation:e.lane.materialActivation,...r===`passkey`?{resolvedKey:e.lane.resolvedKey}:{},keyHandle:e.lane.publicFacts.keyHandle,chainTarget:e.lane.chainTarget};switch(e.lane.source){case`active_wallet_authority`:return{...i,source:`active_wallet_authority`,runtime:e.lane.runtime,authorizationState:`authorization_required`,state:`deferred`};case`canonical_capability`:return e.lane.authorization?{...i,source:`canonical_capability`,authorizationState:`authorized`,authorization:e.lane.authorization,state:t}:{...i,source:`canonical_capability`,authorizationState:`authorization_required`,state:`deferred`};default:return e.lane}}function le(e){if(!e||e.curve!==`ecdsa`||!e.chainTarget||!(`key`in e)||!e.key||!(`auth`in e)||!e.auth)return null;let t=u(e.auth);try{let n=d(e.auth);return[t,`ecdsa`,r(e.chainTarget),n,ue(e),w(e.materialActivation)].join(`:`)}catch{return null}}function ue(e){return l({walletId:e.key.walletId,publicFacts:e.publicFacts})}function M(e){if(!e||e.curve!==`ed25519`||e.chain!==`near`||e.state===`missing`||!e.auth)return null;let t=u(e.auth),n=String(e.walletId||``).trim(),r=String(e.nearAccountId||``).trim(),i=String(e.nearEd25519SigningKeyId||``).trim(),a=String(e.signerSlot||``).trim(),o=String(e.thresholdSessionId||``).trim(),s=e.materialActivation?w(e.materialActivation):``;return!t||!n||!r||!i||!a||!o||!s?null:[n,r,i,a,t,`ed25519`,`near`,o,s].join(`:`)}function N(e){return{curve:`ecdsa`,chainTarget:e.chainTarget,state:`missing`}}function de(e,t){let n=r(t);return e.ecdsa.lanesByTarget[n]||N({chainTarget:t})}function fe(e,t){let n=r(t);return e.ecdsa.candidatesByTarget[n]||[]}function pe(){return{curve:`ed25519`,chain:`near`,state:`missing`}}function P(e){let t=Math.floor(Number(e.remainingUses)),n=Math.floor(Number(e.expiresAtMs)),r={};return Number.isFinite(t)&&t>=0&&(r.remainingUses=t),Number.isFinite(n)&&n>0&&(r.expiresAtMs=n),Object.keys(r).length?r:void 0}function F(e){return Math.floor(Number(`updatedAtMs`in e?e.updatedAtMs:0)||0)}function I(e){return m(e.expiresAtMs??e.policyHint?.expiresAtMs)}function L(e){switch(e.state){case`ready`:return 5;case`restorable`:return 4;case`deferred`:return 3;case`expired`:case`exhausted`:return 2;case`missing`:return 1}}function R(e){return!A(e)||e.curve===`ecdsa`?0:e.source===`durable_sealed_record`?1:0}function z(e,t){return L(e)-L(t)||R(e)-R(t)||F(e)-F(t)}function me(e,t){return z(e,t)}function he(e,t){return L(e)-L(t)||R(e)-R(t)||F(e)-F(t)}function B(e){let t=d(e.auth),n=String(e.walletId||``).trim(),r=String(e.nearAccountId||``).trim(),i=String(e.nearEd25519SigningKeyId||``).trim(),a=String(e.signerSlot||``).trim(),o=w(e.materialActivation);return!t||!n||!r||!i||!a||!o?null:{walletId:n,authKey:t,nearAccountId:r,nearEd25519SigningKeyId:i,signerSlot:a,materialActivationKey:o}}function V(e){return[e.walletId,e.authKey,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,e.materialActivationKey].map(e=>encodeURIComponent(e)).join(`|`)}function ge(e){if(!A(e)||e.curve!==`ed25519`)return null;let t=B(e);return t?{groupKey:t,lane:e}:null}function H(e,t){return me(t,e)}function U(e,t){return e>t?1:t>e?-1:0}function W(e,t){let n=e.localeCompare(t);return n>0?1:n<0?-1:0}function G(e){for(let t of e)if(t!==0)return t;return 0}function _e(e){return[]}function ve(e){return!0}function ye(e){return I(e.lane)}function be(){return`exact_target`}function xe(e,t){return G([U(L(e.lane),L(t.lane)),U(R(e.lane),R(t.lane)),W(Se(e.lane),Se(t.lane))])}function Se(e){return[e.thresholdSessionId,e.authorizationState===`authorized`?e.authorization.operationCredential.walletSessionId:``,e.authorizationState===`authorized`?e.authorization.session.quotaId:``,e.source||`durable_sealed_record`].map(e=>String(e)).join(`|`)}const Ce={groupKey:we,groupKeyString:V,groupConflicts:_e,supersession:{isOperationUsable:ve,generation:ye,exactness:be,tieBreak:xe}};function we(e){return e.groupKey}function Te(e){let t=new Map;for(let n of e){let e=V(n.groupKey);t.set(e,[...t.get(e)||[],n])}return t}function Ee(e,t){let n=h(e,Ce);switch(n.kind){case`selected`:return[n.selectedFact.lane];case`no_current_lane`:return[];case`conflicting_key_material`:return t.push({curve:`ed25519`,source:`canonical_lane_inventory`,reason:`conflicting_key_material`,message:`Ed25519 canonical lane inventory has conflicting material facts`}),[];case`ambiguous_material`:return t.push({curve:`ed25519`,source:`canonical_lane_inventory`,reason:`ambiguous_material`,message:`Ed25519 canonical lane inventory has incomparable usable records`}),[];default:return n}}function De(e,t){let n=e.map(ge).filter(e=>e!==null),r=[];for(let e of Te(n).values())r.push(...Ee(e,t));return r.sort(H)}function Oe(e){if(!A(e)||e.curve!==`ed25519`)return null;let t=String(e.thresholdSessionId||``).trim();return e.authorizationState!==`authorized`||!t?null:`${e.authorization.operationCredential.walletSessionId}:${e.authorization.session.quotaId}:${t}`}function ke(e){if(!A(e.primaryLane)||e.primaryLane.curve!==`ed25519`||D(e.primaryLane)!==`passkey`)return e.primaryLane;let t=Oe(e.primaryLane);return t&&e.candidates.find(e=>A(e)&&e.curve===`ed25519`&&D(e)===`email_otp`&&Oe(e)===t)||e.primaryLane}function Ae(){try{return globalThis.localStorage?.getItem(`seams:debug:signing-session`)===`1`}catch{return!1}}function K(e){return e?A(e)?{present:!0,authMethod:u(e.auth),curve:e.curve,keyHandle:e.publicFacts.keyHandle,walletId:e.key.walletId,chainTarget:e.chainTarget,targetKey:r(e.chainTarget),state:e.state,source:e.source,evmFamilyKeyFingerprint:ue(e),ecdsaThresholdKeyId:e.key.ecdsaThresholdKeyId,participantIds:e.publicFacts.participantIds,thresholdOwnerAddress:e.publicFacts.thresholdOwnerAddress,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs}:{present:!0,curve:e.curve,chainTarget:e.chainTarget,state:e.state}:{present:!1}}function je(e){switch(e.source){case`canonical_capability`:return`canonical_capability`;case`active_wallet_authority`:return`active_wallet_authority`;default:return e}}function Me(e){let t=d(e.auth);return{walletId:String(e.key.walletId),authKey:t,materialActivationKey:w(e.materialActivation),ecdsaThresholdKeyId:String(e.key.ecdsaThresholdKeyId),signingRootId:String(e.key.signingRootId),signingRootVersion:String(e.key.signingRootVersion||`default`)}}function Ne(e){return[e.walletId,e.authKey,e.materialActivationKey,e.ecdsaThresholdKeyId,e.signingRootId,e.signingRootVersion].map(e=>encodeURIComponent(e)).join(`|`)}function Pe(e){let t=Me(e);return t?{source:je(e),groupKey:t,chainTargetKey:r(e.chainTarget),lane:e}:null}function Fe(e){let t=d(e.auth);return[String(e.key.walletId),t,w(e.materialActivation),String(e.key.signingRootId),String(e.key.signingRootVersion||`default`)].map(e=>encodeURIComponent(e)).join(`|`)}function q(e,t){return[...new Set(e.map(e=>t(e.lane)).filter(Boolean))].sort()}function Ie(e){return[{field:`ecdsaThresholdKeyId`,values:q(e.facts,e=>String(e.key.ecdsaThresholdKeyId||``))},{field:`thresholdOwnerAddress`,values:q(e.facts,e=>String(e.publicFacts.thresholdOwnerAddress||``).toLowerCase())},{field:`keyHandle`,values:q(e.facts,e=>String(e.publicFacts.keyHandle||``))},{field:`publicKeyB64u`,values:q(e.facts,e=>String(e.publicFacts.publicKeyB64u||``))},{field:`participantIds`,values:q(e.facts,e=>e.publicFacts.participantIds.map(e=>Number(e)).join(`,`))}].filter(e=>e.values.length>1).map(t=>({groupKey:e.key,field:t.field,values:t.values}))}function Le(e){let t=new Map;for(let n of e){let e=Fe(n.lane);e&&t.set(e,[...t.get(e)||[],n])}let n=new Map;for(let[e,r]of t){let t=r[0];if(!t)continue;let i=Ie({key:t.groupKey,facts:r});i.length&&n.set(e,i)}return n}function Re(e){let t=Fe(e.fact.lane);return t&&e.conflictsByFamilyGroup.get(t)||[]}function ze(e){return e.filter(e=>A(e)&&e.curve===`ecdsa`).map(Pe).filter(e=>e!==null)}function Be(e){return e.source===`active_wallet_authority`?2:1}function Ve(e){return e.groupKey}function He(e){let t=e[0];return t?Ie({key:t.groupKey,facts:e}):[]}function Ue(e){return e.lane.source===`active_wallet_authority`?!0:e.lane.state!==`deferred`||!e.lane.authorization}function We(e){return I(e.lane)}function Ge(e){return`exact_target`}function J(e){return[w(e.materialActivation),e.source,r(e.chainTarget)].map(e=>String(e)).join(`|`)}function Ke(e,t){return G([U(L(e.lane),L(t.lane)),U(Be(e.lane),Be(t.lane)),W(J(e.lane),J(t.lane))])}const qe={groupKey:Ve,groupKeyString:Ne,groupConflicts:He,supersession:{isOperationUsable:Ue,generation:We,exactness:Ge,tieBreak:Ke}};function Je(e){let t=new Map;for(let n of e)t.set(Ne(n.groupKey),n.groupKey);return[...t.values()]}function Ye(e){let t=h(e,qe);switch(t.kind){case`selected`:return{kind:`selected`,selectedFact:t.selectedFact,supersededFacts:t.supersededFacts};case`no_current_lane`:return{kind:`no_current_lane`,unusableFacts:t.unusableFacts};case`conflicting_key_material`:return{kind:`conflicting_key_material`,conflicts:t.conflicts};case`ambiguous_material`:return{kind:`ambiguous_material`,candidates:Je(t.candidates),candidateFacts:t.candidates};default:return t}}function Xe(e){return A(e)?J(e):null}function Ze(e){let t={},n={},i=Object.fromEntries(Object.entries(e.candidatesByTarget).map(([e,t])=>[e,Qe(t,Xe)])),a=Le(Object.values(i).flatMap(ze));for(let o of e.targets){let s=r(o),c=ze(i[s]||[]),l=c.flatMap(e=>Re({fact:e,conflictsByFamilyGroup:a}));if(l.length){e.invalidLanes.push({curve:`ecdsa`,source:`canonical_lane_inventory`,reason:`conflicting_key_material`,targetKey:s,groupKey:l[0]?.groupKey,conflicts:l}),t[s]=[],n[s]=N({chainTarget:o});continue}let u=Ye(c);switch(u.kind){case`selected`:t[s]=[u.selectedFact.lane],n[s]=u.selectedFact.lane;break;case`no_current_lane`:t[s]=[],n[s]=N({chainTarget:o});break;case`conflicting_key_material`:e.invalidLanes.push({curve:`ecdsa`,source:`canonical_lane_inventory`,reason:`conflicting_key_material`,targetKey:s,groupKey:u.conflicts[0]?.groupKey,conflicts:u.conflicts}),t[s]=[],n[s]=N({chainTarget:o});break;case`ambiguous_material`:e.invalidLanes.push({curve:`ecdsa`,source:`canonical_lane_inventory`,reason:`ambiguous_material`,targetKey:s}),t[s]=[],n[s]=N({chainTarget:o});break}}return{lanesByTarget:n,candidatesByTarget:t}}function Qe(e,t,n=z){let r=new Map,i=[];for(let n of e){let e=t(n);if(!e){i.push(n);continue}r.set(e,[...r.get(e)||[],n])}return[...[...r.values()].map(e=>[...e].sort((e,t)=>n(t,e))[0]),...i]}function $e(e){let t=new Set(e.filter(e=>A(e)&&e.curve===`ed25519`&&e.source===`durable_sealed_record`&&(e.state===`ready`||e.state===`restorable`)).map(B).filter(e=>e!==null).map(V));return t.size?e.filter(e=>{if(!A(e)||e.curve!==`ed25519`||e.source!==`public_capability_reference`)return!0;let n=B(e);return!n||!t.has(V(n))}):[...e]}async function et(e,t){return e.state===`missing`||d(e.auth)!==d(t.auth)||!await rt(e,t)?!1:t.auth.kind===`passkey`?`keyFamily`in t&&t.keyFamily===`ecdsa`?!1:e.signerSlot===t.signerSlot:!0}function tt(e,t){return e.state===`missing`||d(e.auth)!==d(t.auth)?!1:nt(e,t)}function nt(e,t){let n=t.auth.kind===`passkey`?void 0:t.ownerAuthority;if(!n)return!0;if(e.curve===`ecdsa`&&e.source===`active_wallet_authority`)return e.runtime.factorAuthorityRef.walletAuthMethodId===n.walletAuthMethodId&&String(e.runtime.factorAuthorityRef.authorityDigest)===String(n.authorityDigest);if(e.curve===`ecdsa`&&e.source===`canonical_capability`){let t=e.capability.manifest.signer.authority;return t.walletAuthMethodId===n.walletAuthMethodId&&String(t.authorityDigest)===String(n.authorityDigest)}return!1}async function rt(e,t){let n=t.auth.kind===`passkey`?void 0:t.ownerAuthority;if(!n)return!0;if(e.state===`missing`||e.curve!==`ed25519`)return!1;if(e.authorizationState===`authorization_required`)return!0;try{let t=await a({authority:e.authorization.selectedFactorAuthority});return t.walletId===e.walletId&&t.walletAuthMethodId===n.walletAuthMethodId&&t.authorityDigest===n.authorityDigest}catch{return!1}}async function it(e,t){let n=[];for(let r of e)await et(r,t)&&n.push(r);return n}async function at(e,t){let i=n(e.walletId),a=new Map;for(let t of e.ecdsaChainTargets)a.set(r(t),t);let o=[...a.values()],[s,c,l,d]=await Promise.all([t.listSealedRecordsForWallet({walletId:i,filter:{...e.authMethod?{authMethod:e.authMethod}:{},curve:`ed25519`}}),t.listPublicCapabilityReferences?.()??[],t.readActiveWalletSessionAuthorization?.(i)??{kind:`missing`},o.length>0&&t.listCanonicalEcdsaLanesForWallet?t.listCanonicalEcdsaLanesForWallet({walletId:i}):[]]),f=l.kind===`found`?l.authorization:null,p=[...o],m={},h={},g={};for(let e of p){let t=r(e);m[t]=N({chainTarget:e}),h[t]=[],g[t]=0}let _=[],v=0,y=Ae(),b=[],x=[];for(let t of s){let n=te(t,f,e.ownerScope);if(!n)continue;_.push(n);let r=F(n);v=Math.max(v,r)}for(let n of c){if(String(n.walletId)!==String(i))continue;let r=l.kind===`exhausted`||l.kind===`expired`;if(!t.isPublicCapabilityActive?.(n)&&!r)continue;let a=re(n,f,e.ownerScope);a&&(e.authMethod&&u(a.auth)!==e.authMethod||_.push(a))}for(let t of d){let n=u(t.auth);if(e.authMethod&&n!==e.authMethod||String(t.key.walletId)!==String(i))continue;let o=r(t.chainTarget);if(!a.has(o))continue;h[o]||=[],h[o].push(t);let s=F(t);v=Math.max(v,s),b.push({result:`accepted`,targetKey:o,lane:K(t)})}let S=o.length>0&&t.listActiveWalletAuthorityEcdsaLanesForWallet?await t.listActiveWalletAuthorityEcdsaLanesForWallet({walletId:i,chainTargets:o}):[];for(let t of S){let n=u(t.auth);if(e.authMethod&&n!==e.authMethod||String(t.key.walletId)!==String(i))continue;let o=r(t.chainTarget);a.has(o)&&(h[o]||=[],h[o].push(t),b.push({result:`accepted`,targetKey:o,lane:K(t)}))}let C=e.ownerScope,w=C?await it(_,C):_;if(C)for(let e of Object.keys(h))h[e]=(h[e]||[]).filter(e=>tt(e,C));let T=De(Qe($e(w),M,he).sort(H),x),ee=ke({primaryLane:T[0]||pe(),candidates:T}),E=Ze({targets:p,candidatesByTarget:Ze({targets:p,candidatesByTarget:h,invalidLanes:x}).candidatesByTarget,invalidLanes:x}),D={walletId:i,generation:v,ecdsa:{targets:p,lanesByTarget:E.lanesByTarget,candidatesByTarget:E.candidatesByTarget},lanes:{ed25519:{near:ee}},candidates:{ed25519:{near:T}},diagnostics:{invalidLanes:x}},O=p.map(e=>{let t=r(e),n=D.ecdsa.candidatesByTarget[t]||[],i=D.ecdsa.lanesByTarget[t],a=i?.state||`missing`;return n.length>0&&a!==`missing`?null:{chainTarget:e,targetKey:t,candidateCount:n.length,selectedLane:K(i)}}).filter(e=>!!e),k={walletId:i,authMethod:e.authMethod||`any`,requestedTargets:p.map(e=>({chainTarget:e,targetKey:r(e)})),sealedRecordCount:0,runtimeRecordCount:d.length,durableDiscovery:[],runtimeDiscovery:b,resultSelectedLanesByTarget:Object.fromEntries(Object.entries(D.ecdsa.lanesByTarget).map(([e,t])=>[e,K(t)])),resultCandidatesByTarget:Object.fromEntries(Object.entries(D.ecdsa.candidatesByTarget).map(([e,t])=>[e,t.map(e=>K(e))]))};if(y&&O.length>0)try{console.warn(`[SigningLanes][available][ecdsa][missing-candidates]`,JSON.stringify({...k,missingEcdsaTargets:O}))}catch{}if(y)try{console.info(`[SigningLanes][available][ecdsa]`,JSON.stringify(k))}catch{}return D}function Y(t,n){return e(t,{fallback:n,min:1})}function X(e,t){let n=Error(`[SigningEngine] ${t}`);return n.code=e,n}function ot(e,t){let n=e.get(t);if(n)return n;let r={running:!1,items:[]};return e.set(t,r),r}function st(e){e.timeoutHandle&&=(clearTimeout(e.timeoutHandle),null)}async function ct(e,t){let n=e.get(t);if(!(!n||n.running)){n.running=!0;try{for(;n.items.length>0;){let e=n.items.shift();if(e&&!e.isSettled()){if(st(e),e.shouldAbort?.()){e.reject(e.makeCancelledError(`cancelled`));continue}if(Date.now()-e.enqueuedAtMs>e.timeoutMs){e.reject(e.makeTimeoutError(e.timeoutMs));continue}try{await e.run()}catch(t){e.reject(t)}}}}finally{n.running=!1,n.items.length===0&&e.get(t)===n?e.delete(t):n.items.length>0&&ct(e,t)}}}function lt(e){for(let t of e.values()){for(let e of t.items)st(e),e.reject(e.makeCancelledError(`queue_cleared`));t.items.length=0}e.clear()}function ut(e){return[`material`,encodeURIComponent(String(e.materialActivation.materialOwner)),encodeURIComponent(String(e.materialActivation.capability)),encodeURIComponent(String(e.materialActivation.activationId))].join(`:`)}async function dt(e){let{labels:t,owner:n}=e,r=String(e.queueKey||``).trim();if(!r)throw Error(`[SigningEngine] ${t.queue} requires non-empty queueKey`);if(!e.enabled)return await e.task();let i=Y(e.maxQueueLength,8),a=Y(e.queueTimeoutMs,45e3),o=ot(e.queueByKey,r);if(o.items.length+(o.running?1:0)>=i)throw X(`commit_queue_overflow`,`${t.queue} overflow for ${n} (queueKey=${r}, max=${i})`);return await new Promise((i,s)=>{let c=null,l=!1,u=()=>{c&&=(clearTimeout(c),null)},d=e=>{l||(l=!0,u(),s(e))},f=e=>{l||(l=!0,u(),i(e))},p=e=>X(`cancelled`,`${t.queuedOperation} cancelled for ${n} (queueKey=${r}${e===`queue_cleared`?`, queue_cleared`:``})`),m=e=>X(`commit_queue_timeout`,`${t.queue} timeout for ${n} (queueKey=${r}, waited>${e}ms before start)`),h={enqueuedAtMs:Date.now(),timeoutMs:a,shouldAbort:e.shouldAbort,timeoutHandle:null,isSettled:()=>l,reject:d,makeCancelledError:p,makeTimeoutError:m,run:async()=>{if(e.shouldAbort?.())throw p(`cancelled`);f(await e.task())}};c=setTimeout(()=>{if(h.isSettled())return;let t=o.items.indexOf(h);t>=0&&o.items.splice(t,1),d(m(a)),!o.running&&o.items.length===0&&e.queueByKey.get(r)===o&&e.queueByKey.delete(r)},a),h.timeoutHandle=c,o.items.push(h),ct(e.queueByKey,r)})}function Z(e){let t={walletId:p(e.laneIdentity),authMethod:u(e.laneIdentity.auth),laneIdentity:e.laneIdentity};return e.kind===`ecdsa`?{...t,walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId}:{...t,walletSessionId:e.laneIdentity.walletSessionId,quotaId:e.laneIdentity.quotaId}}function Q(e){return{kind:`invalid`,...Z(e.source)}}function $(e){let t=Number(e);return!Number.isSafeInteger(t)||t<0?null:t}function ft(e){let t=$(e.expiresAtMs),n=$(e.detectedAtMs);if(t===null||t===0)throw Error(`Authoritative expired Wallet Session expiresAtMs is invalid`);if(n===null||n===0)throw Error(`Authoritative expired Wallet Session detectedAtMs is invalid`);if(t>n)throw Error(`Authoritative expired Wallet Session timeline is invalid`);return{kind:`expired`,...Z(e.source),expiresAtMs:t,detectedAtMs:n}}function pt(e){let t=$(e.observation.expiresAtMs);if(t===null||t===0)return Q({source:e.observation.source});let n=Z(e.observation.source);return t<=e.nowMs?{kind:`expired`,...n,expiresAtMs:t,detectedAtMs:e.nowMs}:{kind:`active`,...n,expiresAtMs:t}}function mt(e){let t=$(e.nowMs);if(t===null)return Q({source:e.observation.source});switch(e.observation.kind){case`found`:return pt({observation:e.observation,nowMs:t});case`missing`:return{kind:`missing`,...Z(e.observation.source)};case`unavailable`:return{kind:`unavailable`,...Z(e.observation.source)};case`invalid`:return Q({source:e.observation.source});default:return e.observation}}export{C as _,dt as a,D as c,le as d,ce as f,at as g,A as h,ut as i,fe as l,se as m,ft as n,T as o,M as p,lt as r,E as s,mt as t,de as u,w as v};
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-dVx5-UGu.js";import{v as t}from"./digests-BIaE0DMd.js";import{i as n}from"./chains-B72I4PDH.js";import{r}from"./transactionReviewAdmission-Cf_qUZJt.js";import{t as i}from"./surface-measurement-reporter-DXsvq401.js";import{a,i as o,o as s,r as c,s as l}from"./csp-stylesheet-DUSqfXvZ.js";import{t as u}from"./SeamsWordmark-DwvPx2UA.js";import{a as d,i as f,r as p,t as m}from"./actions-DrtSTGus.js";import{i as h,r as g}from"./intentDigest-HvRsBQ1z.js";import{t as _}from"./promptText-bcKcsSka.js";import{a as v}from"./transaction-activity-DCzHGg3b.js";import{a as y,c as b,i as x,n as S,o as C,r as w,s as T,t as ee}from"./appearance-token-vars-01eH9pgA.js";import{i as E,n as te,r as ne,t as re}from"./ConfirmationDrawer-MJoE0AAo.js";import{n as ie,t as ae}from"./appearance-DL7c6bML.js";let oe=!1;function se(e=!0){oe=!!e}function ce(){return oe}function le(e){if(!e)return``;if(typeof e==`string`)return e;try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,2)}catch{return String(e)}}function D(e){if(!e||e===`0`)return`0 NEAR`;try{let t=BigInt(e),n=BigInt(`1000000000000000000000000`),r=t/n,i=t%n;if(i===BigInt(0))return`${r.toString()} NEAR`;let a=i.toString().padStart(24,`0`).slice(0,5);return a=a.replace(/0+$/g,``),a.length===0?`${r.toString()} NEAR`:`${r.toString()}.${a} NEAR`}catch{return e}}function ue(e){if(!e)return``;try{return`${BigInt(e)/BigInt(`1000000000000`)} Tgas`}catch{return e}}function O(e,t={}){if(!e||typeof e!=`string`)return``;let{prefix:n=12,suffix:r=6}=t;return e.length<=n+r+3?e:`${e.slice(0,n)}...${e.slice(-r)}`}function k(e){return e?e instanceof Uint8Array?`${e.byteLength} bytes`:Array.isArray(e)||typeof e==`string`?`${e.length} bytes`:`unknown`:`0 bytes`}function de(e){if(!e)return;let t=String(e.decoded||``),n=String(e.raw||``);if(!(!t||!n)&&t!==n)return{decoded:t,raw:n,defaultMode:e.defaultMode===`raw`?`raw`:`decoded`}}function fe(e,t){if(!/Value \(wei\)$/i.test(e.trim()))return!1;let n=t.trim();if(!n)return!1;if(n===`0`||/^0x0+$/i.test(n))return!0;try{return BigInt(n)===0n}catch{return!1}}function pe(e,t){return!Array.isArray(t)||t.length===0?[]:t.flatMap((t,n)=>{let r=String(t.label||``).trim(),i=String(t.value||``),a=t.renderAs||`inline`;if(fe(r,i))return[];if(a===`file-content`){let a=de(t.contentVariants),o=a?.defaultMode===`raw`?a.raw:a?.decoded||i;return[{id:`${e}-field-${n}`,label:r?`${r}:`:``,fieldLabel:r?`${r}:`:void 0,type:`file`,open:!1,content:o,...a?{contentVariants:a}:{},copyValue:typeof t.copyValue==`string`?t.copyValue:void 0,hideLabel:!!t.hideLabel,hideChevron:typeof t.hideChevron==`boolean`?t.hideChevron:!0}]}return[{id:`${e}-field-${n}`,label:r?`${r}: ${i}`:i,fieldLabel:r?`${r}:`:void 0,type:`file`,open:!1,copyValue:typeof t.copyValue==`string`?t.copyValue:void 0}]})}const me=({operation:e,depth:t,path:n,renderChild:r})=>{let i=String(e.id||``).trim()||`op-${n}`,a=(()=>{let t=String(e.to||``).trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:void 0})(),o=String(e.description||``).trim(),s=Array.isArray(e.children)?e.children.map((e,i)=>r(e,t+1,`${n}.${i}`)):[],c=pe(i,e.fields),l=o?[{id:`${i}-description`,label:o,type:`file`,open:!1}]:[];if(e.kind===`raw.fallback`){let t=String(e.raw||``).trim();t&&l.push({id:`${i}-raw`,label:`Raw payload`,type:`file`,open:!1,content:t})}let u=[...l,...c,...s];return u.length===0?{id:i,label:String(e.label||e.kind),type:`file`,open:!1,contractAddress:a}:{id:i,label:String(e.label||e.kind),type:`folder`,open:t<1,contractAddress:a,children:u}};function he(e){switch(e){case`near`:return`NEAR`;case`evm`:return`EVM`;case`tempo`:return`Tempo`;default:return`Unknown`}}function ge(e){return!Array.isArray(e)||e.length===0?[]:[{id:`warnings-root`,label:`Warnings`,type:`folder`,open:!0,children:e.map((e,t)=>({id:`warning-${t}`,label:`[${String(e.severity||`warning`).toUpperCase()}] ${String(e.message||``)}`,type:`file`,open:!1}))}]}function _e(e,t,n){return me({operation:e,depth:t,path:n,renderChild:(e,t,n)=>_e(e,t,n)})}function ve(e){let t=Array.isArray(e.children)?e.children.map(e=>ve(e)):void 0;return e.type===`folder`?{...e,hideChevron:!0,children:t}:t?{...e,children:t}:e}function ye(e,t){let n=Array.isArray(e.children)?e.children.map(e=>ye(e,t)):void 0;return{...e,chain:t,...n?{children:n}:{}}}function be(e){let t=e.chain===`evm`||e.chain===`tempo`,n=(Array.isArray(e.operations)?e.operations:[]).map((e,t)=>_e(e,0,String(t))).map(t=>ye(t,e.chain)).map(e=>t?ve(e):e),r=[...ge(e.warnings).map(t=>ye(t,e.chain)).map(e=>t?ve(e):e),...n];r.length===0&&r.push({id:`no-operations`,label:`No operations`,type:`file`,open:!1});let i=he(e.chain);return{id:`display-root`,label:String(e.title||``).trim()||`${i} Transaction`,type:`folder`,open:!0,children:r}}function xe(e,n){let r;switch(e.type){case`FunctionCall`:r=[{id:`a${n}-args`,label:`using args:`,type:`file`,open:!1,hideChevron:!0,hideLabel:!0,content:le(e.args)}];break;case`Transfer`:r=[];break;case`CreateAccount`:r=[];break;case`DeployContract`:{let t=k(e.code);r=[{id:`a${n}-code-size`,label:`WASM contract code size: ${t}`,type:`file`,open:!1}];break}case`DeployGlobalContract`:{let t=e.code,i=e.deployMode,a=k(t);r=[{id:`a${n}-deploy-mode`,label:`mode: ${String(i||``)}`,type:`file`,open:!1},{id:`a${n}-code-size`,label:`WASM global contract code size: ${a}`,type:`file`,open:!1}];break}case`UseGlobalContract`:{let t=e.accountId,i=e.codeHash,a;a=t?`by account: ${String(t)}`:i?`by hash: ${O(String(i),{prefix:10,suffix:6})}`:`by global contract identifier`,r=[{id:`a${n}-identifier`,label:a,type:`file`,open:!1}];break}case`Stake`:r=[{id:`a${n}-publicKey`,label:`validator: ${O(e.publicKey)}`,type:`file`,open:!0,copyValue:e.publicKey}];break;case`AddKey`:{let i=e.accessKey,a=``;try{a=(t(i)?JSON.parse(i):i).permission===`FullAccess`?`Full Access`:`Function Call`}catch{a=`Unknown`}r=[{id:`a${n}-publicKey`,label:`key: ${O(e.publicKey)}`,open:!1,type:`file`,copyValue:e.publicKey},{id:`a${n}-permissions`,label:`permissions: ${a}`,open:!1,type:`file`}];break}case`DeleteKey`:r=[{id:`a${n}-publicKey`,label:`key: ${O(e.publicKey)}`,open:!1,type:`file`,copyValue:e.publicKey}];break;case`DeleteAccount`:r=[{id:`a${n}-beneficiaryId`,label:`sending balance to: ${e.beneficiaryId}`,open:!1,type:`file`}];break;default:return Se(e)}return{id:`action-${n}`,label:``,type:`folder`,open:!1,hideChevron:!0,action:e,actionIndex:n,children:r}}function Se(e){throw Error(`Unsupported NEAR action: ${String(e)}`)}function Ce(e,t,n){let r=e.actions.map((e,t)=>xe(e,t));return{id:`tx-${t}`,label:``,type:`folder`,open:!0,hideChevron:!0,transaction:e,transactionIndex:t,totalTransactions:n,children:[...r]}}function we(e){let t=e.length,n=e.map((e,n)=>Ce(e,n,t));return{id:`txs-root`,label:t>1?`Transactions`:`Transaction`,type:`folder`,open:!0,children:n}}function Te(e){let t=e.abiDecodeHint;if(t&&Array.isArray(t.abi)&&t.abi.length>0){let e=String(t.dataHex||``).trim();if(e&&e!==`0x`)return!0}return(Array.isArray(e.children)?e.children:[]).some(Te)}function Ee(e){return(Array.isArray(e.operations)?e.operations:[]).some(Te)}function A(e){let t=Array.isArray(e.txSigningRequests)?e.txSigningRequests:[];if(t.length>0)return we(p(t));let n=e.model;if(!n)return null;let r=Array.isArray(n.operations)?n.operations:[],i=Array.isArray(n.warnings)?n.warnings:[];return r.length>0||i.length>0?be(n):null}const De=/^NEAR account ([^\s]+) needs funding before signing\.$/;function Oe(e){let t=String(e||``).trim();return t.length<=8?t:`${t.slice(0,4)}...${t.slice(-4)}`}function ke(e){let t=String(e||``).trim();return t?`NEAR account ${t} needs funding before signing.`:`NEAR account needs funding before signing.`}function Ae(e){let t=String(e||``).trim(),n=De.exec(t);if(!n)return null;let r=String(n[1]||``).trim();return r?{accountId:r,shortAccountId:Oe(r)}:null}function je(e){return String(e||``).trim()===`Topping up account...`}function Me(e){let t=Oe(e);return t?`Funding NEAR account ${t}...`:`Funding NEAR account...`}function Ne(e){let t=String(e||``).trim();return t.startsWith(`Funding NEAR account`)&&t.endsWith(`...`)}function Pe(e){return je(e)||Ne(e)}function Fe(e){let t=e.trim();if(!t)return{kind:`empty`};if(Pe(t))return{kind:`status`,text:t};let n=Ae(t);return n?{kind:`funding`,accountId:n.accountId,shortAccountId:n.shortAccountId}:{kind:`text`,text:t}}function Ie(e){let t=e.presentation,n=t.errorMessage??``,r=t.cancelText??`Cancel`,i=t.securityContext?.passkeyRegistration;if(i?.kind===`passkey_registration_confirm_display_v1`)return{ok:!0,model:{appearance:e.appearance,content:{kind:`registration`,registration:{display:i,heading:t.title?.trim()||`Create your passkey`,body:t.body?.trim()||`Use Touch ID or your device passkey to create credentials for this account.`,cancelText:r,errorMessage:n,decision:t.loading?{kind:`creating`}:{kind:`ready`,onConfirm:e.callbacks.confirm},onCancel:e.callbacks.cancel}}}};let a;switch(t.signingAuthMode){case`emailOtp`:{let r=t.emailOtpPrompt,i=r?.challengeId.trim();if(!r||!i)return{ok:!1,error:`missing_email_challenge`};a={kind:`email`,email:{prompt:{challengeId:i,title:r.title,body:r.body,helperText:r.helperText,emailHint:r.emailHint,resendDebounceMs:r.resendDebounceMs,onResend:r.onResend},verification:Le(t.loading===!0,n),onSubmit:e.callbacks.submitEmail}};break}case`warmSession`:a={kind:`session`};break;case`webauthn`:case void 0:a={kind:`passkey`};break;default:return He(t.signingAuthMode)}let o=Fe(t.body??``);return{ok:!0,model:{appearance:e.appearance,content:{kind:`transaction`,capture:t.authMethodCapture??null,review:{model:t.model??null,tree:e.tree},header:{heading:Re(t),website:ze(t.securityContext?.rpId?.trim()??``),chainDetails:Be(t,t.loading===!0||o.kind===`status`),errorMessage:n},body:o,prompt:a,transaction:{tree:e.tree,theme:e.appearance.theme.mode,explorers:{near:t.nearExplorerUrl||`https://testnet.nearblocks.io`,tempo:t.tempoExplorerUrl,evm:t.evmExplorerUrl},decision:t.loading||t.preparing?{kind:`preparing`}:{kind:`ready`,onConfirm:e.callbacks.confirm},confirmText:t.signingAuthMode===`emailOtp`?`Confirm Code`:t.confirmText??`Confirm`,cancelText:r,errorMessage:n,onCancel:e.callbacks.cancel,onBack:t.onBack,authMethodApprovalMessage:t.authMethodApprovalMessage}}}}}function Le(e,t){return e?{kind:`pending`}:t?{kind:`rejected`,message:t}:{kind:`ready`}}function Re(e){let t=(e.model?.operations.length??0)===0?`Register with Passkey`:`Confirm with Passkey`;switch(e.signingAuthMode){case`emailOtp`:return e.emailOtpPrompt?.title?.trim()||`Enter email code to sign`;case`warmSession`:return`Review transaction`;case`webauthn`:return t;case void 0:return e.title?.trim()||t;default:return He(e.signingAuthMode)}}function ze(e){return e?{kind:`ready`,text:e}:{kind:`loading`}}function Be(e,t){let n=e.model;if(n?.chainId)return{kind:`ready`,text:`${Ve(n.chain)} | ChainID: ${n.chainId}`};let r=String(e.securityContext?.blockHeight||``).trim();return r?{kind:`ready`,text:`block ${r}`}:t?{kind:`loading`}:{kind:`ready`,text:`block`}}function Ve(e){switch(e){case`near`:return`NEAR`;case`evm`:return`EVM`;case`tempo`:return`Tempo`;case`unknown`:return`Unknown`;default:return He(e)}}function He(e){throw Error(`Unexpected confirmation presentation: ${String(e)}`)}const j=`seams-surface-resize-begin`;function Ue(e,t){return e.dispatchEvent(new CustomEvent(j,{bubbles:!0,composed:!0,detail:t}))}function We(e,t,n){let r=t;return e.addEventListener(j,r,n),()=>e.removeEventListener(j,r,n)}const Ge=`data-seams-confirm-surface`,M=`seams-confirm-surface-pinned`,N=`seams-confirm-surface-pinned-root`,P=`seams-surface-height-driven`,F=`--seams-surface-height-driven-target`;function Ke(e,t){let{fromCssPx:n,toCssPx:r}=t;if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let i=r-n;if(Math.abs(i)<1)return!1;let a=Math.min(n,r),o=Math.max(n,r),s=null,c=!1,l=null,u=e=>{if(c)return;let r=n+(Number.isFinite(e)?Math.min(Math.max(e,0),1):0)*i;t.setHeightCssPx(Math.min(Math.max(r,a),o))},d=()=>{c||(c=!0,l!==null&&window.clearTimeout(l),t.finish())},f=()=>s||c?null:(t.onClaimed?.(),u(0),l=window.setTimeout(()=>{u(1),d()},1500),s={setProgress:u,finish:d},s);return Ue(e,{...t.reason?{reason:t.reason}:{},deltaCssPx:i,claim:f}),s!==null}function qe(e){let t=null,n=null,r=()=>{let e=n;n=null,e&&e.classList.remove(P)};return{capture(){let n=e.element();t=n?n.getBoundingClientRect().height:null},commit(){let i=t;t=null;let a=e.element();!a||i===null||document.documentElement.classList.contains(N)||a.parentElement?.closest(`.${P}`)||(n=a,a.classList.add(P),e.setHeightCssPx(i),Promise.resolve(e.settled?.()).then(()=>new Promise(e=>requestAnimationFrame(()=>e()))).then(()=>{if(n!==a)return;if(document.documentElement.classList.contains(N)){r();return}a.classList.remove(P);let t=a.getBoundingClientRect().height;a.classList.add(P),!I({...e.reason?{reason:e.reason}:{},element:a,fromCssPx:i,toCssPx:t,setHeightCssPx:t=>e.setHeightCssPx(t),onSettled:()=>{n=null}})&&(r(),Je(a,i,t))}))},dispose:r}}function Je(e,t,n){Math.abs(n-t)<1||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches||e.animate([{height:`${t}px`},{height:`${n}px`}],{duration:200,easing:`cubic-bezier(0.32, 0.72, 0, 1)`})}function I(e){let{element:t,fromCssPx:n,toCssPx:r}=e;if(!Number.isFinite(n)||!Number.isFinite(r)||Math.abs(r-n)<1)return!1;let i=e.drivenClasses??[P],a=i.filter(e=>!t.classList.contains(e));t.classList.add(...a),e.setHeightCssPx(n);let o=Ke(t,{...e.reason?{reason:e.reason}:{},fromCssPx:n,toCssPx:r,setHeightCssPx:e.setHeightCssPx,finish:()=>{t.classList.remove(...i),e.onSettled?.()}});return o||t.classList.remove(...a),o}let Ye=null;const Xe={blipFrames:0,trace(e=2e3){return new Promise(t=>{let n=[],r=performance.now(),i=()=>{let a=Ye,o=a?.classList.contains(M)?`*`:``;n.push(`${Math.round(performance.now()-r)}: box=${document.documentElement.clientHeight} content=${a?Math.round(a.getBoundingClientRect().height):`-`}${o}`),performance.now()-r<e?requestAnimationFrame(i):t(n)};requestAnimationFrame(i)})}};function Ze(e){Ye=e;try{window.__seamsSurfaceMotion=Xe}catch{}}function Qe(){let e=document.documentElement?.clientHeight??0;return e>0?e:window.innerHeight}function $e(e,t,n){return Math.min(Math.max(e,t),n)}function et(e){return e.getAttribute(Ge)===`wallet-iframe`}function tt(e){if(typeof CSSStyleSheet!=`function`||!(`adoptedStyleSheets`in document))return null;let t=null,n=()=>{e.classList.remove(M),document.documentElement.classList.remove(N)};return{set(n){try{t||=new CSSStyleSheet,t.replaceSync(`.${M}{height:${Math.max(0,Math.round(n))}px}.${N}{overflow:hidden}`),document.adoptedStyleSheets.includes(t)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,t])}catch{return!1}return e.classList.add(M),document.documentElement.classList.add(N),!0},release:n,dispose(){if(n(),!t)return;let e=t;t=null;try{document.adoptedStyleSheets=document.adoptedStyleSheets.filter(t=>t!==e)}catch{}}}}function nt(e,t={}){let n=t.viewportHeightCssPx??Qe,r=tt(e);Ze(e);let i=null,a=()=>{let e=i;e&&(i=null,e.frame!==null&&cancelAnimationFrame(e.frame),e.driver.setProgress(1),e.driver.finish(),r?.release())},o=()=>{let e=i;if(!e)return;e.frame=null;let t=n();t===e.lastViewportPx?e.framesSinceChange+=1:(e.lastViewportPx=t,e.framesSinceChange=0,e.moved=!0);let r=$e((t-e.originHostPx)/e.deltaCssPx,0,1);if(t===Math.round(e.originHostPx+e.deltaCssPx)){if(e.framesAtTarget+=1,e.sawIntermediate||e.framesAtTarget>=3){a();return}e.frame=requestAnimationFrame(o);return}e.framesAtTarget>0&&(Xe.blipFrames+=1),e.framesAtTarget=0,r>0&&r<1&&(e.sawIntermediate=!0),e.driver.setProgress(r);let s=e.moved?8:20;if(e.framesSinceChange>=s){a();return}e.frame=requestAnimationFrame(o)},s=We(e,t=>{let s=t.detail;if(!r||!s||!et(e))return;let c=s.deltaCssPx;if(!Number.isFinite(c)||Math.abs(c)<1)return;a();let l=n(),u=e.getBoundingClientRect().height;if(!(l>0)||!(u>0)||Math.abs(l-u)>1)return;let d=Math.round(u),f=d+c;if(!(f>0)||!r.set(f))return;let p=s.claim();if(!p){r.release();return}i={driver:p,originHostPx:d,deltaCssPx:c,lastViewportPx:l,framesSinceChange:0,moved:!1,sawIntermediate:!1,framesAtTarget:0,frame:null},i.frame=requestAnimationFrame(o)});return{dispose(){s(),a(),r?.dispose()}}}function L(e){let t=e.size??`100%`,n=e.strokeWidth??2;return c(`svg`,{class:`padlock-icon seams-padlock-icon`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":n,"stroke-linecap":`round`,"stroke-linejoin":`round`,width:t,height:t,"aria-hidden":`true`,focusable:`false`,children:[c(`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`}),c(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]})}let rt=0;var it=class extends o{id=`seams-halo-${++rt}`;element=a();motion=null;frame=null;startedAt=null;angle=null;componentDidMount(){this.motion=this.element.current.ownerDocument.defaultView.matchMedia(`(prefers-reduced-motion: no-preference)`),this.motion.addEventListener(`change`,this.updateAnimation),this.syncDynamicStyles(),this.updateAnimation()}componentDidUpdate(e){e.styles!==this.props.styles&&e.styles.deleteDynamicRule(this.id),e.innerPadding!==this.props.innerPadding&&this.syncDynamicStyles(),(e.animated!==this.props.animated||e.durationMs!==this.props.durationMs||e.styles!==this.props.styles)&&this.updateAnimation()}componentWillUnmount(){this.cancelFrame(),this.motion?.removeEventListener(`change`,this.updateAnimation),this.motion=null,this.props.styles.deleteDynamicRule(this.id)}cancelFrame(){let e=this.element.current?.ownerDocument.defaultView;this.frame!==null&&e?.cancelAnimationFrame(this.frame),this.frame=null,this.startedAt=null}updateAnimation=()=>{this.cancelFrame(),this.angle=null,this.syncDynamicStyles(),this.props.animated&&this.motion?.matches&&(this.frame=this.element.current.ownerDocument.defaultView.requestAnimationFrame(this.tick))};tick=e=>{if(!this.element.current||!this.props.animated||!this.motion?.matches)return;this.startedAt??=e;let t=this.props.durationMs,n=t&&Number.isFinite(t)&&t>0?t:1150;this.angle=`${(e-this.startedAt)%n/n*360}deg`,this.syncDynamicStyles(),this.frame=this.element.current.ownerDocument.defaultView.requestAnimationFrame(this.tick)};syncDynamicStyles(){let e={};if(this.props.innerPadding&&(e[`--inner-padding`]=this.props.innerPadding),this.angle&&(e[`--halo-angle`]=this.angle),Object.keys(e).length===0){this.props.styles.deleteDynamicRule(this.id);return}this.props.styles.setDynamicDeclarations(this.id,`#${this.id}`,e)}render(){return c(`div`,{id:this.id,ref:this.element,class:`seams-halo-border`,children:c(`div`,{class:`halo-root${this.props.animated?` animated`:``}`,children:c(`div`,{class:`halo-inner`,children:c(`div`,{class:`halo-outer`,children:[this.props.animated&&c(`div`,{class:`halo-ring`,"aria-hidden":`true`}),c(`div`,{class:`halo-content`,children:this.props.children})]})})})})}};function at(e){return c(`div`,{class:`seams-passkey-halo-loading`,"aria-hidden":`true`,children:c(`div`,{class:`seams-passkey-loading-root`,children:c(it,{animated:e.animated,innerPadding:e.innerPadding,styles:e.styles,children:c(`div`,{class:`seams-passkey-loading-touch-icon-container`,children:c(`svg`,{class:`seams-passkey-loading-touch-icon`,"data-icon":e.icon,width:e.size??36,height:e.size??36,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,focusable:`false`,children:e.icon===`mail`?c(ot,{}):c(st,{})})})})})})}function ot(){return c(l,{children:[c(`path`,{d:`M4.5 6.5H19.5C20.0523 6.5 20.5 6.94772 20.5 7.5V16.5C20.5 17.0523 20.0523 17.5 19.5 17.5H4.5C3.94772 17.5 3.5 17.0523 3.5 16.5V7.5C3.5 6.94772 3.94772 6.5 4.5 6.5Z`,stroke:`currentColor`,"stroke-width":`var(--seams-modal__passkey-halo-loading-touch-icon__stroke-width, 3)`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"vector-effect":`non-scaling-stroke`}),c(`path`,{d:`M4.25 7.25L12 12.75L19.75 7.25`,stroke:`currentColor`,"stroke-width":`var(--seams-modal__passkey-halo-loading-touch-icon__stroke-width, 3)`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"vector-effect":`non-scaling-stroke`})]})}function st(){return c(`path`,{d:`M6.40519 19.0481C6.58912 18.6051 6.75832 18.1545 6.91219 17.6969M14.3433 20.6926C14.6095 19.9418 14.8456 19.1768 15.0502 18.399C15.2359 17.6934 15.3956 16.9772 15.5283 16.2516M19.4477 17.0583C19.8121 15.0944 20.0026 13.0694 20.0026 11C20.0026 6.58172 16.4209 3 12.0026 3C10.7472 3 9.55932 3.28918 8.50195 3.80456M3.52344 15.0245C3.83663 13.7343 4.00262 12.3865 4.00262 11C4.00262 9.25969 4.55832 7.64917 5.50195 6.33621M12.003 11C12.003 13.7604 11.5557 16.4163 10.7295 18.8992C10.5169 19.5381 10.2792 20.1655 10.0176 20.7803M7.71227 14.5C7.90323 13.3618 8.00262 12.1925 8.00262 11C8.00262 8.79086 9.79348 7 12.0026 7C14.2118 7 16.0026 8.79086 16.0026 11C16.0026 11.6166 15.9834 12.2287 15.9455 12.8357`,stroke:`currentColor`,"stroke-width":`var(--seams-modal__passkey-halo-loading-touch-icon__stroke-width, 3)`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"vector-effect":`non-scaling-stroke`,pathLength:`1`})}function ct(e){return c(l,{children:[c(`span`,{class:`loading-ellipsis`,"aria-hidden":`true`,children:[c(`span`,{class:`loading-ellipsis__dot`,children:`.`}),c(`span`,{class:`loading-ellipsis__dot`,children:`.`}),c(`span`,{class:`loading-ellipsis__dot`,children:`.`})]}),c(`span`,{class:`sr-only`,children:c(x,{copy:e.label})})]})}function lt(e,t){return`${e.trim().replace(/\/$/,``)}/address/${encodeURIComponent(t)}`}function R(e){return c(`a`,{class:`highlight-receiver-id`,href:lt(e.base,e.address),target:`_blank`,rel:`noopener noreferrer`,children:e.children})}function z(e){let t=e.trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?`${t.slice(0,8)}...${t.slice(-4)}`:t}function B(e){let t=e.label.trim().match(/^(Transaction(?:\s+\d+)?\s+to contract)\b/i);return t?`${t[1]} `:void 0}function ut(e){throw Error(`Unsupported transaction action: ${String(e)}`)}function V(e){let t=e.action;if(t)switch(t.type){case m.FunctionCall:return`Calling ${t.methodName} with ${D(t.deposit)} using ${ue(t.gas)}`;case m.Transfer:return`Transfer ${D(t.amount)}`;case m.CreateAccount:return`Creating Account`;case m.DeleteAccount:return`Deleting Account`;case m.Stake:return`Staking ${D(t.stake)}`;case m.AddKey:return`Adding Key`;case m.DeleteKey:return`Deleting Key`;case m.DeployContract:return`Deploying WASM contract`;case m.DeployGlobalContract:return`Deploy global WASM contract (mode: ${t.deployMode}, size ${k(t.code)})`;case m.UseGlobalContract:return t.accountId?`Use global contract by account ${t.accountId}`:t.codeHash?`Use global contract by hash ${t.codeHash}`:`Use global contract`;default:return ut(t)}if(e.transaction)return((e.totalTransactions??1)>1?`Transaction ${(e.transactionIndex??0)+1}: to `:`Transaction to `)+e.transaction.receiverId;let n=B(e);return e.contractAddress?.trim()&&n?n+z(e.contractAddress):e.label}function dt({node:e,explorers:t}){let n=e.action;if(n)switch(n.type){case m.FunctionCall:{let e=ue(n.gas),t=D(n.deposit);return c(l,{children:[c(x,{message:`Calling`}),` `,c(`span`,{class:`highlight-method-name`,children:n.methodName}),t!==`0 NEAR`&&c(l,{children:[` `,c(x,{message:`with`}),` `,c(`span`,{class:`highlight-method-name`,children:t})]}),e&&c(l,{children:[` `,c(x,{message:`using`}),` `,c(`span`,{class:`highlight-method-name`,children:e})]})]})}case m.Transfer:return c(l,{children:[c(x,{message:`Transfer`}),` `,c(`span`,{class:`highlight-amount`,children:D(n.amount)})]});case m.CreateAccount:return c(x,{message:`Creating Account`});case m.DeleteAccount:return c(x,{message:`Deleting Account`});case m.Stake:return c(x,{message:`Staking {value0}`,values:{value0:D(n.stake)}});case m.AddKey:return c(x,{message:`Adding Key`});case m.DeleteKey:return c(x,{message:`Deleting Key`});case m.DeployContract:return c(x,{message:`Deploying WASM contract ({value0})`,values:{value0:k(n.code)}});case m.DeployGlobalContract:return c(x,{copy:V(e)});case m.UseGlobalContract:return n.accountId?c(l,{children:[c(x,{message:`Use global contract`}),` `,c(R,{base:t.near,address:n.accountId,children:n.accountId})]}):n.codeHash?c(l,{children:[c(x,{message:`Use global contract by hash`}),` `,c(`span`,{class:`highlight-method-name`,children:O(n.codeHash,{prefix:10,suffix:6})})]}):c(x,{message:`Use global contract`});default:return ut(n)}if(e.transaction)return c(l,{children:[c(x,{copy:(e.totalTransactions??1)>1?`Transaction ${(e.transactionIndex??0)+1}: to `:`Transaction to `}),c(R,{base:t.near,address:e.transaction.receiverId,children:e.transaction.receiverId})]});let r=B(e),i=e.contractAddress?.trim();if(i&&r){let n=e.chain&&e.chain!==`unknown`?t[e.chain]:void 0;return c(l,{children:[c(x,{copy:r}),n?c(R,{base:n,address:i,children:z(i)}):c(`span`,{class:`highlight-receiver-id`,children:z(i)})]})}let a=e.label.trim();if(a.toLowerCase().startsWith(`calling `)){let e=a.slice(8).trim(),t=e.toLowerCase().indexOf(` using `);if(t<0&&e)return c(l,{children:[c(x,{message:`Calling`}),` `,c(`span`,{class:`highlight-method-name`,children:e})]});let n=e.slice(0,t).trim(),r=e.slice(t+7).trim();if(t>=0&&n)return c(l,{children:[c(x,{message:`Calling`}),` `,c(`span`,{class:`highlight-method-name`,children:n}),r&&c(l,{children:[c(x,{message:`using`}),` `,r]})]})}return e.fieldLabel?c(l,{children:[c(x,{copy:e.fieldLabel}),e.label.slice(e.fieldLabel.length)]}):c(x,{copy:e.label})}const H=[`anim-h`,`anim-h-active`,`anim-h-driven`],ft=[...H,`anim-h-hold`];let pt=0;function mt(){return c(`svg`,{class:`chevron`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:c(`path`,{fill:`currentColor`,d:`M6 3l5 5-5 5z`})})}function ht(e){return!!e.contentVariants?.decoded&&!!e.contentVariants.raw&&e.contentVariants.decoded!==e.contentVariants.raw}function gt(e,t,n){return c(vt,{node:n,depth:t,styles:e.styles,explorers:e.explorers,onToggle:e.onToggle,onCopy:e.onCopy},n.id)}function _t(e){if(!e.node.children?.length)return null;let t=c(`div`,{class:`tooltip-tree-root`,children:c(`div`,{class:`tooltip-tree-children`,children:e.node.children.map(gt.bind(null,e,1))})});return c(`div`,{class:`seams-tx-tree`,"data-theme":e.theme,children:e.showShadow?c(`div`,{class:`tooltip-border-outer`,children:t}):t})}var vt=class extends o{static contextType=w;state={mode:this.props.node.contentVariants?.defaultMode===`raw`?`raw`:`decoded`,copied:!1};id=`seams-tree-node-${++pt}`;details=a();shell=a();disposed=!1;copiedTimer=null;frame=null;motionTimer=null;motion=null;modeHeight=null;componentDidUpdate(e){if(e.styles!==this.props.styles&&e.styles.deleteDynamicRule(this.id),this.modeHeight!==null&&this.shell.current){let e=this.shell.current,t=this.modeHeight;this.modeHeight=null,e.classList.remove(...H);let n=e.getBoundingClientRect().height;e.classList.add(...H),I({reason:`${this.props.node.id}:file-content-mode`,element:e,drivenClasses:H,fromCssPx:t,toCssPx:n,setHeightCssPx:this.setHeight,onSettled:this.releaseHeight})||(e.classList.remove(...H),this.releaseHeight())}}componentWillUnmount(){this.disposed=!0,this.copiedTimer!==null&&clearTimeout(this.copiedTimer),this.motionTimer!==null&&clearTimeout(this.motionTimer),this.frame!==null&&this.details.current?.ownerDocument.defaultView?.cancelAnimationFrame(this.frame),this.motion?.body.removeEventListener(`transitionend`,this.onTransitionEnd),this.motion=null,this.releaseHeight()}setHeight=e=>{this.disposed||this.props.styles.setDynamicDeclarations(this.id,`#${this.id}`,{"--seams-tree__anim-target":`${e}px`})};releaseHeight=()=>{this.props.styles.deleteDynamicRule(this.id)};clearCopied=()=>{this.copiedTimer=null,this.disposed||this.setState({copied:!1})};copy=async e=>{e.preventDefault(),e.stopPropagation();let t=this.props.node.copyValue;if(!t)return;let n=e.currentTarget.closest(`.seams-tx-tree`);if(n)try{if(!await E(n,t)||this.disposed)return;this.copiedTimer!==null&&clearTimeout(this.copiedTimer),this.setState({copied:!0}),this.copiedTimer=setTimeout(this.clearCopied,2e3),this.props.onCopy?.(t)}catch{}};toggleMode=e=>{e.preventDefault(),e.stopPropagation(),ht(this.props.node)&&(this.shell.current&&(this.modeHeight=this.shell.current.getBoundingClientRect().height,this.setHeight(this.modeHeight),this.shell.current.classList.add(...H)),this.setState({mode:this.state.mode===`decoded`?`raw`:`decoded`}))};toggle=e=>{if(e.target.closest(`a, button`)){e.stopPropagation();return}e.preventDefault(),e.stopPropagation();let t=this.details.current;if(!t||this.motion)return;let n=t.querySelector(`:scope > .folder-children`),r=!t.open,i=t.ownerDocument.defaultView.matchMedia(`(prefers-reduced-motion: reduce)`).matches;if(!n||i){t.open=r,this.props.onToggle?.(this.props.node.id,r);return}this.motion={body:n,open:r};let a=r?0:n.getBoundingClientRect().height;this.setHeight(a),n.classList.add(`anim-h`,`anim-h-active`,`anim-h-hold`),t.open=!0,n.offsetHeight,this.frame=t.ownerDocument.defaultView.requestAnimationFrame(this.startMotion)};startMotion=()=>{if(this.frame=null,!this.motion||this.disposed)return;let{body:e,open:t}=this.motion,n=e.getBoundingClientRect().height,r=t?e.scrollHeight:0;I({reason:this.props.node.id,element:e,drivenClasses:H,fromCssPx:n,toCssPx:r,setHeightCssPx:this.setHeight,onSettled:this.finishMotion})||(e.addEventListener(`transitionend`,this.onTransitionEnd),e.classList.remove(`anim-h-hold`),this.setHeight(r),this.motionTimer=setTimeout(this.finishMotion,t?200:250))};onTransitionEnd=e=>{e.target===this.motion?.body&&e.propertyName===`height`&&this.finishMotion()};finishMotion=()=>{if(this.disposed||!this.motion)return;let{body:e,open:t}=this.motion;this.motion=null,this.motionTimer!==null&&clearTimeout(this.motionTimer),this.motionTimer=null,e.removeEventListener(`transitionend`,this.onTransitionEnd),e.classList.remove(...ft),this.details.current&&(this.details.current.open=t),this.releaseHeight(),this.props.onToggle?.(this.props.node.id,t)};label(e){let t=this.props.node;return c(`span`,{class:`label${t.type===`file`?` label-action-node`:``}`,hidden:t.hideLabel,children:[e&&!t.hideChevron&&c(mt,{}),c(`span`,{class:`label-text`,title:T(this.context,V(t)),children:c(dt,{node:t,explorers:this.props.explorers})}),t.type===`file`&&t.copyValue&&c(`button`,{type:`button`,class:`copy-badge`,"data-copied":String(this.state.copied),onClick:this.copy,title:T(this.context,this.state.copied?`Copied`:`Copy`),children:this.state.copied?`copied`:`copy`})]})}render(){let{node:e,depth:t}=this.props,n=`row summary-row depth-${Math.max(0,t-1)}`;if(e.type===`file`&&!e.content)return c(`div`,{id:this.id,class:`row file-row depth-${Math.max(0,t-1)}`,"data-no-elbow":String(!!e.hideLabel),children:[c(`span`,{class:`indent`}),this.label(!1)]});let r=ht(e),i=r&&e.contentVariants?e.contentVariants[this.state.mode]:e.content,a=this.state.mode===`decoded`?`bytes`:`decoded`;return c(`details`,{id:this.id,ref:this.details,class:`tree-node ${e.type}`,open:!!e.open,"data-node-id":e.id,children:[c(`summary`,{class:n,"data-no-elbow":String(!!e.hideLabel),onClick:this.toggle,children:[c(`span`,{class:`indent`}),this.label(!0),e.type===`file`&&c(`div`,{ref:this.shell,class:`file-content-shell${r?` has-mode-toggle`:``}`,children:[r&&c(`button`,{type:`button`,class:`file-content-mode-toggle`,title:T(this.context,`Show ${a}`),"aria-label":T(this.context,`Show ${a}`),onClick:this.toggleMode,children:c(x,{copy:a})}),c(`div`,{class:`file-content`,children:i})]})]}),e.type===`folder`&&!!e.children?.length&&c(`div`,{class:`folder-children`,children:e.children.map(gt.bind(null,this.props,t+1))})]})}};let yt=0;function U(e){e.stopPropagation()}var bt=class extends o{static contextType=w;state={armed:!1};id=`seams-confirm-content-${++yt}`;root=a();reflow;frame=null;capturedBeforeUpdate=!1;reflowEnabled=!0;constructor(e){super(e),this.reflow=qe({reason:`tx-body`,element:this.getReflowElement,setHeightCssPx:this.setHeight})}getReflowElement=()=>{let e=this.root.current;return e?.closest(`.modal-container-root, .seams-confirmation-drawer`)??e};setHeight=e=>{let t=this.getReflowElement(),n=t?.id?`#${t.id}`:`#${this.id}`;this.props.styles.setDynamicDeclarations(this.id,n,{[F]:`${e}px`})};componentDidMount(){this.reflowEnabled=this.getReflowElement()===this.root.current,this.frame=this.root.current.ownerDocument.defaultView.requestAnimationFrame(this.afterFirstPaint)}afterFirstPaint=()=>{this.frame=this.root.current.ownerDocument.defaultView.requestAnimationFrame(this.arm)};arm=()=>{this.frame=null,this.setState({armed:!0})};componentWillReceiveProps(){this.reflowEnabled&&(this.reflow.capture(),this.capturedBeforeUpdate=!0)}componentWillUpdate(){this.reflowEnabled&&(this.capturedBeforeUpdate||this.reflow.capture())}componentDidUpdate(e){this.reflowEnabled&&(this.capturedBeforeUpdate=!1,e.styles!==this.props.styles&&e.styles.deleteDynamicRule(this.id),this.reflow.commit())}componentWillUnmount(){this.frame!==null&&this.root.current?.ownerDocument.defaultView?.cancelAnimationFrame(this.frame),this.frame=null,this.reflow.dispose(),this.props.styles.deleteDynamicRule(this.id)}confirm=()=>{this.state.armed&&this.props.decision.kind===`ready`&&this.props.decision.onConfirm()};cancel=()=>{this.props.onCancel()};render(){let e=this.props.decision.kind===`preparing`;return c(`div`,{class:`seams-tx-confirm-content`,onPointerDown:U,onMouseDown:U,onTouchStart:U,children:c(`div`,{id:this.id,ref:this.root,class:`txc-root`,children:[this.props.errorMessage&&c(`div`,{class:`error`,role:`alert`,children:c(x,{copy:this.props.errorMessage})}),this.props.tree&&c(`div`,{class:`tooltip-width`,children:c(_t,{node:this.props.tree,theme:this.props.theme,explorers:this.props.explorers,styles:this.props.styles,showShadow:!1,onToggle:this.props.onTreeToggle,onCopy:this.props.onCopy})}),this.props.authMethodApprovalMessage&&c(`p`,{class:`seams-voiceid-instructions`,"data-seams-voice-id":`required`,role:`status`,children:this.props.authMethodApprovalMessage}),c(`div`,{class:`actions`,children:[!this.props.cancelInHeader&&c(`button`,{type:`button`,class:`cancel`,onClick:this.cancel,children:c(x,{copy:this.props.cancelText})}),c(`button`,{type:this.props.decision.kind===`form`?`submit`:`button`,form:this.props.decision.kind===`form`?this.props.decision.formId:void 0,class:`confirm${e?` loading`:``}`,onClick:this.confirm,disabled:e||!this.state.armed,children:e?c(l,{children:[c(`span`,{class:`loading-indicator`,role:`progressbar`,"aria-label":b(this.context,`Loading`)}),c(`span`,{children:c(x,{message:`Loading...`})})]}):c(l,{children:[this.props.confirmIcon,c(x,{copy:this.props.confirmText})]})})]})]})})}};function xt(e){throw Error(`Unexpected confirmation body: ${String(e)}`)}var St=class extends o{static contextType=w;copy=()=>{this.props.model.kind===`funding`&&this.props.onCopyAccount(this.props.model.accountId)};render(){let e=this.props.model;switch(e.kind){case`empty`:return null;case`text`:return c(`div`,{class:`confirmation-body`,children:c(x,{copy:e.text})});case`status`:return c(`div`,{class:`confirmation-body confirmation-body--status`,children:c(x,{copy:e.text})});case`funding`:return c(`div`,{class:`confirmation-body confirmation-body--funding`,children:[c(x,{message:`NEAR account`}),c(`button`,{type:`button`,class:`confirmation-body__copy-target`,title:T(this.context,`Copy ${e.accountId}`),"aria-label":T(this.context,`Copy NEAR account ${e.accountId}`),onClick:this.copy,children:e.shortAccountId}),c(x,{message:`needs funding`})]});default:return xt(e)}}};function Ct(e){let t=y();return c(`div`,{class:`passkey-registration-confirm__identity`,"aria-label":b(t,`Passkey registration details`),children:[c(`div`,{class:`passkey-registration-confirm__row`,children:[c(`span`,{class:`passkey-registration-confirm__label`,children:c(x,{message:`Account`})}),c(`span`,{class:`passkey-registration-confirm__value`,title:T(t,e.display.intendedUserName),children:e.display.intendedUserName})]}),c(`div`,{class:`passkey-registration-confirm__row`,children:[c(`span`,{class:`passkey-registration-confirm__label`,children:c(x,{message:`Website`})}),c(`span`,{class:`passkey-registration-confirm__value`,title:T(t,e.display.rpId),children:e.display.rpId})]})]})}var wt=class extends o{static contextType=w;confirm=()=>{this.props.decision.kind===`ready`&&this.props.decision.onConfirm()};cancel=()=>{this.props.onCancel()};render(){let e=this.props.decision.kind===`creating`;return c(`div`,{ref:this.props.root,class:`passkey-registration-confirm`,children:[c(`div`,{class:`hero passkey-registration-confirm__hero`,children:[c(at,{animated:!this.props.errorMessage,icon:`fingerprint`,size:44,styles:this.props.styles}),c(`div`,{class:`hero-container passkey-registration-confirm__hero-copy`,children:[c(`h2`,{class:`hero-heading`,children:c(x,{copy:this.props.heading})}),c(`p`,{class:`passkey-registration-confirm__body`,children:c(x,{copy:this.props.body})})]})]}),this.props.errorMessage&&c(`div`,{class:`error-banner`,children:c(x,{copy:this.props.errorMessage})}),c(Ct,{display:this.props.display}),c(`div`,{class:`passkey-registration-confirm__actions`,children:[c(`button`,{type:`button`,class:`btn btn-cancel`,onClick:this.cancel,children:c(x,{copy:this.props.cancelText})}),c(`button`,{type:`button`,class:`btn btn-confirm`,disabled:e,onClick:this.confirm,children:e?c(l,{children:[c(`span`,{class:`loading-indicator passkey-registration-confirm__spinner`,role:`progressbar`,"aria-label":b(this.context,`Creating passkey`)}),c(`span`,{class:`passkey-registration-confirm__busy-label`,children:c(x,{message:`Creating passkey...`})})]}):c(x,{message:`Create passkey`})})]})]})}};let Tt=0;var Et=class extends o{id=`seams-email-code-${++Tt}`;input=e=>{this.props.state.kind===`editing`&&this.props.state.onInput(e.currentTarget.value)};resend=()=>{this.props.resend?.kind===`available`&&this.props.resend.onResend()};renderDigit=e=>{let t=this.props.code[e]||``;return c(`span`,{class:`email-otp-confirm__slot${t?` is-filled`:``}`,children:t},e)};render(){let e=this.props.state.kind!==`editing`,t=`${this.id}-helper`,n=`${this.id}-error`;return c(`div`,{class:`email-otp-confirm`,children:[c(`label`,{class:`email-otp-confirm__label`,for:this.id,children:c(x,{message:`Email code`})}),c(`div`,{class:`email-otp-confirm__code-field`,"data-disabled":e?`true`:`false`,children:[c(`input`,{id:this.id,name:`email-code`,type:`text`,class:`email-otp-confirm__input`,inputMode:`numeric`,autoComplete:`one-time-code`,"data-email-otp-challenge-id":this.props.challengeId,pattern:`[0-9]*`,maxLength:6,spellcheck:!1,value:this.props.code,disabled:e,onInput:this.input,"aria-invalid":this.props.errorMessage?`true`:void 0,"aria-describedby":this.props.errorMessage?`${t} ${n}`:t}),c(`div`,{class:`email-otp-confirm__slots${e?` is-submitting`:``}`,"aria-hidden":`true`,children:[0,1,2,3,4,5].map(this.renderDigit)})]}),c(`div`,{id:t,class:`email-otp-confirm__helper`,children:c(x,{copy:this.props.helperText})}),this.props.errorMessage&&c(`div`,{id:n,class:`email-otp-confirm__error`,children:c(x,{copy:this.props.errorMessage})}),this.props.resend&&c(`button`,{type:`button`,class:`email-otp-confirm__resend`,disabled:this.props.resend.kind===`unavailable`,onClick:this.resend,children:c(x,{copy:this.props.resend.label})})]})}},Dt=class{codeState={kind:`editing`,code:``};resendState={kind:`available`,label:`Resend code`};error=``;countdown=null;options;constructor(e){this.options=e}input=e=>{if(this.codeState.kind!==`editing`)return;let t=e.replace(/\D/g,``).slice(0,6);this.error=``,this.codeState={kind:`editing`,code:t},t.length===6?this.confirm():this.publish()};confirm(){if(this.codeState.kind!==`editing`)return`ignored`;let e=this.codeState.code;return e.length===6?(this.error=``,this.codeState={kind:`fading`,code:e,timer:setTimeout(this.submit,150)},this.publish(),`accepted`):(this.error=`Enter the 6-digit Email OTP code.`,this.publish(),`invalid`)}submit=()=>{if(this.codeState.kind!==`fading`)return;let e=this.codeState.code;this.codeState={kind:`submitting`,code:e},this.publish(),this.isDisposed()||this.options.onSubmit(e)};retry(e){this.codeState.kind!==`disposed`&&(this.cancelFade(),this.codeState={kind:`editing`,code:this.codeState.code},this.error=e,this.publish())}setVerification(e){if(this.codeState.kind!==`disposed`)switch(e.kind){case`ready`:this.codeState.kind===`submitting`&&this.retry(``);return;case`pending`:this.cancelFade(),this.codeState={kind:`submitting`,code:this.codeState.code},this.publish();return;case`rejected`:this.retry(e.message);return}}resend=async()=>{if(this.codeState.kind!==`editing`||this.resendState.kind!==`available`)return;let e=this.options.resend;if(!e)return;let t=Date.now()+e.cooldownMs,n={kind:`sending`,until:t};if(this.resendState=n,this.error=``,this.publish(),this.isDisposed())return;let r;try{r=await e.send()}catch{r={kind:`failed`,message:`Could not send code.`}}if(this.isDisposed()||this.resendState!==n)return;let i=r.kind===`sent`?`Code sent`:`Resend code`;r.kind===`failed`&&(this.error=r.message),Date.now()>=t?this.resendState={kind:`available`,label:i}:(this.resendState={kind:`cooldown`,until:t,label:i},this.countdown=setInterval(this.tick,250)),this.publish()};tick=()=>{this.resendState.kind===`cooldown`&&(Date.now()>=this.resendState.until&&(this.resendState={kind:`available`,label:this.resendState.label},this.clearCountdown()),this.publish())};isDisposed(){return this.codeState.kind===`disposed`}publish(){this.codeState.kind!==`disposed`&&this.options.onChange({code:this.codeState.code,phase:this.codeState.kind,error:this.error,resend:this.options.resend?this.resendSnapshot():null})}resendSnapshot(){switch(this.resendState.kind){case`available`:return{available:this.codeState.kind===`editing`,label:this.resendState.label};case`sending`:return{available:!1,label:`Sending...`};case`cooldown`:return{available:!1,label:`Resend in ${Math.max(1,Math.ceil((this.resendState.until-Date.now())/1e3))}s`}}}cancelFade(){this.codeState.kind===`fading`&&clearTimeout(this.codeState.timer)}clearCountdown(){this.countdown!==null&&clearInterval(this.countdown),this.countdown=null}dispose(){this.cancelFade(),this.clearCountdown(),this.codeState={kind:`disposed`},this.error=``}};function Ot(e){return c(kt,{...e},e.prompt.challengeId)}var kt=class extends o{static contextType=w;session;form=a();lifetime;constructor(e){super(e),this.lifetime={kind:`active`,challengeId:e.prompt.challengeId,emailHint:e.prompt.emailHint?.trim()||``},this.state={code:``,phase:`editing`,error:``,resend:e.prompt.onResend?{available:!0,label:`Resend code`}:null},this.session=new Dt({onSubmit:this.submit,onChange:this.change,resend:e.prompt.onResend?{send:this.send,cooldownMs:Math.max(1e3,Math.floor(Number(e.prompt.resendDebounceMs)||1e4))}:null})}submit=e=>{this.lifetime.kind===`active`&&this.props.onSubmit(e,this.lifetime.challengeId)};send=async()=>{let e=this.props.prompt.onResend;if(!e)return{kind:`failed`,message:`Could not send code.`};try{let t=await e();if(this.lifetime.kind===`disposed`)return{kind:`sent`};let n=String(t?.challengeId||``).trim(),r=String(t?.emailHint||``).trim();return n&&(this.lifetime={kind:`active`,challengeId:n,emailHint:r||this.lifetime.emailHint}),{kind:`sent`}}catch(e){return{kind:`failed`,message:jt(e)}}};change=e=>{this.setState(e)};confirm=e=>{e.preventDefault(),e.stopPropagation(),this.session.confirm()===`invalid`&&this.setState({},this.focusCode)};focusCode=()=>{this.form.current?.querySelector(`input`)?.focus({preventScroll:!0})};componentDidMount(){this.session.setVerification(this.props.verification)}componentDidUpdate(e){At(e.verification,this.props.verification)&&this.session.setVerification(this.props.verification)}componentWillUnmount(){this.lifetime={kind:`disposed`},this.session.dispose()}inputState(){switch(this.state.phase){case`editing`:return{kind:`editing`,onInput:this.session.input};case`fading`:return{kind:`fading`};case`submitting`:return{kind:`submitting`}}}resendAction(){let e=this.state.resend;return e?e.available?{kind:`available`,label:e.label,onResend:this.session.resend}:{kind:`unavailable`,label:e.label}:null}render(){return c(`form`,{ref:this.form,id:this.props.formId,onSubmit:this.confirm,noValidate:!0,children:c(Et,{challengeId:this.lifetime.kind===`active`?this.lifetime.challengeId:``,code:this.state.code,helperText:this.props.prompt.helperText?.trim()||_(this.lifetime.kind===`active`?this.lifetime.emailHint:``),errorMessage:T(this.context,this.state.error||void 0),state:this.inputState(),resend:this.resendAction()})})}};function At(e,t){return e.kind===t.kind?e.kind===`rejected`&&t.kind===`rejected`&&e.message!==t.message:!0}function jt(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`rate_limited`){let t=`retryAfterMs`in e?Number(e.retryAfterMs):NaN;return Number.isFinite(t)&&t>0?`Too many requests. Try again in ${Math.max(1,Math.ceil(t/1e3))}s.`:`Too many requests. Try again shortly.`}return e instanceof Error&&e.message?e.message:`Could not send code.`}let Mt=0;var W=class extends o{root=a();id=`seams-review-disclosure-${++Mt}`;componentDidMount(){this.root.current&&(this.root.current.open=this.props.initiallyOpen??!1)}motion=null;componentWillUnmount(){this.clearMotion(),this.root.current&&S(this.root.current.ownerDocument).deleteDynamicRule(this.id)}clearMotion(){this.motion&&(this.motion.kind===`local`&&(this.motion.size.onfinish=null,this.motion.size.cancel(),this.motion.fade.cancel()),this.motion=null,this.root.current?.removeAttribute(`data-resizing`))}setHeight=e=>{let t=this.root.current;t&&S(t.ownerDocument).setDynamicDeclarations(this.id,`#${this.id}`,{"--seams-review-disclosure-height":`${e}px`})};finish=()=>{let e=this.motion?.kind===`local`;if(this.root.current&&this.motion&&(this.root.current.open=this.motion.opening,this.root.current.removeAttribute(`data-closing`)),this.clearMotion(),e){let e=this.root.current?.closest(`.seams-confirmation-surface`),t=e?.ownerDocument.activeElement;if(t instanceof HTMLElement&&t.tabIndex>=0&&e?.contains(t)){let e=t.getBoundingClientRect(),n=t.ownerDocument.documentElement.clientHeight;(e.top<0||e.bottom>n)&&t.scrollIntoView({block:`center`,inline:`nearest`})}}};toggle=e=>{let t=this.root.current;if(!t||(e.preventDefault(),this.motion?.kind===`hosted`))return;let n=this.motion?!this.motion.opening:!t.open,r=t.lastElementChild;if(!(r instanceof HTMLElement))return;let i=t.open?r.getBoundingClientRect().height:0;if(this.clearMotion(),t.toggleAttribute(`data-closing`,!n),window.matchMedia(`(prefers-reduced-motion: reduce)`).matches||!t.animate){t.open=n,t.removeAttribute(`data-closing`);return}t.open=!0;let a=t.parentElement?.closest(`.seams-review-technical > div`);if(a&&a.scrollHeight>a.clientHeight){t.open=n,t.removeAttribute(`data-closing`);return}t.setAttribute(`data-resizing`,``);let o=n?r.getBoundingClientRect().height:0;if(this.motion={kind:`hosted`,opening:n},I({element:r,reason:`review-details`,fromCssPx:i,toCssPx:o,drivenClasses:[`seams-review-disclosure-driven`],setHeightCssPx:this.setHeight,onSettled:this.finish}))return;let s=r.animate([{height:`${i}px`,overflow:`hidden`},{height:`${o}px`,overflow:`hidden`}],{duration:n?220:180,easing:`cubic-bezier(.2,0,0,1)`,fill:`both`});this.motion={kind:`local`,opening:n,size:s,fade:r.animate(n?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],{duration:n?180:100,easing:`ease-out`,fill:`both`})},s.onfinish=this.finish};render(){return c(`details`,{ref:this.root,class:`seams-review-${this.props.kind??`technical`}`,children:[c(`summary`,{onClick:this.toggle,children:[c(x,{copy:this.props.label}),c(`svg`,{class:`seams-review-caret`,viewBox:`0 0 20 20`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.6`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`,children:c(`path`,{d:`m5 7.5 5 5 5-5`})})]}),c(`div`,{id:this.id,children:this.props.children})]})}};function G({kind:e}){let t={back:`m15 6-6 6 6 6`,close:`M6 6l12 12M6 18L18 6`,minimize:`M5 12h14`,check:`m5 12 4 4L19 6`,arrow:`M7 17 17 7M7 7h10v10`,copy:`M8 8h12v12H8ZM4 16V4h12`,loader:`M12 3a9 9 0 1 1-9 9`,alert:`M12 8v5m0 3v.1M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0`,fingerprint:`M6.405 19.048c.184-.443.353-.894.507-1.351M14.343 20.693c.266-.751.502-1.516.707-2.294.186-.706.346-1.422.478-2.147M19.448 17.058c.364-1.964.555-3.989.555-6.058 0-4.418-3.582-8-8-8-1.255 0-2.443.289-3.501.805M3.523 15.025c.314-1.29.48-2.638.48-4.025 0-1.74.556-3.351 1.499-4.664M12.003 11c0 2.76-.447 5.416-1.273 7.899-.213.639-.451 1.266-.712 1.881M7.712 14.5c.191-1.138.291-2.308.291-3.5 0-2.209 1.791-4 4-4s4 1.791 4 4c0 .617-.02 1.229-.058 1.836`};return c(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.6`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`,children:c(`path`,{d:t[e]})})}function Nt(e){return e?e.chain===`evm`&&e.chainId===5042?`Arc`:e.chain===`evm`&&e.chainId===5042002?`Arc Testnet`:e.chain===`evm`&&e.chainId===8453?`Base`:e.chain===`evm`&&e.chainId===84532?`Base Sepolia`:e.chain===`evm`&&e.chainId===1?`Ethereum`:e.chain===`evm`&&e.chainId===11155111?`Ethereum Sepolia`:`${e.chain.toUpperCase()}${e.chainId?` · ${e.chainId}`:``}`:`Wallet transaction`}function Pt(e){if(e?.operations.length!==1)return null;let t=e.operations[0];return t.kind===`generic.contractCall`||t.kind===`tempo.eip2718`?t.to??null:null}function Ft({value:e,class:t}){let n=y();return c(`bdi`,{class:`seams-review-middle ${t}`,dir:`ltr`,title:T(n,e),children:[c(`span`,{children:e.slice(0,-8)}),c(`span`,{children:e.slice(-8)})]})}function It({symbol:e}){return e===`NEAR`?c(`svg`,{class:`seams-review-token`,viewBox:`0 0 48 48`,"aria-hidden":`true`,children:[c(`circle`,{cx:`24`,cy:`24`,r:`24`,fill:`#000`}),c(`svg`,{x:`9`,y:`9`,width:`30`,height:`30`,viewBox:`108 108 351 351`,children:c(`path`,{d:`m421.61,108c-13,0-25.07,6.74-31.88,17.82l-73.37,108.93c-2.39,3.59-1.42,8.43,2.17,10.82,2.91,1.94,6.76,1.7,9.41-.58l72.22-62.64c1.2-1.08,3.05-.97,4.13.23.49.55.75,1.26.75,1.99v196.12c0,1.62-1.31,2.92-2.93,2.92-.87,0-1.69-.38-2.24-1.05L181.56,121.24c-7.11-8.39-17.55-13.23-28.54-13.24h-7.63c-20.65,0-37.39,16.74-37.39,37.39v276.22c0,20.65,16.74,37.39,37.39,37.39,13,0,25.07-6.74,31.88-17.82l73.37-108.93c2.39-3.59,1.42-8.43-2.17-10.82-2.91-1.94-6.76-1.7-9.41.58l-72.22,62.64c-1.2,1.08-3.05.97-4.13-.23-.49-.55-.75-1.26-.74-1.99v-196.17c0-1.62,1.31-2.92,2.93-2.92.86,0,1.69.38,2.24,1.05l218.28,261.37c7.11,8.39,17.55,13.23,28.54,13.24h7.63c20.65.01,37.4-16.72,37.42-37.37V145.39c0-20.65-16.74-37.39-37.39-37.39Z`,fill:`#fff`})})]}):e===`ETH`?c(`svg`,{class:`seams-review-token`,viewBox:`0 0 42 42`,"aria-hidden":`true`,children:[c(`circle`,{cx:`21`,cy:`21`,r:`21`,fill:`#eef0fb`}),c(`path`,{d:`m21 6-9 15 9 5 9-5Z`,fill:`#627eea`}),c(`path`,{d:`m21 6 9 15-9 5Z`,fill:`#465da9`}),c(`path`,{d:`m12 23 9 13 9-13-9 5Z`,fill:`#627eea`})]}):e===`USDC`?c(`svg`,{class:`seams-review-token`,viewBox:`0 0 96 96`,fill:`none`,"aria-hidden":`true`,children:[c(`path`,{d:`M48 95C73.9574 95 95 73.9574 95 48C95 22.0426 73.9574 1 48 1C22.0426 1 1 22.0426 1 48C1 73.9574 22.0426 95 48 95Z`,fill:`#0B53BF`}),c(`path`,{d:`M56.4609 13.7778V19.8291C68.5341 23.4716 77.3759 34.6928 77.3759 47.9997C77.3759 61.3066 68.5341 72.5278 56.4609 76.1703V82.2216C71.8534 78.4616 83.2509 64.5672 83.2509 47.9997C83.2509 31.4322 71.8534 17.5378 56.4609 13.7778Z`,fill:`white`}),c(`path`,{d:`M18.625 47.9997C18.625 34.6928 27.4669 23.4716 39.54 19.8291V13.7778C24.1475 17.5378 12.75 31.4322 12.75 47.9997C12.75 64.5672 24.1475 78.4616 39.54 82.2216V76.1703C27.4669 72.5572 18.625 61.3066 18.625 47.9997Z`,fill:`white`}),c(`path`,{d:`M60.6319 54.5506C60.6319 42.5362 41.8025 47.4713 41.8025 40.8325C41.8025 38.4531 43.7119 36.9256 47.3544 36.9256C51.7019 36.9256 53.2 39.0406 53.67 41.89H59.6625C59.1279 36.5426 56.0588 33.1662 50.9382 32.1604V27.4375H45.0632V31.9918C39.4534 32.7062 35.9275 35.973 35.9275 40.8325C35.9275 52.9056 54.7863 48.3819 54.7863 54.9031C54.7863 57.3706 52.4069 59.0156 48.3825 59.0156C43.1244 59.0156 41.3913 56.695 40.745 53.4931H34.8994C35.2781 59.3502 38.8897 63.0159 45.0632 63.9307V68.5625H50.9382V63.9923C56.9633 63.2139 60.6319 59.7089 60.6319 54.5506Z`,fill:`white`})]}):c(`span`,{class:`seams-review-token seams-review-token-fallback`,"aria-hidden":`true`,children:e.slice(0,1)})}function Lt({model:e,compact:t=!1}){let n=Bt(e);return n?c(`div`,{class:`seams-review-amount${t?` seams-review-amount--compact`:``}`,children:[c(It,{symbol:n.symbol}),c(`div`,{children:[c(`span`,{children:n.value}),` `,c(`small`,{children:n.symbol})]})]}):null}function Rt(){return c(`div`,{class:`seams-receipt-footer`,children:[c(`span`,{children:c(x,{message:`Secured by`})}),` `,c(u,{})]})}function zt(e,t){if(!/^\d+$/.test(e))return e;let n=e.padStart(t+1,`0`),r=n.slice(-t).replace(/0+$/,``);return`${n.slice(0,-t)}${r?`.${r}`:``}`}function Bt(e){let t=e?.totals;return t?.nativeValue?t.nativeSymbol===`yoctoNEAR`?{value:zt(t.nativeValue,24),symbol:`NEAR`}:e?.chain===`evm`&&(e.chainId===5042||e.chainId===5042002)&&t.nativeSymbol===`wei`?{value:zt(t.nativeValue,18),symbol:`USDC`}:{value:t.nativeValue,symbol:t.nativeSymbol??``}:null}var K=class extends o{static contextType=w;state={copied:!1};lifetime=new AbortController;timer=null;resetCopied=()=>{this.setState({copied:!1})};componentWillUnmount(){this.lifetime.abort(),this.timer!==null&&clearTimeout(this.timer)}componentDidUpdate(e){e.value!==this.props.value&&(this.lifetime.abort(),this.lifetime=new AbortController,this.timer!==null&&clearTimeout(this.timer),this.resetCopied())}copy=async e=>{let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.lifetime.signal;try{if(!await E(t,this.props.value,n)||n.aborted)return;this.setState({copied:!0}),this.timer!==null&&clearTimeout(this.timer),this.timer=setTimeout(this.resetCopied,3e3)}catch{n.aborted||this.setState({copied:!1})}};render(){return c(`button`,{type:`button`,class:`seams-review-copy${this.props.address?` seams-review-copy-address`:``}${this.state.copied?` copied`:``}`,onClick:this.copy,"aria-label":T(this.context,this.state.copied?`Copied`:this.props.label??`Copy value`),children:[this.props.address&&c(`bdi`,{class:`seams-review-full-address`,dir:`ltr`,children:this.props.value}),c(ne,{})]})}};function Vt({node:e}){let t=y();if(e.action||e.transaction)return c(l,{children:c(x,{copy:V(e)})});let n=B(e);if(n&&e.contractAddress){let r=e.contractAddress;return c(`span`,{class:`seams-review-contract`,children:[c(x,{copy:n.trim()}),c(`span`,{class:`seams-review-contract-value`,children:[c(Ft,{value:r,class:`seams-review-contract-address`}),c(K,{value:r,label:T(t,`Copy contract address ${r}`)})]})]})}if(e.fieldLabel){let t=e.label.slice(e.fieldLabel.length);return c(l,{children:[c(x,{copy:e.fieldLabel}),e.fieldLabel===`Method:`?c(`span`,{class:`seams-review-function`,children:t}):t]})}let r=/^(Call(?:ing)? )([^\s]+)(.*)$/.exec(e.label);return r?c(l,{children:[c(x,{copy:r[1]}),c(`span`,{class:`seams-review-function`,children:r[2]}),r[3]]}):c(l,{children:c(x,{copy:e.label})})}function Ht({node:e}){let t=y(),n=e.contentVariants?.decoded??e.content,r=!!(e.contentVariants||n?.includes(`
2
- `));return c(`div`,{class:`seams-review-detail`,children:[c(`div`,{class:n?`seams-review-detail-row${r?` seams-review-detail-row--block`:``}`:`seams-review-detail-label`,children:[c(`span`,{children:c(Vt,{node:e})}),n&&c(`pre`,{children:n}),e.copyValue&&c(K,{value:e.copyValue})]}),e.contentVariants&&c(W,{label:b(t,`Raw data`),kind:`raw`,children:c(`pre`,{children:e.contentVariants.raw})}),!!e.children?.length&&c(`div`,{class:`seams-review-detail-children`,children:e.children?.map(e=>c(Ht,{node:e},e.id))})]})}function Ut({data:e,details:t=!0}){let n=y(),r=e.model,i=r?.operations[0],a=Pt(r);return c(`div`,{class:`seams-transaction-review`,children:[c(Lt,{model:r}),r?.warnings?.map(e=>c(`div`,{class:`seams-review-warning`,role:`alert`,children:c(x,{copy:e.message})},e.code)),c(`dl`,{class:`seams-review-fields`,children:[a&&c(`div`,{children:[c(`dt`,{children:c(x,{message:`To`})}),c(`dd`,{class:`seams-review-recipient`,children:c(K,{value:a,address:!0,label:T(n,`Copy recipient address ${a}`)})})]}),r&&c(`div`,{children:[c(`dt`,{children:c(x,{message:`Network`})}),c(`dd`,{children:[c(`span`,{class:`seams-review-network-dot`}),Nt(r)]})]}),r?.totals?.estimatedFee&&c(`div`,{children:[c(`dt`,{children:c(x,{message:`Estimated network fee`})}),c(`dd`,{children:[r.totals.estimatedFee,` `,r.totals.feeSymbol]})]})]}),t&&e.tree&&c(W,{initiallyOpen:e.detailsInitiallyOpen,label:T(n,i?.kind===`near.message`?`Message details`:`Transaction details`),children:c(Ht,{node:e.tree})}),r?.signerAccount&&c(`div`,{class:`seams-review-account`,children:[c(`span`,{class:`seams-review-avatar`,"aria-hidden":`true`,children:`S`}),c(`div`,{children:[c(x,{message:`Signing account`}),c(`small`,{children:c(K,{value:r.signerAccount,address:!0,label:T(n,`Copy signing account address ${r.signerAccount}`)})})]})]})]})}let Wt=0;var Gt=class extends o{static contextType=w;root=a();otpFormId=`seams-confirmation-email-${++Wt}`;reflowId=`seams-confirmation-content-surface-${Wt}`;getReflowElement=()=>this.root.current?.closest(`.modal-container-root, .seams-confirmation-drawer`)??null;setHeight=e=>{let t=this.getReflowElement();t?.id&&this.props.styles.setDynamicDeclarations(this.reflowId,`#${t.id}`,{[F]:`${e}px`})};reflow=qe({reason:`confirm-body`,element:this.getReflowElement,setHeightCssPx:this.setHeight});copyAccount=e=>{let t=this.root.current;t&&E(t,e).catch(Kt)};componentWillReceiveProps(){this.reflow.capture()}componentDidUpdate(e){e.styles!==this.props.styles&&e.styles.deleteDynamicRule(this.reflowId),this.reflow.commit()}componentWillUnmount(){this.reflow.dispose(),this.props.styles.deleteDynamicRule(this.reflowId)}render(){let e=this.props.model;switch(e.kind){case`registration`:return c(wt,{...e.registration,root:this.root,styles:this.props.styles});case`transaction`:return this.renderTransaction(e);default:return qt(e)}}renderTransaction(e){let t=this.props.variant===`drawer`?`seams-confirmation-content seams-confirmation-content--drawer`:`seams-confirmation-content`,n=e.prompt.kind===`email`&&e.transaction.decision.kind===`ready`?{kind:`form`,formId:this.otpFormId}:e.transaction.decision;return e.capture?c(`div`,{ref:this.root,class:t,children:c(`div`,{class:`seams-review-content seams-review-content--capture`,children:[this.props.variant!==`drawer`&&this.renderToolbar(e,n),c(Jt,{element:e.capture}),c(Rt,{})]})}):c(`div`,{ref:this.root,class:t,children:c(`div`,{class:`seams-review-content`,children:[this.props.variant!==`drawer`&&this.renderToolbar(e,n),e.review.model&&c(`div`,{class:`seams-review-eyebrow`,children:e.review.model.operations.length===1?c(x,{copy:e.review.model.operations[0].label.replace(/\s+using\s+[\d,.]+\s+gas$/i,``)}):c(x,{message:`Transaction`})}),c(`h2`,{class:`seams-review-title`,children:c(x,{copy:e.header.heading})}),c(Ut,{data:e.review}),c(`div`,{class:`seams-review-context`,children:[c(St,{model:e.body,onCopyAccount:this.copyAccount}),e.prompt.kind===`email`&&c(Ot,{...e.prompt.email,formId:this.otpFormId})]}),c(bt,{...e.transaction,tree:null,styles:this.props.styles,decision:n,cancelInHeader:!0,confirmIcon:e.prompt.kind===`passkey`?c(G,{kind:`fingerprint`}):void 0}),c(Rt,{})]})})}renderToolbar(e,t){return c(`div`,{class:`seams-review-toolbar`,children:[c(`div`,{class:`seams-review-origin`,children:[e.transaction.onBack&&c(`button`,{type:`button`,"aria-label":b(this.context,`Back to review`),title:b(this.context,`Back to review`),disabled:t.kind===`preparing`,onClick:e.transaction.onBack,children:c(G,{kind:`back`})}),c(L,{}),e.header.website.kind===`ready`?e.header.website.text:c(ct,{label:b(this.context,`Loading website`)})]}),c(`button`,{type:`button`,"aria-label":T(this.context,e.transaction.cancelText),onClick:e.transaction.onCancel,children:c(G,{kind:`close`})})]})}};function Kt(){}function qt(e){throw Error(`Unexpected confirmation content: ${String(e)}`)}var Jt=class extends o{container=a();componentDidMount(){this.container.current?.append(this.props.element),this.props.element.querySelector(`button`)?.focus()}componentDidUpdate(e){e.element!==this.props.element&&this.container.current?.replaceChildren(this.props.element)}componentWillUnmount(){this.props.element.remove()}render(){return c(`div`,{ref:this.container,class:`seams-auth-method-capture`})}};function Yt(e){let{kind:t}=e.state;return t===`signing`||t===`broadcasting`||t===`submitted`}function Xt(e){return e.state.kind===`confirmed`||e.state.kind===`signed`}function Zt(e){if(e.subject===`message`)return e.state.kind===`signed`?3:0;let{state:t}=e;switch(t.kind){case`signing`:return 0;case`signed`:case`broadcasting`:return 1;case`submitted`:case`reverted`:return 2;case`confirmed`:return 3;case`failed`:case`unknown`:return t.hash?2:0;default:return q(t)}}function Qt(e){return e.subject===`message`?`Message signature`:`Transaction receipt`}function $t(e){if(e.subject===`message`)return tn(e.state);let{state:t}=e;switch(t.kind){case`signing`:return`Signing transaction`;case`signed`:return`Signature ready`;case`broadcasting`:return`Broadcasting transaction`;case`submitted`:return`Waiting for confirmation`;case`confirmed`:return`Transaction complete`;case`failed`:return`Transaction failed`;case`reverted`:return`Transaction reverted`;case`unknown`:return`Confirmation unavailable`;default:return q(t)}}function en(e){if(e.subject===`message`)return nn(e.state);let{state:t}=e;switch(t.kind){case`signing`:return`Preparing your signed transaction.`;case`signed`:return`Signature created, ready to broadcast.`;case`broadcasting`:return`Submitting your signed transaction to the network.`;case`submitted`:return`Submitted to the network. Waiting for the receipt.`;case`confirmed`:return`The network confirmed your transaction.`;case`failed`:case`reverted`:case`unknown`:return t.message;default:return q(t)}}function tn(e){switch(e.kind){case`signing`:return`Signing message`;case`signed`:return`Message signed`;case`failed`:return`Signature failed`;default:return q(e)}}function nn(e){switch(e.kind){case`signing`:return`Preparing your message signature.`;case`signed`:return`Signed off-chain. Nothing was sent to the network.`;case`failed`:return e.message;default:return q(e)}}function q(e){throw Error(`Unexpected transaction receipt state: ${String(e)}`)}const rn=`cubic-bezier(0.22, 1, 0.36, 1)`;let an=0;var on=class extends o{static contextType=w;explorerRow=a();explorerRowId=`seams-receipt-explorer-row-${++an}`;minimize=()=>{this.props.receipt.onView(`toast`)};expand=()=>{this.props.receipt.onView(`expanded`)};close=()=>{Yt(this.props.receipt)?this.minimize():this.props.receipt.onDismiss()};componentDidUpdate(e){let{receipt:t}=this.props;t.view===`expanded`&&e.receipt.view===`expanded`&&t.subject===`transaction`&&t.state.kind===`confirmed`&&e.receipt.state.kind!==`confirmed`&&this.revealExplorerLink()}componentWillUnmount(){this.releaseExplorerRow()}setExplorerRowHeight=e=>{let t=this.explorerRow.current;t&&S(t.ownerDocument).setDynamicDeclarations(this.explorerRowId,`#${this.explorerRowId}`,{"--seams-receipt-explorer-height":`${e}px`})};releaseExplorerRow=()=>{let e=this.explorerRow.current;e&&(delete e.dataset.opening,S(e.ownerDocument).deleteDynamicRule(this.explorerRowId))};revealExplorerLink(){let e=this.explorerRow.current,t=e?.firstElementChild;if(!e||!t||e.ownerDocument.defaultView?.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;let n=e.getBoundingClientRect().height;e.dataset.opening=``;let r=()=>{this.releaseExplorerRow(),t.animate([{opacity:0,filter:`blur(4px)`,transform:`translateY(6px)`},{opacity:1,filter:`blur(0)`,transform:`translateY(0)`}],{duration:240,easing:rn})};if(!I({reason:`receipt-explorer`,element:e,fromCssPx:0,toCssPx:n,drivenClasses:[`seams-receipt-explorer-driven`],setHeightCssPx:this.setExplorerRowHeight,onSettled:r})){let t=e.animate([{height:`0px`},{height:`${n}px`}],{duration:240,easing:rn});t.onfinish=r,t.oncancel=this.releaseExplorerRow}}render(){let{receipt:e,data:t}=this.props,n=$t(e),r=Xt(e),i=Yt(e),a=Zt(e),o=Pt(t.model),s=e.subject===`transaction`?e.state:null,u=s?.kind===`confirmed`&&s.hash?sn(t.model,this.props.explorers,s.hash):null;return e.view===`toast`?c(`div`,{class:`seams-transaction-toast`,"data-completed-stages":a,"data-stage":e.state.kind,"data-pending":i,children:[c(`div`,{class:`seams-toast-progress`,"aria-hidden":`true`,children:c(`span`,{class:`seams-toast-progress-fill`,children:i&&c(`span`,{class:`seams-toast-progress-active`})})}),c(`span`,{class:`seams-receipt-symbol`,"data-pending":i,children:c(G,{kind:i?`loader`:r?`check`:`alert`})}),c(`div`,{class:`seams-transaction-toast-text`,children:[c(`strong`,{role:`status`,children:c(x,{copy:n})}),c(`span`,{children:Nt(t.model)})]}),c(`button`,{type:`button`,class:`seams-receipt-open`,onClick:this.expand,children:[c(x,{message:`Open`}),` `,c(G,{kind:`arrow`})]}),!i&&c(`button`,{type:`button`,class:`seams-receipt-dismiss`,"aria-label":b(this.context,`Close transaction`),onClick:e.onDismiss,children:c(G,{kind:`close`})})]}):c(`div`,{class:`seams-transaction-receipt`,children:[c(`div`,{class:`seams-review-toolbar`,children:[c(`span`,{children:c(x,{copy:Qt(e)})}),c(`button`,{type:`button`,"aria-label":b(this.context,`Minimize transaction`),onClick:this.minimize,children:c(G,{kind:`minimize`})})]}),c(`div`,{class:`seams-receipt-heading`,children:[c(`span`,{class:`seams-receipt-symbol`,"data-pending":i,children:c(G,{kind:i?`loader`:r?`check`:`alert`})}),c(`div`,{children:[c(`h2`,{role:`status`,children:c(x,{copy:n})}),c(`p`,{children:c(x,{copy:en(e)})})]})]}),c(Lt,{model:t.model,compact:!0}),c(`div`,{class:`seams-receipt-destination`,children:[o&&c(l,{children:[c(x,{message:`To`}),` `,c(K,{value:o,address:!0,label:T(this.context,`Copy recipient address ${o}`)})]}),!o&&Nt(t.model)]}),t.model?.totals?.estimatedFee&&c(`dl`,{class:`seams-review-fields`,children:c(`div`,{children:[c(`dt`,{children:c(x,{message:`Estimated network fee`})}),c(`dd`,{children:[t.model.totals.estimatedFee,` `,t.model.totals.feeSymbol]})]})}),s?c(ln,{state:s}):e.subject===`message`&&c(un,{state:e.state}),c(W,{label:b(this.context,`Receipt details`),children:c(`dl`,{class:`seams-review-fields`,children:[s&&t.model?.signerAccount&&c(`div`,{children:[c(`dt`,{children:c(x,{message:`From`})}),c(`dd`,{class:`seams-review-recipient`,children:c(K,{value:t.model.signerAccount,address:!0,label:T(this.context,`Copy signer address ${t.model.signerAccount}`)})})]}),o&&c(`div`,{children:[c(`dt`,{children:[c(x,{message:`To`}),` `]}),c(`dd`,{class:`seams-review-recipient`,children:c(K,{value:o,address:!0,label:T(this.context,`Copy recipient address ${o}`)})})]}),s?.hash&&c(`div`,{children:[c(`dt`,{children:c(x,{message:`Transaction`})}),c(`dd`,{children:[c(Ft,{value:s.hash,class:`seams-review-hash`}),c(K,{value:s.hash})]})]}),e.subject===`message`&&c(dn,{model:t.model}),c(`div`,{children:[c(`dt`,{children:c(x,{message:`Status`})}),c(`dd`,{children:c(x,{copy:n})})]})]})}),c(`button`,{type:`button`,class:`seams-receipt-primary`,onClick:this.close,children:i?c(x,{message:`Continue in background`}):c(x,{message:`Done`})}),u&&c(`div`,{id:this.explorerRowId,class:`seams-receipt-explorer-row`,ref:this.explorerRow,children:c(`a`,{class:`seams-receipt-explorer`,href:u,target:`_blank`,rel:`noopener noreferrer`,children:[c(x,{message:`View transaction`}),` `,c(G,{kind:`arrow`})]})}),c(Rt,{})]})}};function sn(e,t,n){if(!e)return null;let r;switch(e.chain){case`near`:r=t.near;break;case`evm`:r=t.evm;break;case`tempo`:r=t.tempo;break;case`unknown`:return null;default:return cn(e.chain)}if(!r)return null;let i=e.chain===`near`?`txns`:`tx`;return`${r.trim().replace(/\/$/,``)}/${i}/${encodeURIComponent(n)}`}function cn(e){throw Error(`Unexpected display chain: ${String(e)}`)}function ln({state:e}){let t=y(),n=Zt({subject:`transaction`,state:e});return c(`div`,{class:`seams-receipt-steps`,"aria-label":b(t,`Transaction progress`),children:[c(J,{stage:`signing`,label:b(t,`Signed`),activeLabel:`Signing`,complete:n>=1,active:e.kind===`signing`}),c(J,{stage:`broadcast`,label:b(t,`Broadcast`),activeLabel:`Broadcasting`,complete:n>=2,active:e.kind===`broadcasting`}),c(J,{stage:`confirming`,label:T(t,e.kind===`reverted`?`Reverted`:`Confirmed`),activeLabel:`Confirming`,complete:n===3,active:e.kind===`submitted`})]})}function un({state:e}){let t=y(),n=e.kind===`signed`,r=e.kind===`signing`;return c(`div`,{class:`seams-receipt-steps`,"aria-label":b(t,`Transaction progress`),children:[c(J,{stage:`signing`,label:b(t,`Signed`),activeLabel:`Signing`,complete:n,active:r}),c(J,{stage:`signed`,label:``,activeLabel:``,complete:n,active:!1}),c(J,{stage:`signed`,label:``,activeLabel:``,complete:n,active:!1})]})}function dn({model:e}){let t=y(),n=e?.operations.length===1?e.operations[0]:null;return n?.kind===`near.message`?c(l,{children:n.fields?.map(e=>c(`div`,{children:[c(`dt`,{children:c(x,{copy:e.label})}),e.renderAs===`file-content`?c(`dd`,{children:[c(`span`,{class:`seams-receipt-message`,children:e.value}),c(K,{value:e.copyValue??e.value})]}):c(`dd`,{class:`seams-review-recipient`,children:c(K,{value:e.copyValue??e.value,address:!0,label:T(t,`Copy ${e.label.toLowerCase()} address ${e.value}`)})})]},e.label))}):null}function J(e){let t=e.complete?`complete`:e.active?`active`:`waiting`;return c(`span`,{class:`seams-receipt-step`,"data-stage":e.stage,"data-state":t,"aria-current":e.active?`step`:void 0,children:[c(`span`,{class:`seams-receipt-track`,"aria-hidden":`true`}),c(x,{copy:e.active?e.activeLabel:e.label})]})}const fn=`cubic-bezier(0.22, 1, 0.36, 1)`,pn=[`.seams-receipt-symbol`,`[role="status"]`,`.seams-review-amount`,`.seams-receipt-footer`];function mn(e){let t=[];for(let n of pn){let r=e.querySelector(n);r&&t.push({selector:n,text:r.textContent,bounds:r.getBoundingClientRect(),fontSize:getComputedStyle(r).fontSize,textGeometry:r.matches(`[role="status"]`)?hn(r):null})}return t}function hn(e){let t=e.ownerDocument.createRange();return t.selectNodeContents(e),{bounds:t.getBoundingClientRect(),lineCount:t.getClientRects().length}}function gn(e,t){let n=t.getBoundingClientRect(),r=parseFloat(e.fontSize)/parseFloat(getComputedStyle(t).fontSize),i=r,a=r,o=e.bounds.left-n.left,s=e.bounds.top-n.top;if(e.textGeometry){let r=hn(t),c=e.textGeometry.bounds,l=r.bounds;e.textGeometry.lineCount===r.lineCount&&l.width>0&&l.height>0&&(i=c.width/l.width,a=c.height/l.height,o=c.left-n.left-(l.left-n.left)*i,s=c.top-n.top-(l.top-n.top)*a)}return`translate(${o}px, ${s}px) scale(${i}, ${a})`}function _n(e){let t=e.querySelector(`[data-seams-progress-line]`);if(!t)return[];let n=getComputedStyle(t).color,r=Array.from(t.querySelectorAll(`[data-seams-progress-segment]`));if(r.length===3&&r.every(yn))return r.map(e=>({bounds:e.getBoundingClientRect(),opacity:e.getAttribute(`opacity`)??`1`,color:n})).sort((e,t)=>e.bounds.left-t.bounds.left);let i=t.getBoundingClientRect(),a=i.width/3;return[0,1,2].map(e=>({bounds:new DOMRect(i.left+e*a,i.top+i.height/2,a,0),opacity:`0.55`,color:n}))}function vn(){}function yn(e){return e.getAttribute(`opacity`)!==`0`}let bn=0;var xn=class{element;styles;presentation;state;receipt=null;receiptMotion=[];receiptShell=null;receiptGhost=null;receiptSegments=[];receiptResize=null;clearReceiptMotion=()=>{this.element.querySelector(`.seams-receipt-footer--hosted`)?.classList.remove(`seams-receipt-footer--hosted`),this.receiptResize?.element.classList.remove(`seams-surface-height-driven`),this.receiptResize=null,this.styles.deleteDynamicRule(`${this.element.id}-receipt-resize`);for(let e of this.receiptMotion)e.cancel();this.receiptMotion=[],this.receiptShell?.remove(),this.receiptShell=null,this.receiptGhost?.remove(),this.receiptGhost=null;for(let e of this.receiptSegments)e.remove();this.receiptSegments=[],this.element.removeAttribute(`data-receipt-segments`),this.element.removeAttribute(`data-receipt-morphing`)};constructor(e){let t=e.parent.ownerDocument;this.styles=S(t),this.presentation={variant:e.presentation.variant,context:e.presentation.context},this.state={kind:`mounted`,model:e.model,onClosed:e.onClosed},this.element=t.createElement(`div`),this.element.id=`seams-confirmation-surface-${++bn}`,this.element.className=`seams-wallet-ui seams-confirmation-surface`,this.element.dataset.seamsConfirmSurface=e.presentation.context,this.element.dataset.seamsConfirmVariant=e.presentation.variant,this.element.addEventListener(`cancel`,this.cancel),e.parent.appendChild(this.element);try{this.update(e.model)}catch(e){throw this.remove(),e}}update(e){this.state.kind===`mounted`&&(this.state.model=e,this.element.dataset.confirmationKind=e.content.kind,this.element.dataset.seamsConfirmReady=String(e.content.kind===`transaction`&&e.content.transaction.decision.kind===`ready`),this.element.lang=e.appearance.locale??`en`,this.element.dataset.theme=e.appearance.theme.mode,this.styles.setDynamicRule(this.element.id,ee(this.element.id,e.appearance)),this.renderSurface())}close(){this.state.kind===`mounted`&&(this.state={kind:`closing`,model:this.state.model,onClosed:this.state.onClosed},this.presentation.variant===`modal`?this.dispose():this.renderSurface())}showReceipt(e){if(this.state.kind!==`mounted`||this.state.model.content.kind!==`transaction`)return;let t=this.receipt?.view!==e.view||this.receiptMotion.length>0,n=this.receiptShell??this.element.querySelector(`.modal-container-root`),r=n?.getBoundingClientRect(),i=t?mn(this.element):[],a=t?this.liveCapture():null,o=n?getComputedStyle(n).borderRadius:`26px`;t&&this.clearReceiptMotion(),this.receipt=e,this.element.dataset.receiptView=e.view,this.element.dataset.seamsConfirmSurface=`wallet-iframe`,this.element.dataset.seamsConfirmVariant=`modal`,this.renderSurface();let s=this.element.querySelector(`.modal-container-root`);if(t&&r&&s&&!window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){let t=s.getBoundingClientRect(),n=this.element.ownerDocument.createElement(`div`);n.className=`seams-receipt-morph-shell`,n.setAttribute(`aria-hidden`,`true`),this.element.appendChild(n),this.receiptShell=n,this.element.setAttribute(`data-receipt-morphing`,``);let c=n.animate([{left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`,borderRadius:o},{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`,borderRadius:getComputedStyle(s).borderRadius}],{duration:640,easing:fn,fill:`both`});this.receiptMotion=[c];let l=[c],u=a?this.handOverCapture(a,s):!1,d=new Set;for(let e of i){let t=s.querySelector(e.selector);if(!t||t.textContent!==e.text)continue;d.add(t);let n=t.animate([{transform:gn(e,t),transformOrigin:`top left`},{transform:`translate(0, 0) scale(1)`,transformOrigin:`top left`}],{duration:640,easing:fn});this.receiptMotion.push(n),l.push(n)}let f=s.querySelectorAll(`.seams-transaction-receipt > :not(.seams-receipt-heading), .seams-receipt-heading > .seams-receipt-symbol, .seams-receipt-heading h2, .seams-receipt-heading p, .seams-transaction-toast > :not(.seams-transaction-toast-text, .seams-toast-progress), .seams-transaction-toast-text > *`),p=0;for(let t of f){if(d.has(t))continue;let n=a!==null&&t.matches(`.seams-review-toolbar`),r=n||t.matches(`.seams-receipt-footer`);this.receiptMotion.push(t.animate(r?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`translateY(0)`}],a?{duration:360,delay:n?0:u&&t.matches(`.seams-receipt-steps`)?560:200+Math.min(p,6)*40,fill:`backwards`,easing:`cubic-bezier(0.2, 0, 0, 1)`}:{duration:120,delay:e.view===`toast`?240:180+Math.min(p,4)*15,fill:`backwards`,easing:`ease-out`})),n||(p+=1)}this.resizeReceipt({element:s,animations:l,fromHeight:r.height,toHeight:t.height});let m=this.receiptMotion;Promise.all(m.map(e=>e.finished)).then(()=>{this.receiptMotion===m&&this.clearReceiptMotion()},vn)}}resizeReceipt(e){if(!(Math.abs(e.toHeight-e.fromHeight)<1)){this.receiptResize=e;for(let t of e.animations)t.pause(),t.effect?.updateTiming({easing:`linear`});if(e.element.classList.add(`seams-surface-height-driven`),this.setReceiptHeight(e,e.fromHeight),Ke(e.element,{reason:`receipt-transition`,fromCssPx:e.fromHeight,toCssPx:e.toHeight,setHeightCssPx:this.setReceiptHeight.bind(this,e),finish:this.finishReceiptResize.bind(this,e)})){this.fitReceiptToViewport(e);return}this.receiptResize=null,e.element.classList.remove(`seams-surface-height-driven`),this.styles.deleteDynamicRule(`${this.element.id}-receipt-resize`);for(let t of e.animations)t.effect?.updateTiming({easing:fn}),t.play()}}fitReceiptToViewport(e){let t=e.element.querySelector(`.seams-receipt-footer`);for(let n of e.animations){let e=n.effect;if(e instanceof KeyframeEffect){if(e.target===this.receiptShell){this.receiptShell?.classList.add(`seams-receipt-morph-shell--hosted`);let t=e.getKeyframes();for(let e of t)delete e.height,delete e.width;e.setKeyframes(t)}else if(t&&e.target===t){let t=e.getKeyframes();for(let e of t)delete e.transform;e.setKeyframes(t)}}}t?.classList.add(`seams-receipt-footer--hosted`)}setReceiptHeight(e,t){if(this.receiptResize!==e)return;this.styles.setDynamicDeclarations(`${this.element.id}-receipt-resize`,`#${e.element.id}`,{[F]:`${t}px`,"--seams-receipt-target-height":`${e.toHeight}px`});let n=(t-e.fromHeight)/(e.toHeight-e.fromHeight);for(let t of e.animations)t.currentTime=Math.max(0,Math.min(1,n))*640}finishReceiptResize(e){if(this.receiptResize===e){this.receiptResize=null,e.element.classList.remove(`seams-surface-height-driven`),e.element.querySelector(`.seams-receipt-footer--hosted`)?.classList.remove(`seams-receipt-footer--hosted`),this.styles.deleteDynamicRule(`${this.element.id}-receipt-resize`);for(let t of e.animations)t.finish()}}liveCapture(){if(this.state.kind!==`mounted`||this.state.model.content.kind!==`transaction`)return null;let e=this.state.model.content.capture;return e?.isConnected?{element:e,bounds:e.getBoundingClientRect(),segments:_n(e)}:null}handOverCapture(e,t){let n=this.element.ownerDocument.createElement(`div`);n.className=`seams-receipt-capture-ghost`,n.setAttribute(`aria-hidden`,`true`),n.append(e.element),this.element.appendChild(n),this.receiptGhost=n;let r={left:`${e.bounds.left}px`,top:`${e.bounds.top}px`,width:`${e.bounds.width}px`,height:`${e.bounds.height}px`};this.receiptMotion.push(n.animate([{...r,opacity:1},{...r,opacity:0}],{duration:160,easing:`ease-out`,fill:`both`}));let i=t.querySelectorAll(`.seams-receipt-track`);if(e.segments.length===0||i.length!==e.segments.length)return!1;this.element.setAttribute(`data-receipt-segments`,``);for(let[t,n]of i.entries()){let r=e.segments[t],i=n.getBoundingClientRect(),a=n.closest(`.seams-receipt-step`)?.dataset.state===`complete`,o=this.element.ownerDocument.createElement(`div`);o.className=`seams-receipt-segment`,o.setAttribute(`aria-hidden`,`true`),this.element.appendChild(o),this.receiptSegments.push(o),this.receiptMotion.push(o.animate([{left:`${r.bounds.left}px`,top:`${r.bounds.top+r.bounds.height/2-.5}px`,width:`${r.bounds.width}px`,height:`1px`,borderRadius:`1px`,opacity:r.opacity,backgroundColor:r.color},{left:`${i.left}px`,top:`${i.top}px`,width:`${i.width}px`,height:`${i.height}px`,borderRadius:getComputedStyle(n).borderRadius,opacity:1,backgroundColor:getComputedStyle(n,a?`::after`:null).backgroundColor}],{duration:800,delay:120,easing:`cubic-bezier(0.65, 0, 0.35, 1)`,fill:`both`}))}return!0}dispose=()=>{if(this.state.kind===`disposed`)return;let e=this.state.onClosed;this.remove(),e()};remove(){this.clearReceiptMotion(),this.state={kind:`disposed`},this.element.removeEventListener(`cancel`,this.cancel),s(null,this.element),this.styles.deleteDynamicRule(this.element.id),this.element.remove()}cancel=()=>{if(this.state.kind!==`mounted`)return;if(this.receipt){Yt(this.receipt)?this.receipt.onView(`toast`):this.receipt.onDismiss();return}let e=this.state.model.content;e.kind===`registration`?e.registration.onCancel():e.transaction.onCancel()};confirm=()=>{if(this.state.kind!==`mounted`)return;let e=this.state.model.content,t=e.kind===`registration`?e.registration.decision:e.transaction.decision;t.kind===`ready`&&t.onConfirm()};submitOtp=(e,t)=>{if(this.state.kind!==`mounted`)return;let n=this.state.model.content;n.kind===`transaction`&&n.prompt.kind===`email`&&n.prompt.email.onSubmit(e,t)};renderSurface(){let e=this.state;if(e.kind===`disposed`)return;let t=e.model.content,n=this.contentModel(t,e.kind===`closing`),r=this.receipt&&t.kind===`transaction`?c(on,{receipt:this.receipt,data:t.review,explorers:t.transaction.explorers}):c(Gt,{model:n,styles:this.styles,variant:this.presentation.variant}),i=t.kind===`registration`?t.registration.heading:t.header.heading;if(this.receipt||this.presentation.variant===`modal`){s(C(e.model.appearance.locale??`en`,c(te,{context:this.receipt?`wallet-iframe`:this.presentation.context,label:i,onCancel:this.cancel,children:r})),this.element);return}let a=t.kind===`registration`?t.registration.decision:t.transaction.decision;s(C(e.model.appearance.locale??`en`,c(re,{context:this.presentation.context,label:i,origin:t.kind===`transaction`&&t.header.website.kind===`ready`?c(l,{children:[c(L,{}),t.header.website.text]}):void 0,errorMessage:t.kind===`registration`?t.registration.errorMessage:t.transaction.errorMessage,styles:this.styles,state:e.kind===`closing`?{kind:`closing`,onClosed:this.dispose}:{kind:`open`,interaction:a.kind===`ready`?`ready`:`busy`},onCancel:this.cancel,children:r})),this.element)}contentModel(e,t){switch(e.kind){case`registration`:return{kind:`registration`,registration:{...e.registration,decision:!t&&e.registration.decision.kind===`ready`?{kind:`ready`,onConfirm:this.confirm}:{kind:`creating`},onCancel:this.cancel}};case`transaction`:return{kind:`transaction`,capture:e.capture,header:e.header,body:e.body,review:e.review,prompt:e.prompt.kind===`email`?{kind:`email`,email:{prompt:e.prompt.email.prompt,verification:t?{kind:`pending`}:e.prompt.email.verification,onSubmit:this.submitOtp}}:e.prompt,transaction:{...e.transaction,decision:!t&&e.transaction.decision.kind===`ready`?{kind:`ready`,onConfirm:this.confirm}:{kind:`preparing`},onCancel:this.cancel}};default:return Sn(e)}}};function Sn(e){throw Error(`Unexpected confirmation content: ${String(e)}`)}function Cn(e){return new xn(e)}var wn=class{element;surface;callbacks;appearance;presentation;tree;currentModel;constructor(e){this.callbacks=e.callbacks,this.appearance=e.appearance,this.presentation=e.presentation,this.tree=e.tree,this.currentModel=this.normalize(),this.surface=Cn({parent:e.parent,presentation:{variant:e.variant,context:e.context},model:this.currentModel,onClosed:e.onClosed}),this.element=this.surface.element}update(e){this.presentation=Tn(this.presentation,e),e.appearance&&(this.appearance=e.appearance),Object.hasOwn(e,`model`)&&(this.tree=A({model:e.model})),this.currentModel=this.normalize(),this.surface.update(this.currentModel)}setTree(e){this.tree=e,this.currentModel=this.normalize(),this.surface.update(this.currentModel)}close(){this.surface.close()}showReceipt(e){this.surface.showReceipt(e)}dispose(){this.surface.dispose()}normalize(){let e=Ie({presentation:this.presentation,appearance:this.appearance,tree:this.tree,callbacks:this.callbacks});if(!e.ok)throw Error(`Cannot render confirmation surface: ${e.error}`);return e.model}};function Tn(e,t){return{model:Object.hasOwn(t,`model`)?t.model:e.model,securityContext:Object.hasOwn(t,`securityContext`)?t.securityContext:e.securityContext,loading:Object.hasOwn(t,`loading`)?t.loading:e.loading,preparing:Object.hasOwn(t,`preparing`)?t.preparing:e.preparing,title:Object.hasOwn(t,`title`)?t.title:e.title,body:Object.hasOwn(t,`body`)?t.body:e.body,authMethodCapture:Object.hasOwn(t,`authMethodCapture`)?t.authMethodCapture:e.authMethodCapture,authMethodApprovalMessage:Object.hasOwn(t,`authMethodApprovalMessage`)?t.authMethodApprovalMessage:e.authMethodApprovalMessage,errorMessage:Object.hasOwn(t,`errorMessage`)?t.errorMessage:e.errorMessage,confirmText:Object.hasOwn(t,`confirmText`)?t.confirmText:e.confirmText,cancelText:Object.hasOwn(t,`cancelText`)?t.cancelText:e.cancelText,onBack:Object.hasOwn(t,`onBack`)?t.onBack:e.onBack,signingAuthMode:Object.hasOwn(t,`signingAuthMode`)?t.signingAuthMode:e.signingAuthMode,emailOtpPrompt:Object.hasOwn(t,`emailOtpPrompt`)?t.emailOtpPrompt:e.emailOtpPrompt,nearExplorerUrl:Object.hasOwn(t,`nearExplorerUrl`)?t.nearExplorerUrl:e.nearExplorerUrl,tempoExplorerUrl:Object.hasOwn(t,`tempoExplorerUrl`)?t.tempoExplorerUrl:e.tempoExplorerUrl,evmExplorerUrl:Object.hasOwn(t,`evmExplorerUrl`)?t.evmExplorerUrl:e.evmExplorerUrl}}function En(e){return new wn(e)}var Dn=e({awaitConfirmUIDecision:()=>nr,mountConfirmUI:()=>Zn,prepareConfirmUISurface:()=>tr});const Y=`seams-confirm-portal`;function On(e){return Math.max(0,Math.round(performance.now()-e))}const kn=new WeakMap,An=new WeakMap,jn=new WeakMap,X=new WeakMap,Mn=new WeakMap,Z=new WeakMap;function Nn(e){try{if(!ce()||typeof window>`u`||window.parent===window)return;window.parent?.postMessage({type:e},`*`)}catch{}}function Pn(e){return e===`drawer`?`drawer`:`modal`}function Fn(e){return(e||[]).map(e=>({receiverId:e.receiverId,actions:(e.actions||[]).map(e=>f(e)?e:d(e)).map(e=>h(e))}))}async function In(e,t){if(!(!((t?.length||0)>0)||!e))try{return await g(Fn(t))===e?void 0:`INTENT_DIGEST_MISMATCH`}catch{return`UI_DIGEST_VALIDATION_FAILED`}}function Ln(e){e.childElementCount>0?e.classList.add(`seams-portal--visible`):e.classList.remove(`seams-portal--visible`)}function Rn(){let e=[];for(let t of document.querySelectorAll(`.seams-confirmation-surface`))t.parentElement?.closest(`.seams-confirmation-surface`)||e.push(t);return e}function zn(){for(let e of Rn())Mn.get(e)?.callbacks.cancel(),X.get(e)?.dispose(),Z.delete(e),$(e),e.remove();let e=document.getElementById(Y);e&&Ln(e)}function Bn(){let e=document.getElementById(Y);if(!e){e=document.createElement(`div`),e.id=Y,e.classList.add(`seams-portal`);let t=document.body??document.documentElement;t&&t.appendChild(e)}return e}function Vn(e){X.delete(e),Z.delete(e),$(e),e.remove();let t=document.getElementById(Y);t&&Ln(t)}function Hn(){(document.getElementById(Y)?.childElementCount??0)>0||Nn(`WALLET_UI_CLOSED`)}function Un(e,t){let r=t?.chain;if(r!==`near`&&r!==`tempo`&&r!==`evm`)return{};let i=n({chains:e.chains,family:r,chainId:t?.chainId});return i?r===`near`?{nearExplorerUrl:i}:r===`tempo`?{tempoExplorerUrl:i}:{evmExplorerUrl:i}:{}}function Wn(e,t){t&&(e.update(t),Object.hasOwn(t,`model`)&&Q(e.element,e,t.model))}function Q(e,t,n){let r=(Z.get(e)??0)+1;Z.set(e,r),!(!n||!Ee(n))&&import(`./enrichDisplayModelWithAbi-O6Mw4i2E.js`).then(i=>{if(Z.get(e)!==r||!e.isConnected||X.get(e)!==t)return;let a=i.enrichDisplayModelWithAbi(n);Z.get(e)===r&&t.setTree(A({model:a}))}).catch(e=>{console.warn(`[ConfirmUI] failed to lazy-load ABI display enrichment`,e)})}function $(e){kn.get(e)?.disconnect(),kn.delete(e),An.get(e)?.dispose(),An.delete(e),jn.delete(e)}function Gn(e,t){switch(e.kind){case`disabled`:return null;case`wallet_iframe`:return i({kind:t.getAttribute(`data-seams-confirm-variant`)===`modal`?`request_scroll_surface`:`request_surface`,element:t,requestId:e.requestId,postMeasurement:e.postMeasurement});default:{let t=e;throw Error(`Unhandled confirmation measurement binding: ${String(t)}`)}}}function Kn(e,t,n){e.setAttribute(Ge,ir(n,t)),e.setAttribute(`data-seams-confirm-variant`,t),e.toggleAttribute(`data-seams-review-frame`,!!r(n))}function qn(e,t,n){if(r(n)?.attach(e),Kn(e,t,n),ie(jn.get(e),n))return;$(e),jn.set(e,n);let i=Gn(n,e);i&&(kn.set(e,i),An.set(e,nt(e)))}function Jn(e,t){t.kind===`review_available`&&e.returnToReview()}var Yn=class{view=null;navigation={kind:`review_available`};queuedDecisions=[];decisionWaiters=[];phase=`pending`;cancelListeners=new Set;onBack;callbacks={confirm:this.confirm.bind(this),cancel:this.cancel.bind(this),submitEmail:this.submitEmail.bind(this)};constructor(e){this.admission=e,this.onBack=e?this.back.bind(this):void 0}attachView(e){this.view=e;let t=this.admission;t?.requiresAuthMethodApproval&&this.prepareAuthMethod(t,e)}async prepareAuthMethod(e,t){this.phase=`preparing`,t.update({preparing:!0,authMethodCapture:e.authMethodApprovalSurface});try{if(await e.prepareAuthMethod(),this.phase!==`preparing`)return;this.phase=`pending`,t.update({preparing:!1,authMethodCapture:null})}catch(e){this.cancel(e instanceof Error?e.message:`VoiceID preparation failed.`)}}publishDecision(e){if(this.phase===`published`)return;this.phase=`published`,this.navigation.kind=`decision_published`;let t=this.decisionWaiters.shift();if(t){t(e);return}this.queuedDecisions.push(e)}back(){this.phase===`preparing`||this.phase===`checking`?this.cancel(`Voice approval was cancelled.`):this.admission&&Jn(this.admission,this.navigation)}cancel(e){if(this.phase!==`published`){this.publishDecision({kind:`cancelled`,error:e??null}),this.admission?.cancel(Error(e??`Wallet approval was cancelled.`));for(let t of this.cancelListeners)t({...e?{error:e}:{}})}}confirm(){this.approve({kind:`confirmed`,emailOtp:{kind:`absent`}})}submitEmail(e,t){let n=e.trim(),r=t.trim();if(!n||!r){this.cancel(`Email OTP challenge is missing.`);return}this.approve({kind:`confirmed`,emailOtp:{kind:`provided`,code:n,challengeId:r}})}async approve(e){if(!(this.phase!==`pending`||this.admission&&!this.admission.allowInteraction())){this.phase=`checking`;try{this.admission?.authMethodApprovalMessages&&this.view?.update({preparing:!0,authMethodCapture:this.admission.authMethodApprovalSurface});let t=await this.admission?.approveAuthMethod();if(t?.kind===`retry`){this.phase=`pending`,this.view?.update({preparing:!1,authMethodCapture:null,authMethodApprovalMessage:t.message});return}this.admission?.authMethodApprovalMessages&&this.view?.update({preparing:!1,authMethodApprovalMessage:this.admission.authMethodApprovalMessages.approved}),this.publishDecision(e)}catch(e){this.cancel(e instanceof Error?e.message:`Authentication method approval failed.`)}}}async takeDecision(){return this.queuedDecisions.shift()||(this.phase===`published`&&(this.phase=`pending`),await new Promise(this.waitForDecision))}waitForDecision=e=>{this.decisionWaiters.push(e)}};function Xn(e,t,n){let r=!1;return{element:e.element,close:i=>{r||(r=!0,i||t.callbacks.cancel(),t.cancelListeners.clear(),!(i&&n.kind===`wallet_iframe`&&v(n.requestId,e))&&($(e.element),e.close()))},update:t=>Wn(e,t),onCancel:e=>(t.cancelListeners.add(e),()=>t.cancelListeners.delete(e)),takeDecision:()=>t.takeDecision()}}async function Zn({ctx:e,summary:t,txSigningRequests:n,model:r,securityContext:i,loading:a,theme:o,appearance:s,uiMode:c,signingAuthMode:l,emailOtpPrompt:u}){return rr({ctx:e,summary:t,txSigningRequests:n,model:r,securityContext:i,loading:a,theme:o,appearance:s,variant:Pn(c),signingAuthMode:l,emailOtpPrompt:u})}function Qn(e){let t=e.surface.handle,n=t.element;if(!n.isConnected)throw Error(`Cannot reuse a detached confirmation surface`);let r=X.get(n);if(!r)throw Error(`Cannot reuse an unmanaged confirmation surface`);qn(n,e.variant,e.ctx.surfaceMeasurementBinding);let i=ae({getAppearance:e.ctx.getAppearance,requestedAppearance:e.appearance,requestedMode:e.theme}),a=Un(e.ctx,e.model);return r.update({model:e.model,securityContext:e.securityContext,loading:e.loading??!1,appearance:i,title:e.summary.title??``,body:e.summary.body??``,signingAuthMode:e.signingAuthMode,emailOtpPrompt:e.emailOtpPrompt,errorMessage:``,...a}),r.setTree(A({txSigningRequests:e.txSigningRequests,model:e.model})),Q(n,r,e.model),{handle:t,reused:!0}}function $n(e){throw Error(`Unhandled confirmation surface: ${JSON.stringify(e)}`)}function er(e){switch(e.surface.kind){case`mount_new`:return{handle:rr({ctx:e.ctx,summary:e.summary,txSigningRequests:e.txSigningRequests,model:e.model,securityContext:e.securityContext,loading:e.loading,theme:e.theme,appearance:e.appearance,variant:e.variant,signingAuthMode:e.signingAuthMode,emailOtpPrompt:e.emailOtpPrompt}),reused:!1};case`reuse_mounted`:return Qn({...e,surface:e.surface});case`preparation_cancelled`:throw Error(`A cancelled preparation surface cannot be mounted`);default:return $n(e.surface)}}async function tr(e){return er({ctx:e.ctx,summary:e.summary,txSigningRequests:e.txSigningRequests,model:e.model,securityContext:e.securityContext,loading:e.loading,theme:e.theme,appearance:e.appearance,variant:Pn(e.uiMode),signingAuthMode:e.signingAuthMode,emailOtpPrompt:e.emailOtpPrompt,surface:e.surface}).handle}async function nr({ctx:e,summary:t,txSigningRequests:n,model:r,securityContext:i,loading:a,theme:o,appearance:s,uiMode:c,onMounted:l,signingAuthMode:u,emailOtpPrompt:d,surface:f}){let p=Pn(c);return new Promise(c=>{let m=performance.now(),{handle:h,reused:g}=er({ctx:e,summary:t,txSigningRequests:n,model:r,securityContext:i,loading:a,theme:o,appearance:s,variant:p,signingAuthMode:u,emailOtpPrompt:d,surface:f}),_=On(m),v=performance.now(),y=0,b=g?_:0,x=0,S=e=>e>0?e:On(v);Promise.resolve().then(()=>{y=S(y),g||(b=S(b))});try{l?.(h)}catch{}let C=e=>{let t={kind:`confirm_ui_prompt_diagnostics_v1`,elementDefineMs:0,mountMs:_,hostFirstUpdateMs:y,hostInteractiveMs:b,confirmEventMs:x,decisionWaitMs:On(v)};T(),c({...e,handle:h,diagnostics:t})},w=async e=>{if(x=S(x),e.kind===`cancelled`){let t=e.error||void 0;h.update({...t?{errorMessage:t}:{},loading:!1}),C({confirmed:!1,error:t});return}let i,a=await In(String(r?.intentDigest||t?.intentDigest||``).trim(),n);if(a&&(i=a),i){h.update({errorMessage:i,loading:!1}),C({confirmed:!1,error:i});return}C({confirmed:!0,...e.emailOtp.kind===`provided`?{otpCode:e.emailOtp.code,emailOtpChallengeId:e.emailOtp.challengeId}:{}})},T=()=>{y=Math.max(y,0)};(async()=>{let e=await h.takeDecision();u===`emailOtp`&&e.kind===`confirmed`&&e.emailOtp.kind===`absent`&&(h.update({loading:!1}),e=await h.takeDecision()),await w(e)})()})}function rr({ctx:e,summary:t,txSigningRequests:n,model:i,securityContext:a,loading:o,theme:s,appearance:c,variant:l,signingAuthMode:u,emailOtpPrompt:d}){r(e.surfaceMeasurementBinding)?.assertPending(),zn();let f=ae({getAppearance:e.getAppearance,requestedAppearance:c,requestedMode:s}),p=Bn(),m=Un(e,i),h=new Yn(r(e.surfaceMeasurementBinding)),g;return g=En({parent:p,variant:l,context:ir(e.surfaceMeasurementBinding,l),appearance:f,presentation:{onBack:h.onBack,model:i,securityContext:a,loading:o,title:t?.title??(t?.delegate?`Sign Delegate Action`:void 0),body:t?.body,confirmText:r(e.surfaceMeasurementBinding)?.authMethodApprovalMessages?.confirm,signingAuthMode:u,emailOtpPrompt:d,nearExplorerUrl:e.nearExplorerUrl??m.nearExplorerUrl,tempoExplorerUrl:e.tempoExplorerUrl??m.tempoExplorerUrl,evmExplorerUrl:e.evmExplorerUrl??m.evmExplorerUrl},tree:A({txSigningRequests:n,model:i}),callbacks:h.callbacks,onClosed:()=>{Vn(g.element),Hn()}}),h.attachView(g),X.set(g.element,g),Mn.set(g.element,h),Ln(p),qn(g.element,l,e.surfaceMeasurementBinding),Q(g.element,g,i),p.classList.remove(`seams-portal--visible`),requestAnimationFrame(()=>{p.classList.add(`seams-portal--visible`)}),Nn(`WALLET_UI_OPENED`),Xn(g,h,e.surfaceMeasurementBinding)}function ir(e,t){let n=e.kind===`wallet_iframe`?e.hostSurfaceVariant??t:t;return e.kind===`wallet_iframe`&&n===`modal`?`wallet-iframe`:`standalone`}export{L as a,ce as c,tr as i,se as l,Dn as n,ke as o,Zn as r,Me as s,nr as t};
@@ -1 +0,0 @@
1
- import{i as e}from"./domainIds-t1lp25yU.js";import{r as t,t as n}from"./digests-BIaE0DMd.js";import{i as r,r as i}from"./base64-BmKR3UqU.js";import{r as a}from"./secureRandomId-8LSc91aN.js";import{s as o}from"./walletDbName-Ca0rCq5r.js";import{g as s}from"./capabilityKinds-DVlGMspk.js";import{r as c}from"./canonicalPrimitives-Jd3i_Ngz.js";import{i as l,n as u}from"./signerDomain-BAsLT3XN.js";import{c as d,o as f}from"./ecdsaChainTarget-Bm5X4k-V.js";import{C as p,Ct as m,E as h,Nt as g,O as _,Pt as v,c as y}from"./digestEncoding-CqNXPZY9.js";import{B as ee,C as te,E as b,I as ne,R as re,S as ie,x,y as S,z as ae}from"./ecdsaCapabilityManifest-DAJEVjlP.js";import{C,h as oe,v as w}from"./emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js";import{r as T}from"./types-f7dyj5N6.js";import{o as se}from"./walletSessionAuthorizationStore-B9Vwkshr.js";import{t as ce}from"./thresholdEcdsa-CqR1fFA-.js";import{p as le}from"./nearEd25519YaoSigningPreparation-DHNk0F8e.js";import{a as ue,i as de,r as fe}from"./walletSessionAuthorizationProjection-BzUH6gHV.js";import{a as pe,d as me,i as he,n as ge,u as _e}from"./ecdsaDerivationClientWasm-AYOJgTJm.js";import{a as ve,r as ye,t as be}from"./walletSessionFailure-CxsVtroW.js";import{a as E,o as D}from"./signingQueue-dMFOFOP5.js";import{t as O}from"./bytes-DXo6uALR.js";const xe=`router-ab-ed25519-yao-seed-export-v1`;function Se(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n=typeof t.id==`string`&&t.id.trim()?t.id.trim():void 0;return t.success===!0&&`data`in t&&t.error===void 0?{id:n,success:!0,data:t.data}:t.success===!1&&typeof t.error==`string`&&t.data===void 0?{id:n,success:!1,error:t.error}:null}function k(e){return e.kind===`credential_free_ecdsa_session_activation_authorization_v1`}function Ce(e,t){return e.error||e.message||e.code||t}function A(e){return _({kind:`router_ab_ecdsa_post_registration_session_activation_v1`,public_capability:e.publicCapability,session_policy:{threshold_session_id:e.thresholdSessionId,wallet_session_mint_id:e.walletSessionMintId,ttl_ms:e.ttlMs,remaining_uses:e.remainingUses,runtime_policy_scope:e.runtimePolicyScope}})}function we(e,t){let n=t.public_identity;return e.applicationBindingDigestB64u===t.context.application_binding_digest_b64u&&e.contextBinding32B64u===n.context_binding_b64u&&e.derivationClientSharePublicKey33B64u===n.derivation_client_share_public_key33_b64u&&e.relayerPublicKey33B64u===n.server_public_key33_b64u&&e.groupPublicKey33B64u===n.threshold_public_key33_b64u&&e.ethereumAddress.toLowerCase()===O(i(n.ethereum_address20_b64u))&&S(e.publicCapability,t)}function Te(e,t){let n=e.normal_signing.scope;return n.wallet_id===String(t.walletId)&&n.ecdsa_threshold_key_id===String(t.ecdsaThresholdKeyId)&&n.signing_root_id===String(t.signingRootId)&&n.signing_root_version===String(t.signingRootVersion)}function Ee(e){let t=e.persistedRoleLocalMaterial.publicFacts;if(!S(e.sessionActivation.public_capability,e.publicCapability)||e.sessionActivation.session.threshold_session_id!==e.thresholdSessionId||!Te(e.sessionActivation,t))throw Error(`Strict ECDSA session activation returned a different registered key identity`)}function De(t){let n=t.sessionActivation.activation,r=t.sessionActivation.authorization,i=r.record,a=g(n.public_capability.material_activation),o=0;for(let t of i.capabilitySubjects)t.kind===`sign`&&t.keyFamily===`ecdsa_secp256k1`&&e(t.materialActivation,a)&&(o+=1);if(Ee({publicCapability:t.publicCapability,persistedRoleLocalMaterial:t.persistedRoleLocalMaterial,thresholdSessionId:t.thresholdSessionId,sessionActivation:n}),String(i.walletId)!==t.walletId||String(i.walletId)!==String(n.public_capability.client_id)||i.authMethodId!==t.persistedRoleLocalMaterial.authority.walletAuthMethodId||i.authorizationId!==n.session.authorization_id||i.quotaId!==n.session.quota_id||i.expiresAtMs!==n.session.expires_at_ms||n.session.remaining_uses!==t.remainingUses||r.operationCredential.walletSessionId!==n.session.wallet_session_id||!e(a,t.persistedRoleLocalMaterial.materialActivation)||o!==1)throw Error(`Strict ECDSA credential-free activation authority does not match its session`)}function j(e){let t=e.persistedRoleLocalMaterial.publicFacts;if(!e.walletId||!e.thresholdSessionId)throw Error(`Strict ECDSA session activation requires exact wallet and session identity`);if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<1)throw Error(`Strict ECDSA session activation requires a positive ttlMs`);if(!Number.isSafeInteger(e.remainingUses)||e.remainingUses<1)throw Error(`Strict ECDSA session activation requires positive remainingUses`);if(String(t.walletId)!==e.walletId||!we(t,e.publicCapability))throw Error(`Strict ECDSA session activation requires exact registered role-local material`)}function Oe(e){switch(e.kind){case`rehydrated`:return e;case`device_link_required`:throw Error(`device_link_required: registered ECDSA role-local material is unavailable on this device`);case`corrupt`:throw Error(`Registered ECDSA role-local material is corrupt (${e.reason}): ${e.message}`);default:{let t=e;throw Error(`Unsupported ECDSA role-local material resolution: ${String(t)}`)}}}async function M(e){let t=Oe(await D({purpose:`registration_activation`,source:E(e.persistedRoleLocalMaterial),workerCtx:e.workerCtx}));return{kind:`existing_ecdsa_role_local_material_activated_v1`,roleLocalMaterial:t.liveHandle,roleLocalMaterialRef:t.materialRef,publicFacts:e.persistedRoleLocalMaterial.publicFacts,publicCapability:e.publicCapability}}async function ke(e){j(e);let t=await ce(e.relayerUrl,{auth:e.routeAuth,request:A(e)});if(!t.ok)throw Error(Ce(t,`Strict ECDSA session activation failed`));return await N({workerCtx:e.workerCtx,publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.persistedRoleLocalMaterial,walletId:e.walletId,thresholdSessionId:e.thresholdSessionId,ttlMs:e.ttlMs,remainingUses:e.remainingUses,runtimePolicyScope:e.runtimePolicyScope,sessionActivation:t.value})}async function N(e){return j(e),Ee({publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.persistedRoleLocalMaterial,thresholdSessionId:e.thresholdSessionId,sessionActivation:e.sessionActivation}),{sessionActivation:e.sessionActivation,roleLocalActivation:await M(e)}}async function Ae(e){return j(e),De(e),{sessionActivation:e.sessionActivation.activation,authorization:e.sessionActivation.authorization,roleLocalActivation:await M(e)}}async function je(e,t){let n=o(e.lanePolicy.runtimePolicyScope);if(!n)throw Error(`Strict ECDSA session activation requires runtimePolicyScope`);let r={workerCtx:e.workerCtx,publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.existingRoleLocalMaterial,walletId:String(e.key.walletId),thresholdSessionId:e.lanePolicy.thresholdSessionId,ttlMs:e.lanePolicy.ttlMs,remainingUses:e.lanePolicy.remainingUses,runtimePolicyScope:n},s=e.sessionActivation?k(e.sessionActivation)?await Ae({...r,sessionActivation:e.sessionActivation}):await N({...r,sessionActivation:e.sessionActivation}):await ke({...r,walletSessionMintId:Me(),relayerUrl:e.relayerUrl,routeAuth:e.bootstrapAuth}),c=s.sessionActivation.public_capability.public_identity,l=`authorization`in s?{thresholdSessionId:s.sessionActivation.session.threshold_session_id,authorizationSessionId:s.sessionActivation.session.authorization_session_id,authorizationId:s.sessionActivation.session.authorization_id,walletSessionId:s.sessionActivation.session.wallet_session_id,quotaId:s.sessionActivation.session.quota_id,expiresAtMs:s.sessionActivation.session.expires_at_ms,remainingUses:s.sessionActivation.session.remaining_uses,walletSession:s.authorization.record,operationCredential:s.authorization.operationCredential}:{thresholdSessionId:s.sessionActivation.session.threshold_session_id,authorizationSessionId:s.sessionActivation.session.authorization_session_id,authorizationId:s.sessionActivation.session.authorization_id,walletSessionId:s.sessionActivation.session.wallet_session_id,quotaId:s.sessionActivation.session.quota_id,expiresAtMs:s.sessionActivation.session.expires_at_ms,remainingUses:s.sessionActivation.session.remaining_uses,walletSession:s.sessionActivation.session.wallet_session,operationCredential:s.sessionActivation.session.operation_credential},u=await m({walletId:String(e.key.walletId),signingRootId:e.key.signingRootId,signingRootVersion:e.key.signingRootVersion});return{ok:!0,bootstrapKind:`strict_post_registration`,keygenSessionId:String(e.requestId||``).trim()||a(`tecdsa-keygen`,32,`threshold ECDSA session IDs`),rpId:t,keyHandle:String(e.keyHandle),clientVerifyingShareB64u:c.derivation_client_share_public_key33_b64u,thresholdEcdsaPublicKeyB64u:c.threshold_public_key33_b64u,ethereumAddress:O(i(c.ethereum_address20_b64u)),relayerKeyId:u,relayerVerifyingShareB64u:c.server_public_key33_b64u,participantIds:e.key.participantIds.map(Number),thresholdSessionId:l.thresholdSessionId,authorizationSessionId:l.authorizationSessionId,authorizationId:l.authorizationId,walletSessionId:l.walletSessionId,quotaId:l.quotaId,expiresAtMs:l.expiresAtMs,remainingUses:l.remainingUses,runtimePolicyScope:n,signingRootId:String(e.key.signingRootId),signingRootVersion:String(e.key.signingRootVersion),walletSession:l.walletSession,operationCredential:l.operationCredential,roleLocalActivation:s.roleLocalActivation,routerAbEcdsaDerivationNormalSigning:s.sessionActivation.normal_signing,secretSourceKind:`persisted_role_local`}}function Me(){let e=s(a(`wallet-session-mint`,32,`Wallet Session mint IDs`));if(!e.ok)throw Error(`Failed to create Wallet Session mint identity`);return e.value}async function Ne(e){let t=e.touchIdPrompt.getRpId();if(!t)return{ok:!1,code:`invalid_args`,message:`Missing rpId for WebAuthn`};try{return await je(e,t)}catch(e){return{ok:!1,code:`strict_post_registration_failed`,message:e instanceof Error?e.message:String(e)}}}const P=`stale_ecdsa_key_identity`;function Pe(e){if(!e)throw Error(`Strict ECDSA session bootstrap requires Wallet Session authority`);switch(e.kind){case`opaque_wallet_session_operation_credential_v1`:return e;case`publishable_key`:throw Error(`Strict ECDSA session bootstrap requires Wallet Session authority`)}throw Error(`Strict ECDSA session bootstrap authority is invalid`)}function Fe(e){let t=String(e.code||``).trim(),n=String(e.message||``).trim().toLowerCase();return t===`stale_session_state`&&n.includes(`threshold-ecdsa bootstrap`)&&n.includes(`client verifying share`)&&n.includes(`integrated key record`)}function Ie(e){let t=String(e.message||e.code||`threshold-ecdsa bootstrap failed`).trim(),n=Fe(e)?P:String(e.code||`threshold_ecdsa_bootstrap_failed`).trim()||`threshold_ecdsa_bootstrap_failed`,r=Error(t||`threshold-ecdsa bootstrap failed`);return r.code=n,r}function Le(e){let t=Error(e);return t.code=P,t}function Re(e){switch(e.authKind){case`email_otp`:return`email_otp`;case`passkey`:return`passkey`}return`unknown`}function ze(e){switch(e.bootstrap.secretSourceKind){case`persisted_role_local`:return e.request.authKind===`email_otp`?x({authSubjectId:e.request.emailOtpWorkerSessionHandle.authSubjectId}):ie({credentialIdB64u:e.request.passkeyCredentialIdB64u,rpId:e.bootstrap.rpId})}}function F(e,t){let n=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw Error(`threshold-ecdsa exact activation returned invalid ${t}`);return n}function Be(e){let t=F(e.bootstrapOwnerAddress,`server owner address`);if(t!==F(e.key.thresholdOwnerAddress,`key owner address`))throw Le(`threshold-ecdsa exact activation owner address mismatches server bootstrap result`);return t}async function Ve(e,t){let n=d(String(t.key.walletId)),r=t.lanePolicy.chainTarget,i=String(t.lanePolicy.thresholdSessionId).trim();if(e.routerAbNormalSigning.mode!==`enabled`)throw Error(`Router A/B ECDSA derivation normal signing must be enabled for activation`);let a={walletId:n,chainTarget:r,targetKey:f(r),operationId:i||null,authMethod:Re(t),evmFamilyKeyFingerprint:oe(t.key),keyHandle:t.keyHandle,chainTargetKey:f(r),ecdsaThresholdKeyId:String(t.key.ecdsaThresholdKeyId),thresholdSessionId:i||null,freshAuthRetrySideEffectState:`not_applicable`,hasRequestedEcdsaThresholdKeyId:!0,requestedSessionId:i||null,authKind:t.walletSessionRouteAuth?.kind||`none`,passkeyCredentialBound:t.authKind===`passkey`},o;try{o=await Ne({touchIdPrompt:e.touchIdPrompt,relayerUrl:t.relayerUrl,requestId:t.requestId,workerCtx:e.workerCtx,...`preauthorizedSessionActivation`in t&&t.preauthorizedSessionActivation?{sessionActivation:t.preauthorizedSessionActivation}:{bootstrapAuth:Pe(t.walletSessionRouteAuth)},keyHandle:t.keyHandle,key:t.key,lanePolicy:t.lanePolicy,publicCapability:t.publicCapability,existingRoleLocalMaterial:t.existingRoleLocalMaterial})}catch(e){try{console.warn(`[threshold-ecdsa][bootstrap][exception]`,{...a,message:e instanceof Error?e.message:String(e)})}catch{}throw e}if(!o.ok){try{console.warn(`[threshold-ecdsa][bootstrap][failure]`,{...a,code:o.code||``,message:o.message||``})}catch{}throw Ie({code:o.code,message:o.message})}let s=String(t.key.ecdsaThresholdKeyId).trim();if(!s)throw Error(`threshold-ecdsa bootstrap returned empty ecdsaThresholdKeyId`);let c=ne(s),l=ae(String(o.keyHandle||``).trim()),u=String(o.relayerKeyId||``).trim();if(!u)throw Error(`threshold-ecdsa bootstrap returned empty relayerKeyId`);let p=ee(u),m=String(o.clientVerifyingShareB64u||``).trim();if(!m)throw Error(`threshold-ecdsa bootstrap returned empty clientVerifyingShareB64u`);let h=re(m),g=String(o.thresholdSessionId||``).trim();if(!g)throw Error(`threshold-ecdsa bootstrap returned empty thresholdSessionId`);let _=Number(o.expiresAtMs);if(!Number.isFinite(_))throw Error(`threshold-ecdsa bootstrap returned invalid expiresAtMs`);let v=Number(o.remainingUses);if(!Number.isFinite(v))throw Error(`threshold-ecdsa bootstrap returned invalid remainingUses`);let y=t.key.participantIds.map(e=>Number(e));if(!y)throw Error(`threshold-ecdsa bootstrap returned empty participantIds`);let b=Be({key:t.key,bootstrapOwnerAddress:o.ethereumAddress}),ie=te({walletId:n,chainTarget:r,keyHandle:l,ecdsaThresholdKeyId:c,signingRootId:o.signingRootId,signingRootVersion:o.signingRootVersion,applicationBindingDigestB64u:o.roleLocalActivation.publicCapability.context.application_binding_digest_b64u,clientParticipantId:1,relayerParticipantId:2,participantIds:y,contextBinding32B64u:o.roleLocalActivation.publicFacts.contextBinding32B64u,derivationClientSharePublicKey33B64u:o.roleLocalActivation.publicFacts.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:o.roleLocalActivation.publicFacts.relayerPublicKey33B64u,groupPublicKey33B64u:o.roleLocalActivation.publicFacts.groupPublicKey33B64u,ethereumAddress:o.roleLocalActivation.publicFacts.ethereumAddress,publicCapability:o.roleLocalActivation.publicCapability}),x=o.routerAbEcdsaDerivationNormalSigning,S=o.roleLocalActivation.roleLocalMaterial,C=ze({request:t,bootstrap:o}),w={ok:!0,thresholdSessionId:g,authorizationSessionId:o.authorizationSessionId,authorizationId:o.authorizationId,walletSessionId:o.walletSessionId,quotaId:o.quotaId,expiresAtMs:_,remainingUses:v,runtimePolicyScope:o.runtimePolicyScope,walletSession:o.walletSession,operationCredential:o.operationCredential,clientVerifyingShareB64u:h};return{thresholdEcdsaKeyRef:{type:`threshold-ecdsa-secp256k1`,userId:n,chainTarget:r,relayerUrl:t.relayerUrl,keyHandle:l,ecdsaThresholdKeyId:c,backendBinding:{materialKind:`role_local_worker_handle`,relayerKeyId:p,clientVerifyingShareB64u:h,roleLocalMaterialHandle:S,roleLocalMaterialRef:o.roleLocalActivation.roleLocalMaterialRef,publicFacts:ie,authMethod:C},participantIds:y,thresholdEcdsaPublicKeyB64u:o.thresholdEcdsaPublicKeyB64u,ethereumAddress:b,relayerVerifyingShareB64u:o.relayerVerifyingShareB64u,routerAbEcdsaDerivationNormalSigning:x},session:w}}async function He(e,t){return await Ve(e,t)}function Ue(e){let t;try{t=c(e.evidenceSetDigest)}catch(e){throw Error(e instanceof Error?e.message:`ECDSA explicit export evidence digest is invalid`)}let n=Math.floor(Number(e.expiresAtMs)),r=h(e.operation);if(r.operation_kind!==`evm.export_key`)throw Error(`ECDSA explicit export operation kind is invalid`);if(!Number.isSafeInteger(n)||n<=Date.now())throw Error(`ECDSA explicit export operation authorization expiry is invalid`);let i=We(e.unseal);return{kind:`verified_step_up`,evidenceSetDigest:t,operation:r,expiresAtMs:n,quotaUse:`none`,unseal:i}}function We(e){switch(e.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_grant`:{let t=String(e.grant||``).trim(),n=String(e.challenge_id||``).trim();if(!t||!n)throw Error(`ECDSA explicit export Email OTP unseal grant is invalid`);return{kind:`email_otp_grant`,grant:t,challenge_id:n}}default:{let t=e;throw Error(`Unsupported ECDSA explicit export unseal state: ${String(t)}`)}}}async function I(e){let t=String(e.relayerUrl||``).trim();if(!t)throw Error(`ECDSA explicit export relayer URL is required`);return{kind:`explicit_key_export_ecdsa_activation_result`,purpose:`explicit_key_export`,material:{kind:`auth_neutral_ecdsa_export_material_v1`,relayerUrl:t,persistedMaterial:e.existingRoleLocalMaterial},authorization:Ue(e.authorization)}}function L(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`Missing relayer url (configs.network.relayer.url)`);return n}function R(e){return`key`in e&&!!e.key&&`keyHandle`in e&&!!String(e.keyHandle||``).trim()}function z(e){return R(e)?e.key.walletId:e.walletId}function B(e){return R(e)?e.lanePolicy.chainTarget:e.chainTarget}function Ge(e){return e.kind===`email_otp_ecdsa_bootstrap`?{authMethod:u.emailOtp,signerSource:l.emailOtpRegistration}:{authMethod:u.passkey,signerSource:l.passkeyRegistration}}function Ke(e){switch(e.kind){case`passkey_preauthorized_ecdsa_bootstrap`:case`wallet_session_reconnect_ecdsa_bootstrap`:return e.authorizationAuthority;case`passkey_fresh_ecdsa_bootstrap`:case`email_otp_ecdsa_bootstrap`:return e.existingRoleLocalMaterial.authority}}function qe(e){if(!(`sessionActivation`in e.request)||!e.request.sessionActivation)return;let t=e.request.sessionActivation,n=k(t)?t.activation:t,r=k(t)?t.authorization:{record:t.session.wallet_session,operationCredential:t.session.operation_credential};ue({walletId:e.walletId,authority:e.authority,walletSession:r.record,operationCredential:r.operationCredential,expectedAuthorizationId:n.session.authorization_id,expectedWalletSessionId:n.session.wallet_session_id,expectedQuotaId:n.session.quota_id,expectedExpiresAtMs:n.session.expires_at_ms}),e.request.kind===`passkey_preauthorized_ecdsa_bootstrap`&&de({expected:e.request.authorizationIdentity,walletSession:r.record})}function Je(e,t){let n=(e,n,r)=>({kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:C(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},...r,...n?{walletSessionRouteAuth:n}:{}}),r=e=>({kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:C(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u,preauthorizedSessionActivation:e.sessionActivation});switch(e.kind){case`passkey_fresh_ecdsa_bootstrap`:return n(e,e.routeAuth,{authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u});case`passkey_preauthorized_ecdsa_bootstrap`:return r(e);case`wallet_session_reconnect_ecdsa_bootstrap`:return n(e,e.routeAuth,{authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u});case`email_otp_ecdsa_bootstrap`:{let r={authKind:`email_otp`,emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle};return e.sessionActivation?{kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:C(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},...r,preauthorizedSessionActivation:e.sessionActivation}:n(e,e.routeAuth,r)}}throw Error(`[SigningEngine][ecdsa] unsupported ECDSA bootstrap request`)}function Ye(e,t){return{purpose:`explicit_key_export`,relayerUrl:t,existingRoleLocalMaterial:e.existingRoleLocalMaterial,authorization:e.authorization}}function Xe(e,t){return{purpose:`explicit_key_export`,relayerUrl:t,existingRoleLocalMaterial:e.existingRoleLocalMaterial,authorization:e.authorization}}async function Ze(e,t){if(t.kind===`reuse_warm_ecdsa_bootstrap`)throw Error(`[SigningEngine][ecdsa] reuse_warm bootstrap must resolve an existing exact material request before activation`);let n=Ke(t),r=d(z(t)),i=B(t),a=L(t.relayerUrl,e.defaultRelayerUrl),o=e.getSignerWorkerContext(),s={touchIdPrompt:e.touchIdPrompt,workerCtx:o,routerAbNormalSigning:e.routerAbNormalSigning};qe({request:t,walletId:r,authority:n});let c=await He(s,Je(t,a)),l=Ge(t);return await e.persistThresholdEcdsaBootstrapForWalletTarget({walletId:r,chainTarget:i,bootstrap:c,signerAuth:l}),await t.beforeAuthorizationPersistence?.(),await fe(se,{walletId:r,authority:n,bootstrap:c}),c}async function Qe(e,t){return await I(Ye(t,L(t.relayerUrl,e.defaultRelayerUrl)))}async function $e(e,t){return await I(Xe(t,L(t.relayerUrl,e.defaultRelayerUrl)))}async function V(e,t,n){let r=String(t),i=(e.get(r)||Promise.resolve()).catch(()=>void 0),a,o=new Promise(e=>{a=e}),s=i.then(()=>o);e.set(r,s),await i;try{return await n()}finally{a(),e.get(r)===s&&e.delete(r)}}function et(e,t){return t.runtimeScopeBootstrap&&(e.runtimeScopeBootstrap=t.runtimeScopeBootstrap),t.operationIntent&&(e.operationIntent=t.operationIntent),typeof t.ttlMs==`number`&&(e.ttlMs=t.ttlMs),e}function H(e){return et({kind:`email_otp_ecdsa_activation`,purpose:`transaction_signing`,walletKey:e.walletKey,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,source:e.source,relayerUrl:e.relayerUrl,sessionIdentity:e.sessionIdentity,sessionKind:e.sessionKind,sessionBudgetUses:e.sessionBudgetUses,runtimePolicy:e.runtimePolicy,emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,emailOtpAuthContext:e.emailOtpAuthContext,...`preauthorizedSessionActivation`in e?{preauthorizedSessionActivation:e.preauthorizedSessionActivation}:{walletSessionRouteAuth:e.walletSessionRouteAuth}},e)}function U(e){if(le(e.context)!==e.expected)throw Error(`Email OTP ${e.label} activation requires ${e.expected} retention`)}function tt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`session bootstrap`}),H(e)}function nt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`recovered session`}),H(e)}function rt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`preauthorized session bootstrap`}),H(e)}function it(e){return U({context:e.emailOtpAuthContext,expected:`single_use`,label:`per-operation reauth`}),H(e)}function at(e){return{kind:`email_otp_ecdsa_export_activation`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}function ot(e){return{kind:`passkey_ecdsa_export_activation`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}function st(e){switch(e.kind){case`default_policy`:return;case`scoped_policy`:return e.scope}throw Error(`[SigningEngine][ecdsa] unsupported ECDSA activation policy`)}function W(e,t){t.runtimeScopeBootstrap&&(e.runtimeScopeBootstrap=t.runtimeScopeBootstrap),t.operationIntent&&(e.operationIntent=t.operationIntent);let n=st(t.runtimePolicy);return`walletId`in e&&(typeof t.ttlMs==`number`&&(e.ttlMs=t.ttlMs),n&&(e.runtimePolicyScope=n)),e}function ct(e){switch(e.kind){case`passkey_ecdsa_activation`:return{kind:`passkey_existing_session_activation`,request:e};case`email_otp_ecdsa_activation`:return{kind:`email_otp_existing_session_activation`,request:e}}throw Error(`[SigningEngine][ecdsa] unsupported activation request`)}function lt(e){let t=String(e.webauthnAuthentication.rawId||e.webauthnAuthentication.id||``).trim();if(!t)throw Error(`[SigningEngine][ecdsa] passkey activation requires credential identity`);return t}function ut(e){let t=ct(e);switch(t.kind){case`passkey_existing_session_activation`:return W({kind:`passkey_fresh_ecdsa_bootstrap`,keyHandle:t.request.walletKey.keyHandle,key:w(t.request.walletKey),lanePolicy:t.request.lanePolicy,publicCapability:t.request.publicCapability,existingRoleLocalMaterial:t.request.existingRoleLocalMaterial,source:t.request.source,relayerUrl:t.request.relayerUrl,requestId:t.request.requestId,passkeyCredentialIdB64u:lt(t.request),routeAuth:t.request.walletSessionRouteAuth},t.request);case`email_otp_existing_session_activation`:{let e={kind:`email_otp_ecdsa_bootstrap`,keyHandle:t.request.walletKey.keyHandle,key:w(t.request.walletKey),lanePolicy:t.request.lanePolicy,publicCapability:t.request.publicCapability,existingRoleLocalMaterial:t.request.existingRoleLocalMaterial,source:`email_otp`,relayerUrl:t.request.relayerUrl,emailOtpWorkerSessionHandle:t.request.emailOtpWorkerSessionHandle,emailOtpAuthContext:t.request.emailOtpAuthContext};return t.request.preauthorizedSessionActivation?W({...e,sessionActivation:t.request.preauthorizedSessionActivation},t.request):W({...e,routeAuth:t.request.walletSessionRouteAuth},t.request)}}throw Error(`[SigningEngine][ecdsa] unsupported activation request`)}function dt(e){return{kind:`passkey_ecdsa_export_bootstrap`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}async function ft(e){let t=e.bootstrap.thresholdEcdsaKeyRef.backendBinding;if(!t)throw Error(`[WarmSessionStore] threshold ECDSA bootstrap is missing its backend binding`);let n=pt(t);if(!n)return;let r=await e.deps.persistEcdsaRoleLocalReadyRecord({record:n,storageKeyFacts:b(n)});if(!r.ok)throw Error(`[WarmSessionStore] threshold ECDSA role-local ready record persistence failed (${r.code}): ${r.message}`)}function pt(e){switch(e.materialKind){case`role_local_ready_state_blob`:return e.ecdsaRoleLocalReadyRecord;case`role_local_worker_handle`:case`role_local_durable_public_anchor`:case`role_local_durable_sealed_ref`:case`metadata_only`:return null;default:{let t=e;throw Error(`[WarmSessionStore] unsupported threshold ECDSA backend binding: ${JSON.stringify(t)}`)}}}async function G(e,t){let n=d(z(t));return await V(e.queueByWallet,n,async()=>{let n=await Ze(e.activationDeps,t);return await ft({deps:e,bootstrap:n}),n})}async function mt(e,t){return await G(e,ut(t))}async function ht(e,t){return await Qe(e.activationDeps,dt(t))}async function gt(e,t){let n={kind:`email_otp_ecdsa_export_bootstrap`,purpose:`explicit_key_export`,existingRoleLocalMaterial:t.existingRoleLocalMaterial,relayerUrl:t.relayerUrl,authorization:t.authorization};return await $e(e.activationDeps,n)}const K=`ecdsa-derivation:role-local:product-export-confirmation:v5`,q=`ecdsa-derivation:role-local:product-export-authorization:v5`;function J(e){return{kind:`operation_step_up`}}function Y(e){return{authorizationKind:e.kind,authorizationId:e.evidenceSetDigest}}function X(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto.getRandomValues is required for threshold ECDSA export`);return r(e.getRandomValues(new Uint8Array(32)))}async function Z(e){let t=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!t)throw Error(`[SigningEngine][ecdsa-export] relayer URL is required`);if(e.authorization.kind===`wallet_session_bearer`&&!e.authorization.token.trim())throw Error(`[SigningEngine][ecdsa-export] Wallet Session operation credential is required`);let n={"Content-Type":`application/json`};e.authorization.kind===`wallet_session_bearer`&&(n.Authorization=`Bearer ${e.authorization.token}`);try{let r=await fetch(`${t}${y}`,{method:`POST`,credentials:e.authorization.kind===`legacy_cookie`?`include`:`omit`,headers:n,body:JSON.stringify({request:e.request,requestDigestB64u:e.requestDigestB64u})}),i=await r.json().catch(()=>null);if(!r.ok){let e=i&&typeof i==`object`&&!Array.isArray(i)?i:null;return{ok:!1,code:String(e?.code||`http_error`),message:String(e?.message||`HTTP ${r.status}`)}}return{ok:!0,value:p(i)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function _t(e){return await Z({...e,authorization:{kind:`legacy_cookie`}})}async function vt(e){return await Z({relayerUrl:e.relayerUrl,request:e.request,requestDigestB64u:e.requestDigestB64u,authorization:{kind:`wallet_session_bearer`,token:e.operationCredential.token}})}function Q(e){let t=Math.min(e.issuedAtUnixMs+6e4,e.authorizationExpiresAtMsCeiling??1/0);if(Number.isFinite(t)&&t>e.issuedAtUnixMs)return t;throw new be({failure:ye(ve.expired),message:`Wallet Session expired before ECDSA export authorization`})}function yt(e){if(String(e.material.persistedMaterial.publicFacts.walletId)!==String(e.walletSessionUserId))throw Error(`[SigningEngine][ecdsa-export] explicit export wallet mismatch`)}async function $(e){return r(await t(n(e)))}function bt(e){switch(e.kind){case`rehydrated`:return e;case`device_link_required`:throw Error(`[SigningEngine][ecdsa-export] device_link_required: local threshold ECDSA material is unavailable`);case`corrupt`:throw Error(`[SigningEngine][ecdsa-export] local threshold ECDSA material is corrupt (${e.reason}): ${e.message}`);default:{let t=e;throw Error(`Unsupported ECDSA export material resolution: ${String(t)}`)}}}async function xt(e){return bt(await D({purpose:`explicit_key_export`,source:E(e.persistedMaterial),workerCtx:e.workerCtx}))}function St(e){let t=Y(e.material.operationAuthorization),n=e.material.persistedMaterial.publicFacts;return{version:q,operation:`explicit_key_export`,keyHandle:n.keyHandle,walletId:String(n.walletId),ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,relayerKeyId:n.publicCapability.signer_set.selected_server.server_id,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,contextBinding32B64u:e.contextBinding32B64u,publicIdentity:e.publicIdentity,exportRequestNonce32B64u:e.exportRequestNonce32B64u,confirmationDigest32B64u:e.confirmationDigest32B64u,issuedAtUnixMs:e.issuedAtUnixMs,expiresAtUnixMs:e.expiresAtUnixMs,authorizationKind:t.authorizationKind,authorizationId:t.authorizationId,materialActivation:v(e.material.persistedMaterial.materialActivation),participantIds:n.participantIds}}async function Ct(e,t){let n=t.persistedMaterial.publicFacts,r=v(t.persistedMaterial.materialActivation);switch(t.factorAuthorization.kind){case`passkey`:{let e=String(t.factorAuthorization.credential.rawId||t.factorAuthorization.credential.id||``).trim();if(!e)throw Error(`[SigningEngine][ecdsa-export] passkey authorization credential is missing`);if(e!==t.factorAuthorization.passkeyCredentialIdB64u)throw Error(`[SigningEngine][ecdsa-export] passkey export authorization credential mismatch`);break}case`email_otp_verified`:break;default:{let e=t.factorAuthorization;throw Error(`Unsupported ECDSA export authorization: ${String(e)}`)}}let i=Date.now(),a=Q({issuedAtUnixMs:i,authorizationExpiresAtMsCeiling:t.operationAuthorization.expiresAtMs}),o={derivationClientSharePublicKey33B64u:n.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:n.relayerPublicKey33B64u,groupPublicKey33B64u:n.groupPublicKey33B64u,ethereumAddress:n.ethereumAddress},s=X(),c=Y(t.operationAuthorization),l=await $({version:K,walletId:String(n.walletId),ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,relayerKeyId:n.publicCapability.signer_set.selected_server.server_id,contextBinding32B64u:n.contextBinding32B64u,publicIdentity:o,authorizationKind:c.authorizationKind,authorizationId:c.authorizationId,materialActivation:r,exportRequestNonce32B64u:s,issuedAtUnixMs:i,expiresAtUnixMs:a}),u=await $(St({ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,contextBinding32B64u:n.contextBinding32B64u,publicIdentity:o,exportRequestNonce32B64u:s,confirmationDigest32B64u:l,issuedAtUnixMs:i,expiresAtUnixMs:a,material:t})),d=n.publicCapability,f=`ecdsa-export:${s}`,p=await pe({workerCtx:e.getSignerWorkerContext(),command:{kind:`create_router_ab_ecdsa_explicit_export_ceremony_v1`,ceremonyId:f,request:{context:d.context,lifecycle:{lifecycle_id:f,work_kind:`key_export`,primitive_request_kind:`export`,root_share_epoch:d.activation_epoch,account_id:String(n.walletId),session_id:T.thresholdEcdsaSession(f),signer_set_id:d.signer_set.signer_set_id,selected_server_id:d.signer_set.selected_server.server_id},public_identity:d.public_identity,signer_set:d.signer_set,router_id:d.router_id,client_id:d.client_id,authorization:J(t.operationAuthorization),authorization_id:t.operationAuthorization.evidenceSetDigest,operation:t.operationAuthorization.operation,material_activation:r,export_authorization_digest_b64u:u,export_nonce:s,expires_at_ms:a,deriver_recipient_keys:d.deriver_recipient_keys}}});if(p.kind!==`router_ab_ecdsa_explicit_export_ceremony_created_v1`)throw Error(`[SigningEngine][ecdsa-export] strict export ceremony kind mismatch`);try{let i=await _t({relayerUrl:t.relayerUrl,request:p.request,requestDigestB64u:p.requestDigestB64u});if(!i.ok)throw Error(i.error||i.message||i.code||`Strict ECDSA explicit export request failed`);let a=await me({workerCtx:e.getSignerWorkerContext(),command:{kind:`finalize_router_ab_ecdsa_explicit_export_v1`,ceremonyId:f,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:i.value.response.bundles},signingWorkerExport:i.value.signing_worker_export,authorizationKind:c.authorizationKind,authorizationId:c.authorizationId,materialActivation:r,roleLocalMaterial:t.liveMaterial.liveHandle,roleLocalMaterialRef:t.liveMaterial.materialRef,publicFacts:n}});return{publicKeyHex:a.publicKeyHex,privateKeyHex:a.privateKeyHex,ethereumAddress:a.ethereumAddress}}catch(t){throw await ge({workerCtx:e.getSignerWorkerContext(),command:{kind:`close_router_ab_ecdsa_post_registration_ceremony_v1`,ceremonyId:f}}).catch(()=>void 0),t}}async function wt(e,t){let n=t.exportProvision.material;yt({material:n,walletSessionUserId:t.walletSessionUserId});let r=String(n.relayerUrl||``).trim();if(!r)throw Error(`[SigningEngine][ecdsa-export] relayer URL is required`);let i=n.persistedMaterial;return await Ct(e,{persistedMaterial:i,liveMaterial:await xt({persistedMaterial:i,workerCtx:e.getSignerWorkerContext()}),relayerUrl:r,operationAuthorization:t.exportProvision.authorization,factorAuthorization:t.factorAuthorization})}function Tt(t){let n=t.runtime.normalSigning.scope,r=t.operationAuthorization.operation,i=g(r.material_activation);if(r.operation_kind!==`evm.export_key`||r.wallet_id!==String(t.runtime.walletId)||r.key_handle!==t.runtime.publicFacts.keyHandle||r.relayer_key_id!==t.runtime.relayerKeyId||r.participant_ids[0]!==t.runtime.publicFacts.participantIds[0]||r.participant_ids[1]!==t.runtime.publicFacts.participantIds[1]||r.signing_worker_id!==n.signing_worker.server_id||r.normal_signing_scope.wallet_id!==n.wallet_id||r.normal_signing_scope.context.application_binding_digest_b64u!==n.context.application_binding_digest_b64u||r.normal_signing_scope.public_identity.context_binding_b64u!==n.public_identity.context_binding_b64u||r.normal_signing_scope.public_identity.threshold_public_key33_b64u!==n.public_identity.threshold_public_key33_b64u||r.normal_signing_scope.signing_worker.server_id!==n.signing_worker.server_id||!e(i,t.runtime.materialActivation)||!e(g(r.normal_signing_scope.material_activation),t.runtime.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority operation identity changed`)}async function Et(e,t){Tt(t);let n=t.runtime,r=n.normalSigning.scope;if(t.operationAuthorization.exportTopology.signer_set.selected_server.server_id!==r.signing_worker.server_id)throw Error(`[SigningEngine][ecdsa-export] active export topology changed`);let i=r.material_activation,a=Date.now(),o=Q({issuedAtUnixMs:a,authorizationExpiresAtMsCeiling:t.operationAuthorization.expiresAtMs}),s={derivationClientSharePublicKey33B64u:r.public_identity.derivation_client_share_public_key33_b64u,relayerPublicKey33B64u:r.public_identity.server_public_key33_b64u,groupPublicKey33B64u:r.public_identity.threshold_public_key33_b64u,ethereumAddress:n.publicFacts.thresholdOwnerAddress},l=X(),u=Y(t.operationAuthorization),d=await $({version:K,walletId:String(n.walletId),ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,relayerKeyId:n.relayerKeyId,contextBinding32B64u:r.public_identity.context_binding_b64u,publicIdentity:s,authorizationKind:u.authorizationKind,authorizationId:u.authorizationId,materialActivation:i,exportRequestNonce32B64u:l,issuedAtUnixMs:a,expiresAtUnixMs:o}),f=await $({version:q,operation:`explicit_key_export`,keyHandle:n.publicFacts.keyHandle,walletId:String(n.walletId),ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,relayerKeyId:n.relayerKeyId,signingRootId:r.signing_root_id,signingRootVersion:r.signing_root_version,contextBinding32B64u:r.public_identity.context_binding_b64u,publicIdentity:s,exportRequestNonce32B64u:l,confirmationDigest32B64u:d,issuedAtUnixMs:a,expiresAtUnixMs:o,authorizationKind:u.authorizationKind,authorizationId:u.authorizationId,materialActivation:i,participantIds:n.publicFacts.participantIds}),p=`ecdsa-export:${l}`,m={context:r.context,lifecycle:{lifecycle_id:p,work_kind:`key_export`,primitive_request_kind:`export`,root_share_epoch:r.activation_epoch,account_id:r.wallet_id,session_id:T.thresholdEcdsaSession(p),signer_set_id:t.operationAuthorization.exportTopology.signer_set.signer_set_id,selected_server_id:t.operationAuthorization.exportTopology.signer_set.selected_server.server_id},public_identity:r.public_identity,signer_set:t.operationAuthorization.exportTopology.signer_set,router_id:t.operationAuthorization.exportTopology.router_id,client_id:String(n.walletId),authorization:J(t.operationAuthorization),operation:t.operationAuthorization.operation,authorization_id:c(t.operationAuthorization.evidenceSetDigest),material_activation:i,export_authorization_digest_b64u:f,export_nonce:l,expires_at_ms:o,deriver_recipient_keys:t.operationAuthorization.exportTopology.deriver_recipient_keys},h=await he({holderHandleId:n.holderRuntime.holderHandleId,request:m,workerCtx:e.getSignerWorkerContext()});if(h.kind!==`ecdsa_holder_ordinary_export_request_created_v1`)throw Error(`[SigningEngine][ecdsa-export] active holder export request kind mismatch`);let g=await vt({relayerUrl:t.relayerUrl,request:h.request,requestDigestB64u:h.requestDigestB64u,operationCredential:n.operationCredential});if(!g.ok)throw Error(g.error||g.message||g.code||`Active Wallet Authority ECDSA export request failed`);let _={wallet_id:r.wallet_id,key_handle:n.publicFacts.keyHandle,ecdsa_threshold_key_id:r.ecdsa_threshold_key_id,signing_root_id:r.signing_root_id,signing_root_version:r.signing_root_version,activation_epoch:r.activation_epoch,signing_worker_id:r.signing_worker.server_id,context_binding_b64u:r.public_identity.context_binding_b64u,threshold_public_key33_b64u:r.public_identity.threshold_public_key33_b64u,export_request_digest_b64u:h.requestDigestB64u,export_authorization_digest_b64u:f,export_nonce:l,authorization_kind:`verified_step_up`,authorization_id:t.operationAuthorization.evidenceSetDigest,material_activation:i,lifecycle_id:p,recipient_identity:h.request.client_id,recipient_public_key:h.request.client_ephemeral_public_key,expires_at_ms:h.request.expires_at_ms},v=await _e({holderHandleId:n.holderRuntime.holderHandleId,requestDigestB64u:h.requestDigestB64u,expectedBinding:_,forwardedResponse:g.value,workerCtx:e.getSignerWorkerContext()});return{publicKeyHex:v.publicKeyHex,privateKeyHex:v.privateKeyHex,ethereumAddress:v.ethereumAddress}}export{k as _,it as a,tt as c,mt as d,G as f,A as g,z as h,at as i,gt as l,B as m,wt as n,rt as o,V as p,ot as r,nt as s,Et as t,ht as u,xe as v,Se as y};