@seams/wallet 0.29.0 → 0.31.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 (264) hide show
  1. package/README.md +7 -7
  2. package/THIRD_PARTY_NOTICES.md +1 -127
  3. package/dist/.build-inputs.sha256 +1 -1
  4. package/dist/esm/SeamsWeb/SeamsWeb.js +2 -0
  5. package/dist/esm/SeamsWeb/walletIframe/client/inboundMessages.js +9 -0
  6. package/dist/esm/SeamsWeb/walletIframe/client/router.js +30 -0
  7. package/dist/esm/SeamsWeb/walletIframe/coordinator.js +18 -0
  8. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +88 -47
  9. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.js +67 -0
  10. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.js +13 -0
  11. package/dist/esm/SeamsWeb/walletIframe/host/walletMutationGuard.js +1 -0
  12. package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +20 -6
  13. package/dist/esm/SeamsWeb/walletIframe/shared/walletAlternatives.js +109 -0
  14. package/dist/esm/core/config/configBuilder.js +1 -1
  15. package/dist/esm/core/config/defaultConfigs.js +9 -2
  16. package/dist/esm/core/ui/messages.js +3 -1
  17. package/dist/esm/core/ui/walletIcon.js +10 -0
  18. package/dist/esm/externalEvm/boundary.js +4 -2
  19. package/dist/esm/react/components/HostedSeamsAuthMenu/shell.js +26 -6
  20. package/dist/esm/react/components/HostedSeamsAuthMenu/walletAlternatives.js +178 -0
  21. package/dist/esm/react/index.js +1 -2
  22. package/dist/esm/react/styles/styles.css +0 -183
  23. package/dist/esm/react/styles.css +0 -1
  24. package/dist/esm/sdk/{ConfirmationDrawer-BRnd5SEf.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
  25. package/dist/{public/sdk/NonceCoordinator-CNXYrOoy.js → esm/sdk/NonceCoordinator-C1lw03Ce.js} +1 -1
  26. package/dist/esm/sdk/{activeWalletSession-BJ4B-nJo.js → activeWalletSession-HAOgRKzn.js} +1 -1
  27. package/dist/esm/sdk/{adapters-B2k8y0MB.js → adapters-BY1wGpm5.js} +1 -1
  28. package/dist/esm/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
  29. package/dist/esm/sdk/{authorization-gVWwKwav.js → authorization-D_NueqAv.js} +1 -1
  30. package/dist/esm/sdk/{clientSessionPersistenceState-BxpITYM_.js → clientSessionPersistenceState-B3gU3515.js} +1 -1
  31. package/dist/esm/sdk/{commitQueue-C1wkey4q.js → commitQueue-CbyuhEW9.js} +1 -1
  32. package/dist/{public/sdk/confirm-ui-Dx6c4-Rk.js → esm/sdk/confirm-ui-DWFcGTsT.js} +1 -1
  33. package/dist/{public/sdk/device-linking-_o3_fgiG.js → esm/sdk/device-linking-BL2aDEUF.js} +1 -1
  34. package/dist/esm/sdk/{deviceLinkApproval-CObsEWBa.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
  35. package/dist/esm/sdk/{digestEncoding-34kXJoJr.js → digestEncoding-Rx8Vjy4J.js} +1 -1
  36. package/dist/esm/sdk/{display-CUWg48tD.js → display-8NGPOhQT.js} +1 -1
  37. package/dist/{public/sdk/ecdsaCapabilityManifest--1Ztngfx.js → esm/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
  38. package/dist/{public/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js → esm/sdk/ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
  39. package/dist/{public/sdk/ecdsaDerivationExport-BUUUGc6o.js → esm/sdk/ecdsaDerivationExport-jm2VBMz_.js} +1 -1
  40. package/dist/esm/sdk/{emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
  41. package/dist/esm/sdk/{export-viewer-host-O0OV1Oou.js → export-viewer-host-TzgdJQuZ.js} +1 -1
  42. package/dist/{public/sdk/exportKeypairOperation-DkqY9Bpf.js → esm/sdk/exportKeypairOperation-B9_ulzNz.js} +1 -1
  43. package/dist/esm/sdk/host-DltV2Oan.js +1 -0
  44. package/dist/esm/sdk/{indexedDB-CA4tGqkr.js → indexedDB-BqsYXybq.js} +1 -1
  45. package/dist/esm/sdk/{lanes-vBKm6yBJ.js → lanes-0WT2w1Xz.js} +1 -1
  46. package/dist/esm/sdk/{localOnly-U_MucUAe.js → localOnly-DFrtrfdO.js} +1 -1
  47. package/dist/esm/sdk/{mountExportPrivateKeySurface-C2-fnvP6.js → mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
  48. package/dist/{public/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js → esm/sdk/mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
  49. package/dist/esm/sdk/{nearEd25519YaoSigningPreparation-CnbgQfZc.js → nearEd25519YaoSigningPreparation-Cz2Gb95g.js} +1 -1
  50. package/dist/esm/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
  51. package/dist/esm/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
  52. package/dist/esm/sdk/{pendingWalletRecoveryCodeBackup-DXFrQmO5.js → pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
  53. package/dist/{public/sdk/presignaturePool-Dq4RhzXn.js → esm/sdk/presignaturePool-CaI45td2.js} +1 -1
  54. package/dist/esm/sdk/{presignatures-CkhuZ0YQ.js → presignatures-B9KnQyfE.js} +1 -1
  55. package/dist/esm/sdk/{recovery-entrypoint-s9OoKBcl.js → recovery-entrypoint-DA2FGLG6.js} +1 -1
  56. package/dist/esm/sdk/registration-Coh0_Nva.js +1 -0
  57. package/dist/esm/sdk/{registration-D3p7muCc.js → registration-XNyt1YRK.js} +1 -1
  58. package/dist/esm/sdk/{registrationIntent-C1-Kyx_-.js → registrationIntent-Cb3tggIM.js} +1 -1
  59. package/dist/{public/sdk/requireStepUpAuth-iVo6h_U-.js → esm/sdk/requireStepUpAuth-ByMTPBu4.js} +1 -1
  60. package/dist/esm/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
  61. package/dist/esm/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
  62. package/dist/esm/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  63. package/dist/esm/sdk/runtime-auth-CP6P681o.js +1 -0
  64. package/dist/esm/sdk/{runtime-device-link-qmYvGep9.js → runtime-device-link-CGDZQK-D.js} +1 -1
  65. package/dist/{public/sdk/runtime-ecdsa-tempo-Zh95TuLV.js → esm/sdk/runtime-ecdsa-tempo-BiJYKWK4.js} +1 -1
  66. package/dist/esm/sdk/{runtime-email-otp-CnLuW4H1.js → runtime-email-otp-B0XCNDRb.js} +1 -1
  67. package/dist/esm/sdk/{runtime-export-m8lvrXtw.js → runtime-export-CXxv6KIx.js} +1 -1
  68. package/dist/esm/sdk/{runtime-near-BiXzXXhH.js → runtime-near-CuyS57wu.js} +1 -1
  69. package/dist/esm/sdk/runtime-preferences-B2WBUZO7.js +1 -0
  70. package/dist/esm/sdk/runtime-recovery-KwVdSe94.js +1 -0
  71. package/dist/esm/sdk/{runtime-recovery-codes-B033ake_.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
  72. package/dist/esm/sdk/{runtimeContext-RNS2E5wy.js → runtimeContext-Iy1vecX0.js} +3 -3
  73. package/dist/esm/sdk/{secp256k1-DPeaOjM0.js → secp256k1-sDDAa4Ga.js} +1 -1
  74. package/dist/{public/sdk/signEvmFamily-Cksw3RpU.js → esm/sdk/signEvmFamily-CMrXkVsZ.js} +1 -1
  75. package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
  76. package/dist/esm/sdk/{signEvmWithUiConfirm-B14zYdwE.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
  77. package/dist/esm/sdk/{signNear-D0rFEYP1.js → signNear-DyFk--I3.js} +1 -1
  78. package/dist/{public/sdk/signingFlow-Bd1X0e-1.js → esm/sdk/signingFlow-DTP4D19E.js} +1 -1
  79. package/dist/{public/sdk/signingQueue-DoUBeaCv.js → esm/sdk/signingQueue-Dy5mYMus.js} +1 -1
  80. package/dist/esm/sdk/{thresholdEcdsa-BxfOZmiR.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
  81. package/dist/esm/sdk/{trace-BnhLKxcu.js → trace-BA8jya7O.js} +1 -1
  82. package/dist/{public/sdk/transactionState-G_FPe-U8.js → esm/sdk/transactionState-BCbaT2hO.js} +1 -1
  83. package/dist/esm/sdk/tx-confirm-ui.js +3 -1
  84. package/dist/esm/sdk/{types-A-w1cYlJ.js → types-D2Zk1W7I.js} +1 -1
  85. package/dist/{public/sdk/unlockedEd25519ExportRootCapability-5F1egCSv.js → esm/sdk/unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
  86. package/dist/esm/sdk/voiceid-host.js +1 -1
  87. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  88. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  89. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  90. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  91. package/dist/esm/sdk/{wallet-recovery-DXdm68_Q.js → wallet-recovery-Bfm-oUoP.js} +1 -1
  92. package/dist/esm/sdk/wallet-ui.css +1 -1
  93. package/dist/{public/sdk/walletAuthMethodRecord-BW-XV4fv.js → esm/sdk/walletAuthMethodRecord--fvGr8r1.js} +1 -1
  94. package/dist/{public/sdk/walletAuthority-DbGaSw7D.js → esm/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
  95. package/dist/esm/sdk/{walletCustodyEcdsaContinuity-BnyL1Ryu.js → walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
  96. package/dist/esm/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
  97. package/dist/esm/sdk/{walletOwnerOperation-CScYv2K6.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
  98. package/dist/esm/sdk/{walletOwnershipGeneration-BZc6UKqX.js → walletOwnershipGeneration-B3uE9GRG.js} +1 -1
  99. package/dist/{public/sdk/walletRecoveryAdminProof-DdwikrW3.js → esm/sdk/walletRecoveryAdminProof-BmZaP0Q8.js} +1 -1
  100. package/dist/{public/sdk/walletRecoveryCommit-DbAoiJp5.js → esm/sdk/walletRecoveryCommit-CSYNbYNd.js} +1 -1
  101. package/dist/esm/sdk/{walletSessionAuthorizationStatus-GhcGvDCX.js → walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
  102. package/dist/{public/sdk/walletSessionAuthorizationStore-BivTUoKY.js → esm/sdk/walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
  103. package/dist/esm/shared-ts/src/utils/index.js +1 -1
  104. package/dist/esm/wasm/near_signer/pkg/wasm_signer_worker_bg.wasm +0 -0
  105. package/dist/esm/wasm/router_ab_ecdsa_client/pkg/router_ab_ecdsa_client_bg.wasm +0 -0
  106. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.d.ts +212 -233
  107. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.js +675 -694
  108. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client_bg.wasm +0 -0
  109. package/dist/public/headers.manifest.json +1 -1
  110. package/dist/public/sdk/{ConfirmationDrawer-BRnd5SEf.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
  111. package/dist/{esm/sdk/NonceCoordinator-CNXYrOoy.js → public/sdk/NonceCoordinator-C1lw03Ce.js} +1 -1
  112. package/dist/public/sdk/{activeWalletSession-BJ4B-nJo.js → activeWalletSession-HAOgRKzn.js} +1 -1
  113. package/dist/public/sdk/{adapters-B2k8y0MB.js → adapters-BY1wGpm5.js} +1 -1
  114. package/dist/public/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
  115. package/dist/public/sdk/{authorization-gVWwKwav.js → authorization-D_NueqAv.js} +1 -1
  116. package/dist/public/sdk/{clientSessionPersistenceState-BxpITYM_.js → clientSessionPersistenceState-B3gU3515.js} +1 -1
  117. package/dist/public/sdk/{commitQueue-C1wkey4q.js → commitQueue-CbyuhEW9.js} +1 -1
  118. package/dist/{esm/sdk/confirm-ui-Dx6c4-Rk.js → public/sdk/confirm-ui-DWFcGTsT.js} +1 -1
  119. package/dist/{esm/sdk/device-linking-_o3_fgiG.js → public/sdk/device-linking-BL2aDEUF.js} +1 -1
  120. package/dist/public/sdk/{deviceLinkApproval-CObsEWBa.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
  121. package/dist/public/sdk/{digestEncoding-34kXJoJr.js → digestEncoding-Rx8Vjy4J.js} +1 -1
  122. package/dist/public/sdk/{display-CUWg48tD.js → display-8NGPOhQT.js} +1 -1
  123. package/dist/{esm/sdk/ecdsaCapabilityManifest--1Ztngfx.js → public/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
  124. package/dist/{esm/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js → public/sdk/ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
  125. package/dist/{esm/sdk/ecdsaDerivationExport-BUUUGc6o.js → public/sdk/ecdsaDerivationExport-jm2VBMz_.js} +1 -1
  126. package/dist/public/sdk/{emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
  127. package/dist/public/sdk/{export-viewer-host-O0OV1Oou.js → export-viewer-host-TzgdJQuZ.js} +1 -1
  128. package/dist/{esm/sdk/exportKeypairOperation-DkqY9Bpf.js → public/sdk/exportKeypairOperation-B9_ulzNz.js} +1 -1
  129. package/dist/public/sdk/host-DltV2Oan.js +1 -0
  130. package/dist/public/sdk/{indexedDB-CA4tGqkr.js → indexedDB-BqsYXybq.js} +1 -1
  131. package/dist/public/sdk/{lanes-vBKm6yBJ.js → lanes-0WT2w1Xz.js} +1 -1
  132. package/dist/public/sdk/{localOnly-U_MucUAe.js → localOnly-DFrtrfdO.js} +1 -1
  133. package/dist/public/sdk/{mountExportPrivateKeySurface-C2-fnvP6.js → mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
  134. package/dist/{esm/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js → public/sdk/mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
  135. package/dist/public/sdk/{nearEd25519YaoSigningPreparation-CnbgQfZc.js → nearEd25519YaoSigningPreparation-Cz2Gb95g.js} +1 -1
  136. package/dist/public/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
  137. package/dist/public/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
  138. package/dist/public/sdk/{pendingWalletRecoveryCodeBackup-DXFrQmO5.js → pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
  139. package/dist/{esm/sdk/presignaturePool-Dq4RhzXn.js → public/sdk/presignaturePool-CaI45td2.js} +1 -1
  140. package/dist/public/sdk/{presignatures-CkhuZ0YQ.js → presignatures-B9KnQyfE.js} +1 -1
  141. package/dist/public/sdk/{recovery-entrypoint-s9OoKBcl.js → recovery-entrypoint-DA2FGLG6.js} +1 -1
  142. package/dist/public/sdk/registration-Coh0_Nva.js +1 -0
  143. package/dist/public/sdk/{registration-D3p7muCc.js → registration-XNyt1YRK.js} +1 -1
  144. package/dist/public/sdk/{registrationIntent-C1-Kyx_-.js → registrationIntent-Cb3tggIM.js} +1 -1
  145. package/dist/{esm/sdk/requireStepUpAuth-iVo6h_U-.js → public/sdk/requireStepUpAuth-ByMTPBu4.js} +1 -1
  146. package/dist/public/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
  147. package/dist/public/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
  148. package/dist/public/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  149. package/dist/public/sdk/runtime-auth-CP6P681o.js +1 -0
  150. package/dist/public/sdk/{runtime-device-link-qmYvGep9.js → runtime-device-link-CGDZQK-D.js} +1 -1
  151. package/dist/{esm/sdk/runtime-ecdsa-tempo-Zh95TuLV.js → public/sdk/runtime-ecdsa-tempo-BiJYKWK4.js} +1 -1
  152. package/dist/public/sdk/{runtime-email-otp-CnLuW4H1.js → runtime-email-otp-B0XCNDRb.js} +1 -1
  153. package/dist/public/sdk/{runtime-export-m8lvrXtw.js → runtime-export-CXxv6KIx.js} +1 -1
  154. package/dist/public/sdk/{runtime-near-BiXzXXhH.js → runtime-near-CuyS57wu.js} +1 -1
  155. package/dist/public/sdk/runtime-preferences-B2WBUZO7.js +1 -0
  156. package/dist/public/sdk/runtime-recovery-KwVdSe94.js +1 -0
  157. package/dist/public/sdk/{runtime-recovery-codes-B033ake_.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
  158. package/dist/public/sdk/{runtimeContext-RNS2E5wy.js → runtimeContext-Iy1vecX0.js} +3 -3
  159. package/dist/public/sdk/{secp256k1-DPeaOjM0.js → secp256k1-sDDAa4Ga.js} +1 -1
  160. package/dist/{esm/sdk/signEvmFamily-Cksw3RpU.js → public/sdk/signEvmFamily-CMrXkVsZ.js} +1 -1
  161. package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
  162. package/dist/public/sdk/{signEvmWithUiConfirm-B14zYdwE.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
  163. package/dist/public/sdk/{signNear-D0rFEYP1.js → signNear-DyFk--I3.js} +1 -1
  164. package/dist/{esm/sdk/signingFlow-Bd1X0e-1.js → public/sdk/signingFlow-DTP4D19E.js} +1 -1
  165. package/dist/{esm/sdk/signingQueue-DoUBeaCv.js → public/sdk/signingQueue-Dy5mYMus.js} +1 -1
  166. package/dist/public/sdk/{thresholdEcdsa-BxfOZmiR.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
  167. package/dist/public/sdk/{trace-BnhLKxcu.js → trace-BA8jya7O.js} +1 -1
  168. package/dist/{esm/sdk/transactionState-G_FPe-U8.js → public/sdk/transactionState-BCbaT2hO.js} +1 -1
  169. package/dist/public/sdk/tx-confirm-ui.js +3 -1
  170. package/dist/public/sdk/{types-A-w1cYlJ.js → types-D2Zk1W7I.js} +1 -1
  171. package/dist/{esm/sdk/unlockedEd25519ExportRootCapability-5F1egCSv.js → public/sdk/unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
  172. package/dist/public/sdk/voiceid-host.js +1 -1
  173. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  174. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  175. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  176. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  177. package/dist/public/sdk/{wallet-recovery-DXdm68_Q.js → wallet-recovery-Bfm-oUoP.js} +1 -1
  178. package/dist/public/sdk/wallet-ui.css +1 -1
  179. package/dist/{esm/sdk/walletAuthMethodRecord-BW-XV4fv.js → public/sdk/walletAuthMethodRecord--fvGr8r1.js} +1 -1
  180. package/dist/{esm/sdk/walletAuthority-DbGaSw7D.js → public/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
  181. package/dist/public/sdk/{walletCustodyEcdsaContinuity-BnyL1Ryu.js → walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
  182. package/dist/public/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
  183. package/dist/public/sdk/{walletOwnerOperation-CScYv2K6.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
  184. package/dist/public/sdk/{walletOwnershipGeneration-BZc6UKqX.js → walletOwnershipGeneration-B3uE9GRG.js} +1 -1
  185. package/dist/{esm/sdk/walletRecoveryAdminProof-DdwikrW3.js → public/sdk/walletRecoveryAdminProof-BmZaP0Q8.js} +1 -1
  186. package/dist/{esm/sdk/walletRecoveryCommit-DbAoiJp5.js → public/sdk/walletRecoveryCommit-CSYNbYNd.js} +1 -1
  187. package/dist/public/sdk/{walletSessionAuthorizationStatus-GhcGvDCX.js → walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
  188. package/dist/{esm/sdk/walletSessionAuthorizationStore-BivTUoKY.js → public/sdk/walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
  189. package/dist/public/sdk/workers/device-linking-key.worker.js +454 -947
  190. package/dist/public/sdk/workers/email-otp.worker.js +588 -820
  191. package/dist/public/sdk/workers/email_otp_runtime_bg.wasm +0 -0
  192. package/dist/public/sdk/workers/evm_crypto_bg.wasm +0 -0
  193. package/dist/public/sdk/workers/passkey-mpc-export.worker.js +572 -804
  194. package/dist/public/sdk/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  195. package/dist/public/sdk/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  196. package/dist/public/sdk/workers/shamir3pass_runtime_bg.wasm +0 -0
  197. package/dist/public/sdk/workers/tempo_signer_bg.wasm +0 -0
  198. package/dist/public/sdk/workers/wallet-custody-ceremony.worker.js +524 -971
  199. package/dist/public/sdk/workers/wallet_custody_ceremony_bg.wasm +0 -0
  200. package/dist/public/sdk/workers/wasm_signer_worker_bg.wasm +0 -0
  201. package/dist/public/wallet-assets.manifest.json +153 -153
  202. package/dist/public/wallet-service/index.html +4 -4
  203. package/dist/types/wallet/src/SeamsWeb/index.d.ts +1 -0
  204. package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +3 -0
  205. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/inboundMessages.d.ts +5 -0
  206. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +3 -0
  207. package/dist/types/wallet/src/SeamsWeb/walletIframe/coordinator.d.ts +6 -0
  208. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/controller.d.ts +2 -0
  209. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/domain.d.ts +3 -0
  210. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/session.d.ts +4 -0
  211. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/requestRouter.d.ts +1 -1
  212. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +5 -0
  213. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.d.ts +13 -0
  214. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.d.ts +3 -0
  215. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +11 -4
  216. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/walletAlternatives.d.ts +52 -0
  217. package/dist/types/wallet/src/core/types/seams.d.ts +2 -2
  218. package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
  219. package/dist/types/wallet/src/core/ui/walletIcon.d.ts +3 -0
  220. package/dist/types/wallet/src/index.d.ts +1 -0
  221. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/public.d.ts +1 -0
  222. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/types.d.ts +4 -0
  223. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/walletAlternatives.d.ts +48 -0
  224. package/dist/types/wallet/src/react/index.d.ts +1 -2
  225. package/dist/workers/device-linking-key.worker.js +454 -947
  226. package/dist/workers/email-otp.worker.js +588 -820
  227. package/dist/workers/email_otp_runtime_bg.wasm +0 -0
  228. package/dist/workers/evm_crypto_bg.wasm +0 -0
  229. package/dist/workers/passkey-mpc-export.worker.js +572 -804
  230. package/dist/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  231. package/dist/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  232. package/dist/workers/shamir3pass_runtime_bg.wasm +0 -0
  233. package/dist/workers/tempo_signer_bg.wasm +0 -0
  234. package/dist/workers/wallet-custody-ceremony.worker.js +524 -971
  235. package/dist/workers/wallet_custody_ceremony_bg.wasm +0 -0
  236. package/dist/workers/wasm_signer_worker_bg.wasm +0 -0
  237. package/package.json +17 -17
  238. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.css +0 -182
  239. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.js +0 -315
  240. package/dist/esm/sdk/appearance-token-vars-DkF3EBbF.js +0 -1
  241. package/dist/esm/sdk/host-BeE2dIU4.js +0 -1
  242. package/dist/esm/sdk/ownerNearOperation-DjNDxW3_.js +0 -1
  243. package/dist/esm/sdk/registration-CTtTocyo.js +0 -1
  244. package/dist/esm/sdk/resealedEnvelopeResult-DXDo-72P.js +0 -1
  245. package/dist/esm/sdk/routerAbNormalSigning-DVFFkNhJ.js +0 -1
  246. package/dist/esm/sdk/runtime-auth-Dsmw_dUA.js +0 -1
  247. package/dist/esm/sdk/runtime-preferences-DlKHDIjb.js +0 -1
  248. package/dist/esm/sdk/runtime-recovery-C6lS71Jp.js +0 -1
  249. package/dist/public/sdk/appearance-token-vars-DkF3EBbF.js +0 -1
  250. package/dist/public/sdk/host-BeE2dIU4.js +0 -1
  251. package/dist/public/sdk/ownerNearOperation-DjNDxW3_.js +0 -1
  252. package/dist/public/sdk/registration-CTtTocyo.js +0 -1
  253. package/dist/public/sdk/resealedEnvelopeResult-DXDo-72P.js +0 -1
  254. package/dist/public/sdk/routerAbNormalSigning-DVFFkNhJ.js +0 -1
  255. package/dist/public/sdk/runtime-auth-Dsmw_dUA.js +0 -1
  256. package/dist/public/sdk/runtime-preferences-DlKHDIjb.js +0 -1
  257. package/dist/public/sdk/runtime-recovery-C6lS71Jp.js +0 -1
  258. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.d.ts +0 -31
  259. /package/dist/esm/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
  260. /package/dist/esm/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
  261. /package/dist/esm/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
  262. /package/dist/public/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
  263. /package/dist/public/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
  264. /package/dist/public/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
@@ -1 +1 @@
1
- import{n as e}from"./chunk-dVx5-UGu.js";import{C as t,H as n,V as r,i}from"./domainIds-t1lp25yU.js";import{b as a,g as o,h as s,m as c,s as l}from"./digests-BIaE0DMd.js";import{c as u,o as d,r as f}from"./participants-BXdREC5k.js";import{i as p,n as m,r as h,t as g}from"./base64-BmKR3UqU.js";import{n as _,r as v}from"./secureRandomId-8LSc91aN.js";import{s as y}from"./walletDbName-Ca0rCq5r.js";import{i as b,t as ee}from"./activeWalletSession-BJ4B-nJo.js";import{a as te,s as ne}from"./chains-B72I4PDH.js";import{o as re}from"./signingSessionSeal-BFOBKj-J.js";import{r as x}from"./transactionReviewAdmission-Cf_qUZJt.js";import{c as ie,d as S,f as C,h as w,m as T,p as E,s as D}from"./capabilityKinds-DVlGMspk.js";import{r as O}from"./canonicalPrimitives-Jd3i_Ngz.js";import{t as k}from"./errors-BJBDbwHk.js";import{a as A,c as j,i as ae,n as oe,o as M,r as N,s as P,t as F}from"./nearRpcResults-CeHdqaS4.js";import{a as se,c as I,i as ce,l as le,n as ue,o as de,r as fe,t as pe}from"./ed25519OperationFingerprint-Dev4P6Og.js";import{n as me,t as he}from"./signerDomain-D-EUTlLK.js";import{a as ge,c as L,i as R,n as _e,o as ve,r as z,s as B,t as ye}from"./types-A-w1cYlJ.js";import{d as be,i as V,t as H,u as xe}from"./accountIds-DGWFzEnw.js";import{a as Se,n as Ce,o as we,t as U}from"./actions-7SvZZut1.js";import{a as Te,c as Ee}from"./ecdsaChainTarget-BoRVQtjQ.js";import{ot as De,ut as Oe}from"./digestEncoding-34kXJoJr.js";import{t as ke}from"./signerSlot-BlijMq8C.js";import{a as Ae,m as je,o as W}from"./sdkSentEvents-BFwv3mBw.js";import{t as Me}from"./jsonRpc-DGzeiNSa.js";import{T as Ne,i as Pe}from"./emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js";import{p as Fe}from"./nonceLaneKeys-DtBpxubF.js";import{t as Ie}from"./walletSessionAuthorizationStatus-GhcGvDCX.js";import{t as Le}from"./executeWorkerOperation-CAYSt0NA.js";import{T as Re,p as ze,t as Be}from"./authorization-gVWwKwav.js";import{i as Ve,n as He}from"./profileAccountProjection-dvLchPBo.js";import{a as Ue,i as We,l as Ge,u as Ke}from"./helpers-B7c1zc7h.js";import{D as qe,T as Je,j as Ye}from"./nearEd25519YaoSigningPreparation-CnbgQfZc.js";import{n as Xe}from"./lanes-vBKm6yBJ.js";import{n as Ze,r as Qe,t as $e}from"./operationFingerprint-Bas59T7L.js";import{a as G,c as et,o as tt,s as nt,t as rt}from"./trace-BnhLKxcu.js";import{i as it,n as at,r as ot}from"./intentDigest-gM3r4SVX.js";import{t as st}from"./challengeDelivery-Dj9HrjW9.js";import{n as ct}from"./NonceCoordinator-CNXYrOoy.js";import{a as lt,i as ut,o as dt,r as ft,t as pt}from"./authorizationAdmission-28jo_IVJ.js";import{i as mt}from"./walletSessionFailure-CxsVtroW.js";import{a as ht,d as gt,i as _t,l as vt,n as yt,p as bt,r as xt,s as St,u as Ct}from"./routerAbNormalSigning-DVFFkNhJ.js";import{i as wt,n as Tt}from"./clientSessionPersistenceState-BxpITYM_.js";import{a as Et,i as Dt,r as Ot,t as kt}from"./types-C4OErbBf.js";import{C as At,b as jt,c as Mt,g as Nt,h as Pt,l as Ft,n as It,o as Lt,s as Rt,t as zt,u as Bt,x as Vt}from"./requireStepUpAuth-iVo6h_U-.js";import{a as Ht,c as Ut,i as Wt,n as Gt,r as Kt,s as qt,t as Jt}from"./transactionState-G_FPe-U8.js";const Yt=Symbol(`ClientSecretSource`),Xt=Symbol(`EmailOtpWorkerSessionHandle`);function Zt(e,t){let n=String(e||``).trim();if(!n)throw Error(`[platform] ${t} is required`);return n}function Qt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[platform] ${t} must be an object`);return e}function $t(e){return en({prfFirstB64u:e.prf.prfFirstB64u,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})}function en(e){return{kind:`webauthn_prf_first`,prfFirstB64u:Zt(e.prfFirstB64u,`prfFirstB64u`),rpId:e.rpId,credentialIdB64u:Zt(e.credentialIdB64u,`credentialIdB64u`),[Yt]:`webauthn_prf_first`}}function tn(e){let t=Zt(e.sessionId,`sessionId`);switch(e.action){case`threshold_ecdsa_bootstrap`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,keyHandle:Zt(e.keyHandle,`keyHandle`),authSubjectId:e.authSubjectId,action:`threshold_ecdsa_bootstrap`,operation:e.operation,chainTarget:e.chainTarget,[Xt]:`email_otp_worker_session_handle`};case`threshold_ed25519_session`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,rpId:e.rpId,authSubjectId:e.authSubjectId,action:`threshold_ed25519_session`,operation:e.operation,[Xt]:`email_otp_worker_session_handle`};default:{let t=e;throw Error(`[platform] unsupported email OTP worker-issued handle action: ${String(t)}`)}}}function nn(e){let t=Qt(e,`email OTP worker-issued session handle`),n=Zt(String(t.kind||``),`email OTP worker-issued handle kind`);if(n!==`email_otp_worker_session_handle_v1`)throw Error(`[platform] unsupported email OTP worker-issued handle kind: ${n}`);let r=Zt(String(t.action||``),`email OTP worker-issued handle action`),i=Zt(String(t.operation||``),`email OTP worker-issued handle operation`);if(i!==`registration`&&i!==`wallet_unlock`&&i!==`sign`&&i!==`export`)throw Error(`[platform] unsupported email OTP worker-issued handle operation: ${i}`);let a=i,o={sessionId:Zt(String(t.sessionId||``),`email OTP worker-issued handle sessionId`),walletId:Ee(t.walletId),authSubjectId:Pe(t.authSubjectId),operation:a};if(r===`threshold_ecdsa_bootstrap`){if(`rpId`in t)throw Error(`[platform] email OTP ECDSA worker-issued handles cannot include rpId`);if(a===`registration`)throw Error(`[platform] registration Email OTP ECDSA worker-issued handles are retired`);let e=Te(Qt(t.chainTarget,`email OTP worker-issued handle chainTarget`));if(`evmFamilySigningKeySlotId`in t)throw Error(`[platform] runtime Email OTP ECDSA handles cannot include evmFamilySigningKeySlotId`);return tn({...o,action:r,operation:a,keyHandle:Zt(String(t.keyHandle||``),`email OTP worker-issued handle keyHandle`),chainTarget:e})}if(r===`threshold_ed25519_session`){if(`chainTarget`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include chainTarget`);if(`evmFamilySigningKeySlotId`in t||`keyHandle`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include ECDSA key identity`);return tn({...o,action:r,rpId:Ne(t.rpId)})}throw Error(`[platform] unsupported email OTP worker-issued handle action: ${r}`)}function rn(e){return e.action===`threshold_ecdsa_bootstrap`&&e.operation===`export`}function an(e){let t=nn(e);if(!rn(t))throw Error(`[platform] Email OTP ECDSA export requires an export worker handle`);return t}const on=15e3;function sn(e){e.abort(`timeout`)}function cn(e,t){let n=String(e??``).trim();if(!n)throw Error(`[threshold-ed25519] ${t} is required`);return n}function ln(e){let t=cn(Ge(e.credential),`prfFirstB64u`);return{ok:!0,operation:`get_passkey`,requirePrfFirst:!0,credential:e.credential,credentialIdB64u:cn(e.credential.rawId||e.credential.id,`credentialIdB64u`),rawIdB64u:String(e.credential.rawId||``).trim(),rpId:Ne(e.rpId),prf:{kind:`required`,prfFirstB64u:t}}}function un(e){return{kind:`webauthn_prf_first_credential`,credential:e.credential,secretSource:$t(ln(e))}}function dn(e){return e.policySecretSource.secretSource.prfFirstB64u}function fn(e){if(typeof e!=`string`)return null;let t=Date.parse(e);return Number.isSafeInteger(t)&&t>Date.now()?t:null}function pn(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}async function mn(e){let i=n(r(e.relayerUrl));if(!i)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Wallet Session mint`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Wallet Session mint`};let a=Ke(e.auth.policySecretSource.credential),s=new AbortController,c=null;try{let n=`${i}${re}`,r=e.existingOperationCredential,l=String(e.publishableKey||``).trim()||void 0,u=r?.token||l,d=!r&&l&&String(e.projectEnvironmentId||``).trim()||void 0;c=setTimeout(sn,on,s);let f=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,...u?{Authorization:`Bearer ${u}`}:{}},credentials:`omit`,signal:s.signal,body:JSON.stringify({sessionKind:e.sessionKind,relayerKeyId:e.relayerKeyId,sessionPolicy:e.sessionPolicy,...d?{projectEnvironmentId:d}:{},walletSessionTarget:{kind:`new_wallet_session`},...a?{webauthn_authentication:a}:{}})}),p;try{let e=await f.json();p=o(e)?e:{}}catch(e){if(s.signal.aborted)throw e;p={}}if(!f.ok)return Be(p)||{ok:!1,code:typeof p.code==`string`?p.code:`http_error`,message:typeof p.message==`string`?p.message:`HTTP ${f.status}`};let m=Be(p);if(m)return m;if(p.ok!==!0)return{ok:!1,code:typeof p.code==`string`?p.code:`invalid_response`,message:typeof p.message==`string`?p.message:`Wallet Session mint returned an unsuccessful response`};let h=t(p.thresholdSessionId);if(!h.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid thresholdSessionId`};let g=w(p.walletSessionId),_=T(p.authorizationId),v=S(p.quotaId);if(!g.ok||!_.ok||!v.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid authorization identity`};let ee=fn(p.expiresAt),te=pn(p.remainingUses),ne=y(p.runtimePolicyScope);if(!ee||!te||!ne)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid lifecycle or policy data`};let x={ok:!0,thresholdSessionId:h.value,walletSessionId:g.value,authorizationId:_.value,quotaId:v.value,expiresAtMs:ee,remainingUses:te,runtimePolicyScope:ne};if(p.sessionKind===`issued_exact_wallet_session`){let e;try{e=b(p.operationCredential)}catch(e){return{ok:!1,code:`invalid_response`,message:k(e)||`Wallet Session mint returned an invalid operation credential`}}return e.walletSessionId===g.value?{...x,sessionKind:p.sessionKind,operationCredential:e}:{ok:!1,code:`invalid_response`,message:`Wallet Session mint credential does not identify its session`}}return p.sessionKind!==`already_committed_exact_wallet_session`||p.operationCredential!==void 0?{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid session branch`}:r?r.walletSessionId===g.value?{...x,sessionKind:p.sessionKind}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint returned another lifecycle identity`}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint requires the credential the caller already holds`}}catch(e){let t=k(e)||`Failed to mint threshold session`,n=s.signal.aborted;return{ok:!1,code:n?`timeout`:`network_error`,message:n?`Wallet Session mint timed out after ${on}ms`:t}}finally{c!==null&&clearTimeout(c)}}function hn(e){switch(e.kind){case`passkey`:return{kind:`passkey`,authority:e.authority,webauthn_authentication:Ke(e.credential)};case`email_otp`:return{kind:`email_otp`,authority_ref:e.authorityRef,provider_subject_id:cn(e.providerSubjectId,`providerSubjectId`),challenge_id:cn(e.challengeId,`challengeId`),otp_code:cn(e.otpCode,`otpCode`)};default:throw Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function gn(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[threshold-ed25519] ${t} must be an object`);return e}function _n(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length)throw Error(`[threshold-ed25519] ${n} contains unexpected fields`);for(let e=0;e<r.length;e+=1)if(r[e]!==i[e])throw Error(`[threshold-ed25519] ${n} contains unexpected fields`)}function vn(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`[threshold-ed25519] ${t} must be a non-empty normalized string`);return e}function yn(e){switch(e.proof.kind){case`passkey`:if(e.materialRecovery.kind!==`not_requested`)throw Error(`[threshold-ed25519] passkey operation step-up cannot request material recovery`);return{kind:`not_requested`};case`email_otp`:switch(e.materialRecovery.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_factor_release_v1`:return{kind:`email_otp_factor_release_v1`,workerEphemeralPublicKey65B64u:vn(e.materialRecovery.workerEphemeralPublicKey65B64u,`workerEphemeralPublicKey65B64u`)};default:throw e.materialRecovery,Error(`[threshold-ed25519] unsupported material recovery request`)}default:throw e.proof,Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function bn(e){let t=gn(e.value,`operation step-up material recovery`);switch(t.kind){case`not_requested`:if(_n(t,[`kind`],`operation step-up material recovery`),e.requested.kind!==`not_requested`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`not_requested`};case`email_otp_factor_release_v1`:if(_n(t,[`kind`,`challengeId`,`enrollmentId`,`enrollmentSealKeyVersion`,`serverEphemeralPublicKey65B64u`,`nonce12B64u`,`ciphertextB64u`],`operation step-up material recovery`),e.requested.kind!==`email_otp_factor_release_v1`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`email_otp_factor_release_v1`,challengeId:vn(t.challengeId,`materialRecovery.challengeId`),enrollmentId:vn(t.enrollmentId,`materialRecovery.enrollmentId`),enrollmentSealKeyVersion:vn(t.enrollmentSealKeyVersion,`materialRecovery.enrollmentSealKeyVersion`),serverEphemeralPublicKey65B64u:vn(t.serverEphemeralPublicKey65B64u,`materialRecovery.serverEphemeralPublicKey65B64u`),nonce12B64u:vn(t.nonce12B64u,`materialRecovery.nonce12B64u`),ciphertextB64u:vn(t.ciphertextB64u,`materialRecovery.ciphertextB64u`)};default:throw Error(`[threshold-ed25519] operation step-up material recovery kind is invalid`)}}function xn(e){let t=gn(e.body,`operation step-up response`);if(_n(t,[`ok`,`kind`,`authorization`,`expiresAtMs`,`materialRecovery`],`operation step-up response`),t.ok!==!0||t.kind!==`verified_step_up`)throw Error(`[threshold-ed25519] operation step-up response kind is invalid`);let n=gn(t.authorization,`operation step-up authorization`);if(_n(n,[`kind`,`evidence_set_digest`],`operation step-up authorization`),n.kind!==`operation_step_up`)throw Error(`[threshold-ed25519] operation step-up authorization marker is invalid`);let r=vn(n.evidence_set_digest,`operation step-up authorization.evidence_set_digest`);if(O(r),typeof t.expiresAtMs!=`number`||!Number.isSafeInteger(t.expiresAtMs)||t.expiresAtMs<=Date.now())throw Error(`[threshold-ed25519] operation step-up expiry is invalid`);return{kind:`verified_step_up`,authorization:{kind:`operation_step_up`,evidence_set_digest:r},expiresAtMs:t.expiresAtMs,materialRecovery:bn({value:t.materialRecovery,requested:e.requestedMaterialRecovery})}}async function Sn(e){let t=n(r(e.relayerUrl));if(!t)throw Error(`[threshold-ed25519] operation step-up relayerUrl is required`);let i=yn(e),a=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null,o=d({...a?{headers:u(a)}:{},body:{kind:`router_ab_ed25519_yao_operation_step_up_grant_v1`,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:hn(e.proof),materialRecovery:i.kind===`email_otp_factor_release_v1`?{kind:i.kind,worker_ephemeral_public_key_65_b64u:i.workerEphemeralPublicKey65B64u}:i}}),s=await fetch(`${t}${re}`,{...o}),c=await s.json().catch(()=>({}));if(!s.ok){let e=c&&typeof c==`object`&&!Array.isArray(c)?c:{};throw Error(`[threshold-ed25519] operation step-up failed: ${String(e.message||`HTTP ${s.status}`)}`)}return xn({body:c,requestedMaterialRecovery:i})}function Cn(e){let t=e.lane,n=e.readiness;if(t.curve!==n.curve)throw Error(`[SigningSession] planner lane and readiness curves do not match`);if(t.curve===`ecdsa`&&n.curve===`ecdsa`){let e=t.authorization,r=n.authorization,a=e.session,o=r.session;if(!i(t.materialActivation,n.materialActivation)||e.selectedAuthority.authorityId!==r.selectedAuthority.authorityId||e.selectedAuthMethod.kind!==r.selectedAuthMethod.kind||e.selectedAuthMethod.walletAuthMethodId!==r.selectedAuthMethod.walletAuthMethodId||a.walletId!==o.walletId||a.authorityId!==o.authorityId||a.authMethodId!==o.authMethodId||a.authorizationId!==o.authorizationId||a.quotaId!==o.quotaId||a.authorityDigestB64u!==o.authorityDigestB64u||a.authorityRevocationEpoch!==o.authorityRevocationEpoch||e.operationCredential.walletSessionId!==r.operationCredential.walletSessionId||e.operationCredential.token!==r.operationCredential.token)throw Error(`[SigningSession] planner ECDSA readiness authority does not match its lane`)}let r=Tn(e);if(r)return{kind:R.NotReady,lane:t,reason:r};let a=e.forceFreshAuth||e.sensitiveOperationPolicy===`require_fresh_same_method`||t.retention===`single_use`;if(n.status===`ready`&&!a){if(t.curve===`ed25519`&&n.curve===`ed25519`)return{kind:R.WarmSession,lane:t,keyRef:{kind:ye.Cached,curve:`ed25519`,thresholdSessionId:n.thresholdSessionId}};if(t.curve!==`ecdsa`||n.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:R.WarmSession,lane:t,keyRef:{kind:ye.Cached,curve:`ecdsa`,materialActivation:n.materialActivation,authorization:n.authorization}}}if(n.status===`auth_unavailable`||n.status===`status_unavailable`||n.status===`status_unknown`)return{kind:R.NotReady,lane:t,reason:n.status};if(L(t.auth)===`email_otp`)return{kind:R.EmailOtpReauth,lane:t,challenge:{chainFamily:t.chainFamily,lane:t}};if(t.curve===`ed25519`&&n.curve===`ed25519`)return{kind:R.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ed25519`,thresholdSessionId:n.thresholdSessionId}};if(t.curve!==`ecdsa`||n.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:R.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ecdsa`,materialActivation:n.materialActivation,authorization:n.authorization}}}function wn(e,t){return{event:`signing_planner_decision`,readinessStatus:e.readiness.status,forceFreshAuth:!!e.forceFreshAuth,...e.sensitiveOperationPolicy?{sensitiveOperationPolicy:e.sensitiveOperationPolicy}:{},plan:ve(t),lane:ge(e.lane),...t.kind===R.NotReady?{reason:t.reason}:{}}}function Tn(e){return L(e.lane.auth)===`email_otp`&&(e.sensitiveOperationPolicy===`deny_email_otp`||e.sensitiveOperationPolicy===`require_passkey`)?`policy_blocked`:null}async function En(e,t){let n=H(e),r=await He(t,Ve(n)).catch(()=>null);if(!r?.profileId)throw Error(`No profile/account mapping for account ${n}`);let i=await t.getLastProfileState().catch(()=>null);if(!i?.profileId||i.profileId!==r.profileId)throw Error(`No last user session for account ${n}`);let a=ke(i.activeSignerSlot,{min:1});if(a===null)throw Error(`Invalid last-user signerSlot for account ${n}`);return a}var K=function(e){return e.Query=`query`,e.Send=`send_tx`,e.Block=`block`,e}(K||{}),Dn=class e{transaction;signature;borsh_bytes;nonceLease;serverDispatch;constructor(e){this.transaction=e.transaction,this.signature=e.signature,this.borsh_bytes=e.borsh_bytes,e.nonceLease&&(this.nonceLease=e.nonceLease),e.serverDispatch&&(this.serverDispatch=e.serverDispatch)}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}encode(){return new Uint8Array(this.borsh_bytes).buffer}base64Encode(){return m(this.encode())}};function On(e){if(!e)return null;if(Array.isArray(e))return new Uint8Array(e).buffer;if(ArrayBuffer.isView(e)){let t=e;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return e instanceof ArrayBuffer?e:null}function kn(e){let t=e?.signedTransaction,n=t&&typeof t==`object`?t:e,r=n.base64Encode;if(c(r))return r.call(n);let i=n.encode;if(c(i))return m(i.call(n));let a=On(n.borsh_bytes);if(a)return m(a);let o=On(n.borshBytes);if(o)return m(o);throw Error(`Invalid signed transaction payload: cannot serialize to base64`)}var An=class e{rpcUrls;constructor(t){this.rpcUrls=e.normalizeRpcUrls(t)}static normalizeRpcUrls(e){let t=(Array.isArray(e)?e:e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean)).map(e=>{try{return new URL(e).toString()}catch(t){let n=k(t)||`Invalid NEAR RPC URL: ${e}`;throw Error(n)}});if(!t.length)throw Error(`NEAR RPC URL cannot be empty`);return Array.from(new Set(t))}errorFromHttpStatus(e){return Error(`RPC request failed: ${e.status} ${e.statusText}`)}errorFromFailedCall(e,t){return t}sendWithRetry(e){return e()}buildRequestBody(e,t){return JSON.stringify({jsonrpc:`2.0`,id:v(`near-rpc`,32,`NEAR JSON-RPC request IDs`),method:e,params:t})}async postOnce(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:t});if(!n.ok)throw this.errorFromHttpStatus(n);let r=await n.text();if(!r?.trim())throw Error(`Empty response from RPC server`);let i=Me(JSON.parse(r));if(!i.ok)throw Error(`Invalid NEAR JSON-RPC response: ${i.error}`);return i.value}async requestWithFallback(e){let t;for(let[n,r]of this.rpcUrls.entries())try{let t=await this.postOnce(r,e);return n>0&&console.warn(`[NearClient] RPC succeeded via fallback: ${r}`),t}catch(e){t=e;let i=n<this.rpcUrls.length-1;if(console.warn(`[NearClient] RPC call to ${r} failed${i?`, trying next`:``}: ${k(e)||`RPC request failed`}`),!i)throw e instanceof Error?e:Error(String(e))}throw Error(k(t)||`RPC request failed`)}unwrapRpcResult(e,t){if(e.kind===`failure`)throw this.errorFromRpc(t,e.error);let n=e.result;if(typeof n==`object`&&n&&`error`in n){let e=Reflect.get(n,`error`),r=typeof e==`string`?e:JSON.stringify(e);throw this.errorFromWrappedResult(`${t} Error: ${r}`)}return e.result}async makeRpcCall(e,t,n,r){let i=this.buildRequestBody(e,t);try{let e=await this.requestWithFallback(i);return r(this.unwrapRpcResult(e,n))}catch(e){throw this.errorFromFailedCall(n,e)}}async query(e,t){return this.makeRpcCall(K.Query,e,`Query`,t)}async viewAccessKey(e,t,n){let r={request_type:`view_access_key`,finality:n?.finality||`final`,account_id:e,public_key:t};return this.makeRpcCall(K.Query,r,`View Access Key`,oe)}async viewAccessKeyList(e,t){let n={request_type:`view_access_key_list`,finality:t?.finality||`final`,account_id:e};return this.makeRpcCall(K.Query,n,`View Access Key List`,F)}async viewAccount(e){let t={request_type:`view_account`,finality:`final`,account_id:e};return this.makeRpcCall(K.Query,t,`View Account`,N)}async viewCode(e,t){let n={request_type:`view_code`,finality:t?.finality||`final`,account_id:e};return g(await this.makeRpcCall(K.Query,n,`View Code`,A))}async viewBlock(e){return this.makeRpcCall(K.Block,e,`View Block`,ae)}async sendTransaction(e,t=`EXECUTED_OPTIMISTIC`){let n={signed_tx_base64:kn(e),wait_until:t};return this.sendWithRetry(async()=>{let e=await this.makeRpcCall(K.Send,n,`Send Transaction`,P),t=e.status;if(t&&typeof t==`object`&&`Failure`in t)throw this.errorFromOutcome(`Send Transaction`,e,t.Failure);return e})}async txStatus(e,t){let n={tx_hash:e,sender_account_id:t};return this.makeRpcCall(`EXPERIMENTAL_tx_status`,n,`Tx Status`,P)}async callFunction(e,t,n,r,i){let a={request_type:`call_function`,...i??{finality:`final`},account_id:e,method_name:t,args_base64:m(new TextEncoder().encode(JSON.stringify(n)).buffer)};return r(j((await this.makeRpcCall(K.Query,a,`View Function`,M)).result))}async view(e){return this.callFunction(e.account,e.method,e.args,e.decodeResult)}async getAccessKeys({account:e,block_id:t}){let n={request_type:`view_access_key_list`,account_id:e,finality:`final`};t&&(n.block_id=t,delete n.finality);let r=await this.makeRpcCall(K.Query,n,`View Access Key List`,F),i=[],a=[];for(let e of r.keys)e.access_key.permission===`FullAccess`?i.push(e):e.access_key.permission&&typeof e.access_key.permission==`object`&&`FunctionCall`in e.access_key.permission&&a.push(e);return{fullAccessKeys:i,functionCallAccessKeys:a}}};function jn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Mn(e){if(!e)return;let t=Object.keys(e);return t.length?t[0]:void 0}var Nn=class e extends Error{code;type;kind;index;short;details;operation;constructor(e){super(e.message),this.name=e.name||`NearRpcError`,this.code=e.code,this.type=e.type||`Unknown`,this.kind=e.kind,this.index=e.index,this.short=e.short,this.details=e.details,this.operation=e.operation}static fromOutcome(t,n,r){let{message:i,type:a,kind:o,index:s,short:c}=Fn(t,r);return new e({message:i||`${t} failed`,short:c||o||`TxExecutionError`,type:a||`Failure`,kind:o,index:s,name:`TxExecutionFailure`,operation:t,details:{Failure:r,outcome:n}})}static fromRpcError(t,n){let r=n.data,{message:i,type:a,kind:o,index:s,short:c}=Pn(t,r,n.message);return new e({message:i||n.message||`${t} RPC error`,short:c||o||`RPC error`,type:a||`RpcError`,kind:o,index:s,code:typeof n.code==`number`?n.code:void 0,name:n.name||`NearRpcError`,operation:t,details:r})}};function Pn(e,t,n=``){let r=jn(t)?t:void 0,i=jn(r?.TxExecutionError)?r.TxExecutionError:void 0;if(!i){let i=typeof t==`string`&&t.trim()?t.trim():r?JSON.stringify(r):n.trim();return{message:`${e} RPC error${i?`: ${i}`:``}`}}return In(e,i)}function Fn(e,t){let n=jn(t)?t:void 0;return n?In(e,n):{message:`${e} failed (Unknown Failure)`}}function In(e,t){if(jn(t.InvalidTxError)){let n=t.InvalidTxError,r=Mn(n)||`InvalidTxError`;jn(n.ActionsValidation)&&(r=`ActionsValidation.${Mn(n.ActionsValidation)}`);let i=r.startsWith(`ActionsValidation.`)?`InvalidTxError: ${r.split(`.`)[1]||`ActionsValidation`}`:`InvalidTxError: ${r}`;return{message:`${e} failed (InvalidTxError: ${r})`,type:`InvalidTxError`,kind:r,short:i}}if(jn(t.ActionError)){let n=t.ActionError,r=typeof n.index==`number`?n.index:void 0,i=Mn(jn(n.kind)?n.kind:void 0)||`ActionError`,a=typeof r==`number`?` at action ${r}`:``,o=`ActionError: ${i}`;return{message:`${e} failed${a} (ActionError: ${i})`,type:`ActionError`,kind:i,index:r,short:o}}return{message:`${e} failed (TxExecutionError)`,type:`TxExecutionError`,kind:`TxExecutionError`,short:`TxExecutionError`}}var Ln=class e extends Dn{transactionHash;constructor(e){super(e),this.transactionHash=e.transactionHash}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,transactionHash:a(t.transactionHash,`signed transaction hash`),...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}static decode(){throw Error(`SignedTransaction.decode(): borsh deserialization not implemented`)}},Rn=class extends An{errorFromRpc(e,t){return Nn.fromRpcError(e,t)}errorFromWrappedResult(e){return new Nn({message:e,short:`RpcError`,type:`RpcError`})}errorFromOutcome(e,t,n){return Nn.fromOutcome(e,t,n)}errorFromHttpStatus(e){return e.status===429?Error(`RPC throttled; retry shortly`):super.errorFromHttpStatus(e)}async sendWithRetry(e){let t=null;for(let n=1;n<=5;n++)try{return await e()}catch(e){t=e;let r=k(e);if(!/server error|internal|temporar|timeout|throttl|too many requests|429|unavailable|bad gateway|gateway timeout/i.test(r||``)||n===5)throw e;let i=200*2**(n-1),a=Math.floor(Math.random()*150);await new Promise(e=>setTimeout(e,i+a))}throw t instanceof Error?t:Error(String(t))}},zn=class extends Rn{sendWithRetry(e){return e()}};function Bn(e){try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,2)}catch{return String(e)}}function q(e,t,n){let r=String(t??``).trim();if(r)return{label:e,value:r,...typeof n==`string`&&n.trim()?{copyValue:n}:{}}}function Vn(e){switch(e.action_type){case U.Transfer:case U.FunctionCall:return BigInt(e.deposit||`0`);case U.Stake:return BigInt(e.stake||`0`);default:return BigInt(0)}}function Hn(e){try{let t=JSON.parse(e)?.permission;if(t===`FullAccess`)return`FullAccess`;if(t&&typeof t==`object`){if(`FullAccess`in t)return`FullAccess`;if(`FunctionCall`in t)return`FunctionCall`}}catch{return`Unknown`}return`Unknown`}function Un(e){let{action:t,txIndex:n,actionIndex:r,receiverId:i}=e,a=`near.tx.${n}.action.${r}`;switch(t.action_type){case U.CreateAccount:return{id:a,kind:`near.action`,actionType:`createAccount`,label:`Action ${r+1}: CreateAccount`,fields:[q(`Receiver`,i)].filter(Boolean)};case U.Transfer:return{id:a,kind:`near.action`,actionType:`transfer`,label:`Action ${r+1}: Transfer`,fields:[q(`Receiver`,i),q(`Amount (yoctoNEAR)`,t.deposit)].filter(Boolean)};case U.FunctionCall:{let e=String(t.args||``),n=e?[{id:`${a}.args`,kind:`raw.fallback`,label:`Function Arguments`,raw:e}]:[];return{id:a,kind:`near.action`,actionType:`functionCall`,label:`Action ${r+1}: FunctionCall`,fields:[q(`Receiver`,i),q(`Method`,t.method_name),q(`Gas`,t.gas),q(`Deposit (yoctoNEAR)`,t.deposit)].filter(Boolean),...n.length?{children:n}:{}}}case U.Stake:return{id:a,kind:`near.action`,actionType:`stake`,label:`Action ${r+1}: Stake`,fields:[q(`Receiver`,i),q(`Stake (yoctoNEAR)`,t.stake),q(`Validator Key`,t.public_key,t.public_key)].filter(Boolean)};case U.AddKey:return{id:a,kind:`near.action`,actionType:`addKey`,label:`Action ${r+1}: AddKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key),q(`Permission`,Hn(t.access_key))].filter(Boolean)};case U.DeleteKey:return{id:a,kind:`near.action`,actionType:`deleteKey`,label:`Action ${r+1}: DeleteKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key)].filter(Boolean)};case U.DeployContract:return{id:a,kind:`near.action`,actionType:`deployContract`,label:`Action ${r+1}: DeployContract`,fields:[q(`Receiver`,i),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case U.DeployGlobalContract:return{id:a,kind:`near.action`,actionType:`deployGlobalContract`,label:`Action ${r+1}: DeployGlobalContract`,fields:[q(`Receiver`,i),q(`Deploy Mode`,t.deploy_mode),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case U.UseGlobalContract:return{id:a,kind:`near.action`,actionType:`useGlobalContract`,label:`Action ${r+1}: UseGlobalContract`,fields:[q(`Receiver`,i),q(`By Account`,t.account_id),q(`By Code Hash`,t.code_hash,t.code_hash)].filter(Boolean)};case U.DeleteAccount:return{id:a,kind:`near.action`,actionType:`deleteAccount`,label:`Action ${r+1}: DeleteAccount`,fields:[q(`Receiver`,i),q(`Beneficiary`,t.beneficiary_id)].filter(Boolean)};case U.SignedDelegate:return{id:a,kind:`near.action`,actionType:`signedDelegate`,label:`Action ${r+1}: SignedDelegate`,children:[{id:`${a}.delegate`,kind:`raw.fallback`,label:`Signed Delegate Payload`,raw:Bn(t)}]};default:return{id:a,kind:`raw.fallback`,label:`Action ${r+1}: Unsupported`,raw:Bn(t)}}}function Wn(e,t,n){let r=String(e.receiverId||``).trim()||`(unknown receiver)`,i=Array.isArray(e.actions)?e.actions:[],a=i.reduce((e,t)=>e+Vn(t),BigInt(0)),o=[q(`Receiver`,r),q(`Action Count`,String(i.length)),q(`Attached Value (yoctoNEAR)`,a>0?a.toString():void 0)].filter(Boolean);return{id:`near.tx.${t}`,kind:`generic.contractCall`,label:n>1?`Transaction ${t+1}`:`Transaction`,to:r,value:a>0?a.toString():void 0,fields:o,children:i.map((e,n)=>Un({action:e,txIndex:t,actionIndex:n,receiverId:r}))}}function Gn(e){let t=Array.isArray(e.txSigningRequests)?e.txSigningRequests:[],n=t.map((e,n)=>Wn(e,n,t.length)),r=t.reduce((e,t)=>e+(Array.isArray(t.actions)?t.actions.reduce((e,t)=>e+Vn(t),BigInt(0)):BigInt(0)),BigInt(0));return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEAR Transaction`,subtitle:e.subtitle,operations:n,...r>0?{totals:{nativeValue:r.toString(),nativeSymbol:`yoctoNEAR`}}:{}}}function Kn(e){let t={id:`near.message`,kind:`near.message`,label:`Message signature`,fields:[q(`Signer`,e.signerAccount,e.signerAccount),q(`Recipient`,e.recipient,e.recipient),{label:`Message`,value:e.message,copyValue:e.message,renderAs:`file-content`,hideChevron:!0}].filter(Boolean)};return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEP-413 message`,subtitle:e.subtitle,operations:[t]}}function qn(e){try{return Gn(e)}catch{return{chain:`near`,signerAccount:e.signerAccount,...e.title?{title:e.title}:{},...e.subtitle?{subtitle:e.subtitle}:{},operations:[]}}}const Jn=e=>typeof e==`string`?e:V(be(e.keyData));function J(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?null:Math.round(e)}function Yn(e){if(e==null||!s(e))return;let t=e;if(t.kind!==`registration_confirmation_diagnostics_v1`)return;let n=J(t.workerReadyMs),r=J(t.workerRequestRoundTripMs),i=J(t.workerResponseValidationMs),a=J(t.requestSetupMs),o=J(t.promptUserMs),c=J(t.promptElementDefineMs),l=J(t.promptMountMs),u=J(t.promptHostFirstUpdateMs),d=J(t.promptHostInteractiveMs),f=J(t.promptConfirmEventMs),p=J(t.promptDecisionWaitMs),m=J(t.credentialCreateStartMs),h=J(t.credentialCreateMs),g=J(t.credentialSerializeMs),_=J(t.duplicateRetryCount),v=J(t.mainThreadTotalMs);if(!(n==null||r==null||i==null||a==null||o==null||c==null||l==null||u==null||d==null||f==null||p==null||m==null||h==null||g==null||_==null||v==null))return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:n,workerRequestRoundTripMs:r,workerResponseValidationMs:i,requestSetupMs:a,promptUserMs:o,promptElementDefineMs:c,promptMountMs:l,promptHostFirstUpdateMs:u,promptHostInteractiveMs:d,promptConfirmEventMs:f,promptDecisionWaitMs:p,credentialCreateStartMs:m,credentialCreateMs:h,credentialSerializeMs:g,duplicateRetryCount:_,mainThreadTotalMs:v}}function Xn(e){if(e==null)return;if(!s(e))throw Error(`Invalid transactionContext: expected object`);let{nearPublicKeyStr:t,nextNonce:n,txBlockHeight:r,txBlockHash:i,accessKeyInfo:a}=e,o=l(t,`transactionContext.nearPublicKeyStr`),c=l(n,`transactionContext.nextNonce`),u=l(r,`transactionContext.txBlockHeight`),d=l(i,`transactionContext.txBlockHash`),f=a;if(f!=null&&!s(f))throw Error(`Invalid transactionContext.accessKeyInfo: expected object`);return f??={nonce:0},{nearPublicKeyStr:o,nextNonce:c,txBlockHeight:u,txBlockHash:d,accessKeyInfo:f}}function Zn(e){if(e==null)return;let t=Ue(e);if(t.type!==`public-key`)throw Error(`Invalid credential.type: expected "public-key"`);let{id:n,rawId:r,response:i,authenticatorAttachment:a}=t;if(l(n,`credential.id`),l(r,`credential.rawId`),!s(i))throw Error(`Invalid credential.response: expected object`);let{clientDataJSON:o,attestationObject:c,transports:u}=i;if(l(o,`credential.response.clientDataJSON`),l(c,`credential.response.attestationObject`),!Array.isArray(u))throw Error(`Invalid credential.response.transports: expected string[]`);for(let e of u)if(typeof e!=`string`)throw Error(`Invalid credential.response.transports item: expected string`);if(a!=null&&typeof a!=`string`)throw Error(`Invalid credential.authenticatorAttachment: expected string | undefined`);return t}function Qn(e){if(!s(e))throw Error(`Invalid response payload: expected object`);let{confirmed:t,requestId:n,intentDigest:r,credential:i,transactionContext:a,registrationDiagnostics:o,error:c}=e,u=l(n,`requestId`),d=r==null?``:l(r,`intentDigest`),f=i==null?void 0:Zn(i);if(!f)throw Error(`Missing registration credential`);let p=a==null?void 0:Xn(a),m=Yn(o),h=c==null?void 0:l(c,`error`);return{confirmed:!!t,requestId:u,intentDigest:d,credential:f,...p?{transactionContext:p}:{},...m?{registrationDiagnostics:m}:{},...h==null?{}:{error:h}}}function $n(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`operation step-up preparation ref must be an object`);let t=e;if(Object.keys(t).length!==3||t.kind!==`near_operation_step_up_prepared_v1`)throw Error(`operation step-up preparation ref is invalid`);let n=String(t.handle||``).trim();if(!n.startsWith(`near-operation-step-up:`)||/\s/.test(n))throw Error(`operation step-up preparation handle is invalid`);return{kind:`near_operation_step_up_prepared_v1`,handle:n,challengeB64u:O(t.challengeB64u)}}const er=new Map,tr=new Map;function nr(e,t){let n=String(e||``).trim();if(!n)throw Error(`[SigningEngine][near] ${t} is required`);return n}function rr(e){er.set(nr(e.requestId,`requestId`),e.build)}function ir(e){er.delete(String(e||``).trim())}const ar={async prepare(e){let t=nr(e.requestId,`requestId`),n=er.get(t);if(!n)throw Error(`[SigningEngine][near] operation step-up preparation is unavailable`);er.delete(t);let r=e.kind===`near_transaction`?await n({kind:`near_transaction`,transactionContext:e.transactionContext,operationId:nr(e.operationId,`operationId`),operationFingerprint:nr(e.operationFingerprint,`operationFingerprint`),displayDigest:nr(e.displayDigest,`displayDigest`)}):await n({kind:`near_signature_only`,displayDigest:nr(e.displayDigest,`displayDigest`)}),i=await Ze(r.envelope),a=$n({kind:`near_operation_step_up_prepared_v1`,handle:`near-operation-step-up:${_(24,`operation step-up handle`)}`,challengeB64u:i});return tr.set(a.handle,{requestId:t,operation:r.operation}),a},cancel(e){let t=String(e.requestId||``).trim();t&&er.delete(t),e.handle&&tr.delete(e.handle);for(let[e,n]of tr)n.requestId===t&&tr.delete(e)}};function or(e){let t=nr(e.requestId,`requestId`),n=nr($n(e.ref).handle,`operation step-up handle`),r=tr.get(n);if(tr.delete(n),!r||r.requestId!==t)throw Error(`[SigningEngine][near] prepared operation step-up is unavailable`);return r.operation}function sr(e){if(!i(e.expected,e.actual))throw Error(`[SigningEngine][near] operation assertion changed material activation`)}const cr=new Map;function lr(e){let t=String(e||``).trim();if(!t)throw Error(`[SigningEngine][near] requestId is required`);return t}function ur(e){cr.set(lr(e.requestId),e.fund)}function dr(e){cr.delete(String(e||``).trim())}const fr={async fund(e){let t=lr(e.requestId),n=cr.get(t);if(!n)throw Error(`[SigningEngine][near] implicit-account funding is unavailable`);return cr.delete(t),await n(e.request)}};async function pr(e){let t=H(e.nearAccount.accountId),n=ke(e.signerSlot,{min:1});if(n===null)throw Error(`Invalid signerSlot for ${e.operationLabel}: ${e.signerSlot}`);if(e.requestedSignerSlot!==void 0){let t=ke(e.requestedSignerSlot,{min:1});if(t===null||t!==n)throw Error(`Requested signerSlot does not match the selected signing lane for ${e.operationLabel}`)}let r=await e.materialExecutor.resolveSigningKeyMaterial();if(r.nearAccountId!==t||r.signerSlot!==n)throw Error(`[SigningEngine] threshold key material does not match the selected lane`);return{thresholdKeyMaterial:r}}function mr(e){let t=gr({nearAccountId:e.nearAccountId,tx:e.transaction,txIndex:0});return{txSigningRequest:t,confirmationTransaction:{receiverId:t.receiverId,actions:t.actions}}}function hr(e){let t=e.delegate.actions.map(Se);t.forEach((e,t)=>{try{we(e)}catch(e){throw Error(`Delegate action ${t} validation failed: ${e instanceof Error?e.message:String(e)}`)}});let n={senderId:e.delegate.senderId||e.nearAccountId,receiverId:e.delegate.receiverId,actions:t,nonce:e.delegate.nonce,maxBlockHeight:e.delegate.maxBlockHeight};return{confirmationDelegate:n,workerDelegate:{...n,nonce:e.delegate.nonce.toString(),maxBlockHeight:e.delegate.maxBlockHeight.toString(),publicKey:e.signingPublicKey}}}function gr(e){let t=String(e.tx?.receiverId||``).trim();if(!t)throw Error(`[SigningEngine] transactions[${e.txIndex}].receiverId is required`);let n=Array.isArray(e.tx?.actions)?e.tx.actions:[];if(n.length===0)throw Error(`[SigningEngine] transactions[${e.txIndex}].actions must be non-empty`);for(let e=0;e<n.length;e++)we(n[e]);return{nearAccountId:e.nearAccountId,receiverId:t,actions:n}}async function _r(e){if(Ot(e.signingAuthPlan)&&!e.emailOtpEd25519StepUp)throw Error(`[SigningEngine][near] Email OTP step-up runner is unavailable`);if(Dt(e.signingAuthPlan)&&!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);let t=null,n=await zt({operation:{kind:`near_ed25519_step_up`,requiredSignatureUses:e.requiredSignatureUses},selectedLane:{authMethod:L(e.signingLaneAuth)},policy:Sr(e.signingAuthPlan),methods:{...e.emailOtpEd25519StepUp?{emailOtp:{method:`email_otp`,prepareChallenge:async()=>await e.emailOtpEd25519StepUp.prepare({operationFingerprintDigest:e.operationFingerprintDigest}),...e.emailOtpEd25519StepUp.resend?{resendChallenge:async()=>await e.emailOtpEd25519StepUp.resend({operationFingerprintDigest:e.operationFingerprintDigest})}:{},complete:yr}}:{},passkey:{method:`passkey`,prepare:async()=>{if(!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);return t=await e.passkeyEd25519OperationStepUp.prepare(),{}},complete:br}}}),r=e.signingAuthPlan;if(n.method===`warm_session`){if(!Cr(r))throw Error(`[SigningEngine][near] warm-session step-up requires a warm-session plan`);return{kind:`warm_session`,confirmationAuthPayload:{signingAuthPlan:r}}}if(n.method===`email_otp`){if(!Ot(r))throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP plan`);return{kind:`email_otp`,confirmationAuthPayload:{signingAuthPlan:{kind:`emailOtpReauth`,method:`email_otp`,emailOtpPrompt:n.prompt}},emailOtpPrompt:n.prompt}}if(!Dt(r))throw Error(`[SigningEngine][near] passkey step-up requires a passkey plan`);return{kind:`passkey`,confirmationAuthPayload:{signingAuthPlan:r},plannedPasskeyOperationStepUp:xr(t)}}function vr(e){switch(e.kind){case`voiceid`:throw Error(`Unlock with VoiceID again before signing.`);case`passkey`:return{kind:`passkeyReauth`,method:`passkey`};case`email_otp`:return{kind:`emailOtpReauth`,method:`email_otp`};default:throw Error(`[SigningEngine][near] unsupported material auth requirement`)}}async function yr(){}async function br(){}function xr(e){if(!e)throw Error(`[SigningEngine][near] Passkey operation step-up plan is required`);return e}function Sr(e){if(Et(e)){if(e.curve!==`ed25519`)throw Error(`[SigningEngine][near] warm-session step-up requires an Ed25519 auth plan`);return{kind:`reuse_warm_session`,authorization:{method:e.method,curve:`ed25519`,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}}return{kind:`use_selected_lane`}}function Cr(e){return Et(e)&&e.curve===`ed25519`}function wr(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Tr(e,t){let n=Rt(e.signingAuthPlan);if(t.phase===`confirmation.complete`){if(n===`passkey`&&t.status===`succeeded`)return}else if(n!==`passkey`||t.phase!==`auth.passkey.prompt.started`&&t.phase!==`auth.passkey.prompt.succeeded`)return;let r=Lt(t,n);r&&wr(e.onEvent,e.nearAccountId,{...r,authMethod:n})}function Er(e){return{kind:`warm_session`,signingAuthPlan:e,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}function Dr(e){if(e.prepared.kind===`warm_session`)return Er(e.prepared.confirmationAuthPayload.signingAuthPlan);if(e.prepared.kind===`email_otp`)return{kind:`email_otp`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,challengeId:kr(e.confirmation.emailOtpChallengeId,e.prepared.emailOtpPrompt.challengeId),otpCode:Or(e.confirmation.otpCode),...e.prepared.emailOtpPrompt.emailHint?{emailHint:e.prepared.emailOtpPrompt.emailHint}:{}};if(!e.confirmation.credential)throw Error(`[SigningEngine] missing WebAuthn credential for NEAR step-up authorization`);return{kind:`passkey`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,credential:We(e.confirmation.credential),plannedPasskeyOperationStepUp:e.prepared.plannedPasskeyOperationStepUp}}function Or(e){let t=String(e||``).trim();if(!/^\d{6}$/.test(t))throw Error(`[SigningEngine] missing Email OTP code for NEAR step-up authorization`);return t}function kr(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`[SigningEngine] missing Email OTP challenge id for NEAR step-up authorization`);return n}function Ar(e){if(!e||!Array.isArray(e.actions)||e.actions.length===0)throw Error(`[SigningEngine][near] one NEAR transaction with actions is required`);return 1}function jr(e){throw Error(`[SigningEngine][near] exactly one NEAR transaction is supported per signing operation; received ${e.length}`)}const Mr=2e4;async function Nr(e){return Br(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519ComputeNep413SigningDigest,timeoutMs:Mr,payload:{message:e.message,recipient:e.recipient,nonce:e.nonce,callbackUrl:e.callbackUrl}}}))}async function Pr(e){return Br(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519ComputeDelegateSigningDigest,timeoutMs:Mr,payload:{delegate:e.delegate}}}))}async function Fr(e){return Vr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519BuildDelegateSigningPayload,timeoutMs:Mr,payload:{delegate:e.delegate}}}))}async function Ir(e){return Hr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519FinalizeDelegateFromSignature,timeoutMs:Mr,payload:{delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u}}}))}async function Lr(e){let t=Ur(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519BuildNearTxUnsignedBorsh,timeoutMs:Mr,payload:{txSigningRequests:[e.txSigningRequest],transactionContext:e.transactionContext}}})),n=t[0];if(!n||t.length!==1)throw Error(`near signer worker returned invalid single-transaction unsigned payload`);return n}async function Rr(e){return Wr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519FinalizeNearTxFromSignature,timeoutMs:Mr,payload:{unsignedTransactionBorshB64u:e.unsignedTransactionBorshB64u,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,expectedNearAccountId:e.expectedNearAccountId,expectedSignerPublicKey:e.expectedSignerPublicKey}}}))}async function zr(e){return Gr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519DecodeSignedNearTxBorsh,timeoutMs:Mr,payload:{signedTransactionBorshB64u:e.signedTransactionBorshB64u}}}))}function Br(e){let t=e;if(!t?.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 signing digest result`);return t}function Vr(e){let t=e;if(!t?.canonicalDelegateBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 delegate signing payload`);return t}function Hr(e){let t=e;if(!t?.delegateAction||!t.signature||!t.borshBytes)throw Error(`near signer worker returned invalid Ed25519 signed delegate result`);return t}function Ur(e){if(!Array.isArray(e))throw Error(`near signer worker returned invalid Ed25519 unsigned tx result`);return e.map(e=>{let t=e;if(!t?.unsignedTransactionBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 unsigned tx item`);return t})}function Wr(e){let t=e;if(!t?.signedTransactionBorshB64u||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 finalized tx result`);return t}function Gr(e){let t=e;if(!t?.signedTransaction?.transaction||!t.signedTransaction.signature||!t.signedTransaction.borshBytes||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 signed tx decode result`);return t}function Kr(e,t){return e.request_id===t.request_id&&e.account_id===t.account_id&&e.authorization.kind===t.authorization.kind&&(e.authorization.kind===`reusable_wallet_session`?t.authorization.kind===`reusable_wallet_session`&&e.authorization.wallet_session_id===t.authorization.wallet_session_id:t.authorization.kind===`operation_step_up`)&&e.material_activation.kind===t.material_activation.kind&&e.material_activation.activation_id===t.material_activation.activation_id&&e.material_activation.capability===t.material_activation.capability&&e.material_activation.material_owner===t.material_activation.material_owner&&e.material_activation.key_binding===t.material_activation.key_binding&&e.material_activation.lifecycle_binding===t.material_activation.lifecycle_binding&&e.material_activation.signing_worker===t.material_activation.signing_worker&&e.signing_worker_id===t.signing_worker_id}function qr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Jr(e){if(!Kr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing prepare response scope mismatch`);if(e.request.expires_at_ms!==e.response.expires_at_ms)throw Error(`Router A/B normal-signing prepare response expiry mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing prepare response SigningWorker mismatch`);if(!qr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing prepare response payload digest mismatch`)}function Yr(e){if(!Kr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing response scope mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing response SigningWorker mismatch`);if(!qr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing response payload digest mismatch`);if(e.response.signature.bytes.length!==64)throw Error(`Router A/B normal-signing response signature must be 64 bytes`)}function Y(e,t){let n=String(e||``).trim();if(!n)throw Error(`Router A/B Ed25519 normal-signing ready state is missing ${t}`);return n}function X(e,t,n){if(e!==t)throw Error(`Router A/B Ed25519 normal-signing ready state ${n} mismatch`)}function Xr(e,t){let n=Math.floor(Number(e));if(!Number.isFinite(n)||n<=Date.now())throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is expired`);return n}function Zr(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is exhausted`);return n}function Qr(e){let t=e.state,n=t.signingWalletSession,r=Y(e.thresholdSessionId,`thresholdSessionId`),i=Y(t.thresholdSessionId,`state.thresholdSessionId`),a=Y(t.signingLane.thresholdSessionId,`state.signingLane.thresholdSessionId`);X(i,r,`thresholdSessionId`),X(a,r,`lane thresholdSessionId`);let o=Y(t.walletSessionId,`state.walletSessionId`),s=Y(t.quotaId,`state.quotaId`);X(t.signingLane.walletSessionId,o,`lane walletSessionId`),X(t.signingLane.quotaId,s,`lane quotaId`);let c=Y(e.nearAccountId,`nearAccountId`);Y(t.signingLane.identity.signer.account.wallet.walletId,`state.signingLane.identity.signer.account.wallet.walletId`),X(Y(e.thresholdKeyMaterial.nearAccountId,`thresholdKeyMaterial.nearAccountId`),c,`threshold key accountId`);let l=n.routerAbNormalSigning,u=Y(n.auth.walletSessionToken,`Wallet Session bearer token`),d=Y(t.signingRootId,`state.signingRootId`),f=Y(t.signingRootVersion,`state.signingRootVersion`);X(n.thresholdSessionId,r,`Wallet Session thresholdSessionId`),X(n.walletSessionId,o,`Wallet Session walletSessionId`),X(n.quotaId,s,`Wallet Session quotaId`),X(n.signingRootId,d,`signingRootId`),X(n.signingRootVersion,f,`signingRootVersion`),X(t.routerAbNormalSigning.signingWorkerId,l.signingWorkerId,`signingWorkerId`),Xr(n.expiresAtMs,`expiresAtMs`);let p=Zr(n.remainingUses,`remainingUses`);if(t.remainingUses!==p)throw Error(`Router A/B Ed25519 normal-signing ready state remainingUses mismatch`);return{kind:`router_ab_ed25519_normal_signing_ready_state_v1`,relayerUrl:Y(t.relayerUrl,`relayerUrl`),signingWorkerId:Y(l.signingWorkerId,`signingWorkerId`),signerPublicKey:Y(e.thresholdKeyMaterial.publicKey,`signerPublicKey`),credential:{kind:`wallet_session_opaque`,walletSessionToken:u,home:n.auth.credential.home}}}const $r=12e4;async function ei(e){return await e.ctx.resolveOperationStepUpCredential({walletId:e.walletId,relayerUrl:e.relayerUrl,proof:e.proof})}function ti(e){if(e.prepared.prepare.request.scope.authorization.kind!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization scope is missing`);if(e.issuedAuthorization.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization is invalid`)}function ni(e){let t=e.thresholdKeyMaterial.participants.find(t=>t.role===e.role)?.id;if(!t)throw Error(`threshold-ed25519 signing requires ${e.role} participant id`);return t}function ri(e){return[...h(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function ii(e){return te(e.chains||bt.network.chains)}function ai(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return`router-ab-normal-signing/${e}/${t.randomUUID()}`;if(t&&typeof t.getRandomValues==`function`){let n=new Uint8Array(16);return t.getRandomValues(n),`router-ab-normal-signing/${e}/${p(n)}`}throw Error(`secure randomness is unavailable for Router A/B normal-signing request id`)}function oi(e){if(!e.ok)throw Error(e.error.message);return e.value}function si(e){let t=Math.floor(Number(e.walletSessionExpiresAtMs)),n=Math.floor(Number(e.requestedTtlMs));if(!Number.isFinite(t)||t<=Date.now())throw Error(`[SigningEngine][near] Router A/B Ed25519 Wallet Session is expired`);if(!Number.isFinite(n)||n<=0)throw Error(`[SigningEngine][near] Router A/B Ed25519 request TTL is invalid`);return Math.min(t,Date.now()+n)}function ci(e){let t=e.walletSessionState.routerAbNormalSigning;if(!t)return null;let n=String(e.walletId||``).trim();if(!n)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing wallet id`);let r=Re(e.activeClient.metadata());return{request_id:ai(e.operationId),account_id:n,authorization:{kind:`reusable_wallet_session`,wallet_session_id:e.walletSessionState.walletSessionId},material_activation:{kind:`mpc_material_activation_ref`,activation_id:r.activationId,capability:r.capability,material_owner:r.materialOwner,key_binding:r.keyBinding,lifecycle_binding:r.lifecycleBinding,signing_worker:r.signingWorker},signing_worker_id:t.signingWorkerId}}function li(e){let t=e.materialFacts.routerAbNormalSigning;if(!t)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return{request_id:ai(e.operationId),account_id:String(e.walletId),authorization:{kind:`operation_step_up`},material_activation:{kind:`mpc_material_activation_ref`,activation_id:e.materialActivation.activationId,capability:e.materialActivation.capability,material_owner:e.materialActivation.materialOwner,key_binding:e.materialActivation.keyBinding,lifecycle_binding:e.materialActivation.lifecycleBinding,signing_worker:e.materialActivation.signingWorker},signing_worker_id:t.signingWorkerId}}function ui(e){return e.map(e=>{switch(e.action_type){case`CreateAccount`:return{action_type:U.CreateAccount};case`DeployContract`:return{action_type:U.DeployContract,code:[...e.code]};case`FunctionCall`:return{action_type:U.FunctionCall,method_name:e.method_name,args:e.args,gas:e.gas,deposit:e.deposit};case`Transfer`:return{action_type:U.Transfer,deposit:e.deposit};case`Stake`:return{action_type:U.Stake,stake:e.stake,public_key:e.public_key};case`AddKey`:return{action_type:U.AddKey,public_key:e.public_key,access_key:e.access_key};case`DeleteKey`:return{action_type:U.DeleteKey,public_key:e.public_key};case`DeleteAccount`:return{action_type:U.DeleteAccount,beneficiary_id:e.beneficiary_id};case`SignedDelegate`:{let t=ui(e.delegate_action.actions).map(Ce);return{action_type:U.SignedDelegate,delegate_action:{senderId:e.delegate_action.senderId,receiverId:e.delegate_action.receiverId,actions:t,nonce:e.delegate_action.nonce,maxBlockHeight:e.delegate_action.maxBlockHeight,publicKey:{keyType:e.delegate_action.publicKey.keyType,keyData:[...e.delegate_action.publicKey.keyData]}},signature:{keyType:e.signature.keyType,signatureData:[...e.signature.signatureData]}}}case`DeployGlobalContract`:return{action_type:U.DeployGlobalContract,code:[...e.code],deploy_mode:e.deploy_mode};case`UseGlobalContract`:return`account_id`in e?{action_type:U.UseGlobalContract,account_id:e.account_id}:{action_type:U.UseGlobalContract,code_hash:e.code_hash}}})}async function di(e){return{signedDelegate:await Ir({delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,workerCtx:e.ctx}),hash:ri(e.signingDigestB64u)}}function Z(e,t,n){if(String(e)!==String(t))throw Error(`Router A/B Ed25519 active Client ${n} mismatch`)}function fi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function pi(e,t){if(e.length!==32||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`Router A/B normal-signing ${t} must contain 32 bytes`);return Uint8Array.from(e)}function mi(e){let t=V(e);if(!t.startsWith(`ed25519:`))throw Error(`Router A/B Ed25519 signer public key must use ed25519`);let n=xe(t.slice(8));if(n.length!==32)throw Error(`Router A/B Ed25519 signer public key must decode to 32 bytes`);return n}function hi(e){let t=e.activeClient.metadata(),n=Re(t),r=e.materialFacts.signer,i=ni({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`client`}),a=ni({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`relayer`});if(e.thresholdKeyMaterial.participants.length!==2)throw Error(`Router A/B Ed25519 active Client requires exactly two participants`);Z(t.scope.account_id,e.prepare.request.scope.account_id,`scope account`),Z(t.scope.threshold_session_id,e.materialFacts.thresholdSessionId,`threshold session`),Z(t.scope.account_id,e.walletId,`scope wallet`),Z(n.activationId,e.prepare.request.scope.material_activation.activation_id,`material activation`),Z(n.capability,e.prepare.request.scope.material_activation.capability,`material capability`),Z(n.materialOwner,e.prepare.request.scope.material_activation.material_owner,`material owner`),Z(n.keyBinding,e.prepare.request.scope.material_activation.key_binding,`material key binding`),Z(n.lifecycleBinding,e.prepare.request.scope.material_activation.lifecycle_binding,`material lifecycle`),Z(n.signingWorker,e.prepare.request.scope.material_activation.signing_worker,`material SigningWorker`);let o=e.prepare.request.scope.authorization;if(o.kind!==e.authorization.kind)throw Error(`Router A/B Ed25519 authorization kind mismatch`);switch(e.authorization.kind){case`reusable_wallet_session`:if(o.kind!==`reusable_wallet_session`)throw Error(`Router A/B Ed25519 reusable authorization is missing`);Z(o.wallet_session_id,e.authorization.walletSessionId,`authorization session`);break;case`operation_step_up`:if(o.kind!==`operation_step_up`)throw Error(`Router A/B Ed25519 operation step-up authorization is missing`);break;default:e.authorization}Z(t.scope.signing_worker_id,e.prepare.request.scope.signing_worker_id,`scope SigningWorker`),Z(t.scope.signing_worker_id,e.signingWorkerId,`prepare SigningWorker`),Z(t.applicationBinding.wallet_id,e.walletId,`application wallet`),Z(t.applicationBinding.wallet_id,r.account.wallet.walletId,`lane wallet`),Z(t.applicationBinding.near_ed25519_signing_key_id,r.nearEd25519SigningKeyId,`signing key`),Z(t.applicationBinding.signing_root_id,e.materialFacts.signingRootId,`signing root`),Z(t.applicationBinding.key_creation_signer_slot,r.signerSlot,`signer slot`),Z(t.applicationBinding.key_creation_signer_slot,e.thresholdKeyMaterial.signerSlot,`key-material signer slot`),Z(t.participantIds[0],i,`Client participant`),Z(t.participantIds[1],a,`SigningWorker participant`);let s=mi(e.thresholdKeyMaterial.publicKey);if(!fi(t.registeredPublicKey,s))throw Error(`Router A/B Ed25519 active Client registered public key mismatch`);if(!fi(t.signingWorkerVerifyingShare,e.signingWorkerVerifyingShare))throw Error(`Router A/B Ed25519 active Client SigningWorker verifying share mismatch`)}async function gi(e){let t=e.prepare.request.intent.operation_id,n=performance.now(),r=`failed`;try{let n=await _i(e,t);return r=`succeeded`,n}finally{G(t,`signature_total`,n,r)}}async function _i(e,t){let n=h(e.signingDigestB64u);if(n.length!==32)throw Error(`Router A/B normal-signing ${e.signingPayloadLabel} must be 32 bytes`);let r=pi(e.prepare.admissionMaterial.admittedSigningDigest.bytes,`admitted digest`);if(!fi(n,r))throw Error(`Router A/B normal-signing admitted digest mismatch`);e.authorization===`reusable_wallet_session`&&Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial});let i=e.authorization===`reusable_wallet_session`?{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}:e.materialFacts,a=performance.now(),o=e.startedResponse?await e.startedResponse:await vt({relayServerUrl:i.relayerUrl,credential:e.credential,request:e.prepare.request});if(G(t,`prepare`,a),e.authorization===`reusable_wallet_session`){if(o.kind!==`reusable_wallet_session`)throw Error(`Ed25519 prepare returned the wrong authorization kind`);let t=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.walletSessionState,nowMs:Date.now()}),n=o.sessionStatus;if(!t||n.walletSessionId!==t.walletSessionOperationCredential.walletSessionId||n.quotaId!==t.walletSessionAuthorization.quotaId||n.quotaLifecycle!==`active`||n.remainingUses<=0||n.expiresAtMs<=Date.now()||!ee(n.authorization,t.walletSessionAuthorization))throw Error(`Wallet Session authority changed before Ed25519 client signing`);let r={relayerUrl:i.relayerUrl,operationCredential:t.walletSessionOperationCredential};await Ie.fromPrepare(r,n).read(r,{walletSessionId:n.walletSessionId,quotaId:n.quotaId})}else if(o.kind!==`operation_step_up`)throw Error(`Ed25519 step-up prepare returned a reusable Wallet Session`);let s=o.signing;Jr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:s});let c=h(s.server_verifying_share_b64u);if(c.length!==32)throw Error(`Router A/B normal-signing SigningWorker verifying share must be 32 bytes`);hi({activeClient:e.activeClient,authorization:e.authorization===`reusable_wallet_session`?{kind:`reusable_wallet_session`,walletSessionId:e.walletSessionState.signingWalletSession.walletSessionId}:{kind:`operation_step_up`},materialFacts:i,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,prepare:e.prepare,signingWorkerId:s.signing_worker.server_id,signingWorkerVerifyingShare:c});let l=performance.now(),u=await e.activeClient.createSigningShare({admittedDigest:r,signingWorkerCommitments:s.server_commitments,signingWorkerVerifyingShare:c});if(G(t,`client_share`,l),u.clientVerifyingShare.length!==32)throw Error(`Router A/B normal-signing Client verifying share must be 32 bytes`);let d=performance.now(),f=await St({relayServerUrl:i.relayerUrl,credential:e.credential,request:ht({scope:e.prepare.request.scope,expiresAtMs:e.prepare.request.expires_at_ms,prepareResponse:s,admissionMaterial:e.prepare.admissionMaterial,clientCommitments:u.clientCommitments,clientVerifyingShareB64u:p(u.clientVerifyingShare),clientSignatureShareB64u:u.clientSignatureShareB64u})});return G(t,`finalize`,d),Yr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:f}),{signatureB64u:Ct(f.signature,`Router A/B normal-signing signature`),signerPublicKey:e.thresholdKeyMaterial.publicKey}}async function vi(e){let t=ii(e.ctx);return e.intent.kind===`nep413_message_v1`?await _t({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,message:e.intent.message,recipient:e.intent.recipient,nonce:e.intent.nonce,callbackUrl:e.intent.callbackUrl,expectedSigningDigestB64u:e.signingDigestB64u}):await yt({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,publicKey:e.intent.delegate.publicKey,nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,actionFingerprint:await gt(e.intent.delegate.actions),canonicalDelegateBorshB64u:(await Fr({delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,actions:ui(e.intent.delegate.actions),nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,publicKey:e.intent.delegate.publicKey},workerCtx:e.ctx})).canonicalDelegateBorshB64u},expectedSigningDigestB64u:e.signingDigestB64u})}async function yi(e){let t=li({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),n=await vi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:Date.now()+$r,nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}),r=$e({tenantId:oi(E(e.materialFacts.runtimePolicyScope.orgId)),principalId:oi(C(String(e.walletId))),capabilityId:oi(D(e.materialActivation.capability)),operationId:oi(ie(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:e.intent.kind===`nep413_message_v1`?`near.sign_nep413_message`:`near.sign_delegate_action`},digests:{laneDigest:Qe(e.operationFingerprint),intentDigest:O(p(Uint8Array.from(n.admissionMaterial.intentDigest.bytes))),displayDigest:O(e.displayDigest)}});return{operation:{kind:`near_signature_only`,prepare:n,signingDigestB64u:e.signingDigestB64u,materialActivation:e.materialActivation},envelope:r}}function bi(e){if(e.auth.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);let t=e.preparation.hydration.authority;if(!t||String(t.walletId)!==String(e.walletId))throw Error(`[SigningEngine][near] Email OTP material authority changed`);return{kind:`email_otp`,authorityRef:t,providerSubjectId:e.auth.providerSubjectId,challengeId:e.challengeId,otpCode:e.otpCode}}function xi(e){switch(e.authorization.kind){case`passkey`:return{kind:`passkey`,authority:e.authorization.plannedPasskeyOperationStepUp.authority,credential:e.authorization.credential};case`email_otp`:return bi({preparation:e.preparation,auth:Si(e.auth),walletId:e.walletId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode});default:throw e.authorization,Error(`[SigningEngine][near] unsupported operation step-up authorization`)}}function Si(e){if(e.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);return e}function Ci(e){if(!e)throw Error(`[SigningEngine][near] operation step-up proof is missing`);return e}function wi(e){return e.authorization.kind===`operation_step_up`}async function Ti(e){if(e.issuedAuthorization)return e.issuedAuthorization;switch(e.proof.kind){case`passkey`:return await Sn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});case`email_otp`:return await Sn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});default:throw e.proof,Error(`[SigningEngine][near] unsupported operation step-up proof`)}}async function Ei(e){if(wi(e)){let t=Re(e.activeClient.metadata());if(sr({expected:e.authorization.prepared.materialActivation,actual:t}),e.authorization.prepared.signingDigestB64u!==e.signingDigestB64u)throw Error(`[SigningEngine][near] signature-only operation digest changed`);let n=e.authorization.prepared.prepare,r=await ei({ctx:e.ctx,walletId:e.walletId,relayerUrl:e.materialFacts.relayerUrl,proof:e.authorization.proof}),i=await Ti({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:e.materialFacts.relayerUrl,normalSigningRequest:n.request,displayDigest:e.displayDigest,proof:e.authorization.proof,credential:r});if(n.request.scope.authorization.kind!==`operation_step_up`||i.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);return{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:i,...await gi({thresholdSessionId:e.thresholdSessionId,materialFacts:e.materialFacts,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,credential:r,authorization:`operation_step_up`})}}let t=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===e.signingDigestB64u?e.startedPrepare:null;e.startedPrepare&&!t&&ki(e.startedPrepare);let n=t?.prepare??await Di(e);return n?{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`reusable_wallet_session`,...await gi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,startedResponse:t?.response,credential:Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential,authorization:e.authorization.kind})}:null}async function Di(e){let t=ci({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});return t?await vi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:si({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:$r}),nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}):null}async function Oi(e){let t=await Di(e);if(!t)return null;let n=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),r=performance.now(),i=vt({relayServerUrl:e.walletSessionState.relayerUrl,credential:n.credential,request:t.request});return i.catch(()=>{}),G(String(e.operationId),`prepare_sent`,r),{prepare:t,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,response:i}}function ki(e){e.response.catch(()=>{})}async function Ai(e){let t=await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=ii(e.ctx),r=ue(e.txSigningRequest,`txSigningRequest`),i=await xt({scope:li({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),expiresAtMs:Date.now()+$r,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n,transactions:[{receiverId:r.receiverId,actionFingerprint:await gt(r.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u}),a=$e({tenantId:oi(E(e.materialFacts.runtimePolicyScope.orgId)),principalId:oi(C(String(e.walletId))),capabilityId:oi(D(e.materialActivation.capability)),operationId:oi(ie(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:`near.sign_transaction`},digests:{laneDigest:Qe(e.operationFingerprint),intentDigest:O(p(Uint8Array.from(i.admissionMaterial.intentDigest.bytes))),displayDigest:O(e.displayDigest)}});return{operation:{kind:`near_transaction`,prepare:i,unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u,materialActivation:e.materialActivation},envelope:a}}function ji(e){return e.authorization.kind===`operation_step_up`}function Mi(e){return ji(e)?e.materialFacts:{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}}async function Ni(e,t){let n=ii(e.ctx),r=ue(e.txSigningRequest,`txSigningRequest`);return{nearNetworkId:n,parsedTransaction:r,operationFingerprint:z.signingOperationFingerprint(await ce({nearAccountId:e.nearAccountId,nearNetworkId:n,relayerKeyId:e.thresholdKeyMaterial.relayerKeyId,signerPublicKey:e.thresholdKeyMaterial.publicKey,transactions:[r],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u}))}}async function Pi(e,t,n){let r=ci({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});if(!r)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return await xt({scope:r,expiresAtMs:si({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:$r}),operationId:e.operationId,operationFingerprint:n.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n.nearNetworkId,transactions:[{receiverId:n.parsedTransaction.receiverId,actionFingerprint:await gt(n.parsedTransaction.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u})}async function Fi(e){let t=await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=await Pi(e,t,await Ni(e,t)),r=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),i=performance.now(),a=vt({relayServerUrl:e.walletSessionState.relayerUrl,credential:r.credential,request:n.request});return a.catch(()=>{}),G(String(e.operationId),`prepare_sent`,i),{prepare:n,displayDigest:e.displayDigest,signingDigestB64u:t.signingDigestB64u,response:a}}async function Ii(e){let t=Mi(e);if(!t.routerAbNormalSigning)throw Error(`[SigningEngine][near] Router A/B Ed25519 normal-signing state is missing`);if(!e.transactionContext)throw Error(`[SigningEngine][near] Router A/B Ed25519 transaction signing is missing transaction context from confirmation`);let n=ji(e),r=n?{unsignedTransactionBorshB64u:e.authorization.prepared.unsignedTransactionBorshB64u,signingDigestB64u:e.authorization.prepared.signingDigestB64u}:await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx});if(h(r.signingDigestB64u).length!==32)throw Error(`Router A/B normal-signing NEAR payload digest must be 32 bytes`);let i=await Ni(e,r),a=null,o,s,c;if(n){o=e.authorization.prepared.prepare,s=await ei({ctx:e.ctx,walletId:e.walletId,relayerUrl:t.relayerUrl,proof:e.authorization.proof});let n=await Ti({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:t.relayerUrl,normalSigningRequest:o.request,displayDigest:e.authorization.displayDigest,proof:e.authorization.proof,credential:s});if(o.request.scope.authorization.kind!==`operation_step_up`||n.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);c=n}else a=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===r.signingDigestB64u?e.startedPrepare:null,e.startedPrepare&&!a&&ki(e.startedPrepare),o=a?a.prepare:await Pi(e,r,i),s=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential;e.ctx.beforeSigning?.();let l=ji(e)?await gi({thresholdSessionId:e.thresholdSessionId,materialFacts:t,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`operation_step_up`}):await gi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`reusable_wallet_session`,startedResponse:a?.response}),u=await Rr({unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,signingDigestB64u:r.signingDigestB64u,signatureB64u:l.signatureB64u,expectedNearAccountId:e.nearAccountId,expectedSignerPublicKey:e.thresholdKeyMaterial.publicKey,workerCtx:e.ctx}),d=await zr({signedTransactionBorshB64u:u.signedTransactionBorshB64u,workerCtx:e.ctx}),f=u.transactionHash||d.transactionHash,p={type:le.SignTransactionsWithActionsSuccess,payload:{free:()=>void 0,success:!0,transactionHashes:[f],signedTransactions:[d.signedTransaction],logs:[`NEAR transaction signed through Router A/B normal signing`],error:void 0}};if(n){if(!c)throw Error(`[SigningEngine][near] operation step-up authorization was not issued`);return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:c,okResponse:p}}return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`reusable_wallet_session`,okResponse:p}}const Li=1e3,Ri=[120,180,250,350,500,700,1e3,1e3,1500,1500,2e3],zi=Symbol(`NearWalletSessionFundingAuthority`);function Bi(e=Li){return new Promise(t=>{setTimeout(t,e)})}function Vi(e){let t=String(e.walletSessionToken||``).trim();if(!t)throw Error(`[SigningEngine][near] authenticated Wallet Session token is required for funding`);return t}function Hi(e){return{kind:`near_ed25519_funding_session`,signer:e.signingLane.identity.signer,thresholdSessionId:e.thresholdSessionId,walletSessionToken:e.walletSessionAuth.walletSessionToken}}function Ui(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:return Gi(e)}}function Wi(e){switch(e){case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:throw Error(`[SigningEngine][near] unsupported operation step-up funding method`)}}function Gi(e){throw Error(`Unsupported NEAR funding authorization: ${String(e)}`)}function Ki(e){let t=String(e.fundingSession.signer.account.wallet.walletId),n=String(e.fundingSession.signer.account.nearAccountId),r=e.request.operation;if(String(e.request.subject.walletId)!==t||String(e.request.subject.nearAccountId)!==n||e.request.subject.nearPublicKeyStr!==e.nearPublicKeyStr)throw Error(`[SigningEngine][near] funding request subject does not match authenticated lane`);if(String(r.operationId)!==String(e.signingOperation.operationId)||String(r.operationFingerprint)!==String(e.signingOperation.operationFingerprint)||r.intent!==e.signingOperation.intent||r.accountId!==n)throw Error(`[SigningEngine][near] funding request operation does not match signing operation`);if(e.request.signatureUses!==e.signatureUses)throw Error(`[SigningEngine][near] funding request signature use count mismatch`);if(String(e.fundingSession.thresholdSessionId).trim().length===0)throw Error(`[SigningEngine][near] funding authority threshold session mismatch`)}function qi(e){return{kind:`near_wallet_session_funding_authority`,provenance:e.provenance,request:e.request,thresholdSessionId:e.fundingSession.thresholdSessionId,walletSessionToken:Vi(e.fundingSession),[zi]:!0}}async function Ji(e){let t=e.authority.request,n=ct({chains:e.ctx.chains,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr}),r;for(let i=1;i<=12;i+=1)try{let r=await e.ctx.nonceCoordinator.reserveNearContext({lane:n,operation:t.operation,count:t.signatureUses,nearClient:e.ctx.nearClient});return{transactionContext:r.context,nonceLeases:r.leases.map(Fe),reservedLeases:r.leases}}catch(e){r=e,i<12&&await Bi(Ri[i-1]??Li)}throw r instanceof Error?r:Error(`Funded NEAR account access key did not become available`)}async function Yi(e){let t=e.authority.request,n=await ze({relayerUrl:e.ctx.relayerUrl,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr,walletSessionToken:e.authority.walletSessionToken});if(!n.ok)throw Error(n.message||n.code||`Failed to fund implicit NEAR account`);return await Ji(e)}async function Xi(e){switch(e.confirmation.readiness.kind){case`context_ready`:return e.confirmation.readiness;case`funding_required`:{Ki({request:e.confirmation.readiness.request,fundingSession:Hi(e.walletSessionState),nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=qi({request:e.confirmation.readiness.request,fundingSession:Hi(e.walletSessionState),provenance:Ui(e.authorization)}),n=await Yi({ctx:e.ctx,authority:t});return{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases}}default:return Zi(e.confirmation.readiness)}}function Zi(e){throw Error(`Unsupported confirmed NEAR transaction readiness: ${String(e)}`)}async function Qi(e){Ki({request:e.request,fundingSession:e.fundingSession,nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=qi({request:e.request,fundingSession:e.fundingSession,provenance:Wi(e.method)}),n=await Yi({ctx:e.ctx,authority:t});return{readiness:{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases},reservedNonceLeases:n.reservedLeases}}function $i(e){switch(e.kind){case`passkey_live`:case`email_otp_live`:return e.material.facts;case`passkey_sealed`:case`email_otp_sealed`:return e.facts;default:throw Error(`[SigningEngine][near] unsupported operation material`)}}async function ea(e,t){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return await t.resolve(e);case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] material requires public-anchor reauthorization`);case`blocked`:throw Error(`[SigningEngine][near] material hydration is blocked: ${e.hydration.reason}`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Ed25519 Yao hydration plan`)}}async function ta(e){if(e.method===`passkey`&&e.preparation.hydration.kind===`rehydrate_material_activation`){let t=await e.executor.preparePasskeyOperationStepUp(e.preparation);return{kind:`passkey_sealed`,materialActivation:t.materialActivation,facts:t.facts,rehydrate:t.rehydrate}}if(e.method===`email_otp`){let t=await e.executor.prepareEmailOtpOperationStepUp(e.preparation);switch(t.kind){case`live`:return{kind:`email_otp_live`,materialActivation:t.materialActivation,material:t.material};case`sealed`:return{kind:`email_otp_sealed`,materialActivation:t.materialActivation,facts:t.facts,authorizeAndRehydrate:t.authorizeAndRehydrate};default:throw Error(`[SigningEngine][near] unsupported Email OTP operation material`)}}let t=await ea(e.preparation,e.executor);return{kind:`passkey_live`,materialActivation:Re(t.activeClient.metadata()),material:t}}async function na(e){sr({expected:e.expectedActivation,actual:e.material.materialActivation});let t,n=null;if(e.kind===`email_otp_live`||e.kind===`email_otp_sealed`)if(e.kind===`email_otp_live`)t=e.material.material;else{let r=await e.material.authorizeAndRehydrate({normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof});t=r.material,n=r.issuedAuthorization}else t=e.material.kind===`passkey_live`?e.material.material:await e.material.rehydrate(e.credential);try{return sr({expected:e.expectedActivation,actual:Re(t.activeClient.metadata())}),{material:t,issuedAuthorization:n}}catch(n){throw(e.material.kind===`passkey_sealed`||e.material.kind===`email_otp_sealed`)&&t.activeClient.dispose(),n}}async function ra(e){let t=await ea(e.preparation,e.executor);return{thresholdSessionId:t.facts.thresholdSessionId,material:t,walletSessionState:await e.executor.resolveWalletSessionState()}}function ia(e){if(!e)throw Error(`[SigningEngine][near] confirmed operation step-up is missing preparation`);return e}function aa(e){if(!e)throw Error(`[SigningEngine][near] prepared operation step-up is missing`);if(e.kind!==`near_transaction`)throw Error(`[SigningEngine][near] prepared operation step-up is not a transaction`);return e}function oa(e){if(!e)throw Error(`[SigningEngine][near] transaction operation material is unavailable`);return e}function sa(e){e.owned&&e.resolved?.material.activeClient.dispose()}function ca(e,t){throw sa(e),t}async function la(e){return{material:await ea(e.preparation,e.executor),walletSessionState:await e.executor.resolveWalletSessionState()}}function ua(e){if(!e)throw Error(`[SigningEngine][near] warm signing material was not prepared`);return e}async function da(e){let t=await e.warmMaterial,n=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.walletSessionState,nowMs:Date.now()});if(!n)return null;let r=await ot([{receiverId:e.confirmationTransaction.receiverId,actions:e.confirmationTransaction.actions.map(it)}]);return await Fi({ctx:e.ctx,thresholdSessionId:t.material.facts.thresholdSessionId,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:t.material.activeClient,walletSessionState:n,operationId:e.operationId,displayDigest:r,txSigningRequest:e.txSigningRequest,transactionContext:e.readiness.transactionContext})}function fa(){return null}async function pa(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey transaction material changed factor`);return await na({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP transaction material changed factor`);if(e.proof.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP transaction proof is missing`);return e.material.kind===`email_otp_live`?await na({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await na({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.proof})}function Q(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}async function ma(e){let t=performance.now(),n=`failed`;try{if(!e.state)throw Error(`[SigningEngine][near] reusable Wallet Session state is unavailable`);let t=await e.coordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.state,nowMs:Date.now()});if(!t)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return n=`succeeded`,t}finally{G(e.operationId,`wallet_session_authorization`,t,n)}}async function ha(e){let t=await ta({method:e.method,preparation:e.preparation,executor:e.executor}),n=$i(t);if(String(n.thresholdSessionId)!==e.expectedThresholdSessionId)throw Error(`[SigningEngine][near] prepared operation material changed threshold session`);return rr({requestId:e.requestId,build:async r=>{if(r.kind!==`near_transaction`)throw Error(`[SigningEngine][near] transaction step-up preparation kind changed`);if(r.operationId!==String(e.operation.operationId))throw Error(`[SigningEngine][near] operation step-up operation identity changed`);return await Ai({...e.operation,thresholdSessionId:n.thresholdSessionId,materialFacts:n,materialActivation:t.materialActivation,transactionContext:r.transactionContext,displayDigest:r.displayDigest})}}),ur({requestId:e.requestId,fund:async t=>await Qi({...e.funding,request:t,fundingSession:await e.executor.resolveFundingSession(),method:e.method})}),t}function ga(e){ir(e),dr(e)}function _a(e){if(!e.readiness){ga(e.requestId);return}e.readiness.then(ga.bind(void 0,e.requestId),ga.bind(void 0,e.requestId))}function va(e){return e.selection.kind===`authorization_required`}async function ya(e){return va(e)?await ba(e):await xa(e)}async function ba(e){let{ctx:t,commandSubject:n,nearAccount:r,transaction:i,rpcCall:a,onEvent:o,confirmationConfigOverride:s,title:c,body:l,signerSlot:u,signingOperationState:d,signingSessionCoordinator:f,selection:p,yaoSigningPreparation:m,yaoMaterialExecutor:h,passkeyEd25519OperationStepUp:g,emailOtpEd25519StepUp:_}=e,v=d.operationId,y=p.candidate,b=H(r.accountId),ee=[];if(!t.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);if(!f)throw Error(`[SigningEngine][near] production signing session coordinator is required`);let{thresholdKeyMaterial:re}=await pr({materialExecutor:h,nearAccount:r,signerSlot:y.signerSlot,requestedSignerSlot:u,operationLabel:`signing`,warnings:ee}),x=Ta({nearAccountId:b,relayerUrl:t.relayerUrl,thresholdKeyMaterial:re}),ie={nearRpcUrl:a.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},{txSigningRequest:S,confirmationTransaction:C}=mr({nearAccountId:String(b),transaction:i}),w=ue(S,`txSigningRequest`),T=z.signingOperationFingerprint(await se({nearAccountId:b,nearNetworkId:te(t.chains||bt.network.chains),relayerKeyId:x.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:x.threshold.thresholdKeyMaterial.publicKey,transactions:[w]}));f.bindCallerProvidedOperationIdToFingerprint({operationId:v,operationFingerprint:T});let E=Qe(T),D={kind:`deferred_ed25519_material_identity`,signer:Ye({walletId:y.walletId,nearAccountId:y.nearAccountId,nearEd25519SigningKeyId:y.nearEd25519SigningKeyId,signerSlot:y.signerSlot}),materialActivation:y.materialActivation,thresholdSessionId:z.thresholdEd25519Session(y.thresholdSessionId)},O={kind:R.OperationStepUp,lane:{identity:D,auth:y.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:D.materialActivation,thresholdSessionId:D.thresholdSessionId}},k=vr(y.auth),A={operationId:v,operationFingerprint:T,intent:_e.TransactionSign},j=await _r({signingAuthPlan:k,signingLaneAuth:y.auth,requiredSignatureUses:Ar(i),operationFingerprintDigest:E,...g?{passkeyEd25519OperationStepUp:g}:{},..._?{emailOtpEd25519StepUp:_}:{}});if(j.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred Ed25519 transaction cannot use warm session`);let ae=Ar(i),oe=ha({requestId:String(v),expectedThresholdSessionId:String(D.thresholdSessionId),method:j.kind,preparation:m,executor:h,operation:{ctx:t,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:b,operationId:v,operationFingerprint:T,txSigningRequest:S},funding:{ctx:t,nearPublicKeyStr:x.signingNearPublicKeyStr,signingOperation:A,signatureUses:ae}}),M;try{M=await Ft({signingSessionPlan:O,signingOperation:A,signingOperationState:d,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:String(v),chain:`near`,kind:`transaction`,...Pt({signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan}),walletId:y.walletId,txSigningRequests:[C],rpcCall:ie,nearPublicKeyStr:x.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:y.walletId,nearAccountId:b,nearPublicKeyStr:x.signingNearPublicKeyStr},operation:{...A,accountId:String(b)},signatureUses:ae},confirmationConfigOverride:It({signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan,override:s}),title:c,body:l,confirmationReadiness:{promise:oe},onProgress:Tr.bind(void 0,{onEvent:o,nearAccountId:b,signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan})}})}finally{_a({requestId:String(v),readiness:oe})}let N=await oe,P=$i(N),F=Dr({prepared:j,confirmation:M});if(F.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred transaction requires operation step-up`);let I=xi({authorization:F,preparation:m,auth:y.auth,walletId:n.walletSession.walletId}),ce=aa(or({requestId:String(v),ref:ia(M.operationStepUpPreparation)})),le=await pa({material:N,prepared:ce,displayDigest:M.intentDigest,authorization:F,proof:Ci(I)});Q(o,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Rt(j.confirmationAuthPayload.signingAuthPlan)});try{if(await t.nonceCoordinator.recoverDurableLeases({walletId:String(y.walletId)}),M.readiness.kind!==`context_ready`)throw Error(`[SigningEngine][near] implicit-account funding requires transaction context`);let e=await Ii({ctx:t,thresholdSessionId:P.thresholdSessionId,activeClient:le.material.activeClient,materialFacts:P,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:b,operationId:v,operationFingerprint:T,displayDigest:M.intentDigest,txSigningRequest:S,transactionContext:M.readiness.transactionContext,authorization:{kind:`operation_step_up`,prepared:ce,displayDigest:M.intentDigest,proof:Ci(I),issuedAuthorization:le.issuedAuthorization}});if(!e||e.authorization!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up transaction signing is unavailable`);ti({prepared:ce,issuedAuthorization:e.issuedAuthorization});let r=wa({okResponse:e.okResponse,nearAccountId:b,warnings:ee,nonceLeases:M.readiness.nonceLeases});return await Ca(t,M.readiness.nonceLeases),r}finally{sa({resolved:le,owned:N.kind===`passkey_sealed`||N.kind===`email_otp_sealed`})}}async function xa({ctx:e,commandSubject:t,nearAccount:n,transaction:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:s,body:c,signerSlot:l,signingOperationState:u,signingSessionCoordinator:d,transactionOperation:f,ed25519SigningBoundary:p,passkeyEd25519OperationStepUp:m,emailOtpEd25519StepUp:h,yaoSigningPreparation:g,yaoMaterialExecutor:_}){let v=performance.now(),y=u.operationId,b=H(n.accountId),ee=e.relayerUrl,re=[],x=e.nonceCoordinator.recoverDurableLeases({walletId:String(t.walletSession.walletId)});x.catch(()=>{}),Q(a,b,{phase:W.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:ie}=await pr({materialExecutor:_,nearAccount:n,signerSlot:p.signingLane.identity.signer.signerSlot,requestedSignerSlot:l,operationLabel:`signing`,warnings:re}),S=Ta({nearAccountId:b,relayerUrl:ee,thresholdKeyMaterial:ie}),C={nearRpcUrl:i.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},{txSigningRequest:w,confirmationTransaction:T}=mr({nearAccountId:String(C.nearAccountId),transaction:r}),E=ue(w,`txSigningRequest`),D=z.signingOperationFingerprint(await se({nearAccountId:b,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:S.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:S.threshold.thresholdKeyMaterial.publicKey,transactions:[E]})),O=Qe(D);if(!e.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);let k=e.touchConfirm;if(!d)throw Error(`[SigningEngine][near] production signing session coordinator is required`);d.bindCallerProvidedOperationIdToFingerprint({operationId:y,operationFingerprint:D});let A=Ar(r),j={operationId:y,operationFingerprint:D,intent:_e.TransactionSign},ae=async e=>await At({signingSessionPlan:p.signingSessionPlan,signingOperation:j,commandKind:e.commandKind,execute:e.execute}),oe=p.thresholdSessionId,M=String(oe||``).trim(),N=p.signingAuthPlan,P=p.signingLane;if(!f)throw Error(`[SigningEngine][near] threshold transaction signing requires prepared transaction operation`);if(Et(N)&&N.thresholdSessionId!==oe)throw Error(`[SigningEngine][near] warm-session auth plan must match prepared session identity`);let F={thresholdSessionId:Et(N)?N.thresholdSessionId:oe,lane:P,signingAuthPlan:N,confirmationAuthPayload:{signingAuthPlan:N},warmSessionReady:Et(N)},I=P,ce=new Set,le=e=>{ce.has(e)||(ce.add(e),tt(`near`,rt({event:`auth_side_effect_started`,lane:I,sideEffect:e,phase:`confirmed`})))},de=e=>{e.phase===`auth.passkey.prompt.started`&&le(`passkey_reauth`),Tr({onEvent:a,nearAccountId:b,signingAuthPlan:F.confirmationAuthPayload.signingAuthPlan},e)},fe=await _r({signingAuthPlan:N,signingLaneAuth:P.auth,requiredSignatureUses:A,operationFingerprintDigest:O,...m?{passkeyEd25519OperationStepUp:m}:{},...h?{emailOtpEd25519StepUp:h}:{}}),pe=fe.kind===`warm_session`?la({preparation:g,executor:_}):null;pe?.catch(()=>{});let me=fe.confirmationAuthPayload;Et(me.signingAuthPlan)&&Q(a,b,{phase:W.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:me.signingAuthPlan.thresholdSessionId,expiresAtMs:me.signingAuthPlan.expiresAtMs,remainingUses:me.signingAuthPlan.remainingUses}});let he=!Vt(u.current);he&&Q(a,b,{phase:W.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let ge=fe.kind===`warm_session`?null:ha({requestId:M,expectedThresholdSessionId:M,method:fe.kind,preparation:g,executor:_,operation:{ctx:e,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,txSigningRequest:w},funding:{ctx:e,nearPublicKeyStr:S.signingNearPublicKeyStr,signingOperation:j,signatureUses:A}});G(String(y),`pre_confirmation`,v);let L=null,R=n=>{L||!pe||(L=da({ctx:e,warmMaterial:pe,sessionCoordinator:d,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,txSigningRequest:w,confirmationTransaction:T,readiness:n}).catch(fa))},ve=performance.now(),B;try{B=await Ft({signingSessionPlan:p.signingSessionPlan,signingOperation:j,signingOperationState:u,runtime:k,request:{ctx:{touchConfirm:k},sessionId:M,chain:`near`,kind:`transaction`,...Pt({signingAuthPlan:me.signingAuthPlan}),...pe?{onNearTransactionContextReady:R}:{},walletId:String(P.identity.signer.account.wallet.walletId),txSigningRequests:[T],rpcCall:C,nearPublicKeyStr:S.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:P.identity.signer.account.wallet.walletId,nearAccountId:b,nearPublicKeyStr:S.signingNearPublicKeyStr},operation:{...j,accountId:String(b)},signatureUses:A},confirmationConfigOverride:It({signingAuthPlan:me.signingAuthPlan,override:o}),title:s,body:c,...ge?{confirmationReadiness:{promise:ge}}:{},onProgress:de}})}finally{_a({requestId:M,readiness:ge})}let ye=performance.now();G(String(y),`confirmation`,ve);let be=ge?await ge:null;he&&Q(a,b,{phase:W.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let V=Dr({prepared:fe,confirmation:B}),xe=V.kind===`warm_session`?null:xi({authorization:V,preparation:g,auth:f.lane.auth,walletId:t.walletSession.walletId}),Se=V.kind===`warm_session`?null:or({requestId:M,ref:ia(B.operationStepUpPreparation)}),Ce=V.kind===`warm_session`?null:await pa({material:oa(be),prepared:aa(Se),displayDigest:B.intentDigest,authorization:V,proof:Ci(xe)}),we=be?.kind===`passkey_sealed`||be?.kind===`email_otp_sealed`,U=performance.now();try{await x,G(String(j.operationId),`durable_lease_recovery_wait`,U)}catch(e){throw G(String(j.operationId),`durable_lease_recovery_wait`,U,`failed`),sa({resolved:Ce,owned:we}),e}let Te=!1,{canonicalThresholdSessionId:Ee,activeClient:De,walletSessionState:Oe,operationMaterialFacts:ke,issuedAuthorization:Ae,transactionContext:je,nonceLeaseRefs:Me}=await ae({commandKind:Nt.PreparePayload,execute:async()=>{Q(a,b,{phase:W.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let t=performance.now(),n=V.kind===`warm_session`?{kind:`warm_session`,resolved:await ua(pe)}:{kind:`operation_step_up`,resolved:Ce};G(String(j.operationId),`material_resolution_wait`,t);let r=(n.kind,n.resolved.material.facts.thresholdSessionId),i=(n.kind,n.resolved.material.activeClient),o=n.kind===`warm_session`?n.resolved.walletSessionState:null,s=performance.now(),c=n.kind===`warm_session`?await Xi({confirmation:B,ctx:e,nearPublicKeyStr:S.signingNearPublicKeyStr,walletSessionState:o,authorization:V,signingOperation:j,signatureUses:A}):B.readiness.kind===`context_ready`?B.readiness:(()=>{throw Error(`[SigningEngine][near] operation step-up confirmation did not resolve a transaction context`)})();return G(String(j.operationId),`transaction_context`,s),Q(a,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:F.warmSessionReady?`warm_session`:F.signingAuthPlan.method}),Q(a,b,{phase:W.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:r,clientBaseSource:`yao_active_client`}}),{canonicalThresholdSessionId:r,activeClient:i,walletSessionState:o,operationMaterialFacts:n.kind===`operation_step_up`?n.resolved.material.facts:null,issuedAuthorization:n.kind===`operation_step_up`?n.resolved.issuedAuthorization:null,transactionContext:c.transactionContext,nonceLeaseRefs:c.nonceLeases}}}).catch(ca.bind(void 0,{resolved:Ce,owned:we})),Ne=async t=>{Te||!Me.length||await Sa(e,Me,`signing_failed`).catch(e=>{console.warn(`[SigningEngine][near][transaction] failed to release nonce leases`,{originalError:t instanceof Error?t.message:String(t||``),releaseError:e instanceof Error?e.message:String(e||``)})})},Pe=async n=>{Q(a,b,{phase:W.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let r=V.kind===`warm_session`?await Ii({ctx:e,thresholdSessionId:Ee,activeClient:n,sessionCoordinator:d,walletSessionState:await ma({state:Oe,coordinator:d,operationId:String(j.operationId)}),thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,displayDigest:B.intentDigest,txSigningRequest:w,transactionContext:je,authorization:{kind:`reusable_wallet_session`},startedPrepare:L?await L:null}):await Ii({ctx:e,thresholdSessionId:Ee,activeClient:n,materialFacts:ke,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,displayDigest:B.intentDigest,txSigningRequest:w,transactionContext:je,authorization:{kind:`operation_step_up`,prepared:aa(Se),displayDigest:B.intentDigest,proof:V.kind===`passkey`?{kind:`passkey`,authority:V.plannedPasskeyOperationStepUp.authority,credential:V.credential}:{...bi({preparation:g,auth:f.lane.auth,walletId:t.walletSession.walletId,challengeId:V.challengeId,otpCode:V.otpCode})},issuedAuthorization:Ae}});if(r)return r.okResponse;throw Error(`[SigningEngine][near] Router A/B Ed25519 signing is unavailable`)};return await ae({commandKind:Nt.Sign,execute:async()=>{try{let t=await Pe(De);Te=!0;let n=performance.now();await Ca(e,Me),G(String(j.operationId),`nonce_lease_commit`,n);let r=performance.now(),i=wa({okResponse:t,nearAccountId:b,warnings:re,nonceLeases:Me});return G(String(j.operationId),`transaction_assembly`,r),G(String(j.operationId),`confirmed_to_signed`,ye),Q(a,b,{phase:W.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),Q(a,b,{phase:W.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign`}}),i}catch(e){let t=e instanceof Error?e:Error(String(e));throw await Ne(t),sa({resolved:Ce,owned:we}),t}}})}async function Sa(e,t,n){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.release({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint,reason:n})))}async function Ca(e,t){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.markSigned({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint})))}function wa(e){let t=e.okResponse.payload.signedTransactions||[];if(t.length!==1)throw Error(`Expected one signed transaction but received ${t.length}`);let n=t[0];if(!n||!n.transaction||!n.signature)throw Error(`Incomplete signed transaction data received`);let r=e.nonceLeases?.[0],i=e.okResponse.payload.transactionHashes?.[0];if(!i)throw Error(`Signed transaction is missing its hash`);let a=n.serverDispatch;return{signedTransaction:new Ln({transaction:n.transaction,signature:n.signature,borsh_bytes:Array.from(n.borshBytes||[]),transactionHash:i,...r?{nonceLease:r}:{},...a?{serverDispatch:a}:{}}),nearAccountId:H(e.nearAccountId),logs:[...e.okResponse.payload.logs||[],...e.warnings],...r?{nonceLease:r}:{}}}function Ta(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);let r=String(e.relayerUrl||``).trim();if(!r)throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=f(t.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:n,threshold:{relayerUrl:r,thresholdKeyMaterial:t}}}function Ea(e){let t=e.selectedLane.identity.signer,n=Ee(e.commandSubject.walletSession.walletId),r=String(e.commandSubject.nearAccount.accountId);if(t.account.wallet.walletId!==n||String(t.account.nearAccountId)!==r)throw Error(`[SigningEngine][near] selected Ed25519 lane does not match command subject`);return{walletId:n,nearAccountId:r}}function Da(e){let t=e.selectedLane.identity.signer,n={walletId:t.account.wallet.walletId,nearAccountId:t.account.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,walletSessionId:e.selectedLane.walletSessionId,quotaId:e.selectedLane.quotaId,thresholdSessionId:e.selectedLane.thresholdSessionId};switch(e.selectedLane.auth.kind){case`voiceid`:return Xe({...n,auth:e.selectedLane.auth,storageSource:`login`});case`passkey`:return Xe({...n,auth:e.selectedLane.auth,storageSource:`login`});case`email_otp`:{let t=e.preparation.authorization.kind===`authorized`;return Xe({...n,auth:e.selectedLane.auth,retention:t?`session`:`single_use`,sessionOrigin:t?`login`:`per_operation`})}default:throw e.selectedLane.auth,Error(`[SigningEngine][near] unsupported selected Ed25519 auth binding`)}}function Oa(e){let t=z.thresholdEd25519Session(e.selectedLane.thresholdSessionId);switch(e.preparation.authorization.kind){case`authorized`:{let n=e.preparation.authorization.authorization.status,r=n.remainingUses,i=n.expiresAtMs,a=i<=Date.now()?`expired`:r<e.requiredSignatureUses?`exhausted`:`ready`;return{readiness:a===`expired`?{status:`expired`,curve:`ed25519`,thresholdSessionId:t,expiresAtMs:i}:{status:a,curve:`ed25519`,thresholdSessionId:t,remainingUses:r,expiresAtMs:i},expiresAtMs:i,remainingUses:r,forceFreshAuth:a!==`ready`}}case`authorization_required`:return{readiness:{status:`missing_session`,curve:`ed25519`,thresholdSessionId:t},expiresAtMs:0,remainingUses:0,forceFreshAuth:!0};default:throw e.preparation.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function ka(e){Ea(e);let t=Math.max(1,Math.floor(Number(e.requiredSignatureUses)||1)),n=Da(e),r=Oa({selectedLane:e.selectedLane,preparation:e.preparation,requiredSignatureUses:t});return nt(`near`,n,{reason:`near_threshold_auth_plan`}),{thresholdSessionId:z.thresholdEd25519Session(e.selectedLane.thresholdSessionId),lane:n,coordinatorInput:{lane:n,readiness:r.readiness,expiresAtMs:r.expiresAtMs,remainingUses:r.remainingUses,forceFreshAuth:e.forceFreshAuth||r.forceFreshAuth}}}function Aa(e){let{lane:t}=e.context,n=e.resolvedSigningSession,r=n.signingSessionPlan;if(r.kind===R.NotReady)throw Error(`[SigningEngine][near] signing session is not ready: ${r.reason}`);return{signingAuthPlan:Bt({plan:r,accountId:String(t.identity.signer.account.nearAccountId),intent:_e.TransactionSign,curve:`ed25519`,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses})}}function ja(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up preparation is missing`);return t}function Ma(e,t){if(!t||t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e} operation step-up preparation kind changed`);return t}function Na(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up material is missing`);return t}function Pa(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation signing digest is missing`);return t}function Fa(e){if(!e)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e}async function Ia(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey ${e.label} material changed factor`);return await na({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP ${e.label} material changed factor`);if(!e.emailOtpProof)throw Error(`[SigningEngine][near] Email OTP ${e.label} proof is missing`);return e.material.kind===`email_otp_live`?await na({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await na({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.emailOtpProof})}function La(e){if(e.selection.kind===`authorized`){let t=ka({requiredSignatureUses:1,commandSubject:e.commandSubject,forceFreshAuth:e.forceFreshAuth,selectedLane:e.selection.selectedLane,preparation:e.preparation}),n={signingSessionPlan:Cn({lane:t.coordinatorInput.lane,readiness:t.coordinatorInput.readiness,forceFreshAuth:t.coordinatorInput.forceFreshAuth}),readiness:t.coordinatorInput.readiness,expiresAtMs:t.coordinatorInput.expiresAtMs||0,remainingUses:t.coordinatorInput.remainingUses||0};return{signingAuthPlan:Aa({context:t,resolvedSigningSession:n}).signingAuthPlan,signingSessionPlan:n.signingSessionPlan}}let t=e.selection.candidate,n=vr(t.auth),r={kind:`deferred_ed25519_material_identity`,signer:Ye({walletId:t.walletId,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot}),materialActivation:t.materialActivation,thresholdSessionId:z.thresholdEd25519Session(t.thresholdSessionId)};return{signingAuthPlan:n,signingSessionPlan:{kind:R.OperationStepUp,lane:{identity:r,auth:t.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:r.materialActivation,thresholdSessionId:r.thresholdSessionId}}}}async function Ra(e,t){let n=await _r({signingAuthPlan:t.signingAuthPlan,signingLaneAuth:e.auth,requiredSignatureUses:1,operationFingerprintDigest:Qe(e.signingOperation.operationFingerprint),passkeyEd25519OperationStepUp:t.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:t.emailOtpEd25519StepUp});if(n.kind===`warm_session`)return{preparedStepUp:n,operationStepUp:null};let r=await ta({method:n.kind,preparation:e.preparation,executor:e.executor}),i=$i(r),a=await e.computeSigningDigestB64u();return rr({requestId:String(e.signingOperation.operationId),build:async t=>{if(t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e.label} operation step-up preparation kind changed`);return await yi({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,materialFacts:i,walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:r.materialActivation,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:a,intent:e.intent})}}),{preparedStepUp:n,operationStepUp:{material:r,signingDigestB64u:a}}}async function za(e,t){let n=String(e.signingOperation.operationId);try{return await Mt({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:n,chain:`near`,...t.request,...Pt({signingAuthPlan:t.signingAuthPlan}),walletId:String(e.walletId),nearAccountId:e.nearAccountId,nearPublicKeyStr:t.nearPublicKeyStr,title:t.title,body:t.body,confirmationConfigOverride:It({signingAuthPlan:t.signingAuthPlan,override:t.confirmationConfigOverride}),onProgress:Tr.bind(void 0,{onEvent:t.onEvent,nearAccountId:e.nearAccountId,signingAuthPlan:t.signingAuthPlan})}})}finally{ir(n)}}function Ba(e,t,n){let r=Dr({prepared:t.preparedStepUp,confirmation:n});if(r.kind===`warm_session`)return{kind:`warm_session`,displayDigest:n.intentDigest,stepUpAuthorization:r};let i=xi({authorization:r,preparation:e.preparation,auth:e.auth,walletId:e.walletId}),a=Ma(e.label,or({requestId:String(e.signingOperation.operationId),ref:ja(e.label,n.operationStepUpPreparation)}));return{kind:`operation_step_up`,displayDigest:n.intentDigest,stepUpAuthorization:r,proof:i,prepared:a,...Na(e.label,t.operationStepUp)}}async function Va(e,t,n,r){if(t.preparedStepUp.kind!==`warm_session`)return null;let i=await ra({preparation:e.preparation,executor:e.executor}),a=Fa(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:i.walletSessionState,nowMs:Date.now()})),o=await Oi({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,activeClient:i.material.activeClient,walletSessionState:a,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:r,signingDigestB64u:await e.computeSigningDigestB64u(),intent:e.intent});return o?{resolved:i,started:o}:null}async function Ha(e,t,n=null){if(t.kind===`warm_session`){let r=n?.resolved??await ra({preparation:e.preparation,executor:e.executor});return{kind:`warm_session`,thresholdSessionId:r.thresholdSessionId,displayDigest:t.displayDigest,resolved:r,startedPrepare:n?.started}}return n&&ki(n.started),{kind:`operation_step_up`,thresholdSessionId:$i(t.material).thresholdSessionId,displayDigest:t.displayDigest,resolved:await Ia({label:e.label,material:t.material,prepared:t.prepared,displayDigest:t.displayDigest,authorization:t.stepUpAuthorization,emailOtpProof:t.proof.kind===`email_otp`?t.proof:null}),proof:t.proof,prepared:t.prepared,signingDigestB64u:t.signingDigestB64u}}async function Ua(e,t,n){let r=t.kind===`warm_session`?await e.computeSigningDigestB64u():Pa(e.label,t.signingDigestB64u),i=t.kind===`warm_session`?await Ei({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,sessionCoordinator:n,walletSessionState:Fa(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.resolved.walletSessionState,nowMs:Date.now()})),walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`reusable_wallet_session`},startedPrepare:t.startedPrepare}):await Ei({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,materialFacts:t.resolved.material.facts,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`operation_step_up`,prepared:t.prepared,proof:t.proof,issuedAuthorization:t.resolved.issuedAuthorization}});if(!i)throw Error(`[SigningEngine][near] Router A/B Ed25519 ${e.label} signing is unavailable`);return t.kind===`operation_step_up`&&i.authorization===`operation_step_up`&&ti({prepared:t.prepared,issuedAuthorization:i.issuedAuthorization}),{signingDigestB64u:r,signatureB64u:i.signatureB64u,signerPublicKey:i.signerPublicKey}}async function Wa(e,t){return await At({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,commandKind:Nt.Sign,execute:async()=>{try{return await t()}catch(e){throw e instanceof Error?e:Error(String(e))}}})}function $(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Ga(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey`;case`email_otp`:return`email_otp`;default:return Ka(e)}}function Ka(e){throw Error(`[SigningEngine][near] unsupported prepared step-up: ${String(e)}`)}async function qa({ctx:e,commandSubject:t,nearAccount:n,delegate:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:s,body:c,operationId:l,signerSlot:u,signingSessionCoordinator:d,forceFreshAuth:f,passkeyEd25519OperationStepUp:p,emailOtpEd25519StepUp:m,yaoSigningPreparation:h,yaoMaterialExecutor:g,selection:_}){let v=_.kind===`authorized`?_.selectedLane.auth:_.candidate.auth,y=_.kind===`authorized`?_.selectedLane.identity.signer.signerSlot:_.candidate.signerSlot,b=H(n.accountId),ee=e.relayerUrl,re={nearRpcUrl:i.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},x=[],ie=e.touchConfirm;if(!ie)throw Error(`UiConfirm bridge not available for delegate signing`);let{signingAuthPlan:S,signingSessionPlan:C}=La({selection:_,commandSubject:t,forceFreshAuth:f,preparation:h});$(a,b,{phase:W.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:w}=await pr({materialExecutor:g,nearAccount:n,signerSlot:y,requestedSignerSlot:u,operationLabel:`delegate signing`,warnings:x}),T=Ja({nearAccountId:b,relayerUrl:ee,thresholdKeyMaterial:w,providedDelegatePublicKey:r.publicKey,warnings:x}),E=hr({nearAccountId:b,delegate:r,signingPublicKey:T.delegatePublicKeyStr}),D={...E.workerDelegate,actions:E.workerDelegate.actions.map((e,t)=>pe(e,`delegate.actions[${t}]`))},O={operationId:l,operationFingerprint:z.signingOperationFingerprint(await fe({nearAccountId:b,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:T.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:T.delegatePublicKeyStr,delegate:D})),intent:_e.TransactionSign},k={label:`delegate`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:b,auth:v,signingSessionPlan:C,signingOperation:O,thresholdKeyMaterial:T.threshold.thresholdKeyMaterial,preparation:h,executor:g,intent:{kind:`near_delegate_action_v1`,delegate:D},computeSigningDigestB64u:async()=>(await Pr({delegate:E.workerDelegate,workerCtx:e})).signingDigestB64u},A=await Ra(k,{signingAuthPlan:S,passkeyEd25519OperationStepUp:p,emailOtpEd25519StepUp:m}),j=A.preparedStepUp.confirmationAuthPayload;Et(j.signingAuthPlan)&&$(a,b,{phase:W.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:j.signingAuthPlan.thresholdSessionId,expiresAtMs:j.signingAuthPlan.expiresAtMs,remainingUses:j.signingAuthPlan.remainingUses}});let ae=await Va(k,A,d,await ot([{receiverId:E.confirmationDelegate.receiverId,actions:E.confirmationDelegate.actions.map(it)}])),oe=performance.now();$(a,b,{phase:W.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let M=await za(k,{touchConfirm:ie,signingAuthPlan:j.signingAuthPlan,nearPublicKeyStr:T.signingNearPublicKeyStr,onEvent:a,title:s,body:c,confirmationConfigOverride:o,request:{kind:`delegate`,delegate:E.confirmationDelegate,rpcCall:re}});G(String(l),`confirmation`,oe),$(a,b,{phase:W.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let N=Ba(k,A,M),P=await At({signingSessionPlan:C,signingOperation:O,commandKind:Nt.PreparePayload,execute:async()=>{$(a,b,{phase:W.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let e=await Ha(k,N,ae);return $(a,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Ga(A.preparedStepUp)}),$(a,b,{phase:W.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:e.thresholdSessionId,clientBaseSource:`yao_active_client`}}),e}}),F=await Wa(k,async()=>{$(a,b,{phase:W.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let t=await Ua(k,P,d),n=await di({ctx:e,delegate:E.workerDelegate,signingDigestB64u:t.signingDigestB64u,signatureB64u:t.signatureB64u});return{type:le.SignDelegateActionSuccess,payload:{success:!0,hash:n.hash,signedDelegate:n.signedDelegate,logs:[`Delegate action signed through Router A/B normal signing`],error:void 0}}});return $(a,b,{phase:W.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),$(a,b,{phase:W.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign_delegate`,hash:F.payload.hash}}),{signedDelegate:F.payload.signedDelegate,hash:F.payload.hash,nearAccountId:H(b),logs:[...F.payload.logs||[],...x]}}function Ja(e){let t=V(Jn(e.providedDelegatePublicKey)),n=e.thresholdKeyMaterial;if(!n)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let r=V(n.publicKey);if(!r)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(t&&t!==r&&e.warnings.push(`Delegate public key ${t} does not match threshold signer key; using ${r}`),!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=f(n.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:r,delegatePublicKeyStr:r,threshold:{thresholdKeyMaterial:n}}}async function Ya({ctx:e,commandSubject:t,nearAccount:n,signingSessionCoordinator:r,payload:i,forceFreshAuth:a,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:s,yaoSigningPreparation:c,yaoMaterialExecutor:l,selection:u,onEvent:d}){let f=u.kind===`authorized`?u.selectedLane.auth:u.candidate.auth,p=u.kind===`authorized`?u.selectedLane.identity.signer.signerSlot:u.candidate.signerSlot,g=i.operationId,_=performance.now(),v=e.relayerUrl,y=n.accountId,b=e.touchConfirm;if(!b)throw Error(`UiConfirm bridge not available for NEP-413 signing`);let{signingAuthPlan:ee,signingSessionPlan:ne}=La({selection:u,commandSubject:t,forceFreshAuth:a,preparation:c}),{thresholdKeyMaterial:re}=await pr({materialExecutor:l,nearAccount:n,signerSlot:p,requestedSignerSlot:i.signerSlot,operationLabel:`NEP-413 signing`}),x=Xa({nearAccountId:y,relayerUrl:v,thresholdKeyMaterial:re}),ie={operationId:g,operationFingerprint:z.signingOperationFingerprint(await de({nearAccountId:y,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:x.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:x.threshold.thresholdKeyMaterial.publicKey,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl})),intent:_e.TransactionSign},S={label:`NEP-413`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:y,auth:f,signingSessionPlan:ne,signingOperation:ie,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,preparation:c,executor:l,intent:{kind:`nep413_message_v1`,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl},computeSigningDigestB64u:async()=>(await Nr({message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl,workerCtx:e})).signingDigestB64u},C=await Ra(S,{signingAuthPlan:ee,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:s}),w=await Va(S,C,r,await at({nearAccountId:y,recipient:i.recipient,message:i.message}));G(String(g),`pre_confirmation`,_);let T=performance.now(),E=await za(S,{touchConfirm:b,signingAuthPlan:C.preparedStepUp.confirmationAuthPayload.signingAuthPlan,nearPublicKeyStr:x.nearPublicKey,onEvent:d,title:i.title,body:i.body,confirmationConfigOverride:i.confirmationConfigOverride,request:{kind:`nep413`,message:i.message,recipient:i.recipient}});G(String(g),`confirmation`,T);let D=performance.now(),O=Ba(S,C,E),k=await At({signingSessionPlan:ne,signingOperation:ie,commandKind:Nt.PreparePayload,execute:async()=>await Ha(S,O,w)}),A=await Wa(S,async()=>{let e=await Ua(S,k,r);return{type:le.SignNep413MessageSuccess,payload:{accountId:y,publicKey:e.signerPublicKey,signature:m(h(e.signatureB64u)),state:i.state??void 0}}});return G(String(g),`confirmed_to_signed`,D),{success:!0,accountId:A.payload.accountId,publicKey:A.payload.publicKey,signature:A.payload.signature,state:A.payload.state}}function Xa(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let r=f(t.participants.map(e=>e.id));if(!r||r.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(r||[]).join(`,`)}])`);return{nearPublicKey:n,threshold:{thresholdKeyMaterial:t}}}async function Za(e){if(e.chain!==`near`)throw Error(`[NearSigningFlow] invalid chain`);return e.kind===`transactionWithActions`?(Qa(e.payload),await ya(e.payload)):e.kind===`delegateAction`?(eo(e.payload),await qa(e.payload)):e.kind===`nep413`?(to(e.payload),await Ya(e.payload)):e}function Qa(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);let n=e.transactions;Array.isArray(n)&&jr(n),$a(e.transaction,0)}function $a(e,t){if(!String(e?.receiverId||``).trim())throw Error(`[NearSigningFlow] transactions[${t}].receiverId is required`);let n=Array.isArray(e?.actions)?e.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] transactions[${t}].actions must be non-empty`);n.forEach(we)}function eo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);if(!String(e.delegate?.receiverId||``).trim())throw Error(`[NearSigningFlow] delegate.receiverId is required`);let n=Array.isArray(e.delegate?.actions)?e.delegate.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] delegate.actions must be non-empty`);n.forEach(e=>we(Se(e)))}function to(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required for NEP-413`);if(String(e.payload?.accountId||``).trim()!==t)throw Error(`[NearSigningFlow] payload.accountId must match nearAccount.accountId`);if(!String(e.payload?.recipient||``).trim())throw Error(`[NearSigningFlow] recipient is required for NEP-413`);if(!String(e.payload?.message||``).trim())throw Error(`[NearSigningFlow] message is required for NEP-413`)}var no=e({signDelegateAction:()=>Wo,signNear:()=>oo});function ro(e){if(!(e instanceof pt))return;let t=e.authorizationDecision;if(!(!t||t.kind!==`step_up_required`||!(`request_id`in t.step_up)))return{kind:`step_up_required`,reason:t.reason,step_up:t.step_up}}function io(e){let t=ro(e),n=ut(e);return t?lt(n??{kind:`exhausted`,source:`server_prepare`,detail:`Server requires owner operation step-up`}):n?.kind===`in_flight`?lt(n):null}async function ao(e){if(e.failure?.kind!==`expired`)return;let t=Tt({source:{kind:`ed25519`,laneIdentity:Je(e.lane)},expiresAtMs:e.expiresAtMs,detectedAtMs:Date.now()});if((await e.coordinator.invalidateExpiredWalletSession({state:t,source:Ae.serverRejection})).kind===`unavailable`)throw Error(`[SigningEngine][near] expired Wallet Session cleanup failed`)}async function oo(e,t){let n=e.getSignerWorkerContext(),r=t.kind===`transactionWithActions`?x(n.touchConfirm?.getContext().surfaceMeasurementBinding)??null:null;if(r&&r.assertPending(),e={...e,prepareNearEd25519YaoMaterialBoundary:so.bind(null,e.prepareNearEd25519YaoMaterialBoundary.bind(e),r),getSignerWorkerContext:r?Jo.bind(null,n,r.beforeSigning):e.getSignerWorkerContext},t.kind===`transactionWithActions`)return await Bo(e,t.args);if(t.kind===`delegateAction`)return await Wo(e,t.args);if(t.kind===`nep413`)return await qo(e,t.args);throw Error(`[SigningEngine] unsupported near signing intent: ${String(t.kind||``)}`)}function so(e,t,n){let r=L(n.materialIdentity?n.materialIdentity.auth:n.auth);if(r===`voiceid`&&!t)throw Error(`VoiceID requires a reviewed NEAR transfer.`);return t?.assertAuthMethodPolicy(r),e(n)}function co(e){return e.state===`missing`?{state:e.state,curve:e.curve,chain:e.chain}:{authMethod:L(e.auth),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,state:e.state,source:e.source||`unknown`,...e.authorizationState===`authorized`?{walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId}:{},thresholdSessionId:e.thresholdSessionId,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}}function lo(e){let t=e?.candidates.ed25519.near||[];return{generation:e?.generation||0,candidateCount:t.length,candidates:t.map(co)}}function uo(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function fo(e){if(qe(e.signingLane.identity)!==qe(e.transactionLane.identity))throw Error(`[SigningEngine][near] prepared signing lane drifted from selected transaction lane`)}function po(e,t){let n=e.identity.signer,r=t.identity.signer;return String(n.account.wallet.walletId)===String(r.account.wallet.walletId)&&String(n.account.nearAccountId)===String(r.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(r.nearEd25519SigningKeyId)&&n.signerSlot===r.signerSlot&&B(e.auth)===B(t.auth)}function mo(e){let t=e.readiness.status;return t===`ready`?{status:`ready`,remainingUses:Math.max(0,Math.floor(Number(e.readiness.remainingUses)||0)),expiresAtMs:Math.max(0,Math.floor(Number(e.readiness.expiresAtMs)||0))}:t===`expired`||t===`exhausted`||t===`status_unknown`?t===`status_unknown`?{status:t,reason:`trusted wallet budget status is unavailable`}:{status:t}:t===`auth_unavailable`||t===`status_unavailable`?{status:t,reason:t}:{status:`status_unavailable`,reason:t}}function ho(e){if(e.curve!==`ed25519`||e.keyKind!==`threshold_ed25519`)throw Error(`[SigningEngine][near] prepared signing lane is not Ed25519`);if(e.chainFamily!==`near`)throw Error(`[SigningEngine][near] prepared Ed25519 lane must target NEAR`);let t=String(e.thresholdSessionId||``).trim(),n=String(e.walletSessionId||``).trim(),r=String(e.quotaId||``).trim();if(!t||!n||!r)throw Error(`[SigningEngine][near] prepared Ed25519 lane is missing session identity`);return{...e,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,walletSessionId:z.walletSession(n),quotaId:z.walletSessionQuota(r),thresholdSessionId:z.thresholdEd25519Session(t)}}async function go(e){let t=e.preparedOperation,n=t.lane;nt(`near`,n,{reason:`near_transaction_auth_planning`});let r=e.commandSubject.nearAccount.accountId,i={accountId:r,intent:_e.TransactionSign,curve:`ed25519`},a=t.signingSessionPlan;if(a.kind===R.NotReady)throw console.warn(`[SigningEngine][near][ed25519] transaction auth planning not ready`,{nearAccountId:r,authMethod:L(n.auth),reason:a.reason,readiness:t.readiness.status,walletSessionId:n.walletSessionId,quotaId:n.quotaId,thresholdSessionId:n.thresholdSessionId,retention:n.retention,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs}),a.reason===`policy_blocked`?Error(`[SigningEngine] NEAR operation requires passkey authentication after Email OTP login`):Error(`[SigningEngine][near] signing session is not ready: ${a.reason}`);return{signingAuthPlan:Bt({plan:a,accountId:i.accountId,intent:i.intent,curve:i.curve,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses}),signingLane:n}}function _o(e){let t=String(e.providedThresholdSessionId||``).trim(),n=String(e.identity.thresholdSessionId||``).trim();if(t&&t!==n)throw Error(`[SigningEngine][near] transaction thresholdSessionId must match prepared Ed25519 identity`);return n}function vo(e){switch(e.authorization.kind){case`authorized`:return!1;case`authorization_required`:return!0;default:throw e.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function yo(e){if(e.authorization.kind!==`authorized`)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e.authorization.authorization.status.expiresAtMs}async function bo(e){let t={walletId:Ee(e.commandSubject.walletSession.walletId),nearAccountId:H(e.commandSubject.nearAccount.accountId)};return e.materialIdentity?await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,materialIdentity:e.materialIdentity}):await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,laneIdentity:e.selectedLane.identity,auth:e.selectedLane.auth})}function xo(e,t){return z.signingOperation(e.createSigningSessionId(`near-${t}-operation`))}function So(e){return{kind:`prepared_near_transaction_execution`,thresholdSessionId:e.thresholdSessionId,signingSessionPlan:e.preparedSigningSession.preparedOperation.signingSessionPlan,signingAuthPlan:e.preparedSigningSession.signingAuthPlan,signingLane:e.preparedSigningSession.signingLane,signingSessionCoordinator:e.signingSessionCoordinator,transactionOperation:e.preparedSigningSession.transactionOperation,passkeyEd25519OperationStepUp:e.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.emailOtpEd25519StepUp}}function Co(e){return ft({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.signingLane.walletSessionId),quotaId:String(e.prepared.signingLane.quotaId),projectionVersion:`server-owned`,authorityKey:B(e.prepared.signingLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function wo(e){if(e.prepared.kind!==`authorized`)throw Error(`[SigningEngine][near] deferred Ed25519 material has no reusable session`);return ft({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.selectedLane.walletSessionId),quotaId:String(e.prepared.selectedLane.quotaId),projectionVersion:`projection-unadmitted`,authorityKey:B(e.prepared.selectedLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function To(e){if(e.auth.kind!==`passkey`)return;let t=e.auth;return{prepare:async()=>{let n=e.signer,r=await Do({authorityRef:Eo(e.preparation),walletId:n.account.wallet.walletId,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u});return{thresholdSessionId:e.thresholdSessionId,authority:r}}}}function Eo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.hydration.authority;case`blocked`:throw Error(`[SigningEngine][near] blocked Passkey material has no authority`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Passkey material authority`)}}async function Do(e){let t=De({walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.authorityRef.walletAuthMethodId});if(!t)throw Error(`[SigningEngine][near] exact Passkey step-up authority is invalid`);let n=await Oe({authority:t});if(n.walletId!==e.authorityRef.walletId||n.walletAuthMethodId!==e.authorityRef.walletAuthMethodId||n.authorityDigest!==e.authorityRef.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey step-up authority changed`);return t}function Oo(e){if(e.auth.kind!==me.emailOtp||typeof e.deps.requestEmailOtpEd25519SigningChallenge!=`function`||!e.preparation.hydration.materialActivation)return;if(String(e.signer.account.wallet.walletId)!==String(e.commandSubject.walletSession.walletId)||String(e.signer.account.nearAccountId)!==String(e.commandSubject.nearAccount.accountId))throw Error(`[SigningEngine][near] Email OTP step-up lane changed subject`);let t=async t=>{let n=await e.deps.requestEmailOtpEd25519SigningChallenge({walletSession:e.commandSubject.walletSession,operationFingerprintDigest:t.operationFingerprintDigest});return uo(e.onEvent,e.commandSubject.nearAccount.accountId,{phase:W.STEP_06_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:n.emailHint,demoOtpCode:st(n.delivery)}}),n};return{prepare:t,resend:t}}async function ko(e){let t=qt({availableLanes:await Lo({deps:e.deps,commandSubject:e.commandSubject,authMethod:null}),intent:Po({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:1})});if(!t.ok)throw Error(`[SigningEngine][near] signature-only signing requires exact Ed25519 material`);if(t.kind===`authorization_required`){let n=t.candidate,r=Ye({walletId:n.walletId,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}),i={kind:`near_ed25519_material_identity`,signer:r,auth:n.auth,thresholdSessionId:z.thresholdEd25519Session(n.thresholdSessionId)},a=await bo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:i});return{kind:`authorization_required`,candidate:n,materialIdentity:i,forceFreshAuth:!0,passkeyEd25519OperationStepUp:To({auth:n.auth,signer:r,thresholdSessionId:i.thresholdSessionId,preparation:a.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:r,preparation:a.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:a.preparation,yaoMaterialExecutor:a.executor}}let n=t.lane,r=await bo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:n});return{kind:`authorized`,selectedLane:n,forceFreshAuth:e.attempt.forceFreshAuth||vo(r.preparation),passkeyEd25519OperationStepUp:To({auth:n.auth,signer:n.identity.signer,thresholdSessionId:n.identity.thresholdSessionId,preparation:r.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:n.identity.signer,preparation:r.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:r.preparation,yaoMaterialExecutor:r.executor}}async function Ao(e){let t=wt({materialActivation:e.materialActivation});return await e.deps.withThresholdEd25519CommitQueue({queueKey:t,nearAccountId:e.nearAccountId,enabled:!0,task:e.task})}async function jo(e){let t=e.availableLanes,n=qt({availableLanes:t,intent:Po({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:Ar(e.input.transaction)})});if(!n.ok||n.kind!==`authorization_required`)return null;let r=n.candidate,i=Ye({walletId:r.walletId,nearAccountId:r.nearAccountId,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,signerSlot:r.signerSlot}),a={kind:`near_ed25519_material_identity`,signer:i,auth:r.auth,thresholdSessionId:z.thresholdEd25519Session(r.thresholdSessionId)},o=await bo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:a});return{candidate:r,preparation:o.preparation,executor:o.executor,passkeyEd25519OperationStepUp:To({auth:r.auth,signer:i,thresholdSessionId:a.thresholdSessionId,preparation:o.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:r.auth,signer:i,preparation:o.preparation,onEvent:e.input.onEvent})||null}}function Mo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return e.hydration.materialActivation;case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired public material cannot enter the material commit queue`);case`blocked`:throw Error(`[SigningEngine][near] blocked material cannot enter the material commit queue: ${e.hydration.reason}`)}throw e.hydration,Error(`[SigningEngine][near] unsupported material hydration plan`)}function No(e){let t=e.authSelectionPolicy||null;if(!t)return null;let n=Ut(Ht(Wt(Po({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:t,operationUsesNeeded:e.operationUsesNeeded})),{availableLanes:e.availableLanes}));if(n.tag===`LaneSelected`){if(n.lane.curve!==`ed25519`||n.availableLane.curve!==`ed25519`)throw Error(`[SigningEngine][near] Ed25519 selector returned a non-Ed25519 lane`);return n}if(n.failure.kind===`no_candidate`)return null;throw Error(`[SigningEngine][near] Ed25519 transaction lane selection failed: ${n.failure.kind}`)}function Po(e){return{walletId:Ee(e.commandSubject.walletSession.walletId),curve:`ed25519`,chain:`near`,signerSelection:Fo({nearAccountId:e.commandSubject.nearAccount.accountId,signerSlot:e.signerSlot}),authSelectionPolicy:e.authSelectionPolicy,operationUsesNeeded:e.operationUsesNeeded}}function Fo(e){if(e.signerSlot===void 0)return{kind:`near_account`,nearAccountId:e.nearAccountId};let t=ke(e.signerSlot);if(t===null)throw Error(`[SigningEngine][near] signerSlot must be a positive safe integer`);return{kind:`signer_slot`,nearAccountId:e.nearAccountId,signerSlot:t}}function Io(e){return No({availableLanes:e.availableLanes,authSelectionPolicy:{kind:`any`},commandSubject:e.commandSubject,signerSlot:e.signerSlot,operationUsesNeeded:e.operationUsesNeeded})}async function Lo(e){let t=e.commandSubject.nearAccount.accountId,n=e.commandSubject.walletSession.walletId;if(typeof e.deps.readAvailableSigningLanesForSigning!=`function`)throw Error(`[SigningEngine][near] transaction signing requires available signing lanes reader`);let r=await e.deps.resolveOwnerLaneScope(n);return await e.deps.readAvailableSigningLanesForSigning({walletId:n,curve:`ed25519`,ownerScope:r,...e.authMethod?{authMethod:e.authMethod}:{}}).catch(e=>(console.warn(`[SigningEngine][near] available signing lanes read failed`,{nearAccountId:t,error:e instanceof Error?e.message:String(e||`unknown error`)}),null))}async function Ro(e){let t=e.commandSubject.nearAccount.accountId,n=Math.max(1,Math.floor(Number(e.operationUsesNeeded)||1)),r=e.selectedLane.lane,i=ka({commandSubject:e.commandSubject,selectedLane:r,preparation:e.preparation,forceFreshAuth:e.forceFreshAuth,requiredSignatureUses:n}),a=i.lane;fo({signingLane:a,transactionLane:e.selectedLane.lane});let o={readiness:i.coordinatorInput.readiness,expiresAtMs:i.coordinatorInput.expiresAtMs,remainingUses:i.coordinatorInput.remainingUses};r.auth.kind===`email_otp`&&o.readiness.status!==`ready`&&console.warn(`[SigningEngine][near][email-otp] Ed25519 pre-confirm readiness is not ready`,{nearAccountId:t,readiness:o.readiness.status,thresholdSessionId:r.thresholdSessionId,walletSessionId:r.walletSessionId,quotaId:r.quotaId,retention:a.retention,remainingUses:o.remainingUses,expiresAtMs:o.expiresAtMs,requiredSignatureUses:n}),tt(`near`,rt({event:`pre_confirm_readiness_checked`,lane:a,readinessStatus:o.readiness.status,phase:`pre_confirm`}));let s=Jt(e.selectedLane,mo({readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses})),c=Gt(s),l=ho(a),u={readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses};return{lane:a,transactionLane:e.selectedLane.lane,transactionIntent:e.selectedLane.intent,readiness:u,availableLanesGeneration:e.availableLanes?.generation||0,metadata:{transactionLane:e.selectedLane.lane,transactionOperation:c,transactionReadinessState:s,identity:l,availableLanesGeneration:e.availableLanes?.generation||0,readiness:u}}}async function zo(e){let t=e.commandSubject.nearAccount.accountId,n=Ar(e.input.transaction),r=e.availableLanes,i=Io({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!i)throw console.warn(`[SigningEngine][near][ed25519] exact transaction lane selection failed ${JSON.stringify({nearAccountId:t,signerSlot:e.input.signerSlot??null,requiredSignatureUses:n,availableLanes:lo(r)})}`),Error(`[SigningEngine][near] Ed25519 transaction signing requires an exact selected lane`);let a={kind:`account_class`,authMethod:L(i.lane.auth)},o=await bo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:i.lane});if(o.preparation.authorization.kind===`authorized`){let t=o.preparation.authorization.authorization;if(i.lane.walletSessionId!==t.operationCredential.walletSessionId||i.lane.quotaId!==t.session.quotaId){r=await Lo({deps:e.deps,commandSubject:e.commandSubject,authMethod:L(i.lane.auth)});let a=Io({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!a||!po(i.lane,a.lane)||a.lane.walletSessionId!==t.operationCredential.walletSessionId||a.lane.quotaId!==t.session.quotaId)throw Error(`[SigningEngine][near] material restoration changed the Wallet Session without an exact refreshed lane`);i=a}}let s=e.forceFreshAuth===!0||vo(o.preparation),c=await Kt({intent:Po({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:a,operationUsesNeeded:n}),coordinator:e.signingSessionCoordinator,forceFreshAuth:s,sensitiveOperationPolicy:e.input.sensitivePolicy||he.inheritSessionPolicy,onPlannerTrace:e=>et(`near`,e),lifecycleAdapter:{prepare:async()=>{let t=await Ro({deps:e.deps,commandSubject:e.commandSubject,signingSessionCoordinator:e.signingSessionCoordinator,availableLanes:r,selectedLane:i,preparation:o.preparation,forceFreshAuth:s,operationUsesNeeded:n});return{...t,metadata:t.metadata}}}}),l=c.thresholdOperation,u=c.transactionOperation,d=l.lane,f=u.lane,p=l.metadata.identity,{signingAuthPlan:m}=await go({commandSubject:e.commandSubject,preparedOperation:l});return{preparation:o.preparation,executor:o.executor,signingAuthPlan:m,signingLane:d,transactionLane:f,identity:p,thresholdSessionId:z.thresholdEd25519Session(_o({providedThresholdSessionId:e.input.thresholdSessionId,identity:p})),availableLanesGeneration:l.availableLanesGeneration,preparedOperation:l,transactionOperation:u}}async function Bo(e,t){let n=performance.now();await e.touchConfirm.openTransactionPreparationModal({chain:`near`,walletLabel:String(t.commandSubject.nearAccount.accountId),txSigningRequests:[t.transaction],model:qn({txSigningRequests:[t.transaction],signerAccount:String(t.commandSubject.nearAccount.accountId),title:t.title,subtitle:t.body}),confirmationConfigOverride:t.confirmationConfigOverride});try{let r=z.signingOperation(e.createSigningSessionId(`near-transaction-sign`));return G(String(r),`preparation_modal`,n),await Vo(e,t,{signingOperationState:jt({operationId:r})})}finally{e.touchConfirm.closeTransactionPreparationModal()}}async function Vo(e,t,n){let r=t.commandSubject.nearAccount,i=H(r.accountId),a={signerSlot:t.signerSlot,confirmationConfigOverride:t.confirmationConfigOverride,title:t.title,body:t.body,onEvent:t.onEvent},o=n.signingOperationState.operationId,s=n.signingSessionCoordinator||e.signingSessionCoordinator,c=performance.now(),l=await Lo({deps:e,commandSubject:t.commandSubject,authMethod:null}),u=await jo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,operationId:o});if(G(String(o),`authorization_probe`,c),u){let o=e.getSignerWorkerContext();return await Ao({deps:e,nearAccountId:i,materialActivation:Mo(u.preparation),task:async()=>await Za({chain:`near`,kind:`transactionWithActions`,payload:{ctx:o,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:s,selection:{kind:`authorization_required`,candidate:u.candidate},passkeyEd25519OperationStepUp:u.passkeyEd25519OperationStepUp||void 0,emailOtpEd25519StepUp:u.emailOtpEd25519StepUp||void 0,sensitivePolicy:t.sensitivePolicy,yaoSigningPreparation:u.preparation,yaoMaterialExecutor:u.executor}})})}let d=performance.now(),f=await zo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,signingSessionCoordinator:s,operationId:o,forceFreshAuth:n.forceFreshAuth===!0});G(String(o),`lane_preparation`,d);let p=performance.now(),m=f.preparation.authorization,h=f.signingAuthPlan,g=f.signingLane,_=f.transactionLane,v=f.thresholdSessionId;fo({signingLane:g,transactionLane:_});try{return await Ao({deps:e,nearAccountId:i,materialActivation:Mo(f.preparation),task:async()=>{let i=e.getSignerWorkerContext(),c=f,l=To({auth:_.auth,signer:_.identity.signer,thresholdSessionId:v,preparation:c.preparation}),u=Oo({deps:e,commandSubject:t.commandSubject,auth:_.auth,signer:_.identity.signer,preparation:c.preparation,onEvent:a.onEvent}),d=So({preparedSigningSession:f,thresholdSessionId:v,signingSessionCoordinator:s,passkeyEd25519OperationStepUp:l||null,emailOtpEd25519StepUp:u||null}),m={thresholdSessionId:d.thresholdSessionId,signingSessionPlan:d.signingSessionPlan,signingAuthPlan:d.signingAuthPlan,signingLane:d.signingLane},h={ctx:i,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:d.signingSessionCoordinator,selection:{kind:`authorized`,selectedLane:_},transactionOperation:d.transactionOperation,ed25519SigningBoundary:m,yaoSigningPreparation:c.preparation,yaoMaterialExecutor:c.executor,...d.passkeyEd25519OperationStepUp?{passkeyEd25519OperationStepUp:d.passkeyEd25519OperationStepUp}:{},...d.emailOtpEd25519StepUp?{emailOtpEd25519StepUp:d.emailOtpEd25519StepUp}:{}};return G(String(o),`execution_setup`,p),await Za({chain:`near`,kind:`transactionWithActions`,payload:h})}})}catch(r){let o=h.kind===kt.PasskeyReauth||h.kind===kt.EmailOtpReauth,c=ro(r),l=io(r),u=mt(r),d=c?.kind===`step_up_required`;if(!n.retryingFreshAuth&&!o&&m.kind===`authorized`&&(d||l)){if(l?.kind===`wait_and_retry_admission`)return await dt(l.retryAfterMs),await Vo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s});if(await ao({failure:u,coordinator:s,lane:f.transactionLane,expiresAtMs:m.authorization.status.expiresAtMs}),_.auth.kind===`voiceid`)throw Error(`Unlock with VoiceID again to renew the NEAR Wallet Session.`);let r=_.auth.kind===`email_otp`,o=c?.kind===`step_up_required`?c.reason:void 0,d=l?l.reason===`stale_projection`?`wallet_signing_budget_stale_projection`:`wallet_signing_budget_exhausted`:o===`wallet_session_missing`?`threshold_session_missing`:`threshold_session_expired`;if(uo(a.onEvent,i,{phase:r?W.STEP_06_AUTH_EMAIL_OTP_CHALLENGE_STARTED:W.STEP_09_THRESHOLD_SESSION_RECONNECT_STARTED,status:`running`,message:r?`Signing session needs reauthorization; requesting Email OTP`:`Signing session needs reauthorization; requesting passkey`,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,reason:d}}),l?.kind===`request_fresh_step_up`){let r=Co({walletId:t.commandSubject.walletSession.walletId,nearAccountId:i,prepared:f});return await s.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await Vo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s}),retryAfterRefresh:async()=>await Vo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s})})}return await Vo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s})}throw r}}async function Ho(e){return await Za({chain:`near`,kind:`delegateAction`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:e.input.commandSubject.nearAccount,delegate:e.input.delegate,rpcCall:e.normalizedRpcCall,signingSessionCoordinator:e.deps.signingSessionCoordinator,signerSlot:e.input.signerSlot,confirmationConfigOverride:e.input.confirmationConfigOverride,title:e.input.title,body:e.input.body,onEvent:e.input.onEvent,operationId:e.operationId,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor}})}async function Uo(e){let t=H(e.input.commandSubject.nearAccount.accountId),n=await ko({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt}),r={nearRpcUrl:e.input.rpcCall.nearRpcUrl||e.deps.nearRpcUrl,nearAccountId:t};try{return await Ao({deps:e.deps,nearAccountId:t,materialActivation:Mo(n.yaoSigningPreparation),task:Ho.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n,normalizedRpcCall:r})})}catch(r){let i=ro(r),a=io(r);if(e.attempt.kind===`initial`&&a){if(a.kind===`wait_and_retry_admission`)return await dt(a.retryAfterMs),await Uo(e);let r=wo({walletId:e.input.commandSubject.walletSession.walletId,nearAccountId:t,prepared:n});return await e.deps.signingSessionCoordinator.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await Uo({...e,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}}),retryAfterRefresh:async()=>await Uo({...e,attempt:{kind:`initial`,forceFreshAuth:!1}})})}let o=mt(r);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&i)return await ao({failure:o,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:yo(n.yaoSigningPreparation)}),await Uo({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw r}}async function Wo(e,t){try{return await Uo({deps:e,input:t,operationId:xo(e,`delegate`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){throw console.error(`[SigningEngine][delegate] failed`,e),e}}async function Go(e){let t=e.input.commandSubject.nearAccount;return await Za({chain:`near`,kind:`nep413`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:t,signingSessionCoordinator:e.deps.signingSessionCoordinator,onEvent:e.input.onEvent,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor,payload:{message:e.input.message,recipient:e.input.recipient,nonce:e.input.nonce,callbackUrl:e.input.callbackUrl,state:e.input.state,accountId:t.accountId,signerSlot:e.input.signerSlot,title:e.input.title,body:e.input.body,confirmationConfigOverride:e.input.confirmationConfigOverride,operationId:e.operationId}}})}async function Ko(e){let t=H(e.input.commandSubject.nearAccount.accountId),n=await ko({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt});try{return await Ao({deps:e.deps,nearAccountId:t,materialActivation:Mo(n.yaoSigningPreparation),task:Go.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n})})}catch(t){let r=ro(t),i=mt(t);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&r!==void 0)return await ao({failure:i,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:yo(n.yaoSigningPreparation)}),await Ko({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw t}}async function qo(e,t){try{return await Ko({deps:e,input:t,operationId:xo(e,`nep413`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){return console.error(`SigningEngine: NEP-413 signing error:`,e),{success:!1,error:e instanceof Error?e.message:String(e||`Unknown error`)}}}function Jo(e,t){return{...e,beforeSigning:t}}export{an as _,Qn as a,Rn as c,En as d,wn as f,mn as g,dn as h,ar as i,zn as l,un as m,no as n,Gn as o,Cn as p,fr as r,Kn as s,oo as t,Ln as u,nn as v};
1
+ import{n as e}from"./chunk-dVx5-UGu.js";import{C as t,H as n,V as r,i}from"./domainIds-t1lp25yU.js";import{b as a,g as o,h as s,m as c,s as l}from"./digests-BIaE0DMd.js";import{c as u,o as d,r as f}from"./participants-BXdREC5k.js";import{i as p,n as m,r as h,t as g}from"./base64-BmKR3UqU.js";import{n as _,r as v}from"./secureRandomId-8LSc91aN.js";import{s as y}from"./walletDbName-B6-CV_Rq.js";import{i as b,t as ee}from"./activeWalletSession-HAOgRKzn.js";import{a as te,s as ne}from"./chains-B72I4PDH.js";import{o as re}from"./signingSessionSeal-BFOBKj-J.js";import{r as x}from"./transactionReviewAdmission-Cf_qUZJt.js";import{c as ie,d as S,f as C,h as w,m as T,p as E,s as D}from"./capabilityKinds-Cafn86Y1.js";import{r as O}from"./canonicalPrimitives-DKeS3M40.js";import{t as k}from"./errors-BJBDbwHk.js";import{a as A,c as j,i as ae,n as oe,o as M,r as N,s as P,t as F}from"./nearRpcResults-CeHdqaS4.js";import{a as se,c as I,i as ce,l as le,n as ue,o as de,r as fe,t as pe}from"./ed25519OperationFingerprint-Dev4P6Og.js";import{n as me,t as he}from"./signerDomain-D-EUTlLK.js";import{a as ge,c as L,i as R,n as _e,o as ve,r as z,s as B,t as ye}from"./types-D2Zk1W7I.js";import{d as be,i as V,t as H,u as xe}from"./accountIds-DGWFzEnw.js";import{a as Se,n as Ce,o as we,t as U}from"./actions-7SvZZut1.js";import{a as Te,c as Ee}from"./ecdsaChainTarget-BoRVQtjQ.js";import{ot as De,ut as Oe}from"./digestEncoding-Rx8Vjy4J.js";import{t as ke}from"./signerSlot-BlijMq8C.js";import{a as Ae,m as je,o as W}from"./sdkSentEvents-BFwv3mBw.js";import{t as Me}from"./jsonRpc-DGzeiNSa.js";import{T as Ne,i as Pe}from"./emailOtpEcdsaDerivationIdentity-DJmMyqL-.js";import{p as Fe}from"./nonceLaneKeys-DtBpxubF.js";import{t as Ie}from"./walletSessionAuthorizationStatus-CQ3qA9tI.js";import{t as Le}from"./executeWorkerOperation-CAYSt0NA.js";import{T as Re,p as ze,t as Be}from"./authorization-D_NueqAv.js";import{i as Ve,n as He}from"./profileAccountProjection-dvLchPBo.js";import{a as Ue,i as We,l as Ge,u as Ke}from"./helpers-B7c1zc7h.js";import{D as qe,T as Je,j as Ye}from"./nearEd25519YaoSigningPreparation-Cz2Gb95g.js";import{n as Xe}from"./lanes-0WT2w1Xz.js";import{n as Ze,r as Qe,t as $e}from"./operationFingerprint-GKEY-X5I.js";import{a as G,c as et,o as tt,s as nt,t as rt}from"./trace-BA8jya7O.js";import{i as it,n as at,r as ot}from"./intentDigest-gM3r4SVX.js";import{t as st}from"./challengeDelivery-Dj9HrjW9.js";import{n as ct}from"./NonceCoordinator-C1lw03Ce.js";import{a as lt,i as ut,o as dt,r as ft,t as pt}from"./authorizationAdmission-28jo_IVJ.js";import{i as mt}from"./walletSessionFailure-CxsVtroW.js";import{a as ht,d as gt,i as _t,l as vt,n as yt,p as bt,r as xt,s as St,u as Ct}from"./routerAbNormalSigning-CPLDkttX.js";import{i as wt,n as Tt}from"./clientSessionPersistenceState-B3gU3515.js";import{a as Et,i as Dt,r as Ot,t as kt}from"./types-C4OErbBf.js";import{C as At,b as jt,c as Mt,g as Nt,h as Pt,l as Ft,n as It,o as Lt,s as Rt,t as zt,u as Bt,x as Vt}from"./requireStepUpAuth-ByMTPBu4.js";import{a as Ht,c as Ut,i as Wt,n as Gt,r as Kt,s as qt,t as Jt}from"./transactionState-BCbaT2hO.js";const Yt=Symbol(`ClientSecretSource`),Xt=Symbol(`EmailOtpWorkerSessionHandle`);function Zt(e,t){let n=String(e||``).trim();if(!n)throw Error(`[platform] ${t} is required`);return n}function Qt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[platform] ${t} must be an object`);return e}function $t(e){return en({prfFirstB64u:e.prf.prfFirstB64u,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})}function en(e){return{kind:`webauthn_prf_first`,prfFirstB64u:Zt(e.prfFirstB64u,`prfFirstB64u`),rpId:e.rpId,credentialIdB64u:Zt(e.credentialIdB64u,`credentialIdB64u`),[Yt]:`webauthn_prf_first`}}function tn(e){let t=Zt(e.sessionId,`sessionId`);switch(e.action){case`threshold_ecdsa_bootstrap`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,keyHandle:Zt(e.keyHandle,`keyHandle`),authSubjectId:e.authSubjectId,action:`threshold_ecdsa_bootstrap`,operation:e.operation,chainTarget:e.chainTarget,[Xt]:`email_otp_worker_session_handle`};case`threshold_ed25519_session`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,rpId:e.rpId,authSubjectId:e.authSubjectId,action:`threshold_ed25519_session`,operation:e.operation,[Xt]:`email_otp_worker_session_handle`};default:{let t=e;throw Error(`[platform] unsupported email OTP worker-issued handle action: ${String(t)}`)}}}function nn(e){let t=Qt(e,`email OTP worker-issued session handle`),n=Zt(String(t.kind||``),`email OTP worker-issued handle kind`);if(n!==`email_otp_worker_session_handle_v1`)throw Error(`[platform] unsupported email OTP worker-issued handle kind: ${n}`);let r=Zt(String(t.action||``),`email OTP worker-issued handle action`),i=Zt(String(t.operation||``),`email OTP worker-issued handle operation`);if(i!==`registration`&&i!==`wallet_unlock`&&i!==`sign`&&i!==`export`)throw Error(`[platform] unsupported email OTP worker-issued handle operation: ${i}`);let a=i,o={sessionId:Zt(String(t.sessionId||``),`email OTP worker-issued handle sessionId`),walletId:Ee(t.walletId),authSubjectId:Pe(t.authSubjectId),operation:a};if(r===`threshold_ecdsa_bootstrap`){if(`rpId`in t)throw Error(`[platform] email OTP ECDSA worker-issued handles cannot include rpId`);if(a===`registration`)throw Error(`[platform] registration Email OTP ECDSA worker-issued handles are retired`);let e=Te(Qt(t.chainTarget,`email OTP worker-issued handle chainTarget`));if(`evmFamilySigningKeySlotId`in t)throw Error(`[platform] runtime Email OTP ECDSA handles cannot include evmFamilySigningKeySlotId`);return tn({...o,action:r,operation:a,keyHandle:Zt(String(t.keyHandle||``),`email OTP worker-issued handle keyHandle`),chainTarget:e})}if(r===`threshold_ed25519_session`){if(`chainTarget`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include chainTarget`);if(`evmFamilySigningKeySlotId`in t||`keyHandle`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include ECDSA key identity`);return tn({...o,action:r,rpId:Ne(t.rpId)})}throw Error(`[platform] unsupported email OTP worker-issued handle action: ${r}`)}function rn(e){return e.action===`threshold_ecdsa_bootstrap`&&e.operation===`export`}function an(e){let t=nn(e);if(!rn(t))throw Error(`[platform] Email OTP ECDSA export requires an export worker handle`);return t}const on=15e3;function sn(e){e.abort(`timeout`)}function cn(e,t){let n=String(e??``).trim();if(!n)throw Error(`[threshold-ed25519] ${t} is required`);return n}function ln(e){let t=cn(Ge(e.credential),`prfFirstB64u`);return{ok:!0,operation:`get_passkey`,requirePrfFirst:!0,credential:e.credential,credentialIdB64u:cn(e.credential.rawId||e.credential.id,`credentialIdB64u`),rawIdB64u:String(e.credential.rawId||``).trim(),rpId:Ne(e.rpId),prf:{kind:`required`,prfFirstB64u:t}}}function un(e){return{kind:`webauthn_prf_first_credential`,credential:e.credential,secretSource:$t(ln(e))}}function dn(e){return e.policySecretSource.secretSource.prfFirstB64u}function fn(e){if(typeof e!=`string`)return null;let t=Date.parse(e);return Number.isSafeInteger(t)&&t>Date.now()?t:null}function pn(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}async function mn(e){let i=n(r(e.relayerUrl));if(!i)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Wallet Session mint`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Wallet Session mint`};let a=Ke(e.auth.policySecretSource.credential),s=new AbortController,c=null;try{let n=`${i}${re}`,r=e.existingOperationCredential,l=String(e.publishableKey||``).trim()||void 0,u=r?.token||l,d=!r&&l&&String(e.projectEnvironmentId||``).trim()||void 0;c=setTimeout(sn,on,s);let f=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,...u?{Authorization:`Bearer ${u}`}:{}},credentials:`omit`,signal:s.signal,body:JSON.stringify({sessionKind:e.sessionKind,relayerKeyId:e.relayerKeyId,sessionPolicy:e.sessionPolicy,...d?{projectEnvironmentId:d}:{},walletSessionTarget:{kind:`new_wallet_session`},...a?{webauthn_authentication:a}:{}})}),p;try{let e=await f.json();p=o(e)?e:{}}catch(e){if(s.signal.aborted)throw e;p={}}if(!f.ok)return Be(p)||{ok:!1,code:typeof p.code==`string`?p.code:`http_error`,message:typeof p.message==`string`?p.message:`HTTP ${f.status}`};let m=Be(p);if(m)return m;if(p.ok!==!0)return{ok:!1,code:typeof p.code==`string`?p.code:`invalid_response`,message:typeof p.message==`string`?p.message:`Wallet Session mint returned an unsuccessful response`};let h=t(p.thresholdSessionId);if(!h.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid thresholdSessionId`};let g=w(p.walletSessionId),_=T(p.authorizationId),v=S(p.quotaId);if(!g.ok||!_.ok||!v.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid authorization identity`};let ee=fn(p.expiresAt),te=pn(p.remainingUses),ne=y(p.runtimePolicyScope);if(!ee||!te||!ne)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid lifecycle or policy data`};let x={ok:!0,thresholdSessionId:h.value,walletSessionId:g.value,authorizationId:_.value,quotaId:v.value,expiresAtMs:ee,remainingUses:te,runtimePolicyScope:ne};if(p.sessionKind===`issued_exact_wallet_session`){let e;try{e=b(p.operationCredential)}catch(e){return{ok:!1,code:`invalid_response`,message:k(e)||`Wallet Session mint returned an invalid operation credential`}}return e.walletSessionId===g.value?{...x,sessionKind:p.sessionKind,operationCredential:e}:{ok:!1,code:`invalid_response`,message:`Wallet Session mint credential does not identify its session`}}return p.sessionKind!==`already_committed_exact_wallet_session`||p.operationCredential!==void 0?{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid session branch`}:r?r.walletSessionId===g.value?{...x,sessionKind:p.sessionKind}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint returned another lifecycle identity`}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint requires the credential the caller already holds`}}catch(e){let t=k(e)||`Failed to mint threshold session`,n=s.signal.aborted;return{ok:!1,code:n?`timeout`:`network_error`,message:n?`Wallet Session mint timed out after ${on}ms`:t}}finally{c!==null&&clearTimeout(c)}}function hn(e){switch(e.kind){case`passkey`:return{kind:`passkey`,authority:e.authority,webauthn_authentication:Ke(e.credential)};case`email_otp`:return{kind:`email_otp`,authority_ref:e.authorityRef,provider_subject_id:cn(e.providerSubjectId,`providerSubjectId`),challenge_id:cn(e.challengeId,`challengeId`),otp_code:cn(e.otpCode,`otpCode`)};default:throw Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function gn(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[threshold-ed25519] ${t} must be an object`);return e}function _n(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length)throw Error(`[threshold-ed25519] ${n} contains unexpected fields`);for(let e=0;e<r.length;e+=1)if(r[e]!==i[e])throw Error(`[threshold-ed25519] ${n} contains unexpected fields`)}function vn(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`[threshold-ed25519] ${t} must be a non-empty normalized string`);return e}function yn(e){switch(e.proof.kind){case`passkey`:if(e.materialRecovery.kind!==`not_requested`)throw Error(`[threshold-ed25519] passkey operation step-up cannot request material recovery`);return{kind:`not_requested`};case`email_otp`:switch(e.materialRecovery.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_factor_release_v1`:return{kind:`email_otp_factor_release_v1`,workerEphemeralPublicKey65B64u:vn(e.materialRecovery.workerEphemeralPublicKey65B64u,`workerEphemeralPublicKey65B64u`)};default:throw e.materialRecovery,Error(`[threshold-ed25519] unsupported material recovery request`)}default:throw e.proof,Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function bn(e){let t=gn(e.value,`operation step-up material recovery`);switch(t.kind){case`not_requested`:if(_n(t,[`kind`],`operation step-up material recovery`),e.requested.kind!==`not_requested`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`not_requested`};case`email_otp_factor_release_v1`:if(_n(t,[`kind`,`challengeId`,`enrollmentId`,`enrollmentSealKeyVersion`,`serverEphemeralPublicKey65B64u`,`nonce12B64u`,`ciphertextB64u`],`operation step-up material recovery`),e.requested.kind!==`email_otp_factor_release_v1`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`email_otp_factor_release_v1`,challengeId:vn(t.challengeId,`materialRecovery.challengeId`),enrollmentId:vn(t.enrollmentId,`materialRecovery.enrollmentId`),enrollmentSealKeyVersion:vn(t.enrollmentSealKeyVersion,`materialRecovery.enrollmentSealKeyVersion`),serverEphemeralPublicKey65B64u:vn(t.serverEphemeralPublicKey65B64u,`materialRecovery.serverEphemeralPublicKey65B64u`),nonce12B64u:vn(t.nonce12B64u,`materialRecovery.nonce12B64u`),ciphertextB64u:vn(t.ciphertextB64u,`materialRecovery.ciphertextB64u`)};default:throw Error(`[threshold-ed25519] operation step-up material recovery kind is invalid`)}}function xn(e){let t=gn(e.body,`operation step-up response`);if(_n(t,[`ok`,`kind`,`authorization`,`expiresAtMs`,`materialRecovery`],`operation step-up response`),t.ok!==!0||t.kind!==`verified_step_up`)throw Error(`[threshold-ed25519] operation step-up response kind is invalid`);let n=gn(t.authorization,`operation step-up authorization`);if(_n(n,[`kind`,`evidence_set_digest`],`operation step-up authorization`),n.kind!==`operation_step_up`)throw Error(`[threshold-ed25519] operation step-up authorization marker is invalid`);let r=vn(n.evidence_set_digest,`operation step-up authorization.evidence_set_digest`);if(O(r),typeof t.expiresAtMs!=`number`||!Number.isSafeInteger(t.expiresAtMs)||t.expiresAtMs<=Date.now())throw Error(`[threshold-ed25519] operation step-up expiry is invalid`);return{kind:`verified_step_up`,authorization:{kind:`operation_step_up`,evidence_set_digest:r},expiresAtMs:t.expiresAtMs,materialRecovery:bn({value:t.materialRecovery,requested:e.requestedMaterialRecovery})}}async function Sn(e){let t=n(r(e.relayerUrl));if(!t)throw Error(`[threshold-ed25519] operation step-up relayerUrl is required`);let i=yn(e),a=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null,o=d({...a?{headers:u(a)}:{},body:{kind:`router_ab_ed25519_yao_operation_step_up_grant_v1`,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:hn(e.proof),materialRecovery:i.kind===`email_otp_factor_release_v1`?{kind:i.kind,worker_ephemeral_public_key_65_b64u:i.workerEphemeralPublicKey65B64u}:i}}),s=await fetch(`${t}${re}`,{...o}),c=await s.json().catch(()=>({}));if(!s.ok){let e=c&&typeof c==`object`&&!Array.isArray(c)?c:{};throw Error(`[threshold-ed25519] operation step-up failed: ${String(e.message||`HTTP ${s.status}`)}`)}return xn({body:c,requestedMaterialRecovery:i})}function Cn(e){let t=e.lane,n=e.readiness;if(t.curve!==n.curve)throw Error(`[SigningSession] planner lane and readiness curves do not match`);if(t.curve===`ecdsa`&&n.curve===`ecdsa`){let e=t.authorization,r=n.authorization,a=e.session,o=r.session;if(!i(t.materialActivation,n.materialActivation)||e.selectedAuthority.authorityId!==r.selectedAuthority.authorityId||e.selectedAuthMethod.kind!==r.selectedAuthMethod.kind||e.selectedAuthMethod.walletAuthMethodId!==r.selectedAuthMethod.walletAuthMethodId||a.walletId!==o.walletId||a.authorityId!==o.authorityId||a.authMethodId!==o.authMethodId||a.authorizationId!==o.authorizationId||a.quotaId!==o.quotaId||a.authorityDigestB64u!==o.authorityDigestB64u||a.authorityRevocationEpoch!==o.authorityRevocationEpoch||e.operationCredential.walletSessionId!==r.operationCredential.walletSessionId||e.operationCredential.token!==r.operationCredential.token)throw Error(`[SigningSession] planner ECDSA readiness authority does not match its lane`)}let r=Tn(e);if(r)return{kind:R.NotReady,lane:t,reason:r};let a=e.forceFreshAuth||e.sensitiveOperationPolicy===`require_fresh_same_method`||t.retention===`single_use`;if(n.status===`ready`&&!a){if(t.curve===`ed25519`&&n.curve===`ed25519`)return{kind:R.WarmSession,lane:t,keyRef:{kind:ye.Cached,curve:`ed25519`,thresholdSessionId:n.thresholdSessionId}};if(t.curve!==`ecdsa`||n.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:R.WarmSession,lane:t,keyRef:{kind:ye.Cached,curve:`ecdsa`,materialActivation:n.materialActivation,authorization:n.authorization}}}if(n.status===`auth_unavailable`||n.status===`status_unavailable`||n.status===`status_unknown`)return{kind:R.NotReady,lane:t,reason:n.status};if(L(t.auth)===`email_otp`)return{kind:R.EmailOtpReauth,lane:t,challenge:{chainFamily:t.chainFamily,lane:t}};if(t.curve===`ed25519`&&n.curve===`ed25519`)return{kind:R.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ed25519`,thresholdSessionId:n.thresholdSessionId}};if(t.curve!==`ecdsa`||n.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:R.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ecdsa`,materialActivation:n.materialActivation,authorization:n.authorization}}}function wn(e,t){return{event:`signing_planner_decision`,readinessStatus:e.readiness.status,forceFreshAuth:!!e.forceFreshAuth,...e.sensitiveOperationPolicy?{sensitiveOperationPolicy:e.sensitiveOperationPolicy}:{},plan:ve(t),lane:ge(e.lane),...t.kind===R.NotReady?{reason:t.reason}:{}}}function Tn(e){return L(e.lane.auth)===`email_otp`&&(e.sensitiveOperationPolicy===`deny_email_otp`||e.sensitiveOperationPolicy===`require_passkey`)?`policy_blocked`:null}async function En(e,t){let n=H(e),r=await He(t,Ve(n)).catch(()=>null);if(!r?.profileId)throw Error(`No profile/account mapping for account ${n}`);let i=await t.getLastProfileState().catch(()=>null);if(!i?.profileId||i.profileId!==r.profileId)throw Error(`No last user session for account ${n}`);let a=ke(i.activeSignerSlot,{min:1});if(a===null)throw Error(`Invalid last-user signerSlot for account ${n}`);return a}var K=function(e){return e.Query=`query`,e.Send=`send_tx`,e.Block=`block`,e}(K||{}),Dn=class e{transaction;signature;borsh_bytes;nonceLease;serverDispatch;constructor(e){this.transaction=e.transaction,this.signature=e.signature,this.borsh_bytes=e.borsh_bytes,e.nonceLease&&(this.nonceLease=e.nonceLease),e.serverDispatch&&(this.serverDispatch=e.serverDispatch)}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}encode(){return new Uint8Array(this.borsh_bytes).buffer}base64Encode(){return m(this.encode())}};function On(e){if(!e)return null;if(Array.isArray(e))return new Uint8Array(e).buffer;if(ArrayBuffer.isView(e)){let t=e;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return e instanceof ArrayBuffer?e:null}function kn(e){let t=e?.signedTransaction,n=t&&typeof t==`object`?t:e,r=n.base64Encode;if(c(r))return r.call(n);let i=n.encode;if(c(i))return m(i.call(n));let a=On(n.borsh_bytes);if(a)return m(a);let o=On(n.borshBytes);if(o)return m(o);throw Error(`Invalid signed transaction payload: cannot serialize to base64`)}var An=class e{rpcUrls;constructor(t){this.rpcUrls=e.normalizeRpcUrls(t)}static normalizeRpcUrls(e){let t=(Array.isArray(e)?e:e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean)).map(e=>{try{return new URL(e).toString()}catch(t){let n=k(t)||`Invalid NEAR RPC URL: ${e}`;throw Error(n)}});if(!t.length)throw Error(`NEAR RPC URL cannot be empty`);return Array.from(new Set(t))}errorFromHttpStatus(e){return Error(`RPC request failed: ${e.status} ${e.statusText}`)}errorFromFailedCall(e,t){return t}sendWithRetry(e){return e()}buildRequestBody(e,t){return JSON.stringify({jsonrpc:`2.0`,id:v(`near-rpc`,32,`NEAR JSON-RPC request IDs`),method:e,params:t})}async postOnce(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:t});if(!n.ok)throw this.errorFromHttpStatus(n);let r=await n.text();if(!r?.trim())throw Error(`Empty response from RPC server`);let i=Me(JSON.parse(r));if(!i.ok)throw Error(`Invalid NEAR JSON-RPC response: ${i.error}`);return i.value}async requestWithFallback(e){let t;for(let[n,r]of this.rpcUrls.entries())try{let t=await this.postOnce(r,e);return n>0&&console.warn(`[NearClient] RPC succeeded via fallback: ${r}`),t}catch(e){t=e;let i=n<this.rpcUrls.length-1;if(console.warn(`[NearClient] RPC call to ${r} failed${i?`, trying next`:``}: ${k(e)||`RPC request failed`}`),!i)throw e instanceof Error?e:Error(String(e))}throw Error(k(t)||`RPC request failed`)}unwrapRpcResult(e,t){if(e.kind===`failure`)throw this.errorFromRpc(t,e.error);let n=e.result;if(typeof n==`object`&&n&&`error`in n){let e=Reflect.get(n,`error`),r=typeof e==`string`?e:JSON.stringify(e);throw this.errorFromWrappedResult(`${t} Error: ${r}`)}return e.result}async makeRpcCall(e,t,n,r){let i=this.buildRequestBody(e,t);try{let e=await this.requestWithFallback(i);return r(this.unwrapRpcResult(e,n))}catch(e){throw this.errorFromFailedCall(n,e)}}async query(e,t){return this.makeRpcCall(K.Query,e,`Query`,t)}async viewAccessKey(e,t,n){let r={request_type:`view_access_key`,finality:n?.finality||`final`,account_id:e,public_key:t};return this.makeRpcCall(K.Query,r,`View Access Key`,oe)}async viewAccessKeyList(e,t){let n={request_type:`view_access_key_list`,finality:t?.finality||`final`,account_id:e};return this.makeRpcCall(K.Query,n,`View Access Key List`,F)}async viewAccount(e){let t={request_type:`view_account`,finality:`final`,account_id:e};return this.makeRpcCall(K.Query,t,`View Account`,N)}async viewCode(e,t){let n={request_type:`view_code`,finality:t?.finality||`final`,account_id:e};return g(await this.makeRpcCall(K.Query,n,`View Code`,A))}async viewBlock(e){return this.makeRpcCall(K.Block,e,`View Block`,ae)}async sendTransaction(e,t=`EXECUTED_OPTIMISTIC`){let n={signed_tx_base64:kn(e),wait_until:t};return this.sendWithRetry(async()=>{let e=await this.makeRpcCall(K.Send,n,`Send Transaction`,P),t=e.status;if(t&&typeof t==`object`&&`Failure`in t)throw this.errorFromOutcome(`Send Transaction`,e,t.Failure);return e})}async txStatus(e,t){let n={tx_hash:e,sender_account_id:t};return this.makeRpcCall(`EXPERIMENTAL_tx_status`,n,`Tx Status`,P)}async callFunction(e,t,n,r,i){let a={request_type:`call_function`,...i??{finality:`final`},account_id:e,method_name:t,args_base64:m(new TextEncoder().encode(JSON.stringify(n)).buffer)};return r(j((await this.makeRpcCall(K.Query,a,`View Function`,M)).result))}async view(e){return this.callFunction(e.account,e.method,e.args,e.decodeResult)}async getAccessKeys({account:e,block_id:t}){let n={request_type:`view_access_key_list`,account_id:e,finality:`final`};t&&(n.block_id=t,delete n.finality);let r=await this.makeRpcCall(K.Query,n,`View Access Key List`,F),i=[],a=[];for(let e of r.keys)e.access_key.permission===`FullAccess`?i.push(e):e.access_key.permission&&typeof e.access_key.permission==`object`&&`FunctionCall`in e.access_key.permission&&a.push(e);return{fullAccessKeys:i,functionCallAccessKeys:a}}};function jn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Mn(e){if(!e)return;let t=Object.keys(e);return t.length?t[0]:void 0}var Nn=class e extends Error{code;type;kind;index;short;details;operation;constructor(e){super(e.message),this.name=e.name||`NearRpcError`,this.code=e.code,this.type=e.type||`Unknown`,this.kind=e.kind,this.index=e.index,this.short=e.short,this.details=e.details,this.operation=e.operation}static fromOutcome(t,n,r){let{message:i,type:a,kind:o,index:s,short:c}=Fn(t,r);return new e({message:i||`${t} failed`,short:c||o||`TxExecutionError`,type:a||`Failure`,kind:o,index:s,name:`TxExecutionFailure`,operation:t,details:{Failure:r,outcome:n}})}static fromRpcError(t,n){let r=n.data,{message:i,type:a,kind:o,index:s,short:c}=Pn(t,r,n.message);return new e({message:i||n.message||`${t} RPC error`,short:c||o||`RPC error`,type:a||`RpcError`,kind:o,index:s,code:typeof n.code==`number`?n.code:void 0,name:n.name||`NearRpcError`,operation:t,details:r})}};function Pn(e,t,n=``){let r=jn(t)?t:void 0,i=jn(r?.TxExecutionError)?r.TxExecutionError:void 0;if(!i){let i=typeof t==`string`&&t.trim()?t.trim():r?JSON.stringify(r):n.trim();return{message:`${e} RPC error${i?`: ${i}`:``}`}}return In(e,i)}function Fn(e,t){let n=jn(t)?t:void 0;return n?In(e,n):{message:`${e} failed (Unknown Failure)`}}function In(e,t){if(jn(t.InvalidTxError)){let n=t.InvalidTxError,r=Mn(n)||`InvalidTxError`;jn(n.ActionsValidation)&&(r=`ActionsValidation.${Mn(n.ActionsValidation)}`);let i=r.startsWith(`ActionsValidation.`)?`InvalidTxError: ${r.split(`.`)[1]||`ActionsValidation`}`:`InvalidTxError: ${r}`;return{message:`${e} failed (InvalidTxError: ${r})`,type:`InvalidTxError`,kind:r,short:i}}if(jn(t.ActionError)){let n=t.ActionError,r=typeof n.index==`number`?n.index:void 0,i=Mn(jn(n.kind)?n.kind:void 0)||`ActionError`,a=typeof r==`number`?` at action ${r}`:``,o=`ActionError: ${i}`;return{message:`${e} failed${a} (ActionError: ${i})`,type:`ActionError`,kind:i,index:r,short:o}}return{message:`${e} failed (TxExecutionError)`,type:`TxExecutionError`,kind:`TxExecutionError`,short:`TxExecutionError`}}var Ln=class e extends Dn{transactionHash;constructor(e){super(e),this.transactionHash=e.transactionHash}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,transactionHash:a(t.transactionHash,`signed transaction hash`),...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}static decode(){throw Error(`SignedTransaction.decode(): borsh deserialization not implemented`)}},Rn=class extends An{errorFromRpc(e,t){return Nn.fromRpcError(e,t)}errorFromWrappedResult(e){return new Nn({message:e,short:`RpcError`,type:`RpcError`})}errorFromOutcome(e,t,n){return Nn.fromOutcome(e,t,n)}errorFromHttpStatus(e){return e.status===429?Error(`RPC throttled; retry shortly`):super.errorFromHttpStatus(e)}async sendWithRetry(e){let t=null;for(let n=1;n<=5;n++)try{return await e()}catch(e){t=e;let r=k(e);if(!/server error|internal|temporar|timeout|throttl|too many requests|429|unavailable|bad gateway|gateway timeout/i.test(r||``)||n===5)throw e;let i=200*2**(n-1),a=Math.floor(Math.random()*150);await new Promise(e=>setTimeout(e,i+a))}throw t instanceof Error?t:Error(String(t))}},zn=class extends Rn{sendWithRetry(e){return e()}};function Bn(e){try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,2)}catch{return String(e)}}function q(e,t,n){let r=String(t??``).trim();if(r)return{label:e,value:r,...typeof n==`string`&&n.trim()?{copyValue:n}:{}}}function Vn(e){switch(e.action_type){case U.Transfer:case U.FunctionCall:return BigInt(e.deposit||`0`);case U.Stake:return BigInt(e.stake||`0`);default:return BigInt(0)}}function Hn(e){try{let t=JSON.parse(e)?.permission;if(t===`FullAccess`)return`FullAccess`;if(t&&typeof t==`object`){if(`FullAccess`in t)return`FullAccess`;if(`FunctionCall`in t)return`FunctionCall`}}catch{return`Unknown`}return`Unknown`}function Un(e){let{action:t,txIndex:n,actionIndex:r,receiverId:i}=e,a=`near.tx.${n}.action.${r}`;switch(t.action_type){case U.CreateAccount:return{id:a,kind:`near.action`,actionType:`createAccount`,label:`Action ${r+1}: CreateAccount`,fields:[q(`Receiver`,i)].filter(Boolean)};case U.Transfer:return{id:a,kind:`near.action`,actionType:`transfer`,label:`Action ${r+1}: Transfer`,fields:[q(`Receiver`,i),q(`Amount (yoctoNEAR)`,t.deposit)].filter(Boolean)};case U.FunctionCall:{let e=String(t.args||``),n=e?[{id:`${a}.args`,kind:`raw.fallback`,label:`Function Arguments`,raw:e}]:[];return{id:a,kind:`near.action`,actionType:`functionCall`,label:`Action ${r+1}: FunctionCall`,fields:[q(`Receiver`,i),q(`Method`,t.method_name),q(`Gas`,t.gas),q(`Deposit (yoctoNEAR)`,t.deposit)].filter(Boolean),...n.length?{children:n}:{}}}case U.Stake:return{id:a,kind:`near.action`,actionType:`stake`,label:`Action ${r+1}: Stake`,fields:[q(`Receiver`,i),q(`Stake (yoctoNEAR)`,t.stake),q(`Validator Key`,t.public_key,t.public_key)].filter(Boolean)};case U.AddKey:return{id:a,kind:`near.action`,actionType:`addKey`,label:`Action ${r+1}: AddKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key),q(`Permission`,Hn(t.access_key))].filter(Boolean)};case U.DeleteKey:return{id:a,kind:`near.action`,actionType:`deleteKey`,label:`Action ${r+1}: DeleteKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key)].filter(Boolean)};case U.DeployContract:return{id:a,kind:`near.action`,actionType:`deployContract`,label:`Action ${r+1}: DeployContract`,fields:[q(`Receiver`,i),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case U.DeployGlobalContract:return{id:a,kind:`near.action`,actionType:`deployGlobalContract`,label:`Action ${r+1}: DeployGlobalContract`,fields:[q(`Receiver`,i),q(`Deploy Mode`,t.deploy_mode),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case U.UseGlobalContract:return{id:a,kind:`near.action`,actionType:`useGlobalContract`,label:`Action ${r+1}: UseGlobalContract`,fields:[q(`Receiver`,i),q(`By Account`,t.account_id),q(`By Code Hash`,t.code_hash,t.code_hash)].filter(Boolean)};case U.DeleteAccount:return{id:a,kind:`near.action`,actionType:`deleteAccount`,label:`Action ${r+1}: DeleteAccount`,fields:[q(`Receiver`,i),q(`Beneficiary`,t.beneficiary_id)].filter(Boolean)};case U.SignedDelegate:return{id:a,kind:`near.action`,actionType:`signedDelegate`,label:`Action ${r+1}: SignedDelegate`,children:[{id:`${a}.delegate`,kind:`raw.fallback`,label:`Signed Delegate Payload`,raw:Bn(t)}]};default:return{id:a,kind:`raw.fallback`,label:`Action ${r+1}: Unsupported`,raw:Bn(t)}}}function Wn(e,t,n){let r=String(e.receiverId||``).trim()||`(unknown receiver)`,i=Array.isArray(e.actions)?e.actions:[],a=i.reduce((e,t)=>e+Vn(t),BigInt(0)),o=[q(`Receiver`,r),q(`Action Count`,String(i.length)),q(`Attached Value (yoctoNEAR)`,a>0?a.toString():void 0)].filter(Boolean);return{id:`near.tx.${t}`,kind:`generic.contractCall`,label:n>1?`Transaction ${t+1}`:`Transaction`,to:r,value:a>0?a.toString():void 0,fields:o,children:i.map((e,n)=>Un({action:e,txIndex:t,actionIndex:n,receiverId:r}))}}function Gn(e){let t=Array.isArray(e.txSigningRequests)?e.txSigningRequests:[],n=t.map((e,n)=>Wn(e,n,t.length)),r=t.reduce((e,t)=>e+(Array.isArray(t.actions)?t.actions.reduce((e,t)=>e+Vn(t),BigInt(0)):BigInt(0)),BigInt(0));return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEAR Transaction`,subtitle:e.subtitle,operations:n,...r>0?{totals:{nativeValue:r.toString(),nativeSymbol:`yoctoNEAR`}}:{}}}function Kn(e){let t={id:`near.message`,kind:`near.message`,label:`Message signature`,fields:[q(`Signer`,e.signerAccount,e.signerAccount),q(`Recipient`,e.recipient,e.recipient),{label:`Message`,value:e.message,copyValue:e.message,renderAs:`file-content`,hideChevron:!0}].filter(Boolean)};return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEP-413 message`,subtitle:e.subtitle,operations:[t]}}function qn(e){try{return Gn(e)}catch{return{chain:`near`,signerAccount:e.signerAccount,...e.title?{title:e.title}:{},...e.subtitle?{subtitle:e.subtitle}:{},operations:[]}}}const Jn=e=>typeof e==`string`?e:V(be(e.keyData));function J(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?null:Math.round(e)}function Yn(e){if(e==null||!s(e))return;let t=e;if(t.kind!==`registration_confirmation_diagnostics_v1`)return;let n=J(t.workerReadyMs),r=J(t.workerRequestRoundTripMs),i=J(t.workerResponseValidationMs),a=J(t.requestSetupMs),o=J(t.promptUserMs),c=J(t.promptElementDefineMs),l=J(t.promptMountMs),u=J(t.promptHostFirstUpdateMs),d=J(t.promptHostInteractiveMs),f=J(t.promptConfirmEventMs),p=J(t.promptDecisionWaitMs),m=J(t.credentialCreateStartMs),h=J(t.credentialCreateMs),g=J(t.credentialSerializeMs),_=J(t.duplicateRetryCount),v=J(t.mainThreadTotalMs);if(!(n==null||r==null||i==null||a==null||o==null||c==null||l==null||u==null||d==null||f==null||p==null||m==null||h==null||g==null||_==null||v==null))return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:n,workerRequestRoundTripMs:r,workerResponseValidationMs:i,requestSetupMs:a,promptUserMs:o,promptElementDefineMs:c,promptMountMs:l,promptHostFirstUpdateMs:u,promptHostInteractiveMs:d,promptConfirmEventMs:f,promptDecisionWaitMs:p,credentialCreateStartMs:m,credentialCreateMs:h,credentialSerializeMs:g,duplicateRetryCount:_,mainThreadTotalMs:v}}function Xn(e){if(e==null)return;if(!s(e))throw Error(`Invalid transactionContext: expected object`);let{nearPublicKeyStr:t,nextNonce:n,txBlockHeight:r,txBlockHash:i,accessKeyInfo:a}=e,o=l(t,`transactionContext.nearPublicKeyStr`),c=l(n,`transactionContext.nextNonce`),u=l(r,`transactionContext.txBlockHeight`),d=l(i,`transactionContext.txBlockHash`),f=a;if(f!=null&&!s(f))throw Error(`Invalid transactionContext.accessKeyInfo: expected object`);return f??={nonce:0},{nearPublicKeyStr:o,nextNonce:c,txBlockHeight:u,txBlockHash:d,accessKeyInfo:f}}function Zn(e){if(e==null)return;let t=Ue(e);if(t.type!==`public-key`)throw Error(`Invalid credential.type: expected "public-key"`);let{id:n,rawId:r,response:i,authenticatorAttachment:a}=t;if(l(n,`credential.id`),l(r,`credential.rawId`),!s(i))throw Error(`Invalid credential.response: expected object`);let{clientDataJSON:o,attestationObject:c,transports:u}=i;if(l(o,`credential.response.clientDataJSON`),l(c,`credential.response.attestationObject`),!Array.isArray(u))throw Error(`Invalid credential.response.transports: expected string[]`);for(let e of u)if(typeof e!=`string`)throw Error(`Invalid credential.response.transports item: expected string`);if(a!=null&&typeof a!=`string`)throw Error(`Invalid credential.authenticatorAttachment: expected string | undefined`);return t}function Qn(e){if(!s(e))throw Error(`Invalid response payload: expected object`);let{confirmed:t,requestId:n,intentDigest:r,credential:i,transactionContext:a,registrationDiagnostics:o,error:c}=e,u=l(n,`requestId`),d=r==null?``:l(r,`intentDigest`),f=i==null?void 0:Zn(i);if(!f)throw Error(`Missing registration credential`);let p=a==null?void 0:Xn(a),m=Yn(o),h=c==null?void 0:l(c,`error`);return{confirmed:!!t,requestId:u,intentDigest:d,credential:f,...p?{transactionContext:p}:{},...m?{registrationDiagnostics:m}:{},...h==null?{}:{error:h}}}function $n(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`operation step-up preparation ref must be an object`);let t=e;if(Object.keys(t).length!==3||t.kind!==`near_operation_step_up_prepared_v1`)throw Error(`operation step-up preparation ref is invalid`);let n=String(t.handle||``).trim();if(!n.startsWith(`near-operation-step-up:`)||/\s/.test(n))throw Error(`operation step-up preparation handle is invalid`);return{kind:`near_operation_step_up_prepared_v1`,handle:n,challengeB64u:O(t.challengeB64u)}}const er=new Map,tr=new Map;function nr(e,t){let n=String(e||``).trim();if(!n)throw Error(`[SigningEngine][near] ${t} is required`);return n}function rr(e){er.set(nr(e.requestId,`requestId`),e.build)}function ir(e){er.delete(String(e||``).trim())}const ar={async prepare(e){let t=nr(e.requestId,`requestId`),n=er.get(t);if(!n)throw Error(`[SigningEngine][near] operation step-up preparation is unavailable`);er.delete(t);let r=e.kind===`near_transaction`?await n({kind:`near_transaction`,transactionContext:e.transactionContext,operationId:nr(e.operationId,`operationId`),operationFingerprint:nr(e.operationFingerprint,`operationFingerprint`),displayDigest:nr(e.displayDigest,`displayDigest`)}):await n({kind:`near_signature_only`,displayDigest:nr(e.displayDigest,`displayDigest`)}),i=await Ze(r.envelope),a=$n({kind:`near_operation_step_up_prepared_v1`,handle:`near-operation-step-up:${_(24,`operation step-up handle`)}`,challengeB64u:i});return tr.set(a.handle,{requestId:t,operation:r.operation}),a},cancel(e){let t=String(e.requestId||``).trim();t&&er.delete(t),e.handle&&tr.delete(e.handle);for(let[e,n]of tr)n.requestId===t&&tr.delete(e)}};function or(e){let t=nr(e.requestId,`requestId`),n=nr($n(e.ref).handle,`operation step-up handle`),r=tr.get(n);if(tr.delete(n),!r||r.requestId!==t)throw Error(`[SigningEngine][near] prepared operation step-up is unavailable`);return r.operation}function sr(e){if(!i(e.expected,e.actual))throw Error(`[SigningEngine][near] operation assertion changed material activation`)}const cr=new Map;function lr(e){let t=String(e||``).trim();if(!t)throw Error(`[SigningEngine][near] requestId is required`);return t}function ur(e){cr.set(lr(e.requestId),e.fund)}function dr(e){cr.delete(String(e||``).trim())}const fr={async fund(e){let t=lr(e.requestId),n=cr.get(t);if(!n)throw Error(`[SigningEngine][near] implicit-account funding is unavailable`);return cr.delete(t),await n(e.request)}};async function pr(e){let t=H(e.nearAccount.accountId),n=ke(e.signerSlot,{min:1});if(n===null)throw Error(`Invalid signerSlot for ${e.operationLabel}: ${e.signerSlot}`);if(e.requestedSignerSlot!==void 0){let t=ke(e.requestedSignerSlot,{min:1});if(t===null||t!==n)throw Error(`Requested signerSlot does not match the selected signing lane for ${e.operationLabel}`)}let r=await e.materialExecutor.resolveSigningKeyMaterial();if(r.nearAccountId!==t||r.signerSlot!==n)throw Error(`[SigningEngine] threshold key material does not match the selected lane`);return{thresholdKeyMaterial:r}}function mr(e){let t=gr({nearAccountId:e.nearAccountId,tx:e.transaction,txIndex:0});return{txSigningRequest:t,confirmationTransaction:{receiverId:t.receiverId,actions:t.actions}}}function hr(e){let t=e.delegate.actions.map(Se);t.forEach((e,t)=>{try{we(e)}catch(e){throw Error(`Delegate action ${t} validation failed: ${e instanceof Error?e.message:String(e)}`)}});let n={senderId:e.delegate.senderId||e.nearAccountId,receiverId:e.delegate.receiverId,actions:t,nonce:e.delegate.nonce,maxBlockHeight:e.delegate.maxBlockHeight};return{confirmationDelegate:n,workerDelegate:{...n,nonce:e.delegate.nonce.toString(),maxBlockHeight:e.delegate.maxBlockHeight.toString(),publicKey:e.signingPublicKey}}}function gr(e){let t=String(e.tx?.receiverId||``).trim();if(!t)throw Error(`[SigningEngine] transactions[${e.txIndex}].receiverId is required`);let n=Array.isArray(e.tx?.actions)?e.tx.actions:[];if(n.length===0)throw Error(`[SigningEngine] transactions[${e.txIndex}].actions must be non-empty`);for(let e=0;e<n.length;e++)we(n[e]);return{nearAccountId:e.nearAccountId,receiverId:t,actions:n}}async function _r(e){if(Ot(e.signingAuthPlan)&&!e.emailOtpEd25519StepUp)throw Error(`[SigningEngine][near] Email OTP step-up runner is unavailable`);if(Dt(e.signingAuthPlan)&&!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);let t=null,n=await zt({operation:{kind:`near_ed25519_step_up`,requiredSignatureUses:e.requiredSignatureUses},selectedLane:{authMethod:L(e.signingLaneAuth)},policy:Sr(e.signingAuthPlan),methods:{...e.emailOtpEd25519StepUp?{emailOtp:{method:`email_otp`,prepareChallenge:async()=>await e.emailOtpEd25519StepUp.prepare({operationFingerprintDigest:e.operationFingerprintDigest}),...e.emailOtpEd25519StepUp.resend?{resendChallenge:async()=>await e.emailOtpEd25519StepUp.resend({operationFingerprintDigest:e.operationFingerprintDigest})}:{},complete:yr}}:{},passkey:{method:`passkey`,prepare:async()=>{if(!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);return t=await e.passkeyEd25519OperationStepUp.prepare(),{}},complete:br}}}),r=e.signingAuthPlan;if(n.method===`warm_session`){if(!Cr(r))throw Error(`[SigningEngine][near] warm-session step-up requires a warm-session plan`);return{kind:`warm_session`,confirmationAuthPayload:{signingAuthPlan:r}}}if(n.method===`email_otp`){if(!Ot(r))throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP plan`);return{kind:`email_otp`,confirmationAuthPayload:{signingAuthPlan:{kind:`emailOtpReauth`,method:`email_otp`,emailOtpPrompt:n.prompt}},emailOtpPrompt:n.prompt}}if(!Dt(r))throw Error(`[SigningEngine][near] passkey step-up requires a passkey plan`);return{kind:`passkey`,confirmationAuthPayload:{signingAuthPlan:r},plannedPasskeyOperationStepUp:xr(t)}}function vr(e){switch(e.kind){case`voiceid`:throw Error(`Unlock with VoiceID again before signing.`);case`passkey`:return{kind:`passkeyReauth`,method:`passkey`};case`email_otp`:return{kind:`emailOtpReauth`,method:`email_otp`};default:throw Error(`[SigningEngine][near] unsupported material auth requirement`)}}async function yr(){}async function br(){}function xr(e){if(!e)throw Error(`[SigningEngine][near] Passkey operation step-up plan is required`);return e}function Sr(e){if(Et(e)){if(e.curve!==`ed25519`)throw Error(`[SigningEngine][near] warm-session step-up requires an Ed25519 auth plan`);return{kind:`reuse_warm_session`,authorization:{method:e.method,curve:`ed25519`,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}}return{kind:`use_selected_lane`}}function Cr(e){return Et(e)&&e.curve===`ed25519`}function wr(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Tr(e,t){let n=Rt(e.signingAuthPlan);if(t.phase===`confirmation.complete`){if(n===`passkey`&&t.status===`succeeded`)return}else if(n!==`passkey`||t.phase!==`auth.passkey.prompt.started`&&t.phase!==`auth.passkey.prompt.succeeded`)return;let r=Lt(t,n);r&&wr(e.onEvent,e.nearAccountId,{...r,authMethod:n})}function Er(e){return{kind:`warm_session`,signingAuthPlan:e,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}function Dr(e){if(e.prepared.kind===`warm_session`)return Er(e.prepared.confirmationAuthPayload.signingAuthPlan);if(e.prepared.kind===`email_otp`)return{kind:`email_otp`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,challengeId:kr(e.confirmation.emailOtpChallengeId,e.prepared.emailOtpPrompt.challengeId),otpCode:Or(e.confirmation.otpCode),...e.prepared.emailOtpPrompt.emailHint?{emailHint:e.prepared.emailOtpPrompt.emailHint}:{}};if(!e.confirmation.credential)throw Error(`[SigningEngine] missing WebAuthn credential for NEAR step-up authorization`);return{kind:`passkey`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,credential:We(e.confirmation.credential),plannedPasskeyOperationStepUp:e.prepared.plannedPasskeyOperationStepUp}}function Or(e){let t=String(e||``).trim();if(!/^\d{6}$/.test(t))throw Error(`[SigningEngine] missing Email OTP code for NEAR step-up authorization`);return t}function kr(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`[SigningEngine] missing Email OTP challenge id for NEAR step-up authorization`);return n}function Ar(e){if(!e||!Array.isArray(e.actions)||e.actions.length===0)throw Error(`[SigningEngine][near] one NEAR transaction with actions is required`);return 1}function jr(e){throw Error(`[SigningEngine][near] exactly one NEAR transaction is supported per signing operation; received ${e.length}`)}const Mr=2e4;async function Nr(e){return Br(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519ComputeNep413SigningDigest,timeoutMs:Mr,payload:{message:e.message,recipient:e.recipient,nonce:e.nonce,callbackUrl:e.callbackUrl}}}))}async function Pr(e){return Br(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519ComputeDelegateSigningDigest,timeoutMs:Mr,payload:{delegate:e.delegate}}}))}async function Fr(e){return Vr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519BuildDelegateSigningPayload,timeoutMs:Mr,payload:{delegate:e.delegate}}}))}async function Ir(e){return Hr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519FinalizeDelegateFromSignature,timeoutMs:Mr,payload:{delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u}}}))}async function Lr(e){let t=Ur(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519BuildNearTxUnsignedBorsh,timeoutMs:Mr,payload:{txSigningRequests:[e.txSigningRequest],transactionContext:e.transactionContext}}})),n=t[0];if(!n||t.length!==1)throw Error(`near signer worker returned invalid single-transaction unsigned payload`);return n}async function Rr(e){return Wr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519FinalizeNearTxFromSignature,timeoutMs:Mr,payload:{unsignedTransactionBorshB64u:e.unsignedTransactionBorshB64u,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,expectedNearAccountId:e.expectedNearAccountId,expectedSignerPublicKey:e.expectedSignerPublicKey}}}))}async function zr(e){return Gr(await Le({ctx:e.workerCtx,kind:`nearSigner`,request:{type:I.ThresholdEd25519DecodeSignedNearTxBorsh,timeoutMs:Mr,payload:{signedTransactionBorshB64u:e.signedTransactionBorshB64u}}}))}function Br(e){let t=e;if(!t?.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 signing digest result`);return t}function Vr(e){let t=e;if(!t?.canonicalDelegateBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 delegate signing payload`);return t}function Hr(e){let t=e;if(!t?.delegateAction||!t.signature||!t.borshBytes)throw Error(`near signer worker returned invalid Ed25519 signed delegate result`);return t}function Ur(e){if(!Array.isArray(e))throw Error(`near signer worker returned invalid Ed25519 unsigned tx result`);return e.map(e=>{let t=e;if(!t?.unsignedTransactionBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 unsigned tx item`);return t})}function Wr(e){let t=e;if(!t?.signedTransactionBorshB64u||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 finalized tx result`);return t}function Gr(e){let t=e;if(!t?.signedTransaction?.transaction||!t.signedTransaction.signature||!t.signedTransaction.borshBytes||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 signed tx decode result`);return t}function Kr(e,t){return e.request_id===t.request_id&&e.account_id===t.account_id&&e.authorization.kind===t.authorization.kind&&(e.authorization.kind===`reusable_wallet_session`?t.authorization.kind===`reusable_wallet_session`&&e.authorization.wallet_session_id===t.authorization.wallet_session_id:t.authorization.kind===`operation_step_up`)&&e.material_activation.kind===t.material_activation.kind&&e.material_activation.activation_id===t.material_activation.activation_id&&e.material_activation.capability===t.material_activation.capability&&e.material_activation.material_owner===t.material_activation.material_owner&&e.material_activation.key_binding===t.material_activation.key_binding&&e.material_activation.lifecycle_binding===t.material_activation.lifecycle_binding&&e.material_activation.signing_worker===t.material_activation.signing_worker&&e.signing_worker_id===t.signing_worker_id}function qr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Jr(e){if(!Kr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing prepare response scope mismatch`);if(e.request.expires_at_ms!==e.response.expires_at_ms)throw Error(`Router A/B normal-signing prepare response expiry mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing prepare response SigningWorker mismatch`);if(!qr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing prepare response payload digest mismatch`)}function Yr(e){if(!Kr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing response scope mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing response SigningWorker mismatch`);if(!qr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing response payload digest mismatch`);if(e.response.signature.bytes.length!==64)throw Error(`Router A/B normal-signing response signature must be 64 bytes`)}function Y(e,t){let n=String(e||``).trim();if(!n)throw Error(`Router A/B Ed25519 normal-signing ready state is missing ${t}`);return n}function X(e,t,n){if(e!==t)throw Error(`Router A/B Ed25519 normal-signing ready state ${n} mismatch`)}function Xr(e,t){let n=Math.floor(Number(e));if(!Number.isFinite(n)||n<=Date.now())throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is expired`);return n}function Zr(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is exhausted`);return n}function Qr(e){let t=e.state,n=t.signingWalletSession,r=Y(e.thresholdSessionId,`thresholdSessionId`),i=Y(t.thresholdSessionId,`state.thresholdSessionId`),a=Y(t.signingLane.thresholdSessionId,`state.signingLane.thresholdSessionId`);X(i,r,`thresholdSessionId`),X(a,r,`lane thresholdSessionId`);let o=Y(t.walletSessionId,`state.walletSessionId`),s=Y(t.quotaId,`state.quotaId`);X(t.signingLane.walletSessionId,o,`lane walletSessionId`),X(t.signingLane.quotaId,s,`lane quotaId`);let c=Y(e.nearAccountId,`nearAccountId`);Y(t.signingLane.identity.signer.account.wallet.walletId,`state.signingLane.identity.signer.account.wallet.walletId`),X(Y(e.thresholdKeyMaterial.nearAccountId,`thresholdKeyMaterial.nearAccountId`),c,`threshold key accountId`);let l=n.routerAbNormalSigning,u=Y(n.auth.walletSessionToken,`Wallet Session bearer token`),d=Y(t.signingRootId,`state.signingRootId`),f=Y(t.signingRootVersion,`state.signingRootVersion`);X(n.thresholdSessionId,r,`Wallet Session thresholdSessionId`),X(n.walletSessionId,o,`Wallet Session walletSessionId`),X(n.quotaId,s,`Wallet Session quotaId`),X(n.signingRootId,d,`signingRootId`),X(n.signingRootVersion,f,`signingRootVersion`),X(t.routerAbNormalSigning.signingWorkerId,l.signingWorkerId,`signingWorkerId`),Xr(n.expiresAtMs,`expiresAtMs`);let p=Zr(n.remainingUses,`remainingUses`);if(t.remainingUses!==p)throw Error(`Router A/B Ed25519 normal-signing ready state remainingUses mismatch`);return{kind:`router_ab_ed25519_normal_signing_ready_state_v1`,relayerUrl:Y(t.relayerUrl,`relayerUrl`),signingWorkerId:Y(l.signingWorkerId,`signingWorkerId`),signerPublicKey:Y(e.thresholdKeyMaterial.publicKey,`signerPublicKey`),credential:{kind:`wallet_session_opaque`,walletSessionToken:u,home:n.auth.credential.home}}}const $r=12e4;async function ei(e){return await e.ctx.resolveOperationStepUpCredential({walletId:e.walletId,relayerUrl:e.relayerUrl,proof:e.proof})}function ti(e){if(e.prepared.prepare.request.scope.authorization.kind!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization scope is missing`);if(e.issuedAuthorization.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization is invalid`)}function ni(e){let t=e.thresholdKeyMaterial.participants.find(t=>t.role===e.role)?.id;if(!t)throw Error(`threshold-ed25519 signing requires ${e.role} participant id`);return t}function ri(e){return[...h(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function ii(e){return te(e.chains||bt.network.chains)}function ai(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return`router-ab-normal-signing/${e}/${t.randomUUID()}`;if(t&&typeof t.getRandomValues==`function`){let n=new Uint8Array(16);return t.getRandomValues(n),`router-ab-normal-signing/${e}/${p(n)}`}throw Error(`secure randomness is unavailable for Router A/B normal-signing request id`)}function oi(e){if(!e.ok)throw Error(e.error.message);return e.value}function si(e){let t=Math.floor(Number(e.walletSessionExpiresAtMs)),n=Math.floor(Number(e.requestedTtlMs));if(!Number.isFinite(t)||t<=Date.now())throw Error(`[SigningEngine][near] Router A/B Ed25519 Wallet Session is expired`);if(!Number.isFinite(n)||n<=0)throw Error(`[SigningEngine][near] Router A/B Ed25519 request TTL is invalid`);return Math.min(t,Date.now()+n)}function ci(e){let t=e.walletSessionState.routerAbNormalSigning;if(!t)return null;let n=String(e.walletId||``).trim();if(!n)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing wallet id`);let r=Re(e.activeClient.metadata());return{request_id:ai(e.operationId),account_id:n,authorization:{kind:`reusable_wallet_session`,wallet_session_id:e.walletSessionState.walletSessionId},material_activation:{kind:`mpc_material_activation_ref`,activation_id:r.activationId,capability:r.capability,material_owner:r.materialOwner,key_binding:r.keyBinding,lifecycle_binding:r.lifecycleBinding,signing_worker:r.signingWorker},signing_worker_id:t.signingWorkerId}}function li(e){let t=e.materialFacts.routerAbNormalSigning;if(!t)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return{request_id:ai(e.operationId),account_id:String(e.walletId),authorization:{kind:`operation_step_up`},material_activation:{kind:`mpc_material_activation_ref`,activation_id:e.materialActivation.activationId,capability:e.materialActivation.capability,material_owner:e.materialActivation.materialOwner,key_binding:e.materialActivation.keyBinding,lifecycle_binding:e.materialActivation.lifecycleBinding,signing_worker:e.materialActivation.signingWorker},signing_worker_id:t.signingWorkerId}}function ui(e){return e.map(e=>{switch(e.action_type){case`CreateAccount`:return{action_type:U.CreateAccount};case`DeployContract`:return{action_type:U.DeployContract,code:[...e.code]};case`FunctionCall`:return{action_type:U.FunctionCall,method_name:e.method_name,args:e.args,gas:e.gas,deposit:e.deposit};case`Transfer`:return{action_type:U.Transfer,deposit:e.deposit};case`Stake`:return{action_type:U.Stake,stake:e.stake,public_key:e.public_key};case`AddKey`:return{action_type:U.AddKey,public_key:e.public_key,access_key:e.access_key};case`DeleteKey`:return{action_type:U.DeleteKey,public_key:e.public_key};case`DeleteAccount`:return{action_type:U.DeleteAccount,beneficiary_id:e.beneficiary_id};case`SignedDelegate`:{let t=ui(e.delegate_action.actions).map(Ce);return{action_type:U.SignedDelegate,delegate_action:{senderId:e.delegate_action.senderId,receiverId:e.delegate_action.receiverId,actions:t,nonce:e.delegate_action.nonce,maxBlockHeight:e.delegate_action.maxBlockHeight,publicKey:{keyType:e.delegate_action.publicKey.keyType,keyData:[...e.delegate_action.publicKey.keyData]}},signature:{keyType:e.signature.keyType,signatureData:[...e.signature.signatureData]}}}case`DeployGlobalContract`:return{action_type:U.DeployGlobalContract,code:[...e.code],deploy_mode:e.deploy_mode};case`UseGlobalContract`:return`account_id`in e?{action_type:U.UseGlobalContract,account_id:e.account_id}:{action_type:U.UseGlobalContract,code_hash:e.code_hash}}})}async function di(e){return{signedDelegate:await Ir({delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,workerCtx:e.ctx}),hash:ri(e.signingDigestB64u)}}function Z(e,t,n){if(String(e)!==String(t))throw Error(`Router A/B Ed25519 active Client ${n} mismatch`)}function fi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function pi(e,t){if(e.length!==32||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`Router A/B normal-signing ${t} must contain 32 bytes`);return Uint8Array.from(e)}function mi(e){let t=V(e);if(!t.startsWith(`ed25519:`))throw Error(`Router A/B Ed25519 signer public key must use ed25519`);let n=xe(t.slice(8));if(n.length!==32)throw Error(`Router A/B Ed25519 signer public key must decode to 32 bytes`);return n}function hi(e){let t=e.activeClient.metadata(),n=Re(t),r=e.materialFacts.signer,i=ni({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`client`}),a=ni({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`relayer`});if(e.thresholdKeyMaterial.participants.length!==2)throw Error(`Router A/B Ed25519 active Client requires exactly two participants`);Z(t.scope.account_id,e.prepare.request.scope.account_id,`scope account`),Z(t.scope.threshold_session_id,e.materialFacts.thresholdSessionId,`threshold session`),Z(t.scope.account_id,e.walletId,`scope wallet`),Z(n.activationId,e.prepare.request.scope.material_activation.activation_id,`material activation`),Z(n.capability,e.prepare.request.scope.material_activation.capability,`material capability`),Z(n.materialOwner,e.prepare.request.scope.material_activation.material_owner,`material owner`),Z(n.keyBinding,e.prepare.request.scope.material_activation.key_binding,`material key binding`),Z(n.lifecycleBinding,e.prepare.request.scope.material_activation.lifecycle_binding,`material lifecycle`),Z(n.signingWorker,e.prepare.request.scope.material_activation.signing_worker,`material SigningWorker`);let o=e.prepare.request.scope.authorization;if(o.kind!==e.authorization.kind)throw Error(`Router A/B Ed25519 authorization kind mismatch`);switch(e.authorization.kind){case`reusable_wallet_session`:if(o.kind!==`reusable_wallet_session`)throw Error(`Router A/B Ed25519 reusable authorization is missing`);Z(o.wallet_session_id,e.authorization.walletSessionId,`authorization session`);break;case`operation_step_up`:if(o.kind!==`operation_step_up`)throw Error(`Router A/B Ed25519 operation step-up authorization is missing`);break;default:e.authorization}Z(t.scope.signing_worker_id,e.prepare.request.scope.signing_worker_id,`scope SigningWorker`),Z(t.scope.signing_worker_id,e.signingWorkerId,`prepare SigningWorker`),Z(t.applicationBinding.wallet_id,e.walletId,`application wallet`),Z(t.applicationBinding.wallet_id,r.account.wallet.walletId,`lane wallet`),Z(t.applicationBinding.near_ed25519_signing_key_id,r.nearEd25519SigningKeyId,`signing key`),Z(t.applicationBinding.signing_root_id,e.materialFacts.signingRootId,`signing root`),Z(t.applicationBinding.key_creation_signer_slot,r.signerSlot,`signer slot`),Z(t.applicationBinding.key_creation_signer_slot,e.thresholdKeyMaterial.signerSlot,`key-material signer slot`),Z(t.participantIds[0],i,`Client participant`),Z(t.participantIds[1],a,`SigningWorker participant`);let s=mi(e.thresholdKeyMaterial.publicKey);if(!fi(t.registeredPublicKey,s))throw Error(`Router A/B Ed25519 active Client registered public key mismatch`);if(!fi(t.signingWorkerVerifyingShare,e.signingWorkerVerifyingShare))throw Error(`Router A/B Ed25519 active Client SigningWorker verifying share mismatch`)}async function gi(e){let t=e.prepare.request.intent.operation_id,n=performance.now(),r=`failed`;try{let n=await _i(e,t);return r=`succeeded`,n}finally{G(t,`signature_total`,n,r)}}async function _i(e,t){let n=h(e.signingDigestB64u);if(n.length!==32)throw Error(`Router A/B normal-signing ${e.signingPayloadLabel} must be 32 bytes`);let r=pi(e.prepare.admissionMaterial.admittedSigningDigest.bytes,`admitted digest`);if(!fi(n,r))throw Error(`Router A/B normal-signing admitted digest mismatch`);e.authorization===`reusable_wallet_session`&&Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial});let i=e.authorization===`reusable_wallet_session`?{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}:e.materialFacts,a=performance.now(),o=e.startedResponse?await e.startedResponse:await vt({relayServerUrl:i.relayerUrl,credential:e.credential,request:e.prepare.request});if(G(t,`prepare`,a),e.authorization===`reusable_wallet_session`){if(o.kind!==`reusable_wallet_session`)throw Error(`Ed25519 prepare returned the wrong authorization kind`);let t=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.walletSessionState,nowMs:Date.now()}),n=o.sessionStatus;if(!t||n.walletSessionId!==t.walletSessionOperationCredential.walletSessionId||n.quotaId!==t.walletSessionAuthorization.quotaId||n.quotaLifecycle!==`active`||n.remainingUses<=0||n.expiresAtMs<=Date.now()||!ee(n.authorization,t.walletSessionAuthorization))throw Error(`Wallet Session authority changed before Ed25519 client signing`);let r={relayerUrl:i.relayerUrl,operationCredential:t.walletSessionOperationCredential};await Ie.fromPrepare(r,n).read(r,{walletSessionId:n.walletSessionId,quotaId:n.quotaId})}else if(o.kind!==`operation_step_up`)throw Error(`Ed25519 step-up prepare returned a reusable Wallet Session`);let s=o.signing;Jr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:s});let c=h(s.server_verifying_share_b64u);if(c.length!==32)throw Error(`Router A/B normal-signing SigningWorker verifying share must be 32 bytes`);hi({activeClient:e.activeClient,authorization:e.authorization===`reusable_wallet_session`?{kind:`reusable_wallet_session`,walletSessionId:e.walletSessionState.signingWalletSession.walletSessionId}:{kind:`operation_step_up`},materialFacts:i,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,prepare:e.prepare,signingWorkerId:s.signing_worker.server_id,signingWorkerVerifyingShare:c});let l=performance.now(),u=await e.activeClient.createSigningShare({admittedDigest:r,signingWorkerCommitments:s.server_commitments,signingWorkerVerifyingShare:c});if(G(t,`client_share`,l),u.clientVerifyingShare.length!==32)throw Error(`Router A/B normal-signing Client verifying share must be 32 bytes`);let d=performance.now(),f=await St({relayServerUrl:i.relayerUrl,credential:e.credential,request:ht({scope:e.prepare.request.scope,expiresAtMs:e.prepare.request.expires_at_ms,prepareResponse:s,admissionMaterial:e.prepare.admissionMaterial,clientCommitments:u.clientCommitments,clientVerifyingShareB64u:p(u.clientVerifyingShare),clientSignatureShareB64u:u.clientSignatureShareB64u})});return G(t,`finalize`,d),Yr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:f}),{signatureB64u:Ct(f.signature,`Router A/B normal-signing signature`),signerPublicKey:e.thresholdKeyMaterial.publicKey}}async function vi(e){let t=ii(e.ctx);return e.intent.kind===`nep413_message_v1`?await _t({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,message:e.intent.message,recipient:e.intent.recipient,nonce:e.intent.nonce,callbackUrl:e.intent.callbackUrl,expectedSigningDigestB64u:e.signingDigestB64u}):await yt({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,publicKey:e.intent.delegate.publicKey,nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,actionFingerprint:await gt(e.intent.delegate.actions),canonicalDelegateBorshB64u:(await Fr({delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,actions:ui(e.intent.delegate.actions),nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,publicKey:e.intent.delegate.publicKey},workerCtx:e.ctx})).canonicalDelegateBorshB64u},expectedSigningDigestB64u:e.signingDigestB64u})}async function yi(e){let t=li({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),n=await vi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:Date.now()+$r,nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}),r=$e({tenantId:oi(E(e.materialFacts.runtimePolicyScope.orgId)),principalId:oi(C(String(e.walletId))),capabilityId:oi(D(e.materialActivation.capability)),operationId:oi(ie(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:e.intent.kind===`nep413_message_v1`?`near.sign_nep413_message`:`near.sign_delegate_action`},digests:{laneDigest:Qe(e.operationFingerprint),intentDigest:O(p(Uint8Array.from(n.admissionMaterial.intentDigest.bytes))),displayDigest:O(e.displayDigest)}});return{operation:{kind:`near_signature_only`,prepare:n,signingDigestB64u:e.signingDigestB64u,materialActivation:e.materialActivation},envelope:r}}function bi(e){if(e.auth.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);let t=e.preparation.hydration.authority;if(!t||String(t.walletId)!==String(e.walletId))throw Error(`[SigningEngine][near] Email OTP material authority changed`);return{kind:`email_otp`,authorityRef:t,providerSubjectId:e.auth.providerSubjectId,challengeId:e.challengeId,otpCode:e.otpCode}}function xi(e){switch(e.authorization.kind){case`passkey`:return{kind:`passkey`,authority:e.authorization.plannedPasskeyOperationStepUp.authority,credential:e.authorization.credential};case`email_otp`:return bi({preparation:e.preparation,auth:Si(e.auth),walletId:e.walletId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode});default:throw e.authorization,Error(`[SigningEngine][near] unsupported operation step-up authorization`)}}function Si(e){if(e.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);return e}function Ci(e){if(!e)throw Error(`[SigningEngine][near] operation step-up proof is missing`);return e}function wi(e){return e.authorization.kind===`operation_step_up`}async function Ti(e){if(e.issuedAuthorization)return e.issuedAuthorization;switch(e.proof.kind){case`passkey`:return await Sn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});case`email_otp`:return await Sn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});default:throw e.proof,Error(`[SigningEngine][near] unsupported operation step-up proof`)}}async function Ei(e){if(wi(e)){let t=Re(e.activeClient.metadata());if(sr({expected:e.authorization.prepared.materialActivation,actual:t}),e.authorization.prepared.signingDigestB64u!==e.signingDigestB64u)throw Error(`[SigningEngine][near] signature-only operation digest changed`);let n=e.authorization.prepared.prepare,r=await ei({ctx:e.ctx,walletId:e.walletId,relayerUrl:e.materialFacts.relayerUrl,proof:e.authorization.proof}),i=await Ti({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:e.materialFacts.relayerUrl,normalSigningRequest:n.request,displayDigest:e.displayDigest,proof:e.authorization.proof,credential:r});if(n.request.scope.authorization.kind!==`operation_step_up`||i.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);return{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:i,...await gi({thresholdSessionId:e.thresholdSessionId,materialFacts:e.materialFacts,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,credential:r,authorization:`operation_step_up`})}}let t=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===e.signingDigestB64u?e.startedPrepare:null;e.startedPrepare&&!t&&ki(e.startedPrepare);let n=t?.prepare??await Di(e);return n?{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`reusable_wallet_session`,...await gi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,startedResponse:t?.response,credential:Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential,authorization:e.authorization.kind})}:null}async function Di(e){let t=ci({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});return t?await vi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:si({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:$r}),nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}):null}async function Oi(e){let t=await Di(e);if(!t)return null;let n=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),r=performance.now(),i=vt({relayServerUrl:e.walletSessionState.relayerUrl,credential:n.credential,request:t.request});return i.catch(()=>{}),G(String(e.operationId),`prepare_sent`,r),{prepare:t,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,response:i}}function ki(e){e.response.catch(()=>{})}async function Ai(e){let t=await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=ii(e.ctx),r=ue(e.txSigningRequest,`txSigningRequest`),i=await xt({scope:li({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),expiresAtMs:Date.now()+$r,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n,transactions:[{receiverId:r.receiverId,actionFingerprint:await gt(r.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u}),a=$e({tenantId:oi(E(e.materialFacts.runtimePolicyScope.orgId)),principalId:oi(C(String(e.walletId))),capabilityId:oi(D(e.materialActivation.capability)),operationId:oi(ie(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:`near.sign_transaction`},digests:{laneDigest:Qe(e.operationFingerprint),intentDigest:O(p(Uint8Array.from(i.admissionMaterial.intentDigest.bytes))),displayDigest:O(e.displayDigest)}});return{operation:{kind:`near_transaction`,prepare:i,unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u,materialActivation:e.materialActivation},envelope:a}}function ji(e){return e.authorization.kind===`operation_step_up`}function Mi(e){return ji(e)?e.materialFacts:{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}}async function Ni(e,t){let n=ii(e.ctx),r=ue(e.txSigningRequest,`txSigningRequest`);return{nearNetworkId:n,parsedTransaction:r,operationFingerprint:z.signingOperationFingerprint(await ce({nearAccountId:e.nearAccountId,nearNetworkId:n,relayerKeyId:e.thresholdKeyMaterial.relayerKeyId,signerPublicKey:e.thresholdKeyMaterial.publicKey,transactions:[r],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u}))}}async function Pi(e,t,n){let r=ci({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});if(!r)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return await xt({scope:r,expiresAtMs:si({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:$r}),operationId:e.operationId,operationFingerprint:n.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n.nearNetworkId,transactions:[{receiverId:n.parsedTransaction.receiverId,actionFingerprint:await gt(n.parsedTransaction.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u})}async function Fi(e){let t=await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=await Pi(e,t,await Ni(e,t)),r=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),i=performance.now(),a=vt({relayServerUrl:e.walletSessionState.relayerUrl,credential:r.credential,request:n.request});return a.catch(()=>{}),G(String(e.operationId),`prepare_sent`,i),{prepare:n,displayDigest:e.displayDigest,signingDigestB64u:t.signingDigestB64u,response:a}}async function Ii(e){let t=Mi(e);if(!t.routerAbNormalSigning)throw Error(`[SigningEngine][near] Router A/B Ed25519 normal-signing state is missing`);if(!e.transactionContext)throw Error(`[SigningEngine][near] Router A/B Ed25519 transaction signing is missing transaction context from confirmation`);let n=ji(e),r=n?{unsignedTransactionBorshB64u:e.authorization.prepared.unsignedTransactionBorshB64u,signingDigestB64u:e.authorization.prepared.signingDigestB64u}:await Lr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx});if(h(r.signingDigestB64u).length!==32)throw Error(`Router A/B normal-signing NEAR payload digest must be 32 bytes`);let i=await Ni(e,r),a=null,o,s,c;if(n){o=e.authorization.prepared.prepare,s=await ei({ctx:e.ctx,walletId:e.walletId,relayerUrl:t.relayerUrl,proof:e.authorization.proof});let n=await Ti({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:t.relayerUrl,normalSigningRequest:o.request,displayDigest:e.authorization.displayDigest,proof:e.authorization.proof,credential:s});if(o.request.scope.authorization.kind!==`operation_step_up`||n.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);c=n}else a=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===r.signingDigestB64u?e.startedPrepare:null,e.startedPrepare&&!a&&ki(e.startedPrepare),o=a?a.prepare:await Pi(e,r,i),s=Qr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential;e.ctx.beforeSigning?.();let l=ji(e)?await gi({thresholdSessionId:e.thresholdSessionId,materialFacts:t,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`operation_step_up`}):await gi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`reusable_wallet_session`,startedResponse:a?.response}),u=await Rr({unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,signingDigestB64u:r.signingDigestB64u,signatureB64u:l.signatureB64u,expectedNearAccountId:e.nearAccountId,expectedSignerPublicKey:e.thresholdKeyMaterial.publicKey,workerCtx:e.ctx}),d=await zr({signedTransactionBorshB64u:u.signedTransactionBorshB64u,workerCtx:e.ctx}),f=u.transactionHash||d.transactionHash,p={type:le.SignTransactionsWithActionsSuccess,payload:{free:()=>void 0,success:!0,transactionHashes:[f],signedTransactions:[d.signedTransaction],logs:[`NEAR transaction signed through Router A/B normal signing`],error:void 0}};if(n){if(!c)throw Error(`[SigningEngine][near] operation step-up authorization was not issued`);return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:c,okResponse:p}}return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`reusable_wallet_session`,okResponse:p}}const Li=1e3,Ri=[120,180,250,350,500,700,1e3,1e3,1500,1500,2e3],zi=Symbol(`NearWalletSessionFundingAuthority`);function Bi(e=Li){return new Promise(t=>{setTimeout(t,e)})}function Vi(e){let t=String(e.walletSessionToken||``).trim();if(!t)throw Error(`[SigningEngine][near] authenticated Wallet Session token is required for funding`);return t}function Hi(e){return{kind:`near_ed25519_funding_session`,signer:e.signingLane.identity.signer,thresholdSessionId:e.thresholdSessionId,walletSessionToken:e.walletSessionAuth.walletSessionToken}}function Ui(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:return Gi(e)}}function Wi(e){switch(e){case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:throw Error(`[SigningEngine][near] unsupported operation step-up funding method`)}}function Gi(e){throw Error(`Unsupported NEAR funding authorization: ${String(e)}`)}function Ki(e){let t=String(e.fundingSession.signer.account.wallet.walletId),n=String(e.fundingSession.signer.account.nearAccountId),r=e.request.operation;if(String(e.request.subject.walletId)!==t||String(e.request.subject.nearAccountId)!==n||e.request.subject.nearPublicKeyStr!==e.nearPublicKeyStr)throw Error(`[SigningEngine][near] funding request subject does not match authenticated lane`);if(String(r.operationId)!==String(e.signingOperation.operationId)||String(r.operationFingerprint)!==String(e.signingOperation.operationFingerprint)||r.intent!==e.signingOperation.intent||r.accountId!==n)throw Error(`[SigningEngine][near] funding request operation does not match signing operation`);if(e.request.signatureUses!==e.signatureUses)throw Error(`[SigningEngine][near] funding request signature use count mismatch`);if(String(e.fundingSession.thresholdSessionId).trim().length===0)throw Error(`[SigningEngine][near] funding authority threshold session mismatch`)}function qi(e){return{kind:`near_wallet_session_funding_authority`,provenance:e.provenance,request:e.request,thresholdSessionId:e.fundingSession.thresholdSessionId,walletSessionToken:Vi(e.fundingSession),[zi]:!0}}async function Ji(e){let t=e.authority.request,n=ct({chains:e.ctx.chains,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr}),r;for(let i=1;i<=12;i+=1)try{let r=await e.ctx.nonceCoordinator.reserveNearContext({lane:n,operation:t.operation,count:t.signatureUses,nearClient:e.ctx.nearClient});return{transactionContext:r.context,nonceLeases:r.leases.map(Fe),reservedLeases:r.leases}}catch(e){r=e,i<12&&await Bi(Ri[i-1]??Li)}throw r instanceof Error?r:Error(`Funded NEAR account access key did not become available`)}async function Yi(e){let t=e.authority.request,n=await ze({relayerUrl:e.ctx.relayerUrl,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr,walletSessionToken:e.authority.walletSessionToken});if(!n.ok)throw Error(n.message||n.code||`Failed to fund implicit NEAR account`);return await Ji(e)}async function Xi(e){switch(e.confirmation.readiness.kind){case`context_ready`:return e.confirmation.readiness;case`funding_required`:{Ki({request:e.confirmation.readiness.request,fundingSession:Hi(e.walletSessionState),nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=qi({request:e.confirmation.readiness.request,fundingSession:Hi(e.walletSessionState),provenance:Ui(e.authorization)}),n=await Yi({ctx:e.ctx,authority:t});return{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases}}default:return Zi(e.confirmation.readiness)}}function Zi(e){throw Error(`Unsupported confirmed NEAR transaction readiness: ${String(e)}`)}async function Qi(e){Ki({request:e.request,fundingSession:e.fundingSession,nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=qi({request:e.request,fundingSession:e.fundingSession,provenance:Wi(e.method)}),n=await Yi({ctx:e.ctx,authority:t});return{readiness:{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases},reservedNonceLeases:n.reservedLeases}}function $i(e){switch(e.kind){case`passkey_live`:case`email_otp_live`:return e.material.facts;case`passkey_sealed`:case`email_otp_sealed`:return e.facts;default:throw Error(`[SigningEngine][near] unsupported operation material`)}}async function ea(e,t){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return await t.resolve(e);case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] material requires public-anchor reauthorization`);case`blocked`:throw Error(`[SigningEngine][near] material hydration is blocked: ${e.hydration.reason}`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Ed25519 Yao hydration plan`)}}async function ta(e){if(e.method===`passkey`&&e.preparation.hydration.kind===`rehydrate_material_activation`){let t=await e.executor.preparePasskeyOperationStepUp(e.preparation);return{kind:`passkey_sealed`,materialActivation:t.materialActivation,facts:t.facts,rehydrate:t.rehydrate}}if(e.method===`email_otp`){let t=await e.executor.prepareEmailOtpOperationStepUp(e.preparation);switch(t.kind){case`live`:return{kind:`email_otp_live`,materialActivation:t.materialActivation,material:t.material};case`sealed`:return{kind:`email_otp_sealed`,materialActivation:t.materialActivation,facts:t.facts,authorizeAndRehydrate:t.authorizeAndRehydrate};default:throw Error(`[SigningEngine][near] unsupported Email OTP operation material`)}}let t=await ea(e.preparation,e.executor);return{kind:`passkey_live`,materialActivation:Re(t.activeClient.metadata()),material:t}}async function na(e){sr({expected:e.expectedActivation,actual:e.material.materialActivation});let t,n=null;if(e.kind===`email_otp_live`||e.kind===`email_otp_sealed`)if(e.kind===`email_otp_live`)t=e.material.material;else{let r=await e.material.authorizeAndRehydrate({normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof});t=r.material,n=r.issuedAuthorization}else t=e.material.kind===`passkey_live`?e.material.material:await e.material.rehydrate(e.credential);try{return sr({expected:e.expectedActivation,actual:Re(t.activeClient.metadata())}),{material:t,issuedAuthorization:n}}catch(n){throw(e.material.kind===`passkey_sealed`||e.material.kind===`email_otp_sealed`)&&t.activeClient.dispose(),n}}async function ra(e){let t=await ea(e.preparation,e.executor);return{thresholdSessionId:t.facts.thresholdSessionId,material:t,walletSessionState:await e.executor.resolveWalletSessionState()}}function ia(e){if(!e)throw Error(`[SigningEngine][near] confirmed operation step-up is missing preparation`);return e}function aa(e){if(!e)throw Error(`[SigningEngine][near] prepared operation step-up is missing`);if(e.kind!==`near_transaction`)throw Error(`[SigningEngine][near] prepared operation step-up is not a transaction`);return e}function oa(e){if(!e)throw Error(`[SigningEngine][near] transaction operation material is unavailable`);return e}function sa(e){e.owned&&e.resolved?.material.activeClient.dispose()}function ca(e,t){throw sa(e),t}async function la(e){return{material:await ea(e.preparation,e.executor),walletSessionState:await e.executor.resolveWalletSessionState()}}function ua(e){if(!e)throw Error(`[SigningEngine][near] warm signing material was not prepared`);return e}async function da(e){let t=await e.warmMaterial,n=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.walletSessionState,nowMs:Date.now()});if(!n)return null;let r=await ot([{receiverId:e.confirmationTransaction.receiverId,actions:e.confirmationTransaction.actions.map(it)}]);return await Fi({ctx:e.ctx,thresholdSessionId:t.material.facts.thresholdSessionId,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:t.material.activeClient,walletSessionState:n,operationId:e.operationId,displayDigest:r,txSigningRequest:e.txSigningRequest,transactionContext:e.readiness.transactionContext})}function fa(){return null}async function pa(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey transaction material changed factor`);return await na({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP transaction material changed factor`);if(e.proof.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP transaction proof is missing`);return e.material.kind===`email_otp_live`?await na({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await na({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.proof})}function Q(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}async function ma(e){let t=performance.now(),n=`failed`;try{if(!e.state)throw Error(`[SigningEngine][near] reusable Wallet Session state is unavailable`);let t=await e.coordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.state,nowMs:Date.now()});if(!t)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return n=`succeeded`,t}finally{G(e.operationId,`wallet_session_authorization`,t,n)}}async function ha(e){let t=await ta({method:e.method,preparation:e.preparation,executor:e.executor}),n=$i(t);if(String(n.thresholdSessionId)!==e.expectedThresholdSessionId)throw Error(`[SigningEngine][near] prepared operation material changed threshold session`);return rr({requestId:e.requestId,build:async r=>{if(r.kind!==`near_transaction`)throw Error(`[SigningEngine][near] transaction step-up preparation kind changed`);if(r.operationId!==String(e.operation.operationId))throw Error(`[SigningEngine][near] operation step-up operation identity changed`);return await Ai({...e.operation,thresholdSessionId:n.thresholdSessionId,materialFacts:n,materialActivation:t.materialActivation,transactionContext:r.transactionContext,displayDigest:r.displayDigest})}}),ur({requestId:e.requestId,fund:async t=>await Qi({...e.funding,request:t,fundingSession:await e.executor.resolveFundingSession(),method:e.method})}),t}function ga(e){ir(e),dr(e)}function _a(e){if(!e.readiness){ga(e.requestId);return}e.readiness.then(ga.bind(void 0,e.requestId),ga.bind(void 0,e.requestId))}function va(e){return e.selection.kind===`authorization_required`}async function ya(e){return va(e)?await ba(e):await xa(e)}async function ba(e){let{ctx:t,commandSubject:n,nearAccount:r,transaction:i,rpcCall:a,onEvent:o,confirmationConfigOverride:s,title:c,body:l,signerSlot:u,signingOperationState:d,signingSessionCoordinator:f,selection:p,yaoSigningPreparation:m,yaoMaterialExecutor:h,passkeyEd25519OperationStepUp:g,emailOtpEd25519StepUp:_}=e,v=d.operationId,y=p.candidate,b=H(r.accountId),ee=[];if(!t.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);if(!f)throw Error(`[SigningEngine][near] production signing session coordinator is required`);let{thresholdKeyMaterial:re}=await pr({materialExecutor:h,nearAccount:r,signerSlot:y.signerSlot,requestedSignerSlot:u,operationLabel:`signing`,warnings:ee}),x=Ta({nearAccountId:b,relayerUrl:t.relayerUrl,thresholdKeyMaterial:re}),ie={nearRpcUrl:a.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},{txSigningRequest:S,confirmationTransaction:C}=mr({nearAccountId:String(b),transaction:i}),w=ue(S,`txSigningRequest`),T=z.signingOperationFingerprint(await se({nearAccountId:b,nearNetworkId:te(t.chains||bt.network.chains),relayerKeyId:x.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:x.threshold.thresholdKeyMaterial.publicKey,transactions:[w]}));f.bindCallerProvidedOperationIdToFingerprint({operationId:v,operationFingerprint:T});let E=Qe(T),D={kind:`deferred_ed25519_material_identity`,signer:Ye({walletId:y.walletId,nearAccountId:y.nearAccountId,nearEd25519SigningKeyId:y.nearEd25519SigningKeyId,signerSlot:y.signerSlot}),materialActivation:y.materialActivation,thresholdSessionId:z.thresholdEd25519Session(y.thresholdSessionId)},O={kind:R.OperationStepUp,lane:{identity:D,auth:y.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:D.materialActivation,thresholdSessionId:D.thresholdSessionId}},k=vr(y.auth),A={operationId:v,operationFingerprint:T,intent:_e.TransactionSign},j=await _r({signingAuthPlan:k,signingLaneAuth:y.auth,requiredSignatureUses:Ar(i),operationFingerprintDigest:E,...g?{passkeyEd25519OperationStepUp:g}:{},..._?{emailOtpEd25519StepUp:_}:{}});if(j.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred Ed25519 transaction cannot use warm session`);let ae=Ar(i),oe=ha({requestId:String(v),expectedThresholdSessionId:String(D.thresholdSessionId),method:j.kind,preparation:m,executor:h,operation:{ctx:t,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:b,operationId:v,operationFingerprint:T,txSigningRequest:S},funding:{ctx:t,nearPublicKeyStr:x.signingNearPublicKeyStr,signingOperation:A,signatureUses:ae}}),M;try{M=await Ft({signingSessionPlan:O,signingOperation:A,signingOperationState:d,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:String(v),chain:`near`,kind:`transaction`,...Pt({signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan}),walletId:y.walletId,txSigningRequests:[C],rpcCall:ie,nearPublicKeyStr:x.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:y.walletId,nearAccountId:b,nearPublicKeyStr:x.signingNearPublicKeyStr},operation:{...A,accountId:String(b)},signatureUses:ae},confirmationConfigOverride:It({signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan,override:s}),title:c,body:l,confirmationReadiness:{promise:oe},onProgress:Tr.bind(void 0,{onEvent:o,nearAccountId:b,signingAuthPlan:j.confirmationAuthPayload.signingAuthPlan})}})}finally{_a({requestId:String(v),readiness:oe})}let N=await oe,P=$i(N),F=Dr({prepared:j,confirmation:M});if(F.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred transaction requires operation step-up`);let I=xi({authorization:F,preparation:m,auth:y.auth,walletId:n.walletSession.walletId}),ce=aa(or({requestId:String(v),ref:ia(M.operationStepUpPreparation)})),le=await pa({material:N,prepared:ce,displayDigest:M.intentDigest,authorization:F,proof:Ci(I)});Q(o,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Rt(j.confirmationAuthPayload.signingAuthPlan)});try{if(await t.nonceCoordinator.recoverDurableLeases({walletId:String(y.walletId)}),M.readiness.kind!==`context_ready`)throw Error(`[SigningEngine][near] implicit-account funding requires transaction context`);let e=await Ii({ctx:t,thresholdSessionId:P.thresholdSessionId,activeClient:le.material.activeClient,materialFacts:P,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:b,operationId:v,operationFingerprint:T,displayDigest:M.intentDigest,txSigningRequest:S,transactionContext:M.readiness.transactionContext,authorization:{kind:`operation_step_up`,prepared:ce,displayDigest:M.intentDigest,proof:Ci(I),issuedAuthorization:le.issuedAuthorization}});if(!e||e.authorization!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up transaction signing is unavailable`);ti({prepared:ce,issuedAuthorization:e.issuedAuthorization});let r=wa({okResponse:e.okResponse,nearAccountId:b,warnings:ee,nonceLeases:M.readiness.nonceLeases});return await Ca(t,M.readiness.nonceLeases),r}finally{sa({resolved:le,owned:N.kind===`passkey_sealed`||N.kind===`email_otp_sealed`})}}async function xa({ctx:e,commandSubject:t,nearAccount:n,transaction:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:s,body:c,signerSlot:l,signingOperationState:u,signingSessionCoordinator:d,transactionOperation:f,ed25519SigningBoundary:p,passkeyEd25519OperationStepUp:m,emailOtpEd25519StepUp:h,yaoSigningPreparation:g,yaoMaterialExecutor:_}){let v=performance.now(),y=u.operationId,b=H(n.accountId),ee=e.relayerUrl,re=[],x=e.nonceCoordinator.recoverDurableLeases({walletId:String(t.walletSession.walletId)});x.catch(()=>{}),Q(a,b,{phase:W.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:ie}=await pr({materialExecutor:_,nearAccount:n,signerSlot:p.signingLane.identity.signer.signerSlot,requestedSignerSlot:l,operationLabel:`signing`,warnings:re}),S=Ta({nearAccountId:b,relayerUrl:ee,thresholdKeyMaterial:ie}),C={nearRpcUrl:i.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},{txSigningRequest:w,confirmationTransaction:T}=mr({nearAccountId:String(C.nearAccountId),transaction:r}),E=ue(w,`txSigningRequest`),D=z.signingOperationFingerprint(await se({nearAccountId:b,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:S.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:S.threshold.thresholdKeyMaterial.publicKey,transactions:[E]})),O=Qe(D);if(!e.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);let k=e.touchConfirm;if(!d)throw Error(`[SigningEngine][near] production signing session coordinator is required`);d.bindCallerProvidedOperationIdToFingerprint({operationId:y,operationFingerprint:D});let A=Ar(r),j={operationId:y,operationFingerprint:D,intent:_e.TransactionSign},ae=async e=>await At({signingSessionPlan:p.signingSessionPlan,signingOperation:j,commandKind:e.commandKind,execute:e.execute}),oe=p.thresholdSessionId,M=String(oe||``).trim(),N=p.signingAuthPlan,P=p.signingLane;if(!f)throw Error(`[SigningEngine][near] threshold transaction signing requires prepared transaction operation`);if(Et(N)&&N.thresholdSessionId!==oe)throw Error(`[SigningEngine][near] warm-session auth plan must match prepared session identity`);let F={thresholdSessionId:Et(N)?N.thresholdSessionId:oe,lane:P,signingAuthPlan:N,confirmationAuthPayload:{signingAuthPlan:N},warmSessionReady:Et(N)},I=P,ce=new Set,le=e=>{ce.has(e)||(ce.add(e),tt(`near`,rt({event:`auth_side_effect_started`,lane:I,sideEffect:e,phase:`confirmed`})))},de=e=>{e.phase===`auth.passkey.prompt.started`&&le(`passkey_reauth`),Tr({onEvent:a,nearAccountId:b,signingAuthPlan:F.confirmationAuthPayload.signingAuthPlan},e)},fe=await _r({signingAuthPlan:N,signingLaneAuth:P.auth,requiredSignatureUses:A,operationFingerprintDigest:O,...m?{passkeyEd25519OperationStepUp:m}:{},...h?{emailOtpEd25519StepUp:h}:{}}),pe=fe.kind===`warm_session`?la({preparation:g,executor:_}):null;pe?.catch(()=>{});let me=fe.confirmationAuthPayload;Et(me.signingAuthPlan)&&Q(a,b,{phase:W.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:me.signingAuthPlan.thresholdSessionId,expiresAtMs:me.signingAuthPlan.expiresAtMs,remainingUses:me.signingAuthPlan.remainingUses}});let he=!Vt(u.current);he&&Q(a,b,{phase:W.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let ge=fe.kind===`warm_session`?null:ha({requestId:M,expectedThresholdSessionId:M,method:fe.kind,preparation:g,executor:_,operation:{ctx:e,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,txSigningRequest:w},funding:{ctx:e,nearPublicKeyStr:S.signingNearPublicKeyStr,signingOperation:j,signatureUses:A}});G(String(y),`pre_confirmation`,v);let L=null,R=n=>{L||!pe||(L=da({ctx:e,warmMaterial:pe,sessionCoordinator:d,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,txSigningRequest:w,confirmationTransaction:T,readiness:n}).catch(fa))},ve=performance.now(),B;try{B=await Ft({signingSessionPlan:p.signingSessionPlan,signingOperation:j,signingOperationState:u,runtime:k,request:{ctx:{touchConfirm:k},sessionId:M,chain:`near`,kind:`transaction`,...Pt({signingAuthPlan:me.signingAuthPlan}),...pe?{onNearTransactionContextReady:R}:{},walletId:String(P.identity.signer.account.wallet.walletId),txSigningRequests:[T],rpcCall:C,nearPublicKeyStr:S.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:P.identity.signer.account.wallet.walletId,nearAccountId:b,nearPublicKeyStr:S.signingNearPublicKeyStr},operation:{...j,accountId:String(b)},signatureUses:A},confirmationConfigOverride:It({signingAuthPlan:me.signingAuthPlan,override:o}),title:s,body:c,...ge?{confirmationReadiness:{promise:ge}}:{},onProgress:de}})}finally{_a({requestId:M,readiness:ge})}let ye=performance.now();G(String(y),`confirmation`,ve);let be=ge?await ge:null;he&&Q(a,b,{phase:W.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let V=Dr({prepared:fe,confirmation:B}),xe=V.kind===`warm_session`?null:xi({authorization:V,preparation:g,auth:f.lane.auth,walletId:t.walletSession.walletId}),Se=V.kind===`warm_session`?null:or({requestId:M,ref:ia(B.operationStepUpPreparation)}),Ce=V.kind===`warm_session`?null:await pa({material:oa(be),prepared:aa(Se),displayDigest:B.intentDigest,authorization:V,proof:Ci(xe)}),we=be?.kind===`passkey_sealed`||be?.kind===`email_otp_sealed`,U=performance.now();try{await x,G(String(j.operationId),`durable_lease_recovery_wait`,U)}catch(e){throw G(String(j.operationId),`durable_lease_recovery_wait`,U,`failed`),sa({resolved:Ce,owned:we}),e}let Te=!1,{canonicalThresholdSessionId:Ee,activeClient:De,walletSessionState:Oe,operationMaterialFacts:ke,issuedAuthorization:Ae,transactionContext:je,nonceLeaseRefs:Me}=await ae({commandKind:Nt.PreparePayload,execute:async()=>{Q(a,b,{phase:W.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let t=performance.now(),n=V.kind===`warm_session`?{kind:`warm_session`,resolved:await ua(pe)}:{kind:`operation_step_up`,resolved:Ce};G(String(j.operationId),`material_resolution_wait`,t);let r=(n.kind,n.resolved.material.facts.thresholdSessionId),i=(n.kind,n.resolved.material.activeClient),o=n.kind===`warm_session`?n.resolved.walletSessionState:null,s=performance.now(),c=n.kind===`warm_session`?await Xi({confirmation:B,ctx:e,nearPublicKeyStr:S.signingNearPublicKeyStr,walletSessionState:o,authorization:V,signingOperation:j,signatureUses:A}):B.readiness.kind===`context_ready`?B.readiness:(()=>{throw Error(`[SigningEngine][near] operation step-up confirmation did not resolve a transaction context`)})();return G(String(j.operationId),`transaction_context`,s),Q(a,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:F.warmSessionReady?`warm_session`:F.signingAuthPlan.method}),Q(a,b,{phase:W.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:r,clientBaseSource:`yao_active_client`}}),{canonicalThresholdSessionId:r,activeClient:i,walletSessionState:o,operationMaterialFacts:n.kind===`operation_step_up`?n.resolved.material.facts:null,issuedAuthorization:n.kind===`operation_step_up`?n.resolved.issuedAuthorization:null,transactionContext:c.transactionContext,nonceLeaseRefs:c.nonceLeases}}}).catch(ca.bind(void 0,{resolved:Ce,owned:we})),Ne=async t=>{Te||!Me.length||await Sa(e,Me,`signing_failed`).catch(e=>{console.warn(`[SigningEngine][near][transaction] failed to release nonce leases`,{originalError:t instanceof Error?t.message:String(t||``),releaseError:e instanceof Error?e.message:String(e||``)})})},Pe=async n=>{Q(a,b,{phase:W.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let r=V.kind===`warm_session`?await Ii({ctx:e,thresholdSessionId:Ee,activeClient:n,sessionCoordinator:d,walletSessionState:await ma({state:Oe,coordinator:d,operationId:String(j.operationId)}),thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,displayDigest:B.intentDigest,txSigningRequest:w,transactionContext:je,authorization:{kind:`reusable_wallet_session`},startedPrepare:L?await L:null}):await Ii({ctx:e,thresholdSessionId:Ee,activeClient:n,materialFacts:ke,thresholdKeyMaterial:S.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:b,operationId:j.operationId,operationFingerprint:D,displayDigest:B.intentDigest,txSigningRequest:w,transactionContext:je,authorization:{kind:`operation_step_up`,prepared:aa(Se),displayDigest:B.intentDigest,proof:V.kind===`passkey`?{kind:`passkey`,authority:V.plannedPasskeyOperationStepUp.authority,credential:V.credential}:{...bi({preparation:g,auth:f.lane.auth,walletId:t.walletSession.walletId,challengeId:V.challengeId,otpCode:V.otpCode})},issuedAuthorization:Ae}});if(r)return r.okResponse;throw Error(`[SigningEngine][near] Router A/B Ed25519 signing is unavailable`)};return await ae({commandKind:Nt.Sign,execute:async()=>{try{let t=await Pe(De);Te=!0;let n=performance.now();await Ca(e,Me),G(String(j.operationId),`nonce_lease_commit`,n);let r=performance.now(),i=wa({okResponse:t,nearAccountId:b,warnings:re,nonceLeases:Me});return G(String(j.operationId),`transaction_assembly`,r),G(String(j.operationId),`confirmed_to_signed`,ye),Q(a,b,{phase:W.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),Q(a,b,{phase:W.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign`}}),i}catch(e){let t=e instanceof Error?e:Error(String(e));throw await Ne(t),sa({resolved:Ce,owned:we}),t}}})}async function Sa(e,t,n){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.release({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint,reason:n})))}async function Ca(e,t){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.markSigned({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint})))}function wa(e){let t=e.okResponse.payload.signedTransactions||[];if(t.length!==1)throw Error(`Expected one signed transaction but received ${t.length}`);let n=t[0];if(!n||!n.transaction||!n.signature)throw Error(`Incomplete signed transaction data received`);let r=e.nonceLeases?.[0],i=e.okResponse.payload.transactionHashes?.[0];if(!i)throw Error(`Signed transaction is missing its hash`);let a=n.serverDispatch;return{signedTransaction:new Ln({transaction:n.transaction,signature:n.signature,borsh_bytes:Array.from(n.borshBytes||[]),transactionHash:i,...r?{nonceLease:r}:{},...a?{serverDispatch:a}:{}}),nearAccountId:H(e.nearAccountId),logs:[...e.okResponse.payload.logs||[],...e.warnings],...r?{nonceLease:r}:{}}}function Ta(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);let r=String(e.relayerUrl||``).trim();if(!r)throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=f(t.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:n,threshold:{relayerUrl:r,thresholdKeyMaterial:t}}}function Ea(e){let t=e.selectedLane.identity.signer,n=Ee(e.commandSubject.walletSession.walletId),r=String(e.commandSubject.nearAccount.accountId);if(t.account.wallet.walletId!==n||String(t.account.nearAccountId)!==r)throw Error(`[SigningEngine][near] selected Ed25519 lane does not match command subject`);return{walletId:n,nearAccountId:r}}function Da(e){let t=e.selectedLane.identity.signer,n={walletId:t.account.wallet.walletId,nearAccountId:t.account.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,walletSessionId:e.selectedLane.walletSessionId,quotaId:e.selectedLane.quotaId,thresholdSessionId:e.selectedLane.thresholdSessionId};switch(e.selectedLane.auth.kind){case`voiceid`:return Xe({...n,auth:e.selectedLane.auth,storageSource:`login`});case`passkey`:return Xe({...n,auth:e.selectedLane.auth,storageSource:`login`});case`email_otp`:{let t=e.preparation.authorization.kind===`authorized`;return Xe({...n,auth:e.selectedLane.auth,retention:t?`session`:`single_use`,sessionOrigin:t?`login`:`per_operation`})}default:throw e.selectedLane.auth,Error(`[SigningEngine][near] unsupported selected Ed25519 auth binding`)}}function Oa(e){let t=z.thresholdEd25519Session(e.selectedLane.thresholdSessionId);switch(e.preparation.authorization.kind){case`authorized`:{let n=e.preparation.authorization.authorization.status,r=n.remainingUses,i=n.expiresAtMs,a=i<=Date.now()?`expired`:r<e.requiredSignatureUses?`exhausted`:`ready`;return{readiness:a===`expired`?{status:`expired`,curve:`ed25519`,thresholdSessionId:t,expiresAtMs:i}:{status:a,curve:`ed25519`,thresholdSessionId:t,remainingUses:r,expiresAtMs:i},expiresAtMs:i,remainingUses:r,forceFreshAuth:a!==`ready`}}case`authorization_required`:return{readiness:{status:`missing_session`,curve:`ed25519`,thresholdSessionId:t},expiresAtMs:0,remainingUses:0,forceFreshAuth:!0};default:throw e.preparation.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function ka(e){Ea(e);let t=Math.max(1,Math.floor(Number(e.requiredSignatureUses)||1)),n=Da(e),r=Oa({selectedLane:e.selectedLane,preparation:e.preparation,requiredSignatureUses:t});return nt(`near`,n,{reason:`near_threshold_auth_plan`}),{thresholdSessionId:z.thresholdEd25519Session(e.selectedLane.thresholdSessionId),lane:n,coordinatorInput:{lane:n,readiness:r.readiness,expiresAtMs:r.expiresAtMs,remainingUses:r.remainingUses,forceFreshAuth:e.forceFreshAuth||r.forceFreshAuth}}}function Aa(e){let{lane:t}=e.context,n=e.resolvedSigningSession,r=n.signingSessionPlan;if(r.kind===R.NotReady)throw Error(`[SigningEngine][near] signing session is not ready: ${r.reason}`);return{signingAuthPlan:Bt({plan:r,accountId:String(t.identity.signer.account.nearAccountId),intent:_e.TransactionSign,curve:`ed25519`,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses})}}function ja(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up preparation is missing`);return t}function Ma(e,t){if(!t||t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e} operation step-up preparation kind changed`);return t}function Na(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up material is missing`);return t}function Pa(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation signing digest is missing`);return t}function Fa(e){if(!e)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e}async function Ia(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey ${e.label} material changed factor`);return await na({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP ${e.label} material changed factor`);if(!e.emailOtpProof)throw Error(`[SigningEngine][near] Email OTP ${e.label} proof is missing`);return e.material.kind===`email_otp_live`?await na({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await na({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.emailOtpProof})}function La(e){if(e.selection.kind===`authorized`){let t=ka({requiredSignatureUses:1,commandSubject:e.commandSubject,forceFreshAuth:e.forceFreshAuth,selectedLane:e.selection.selectedLane,preparation:e.preparation}),n={signingSessionPlan:Cn({lane:t.coordinatorInput.lane,readiness:t.coordinatorInput.readiness,forceFreshAuth:t.coordinatorInput.forceFreshAuth}),readiness:t.coordinatorInput.readiness,expiresAtMs:t.coordinatorInput.expiresAtMs||0,remainingUses:t.coordinatorInput.remainingUses||0};return{signingAuthPlan:Aa({context:t,resolvedSigningSession:n}).signingAuthPlan,signingSessionPlan:n.signingSessionPlan}}let t=e.selection.candidate,n=vr(t.auth),r={kind:`deferred_ed25519_material_identity`,signer:Ye({walletId:t.walletId,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot}),materialActivation:t.materialActivation,thresholdSessionId:z.thresholdEd25519Session(t.thresholdSessionId)};return{signingAuthPlan:n,signingSessionPlan:{kind:R.OperationStepUp,lane:{identity:r,auth:t.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:r.materialActivation,thresholdSessionId:r.thresholdSessionId}}}}async function Ra(e,t){let n=await _r({signingAuthPlan:t.signingAuthPlan,signingLaneAuth:e.auth,requiredSignatureUses:1,operationFingerprintDigest:Qe(e.signingOperation.operationFingerprint),passkeyEd25519OperationStepUp:t.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:t.emailOtpEd25519StepUp});if(n.kind===`warm_session`)return{preparedStepUp:n,operationStepUp:null};let r=await ta({method:n.kind,preparation:e.preparation,executor:e.executor}),i=$i(r),a=await e.computeSigningDigestB64u();return rr({requestId:String(e.signingOperation.operationId),build:async t=>{if(t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e.label} operation step-up preparation kind changed`);return await yi({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,materialFacts:i,walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:r.materialActivation,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:a,intent:e.intent})}}),{preparedStepUp:n,operationStepUp:{material:r,signingDigestB64u:a}}}async function za(e,t){let n=String(e.signingOperation.operationId);try{return await Mt({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:n,chain:`near`,...t.request,...Pt({signingAuthPlan:t.signingAuthPlan}),walletId:String(e.walletId),nearAccountId:e.nearAccountId,nearPublicKeyStr:t.nearPublicKeyStr,title:t.title,body:t.body,confirmationConfigOverride:It({signingAuthPlan:t.signingAuthPlan,override:t.confirmationConfigOverride}),onProgress:Tr.bind(void 0,{onEvent:t.onEvent,nearAccountId:e.nearAccountId,signingAuthPlan:t.signingAuthPlan})}})}finally{ir(n)}}function Ba(e,t,n){let r=Dr({prepared:t.preparedStepUp,confirmation:n});if(r.kind===`warm_session`)return{kind:`warm_session`,displayDigest:n.intentDigest,stepUpAuthorization:r};let i=xi({authorization:r,preparation:e.preparation,auth:e.auth,walletId:e.walletId}),a=Ma(e.label,or({requestId:String(e.signingOperation.operationId),ref:ja(e.label,n.operationStepUpPreparation)}));return{kind:`operation_step_up`,displayDigest:n.intentDigest,stepUpAuthorization:r,proof:i,prepared:a,...Na(e.label,t.operationStepUp)}}async function Va(e,t,n,r){if(t.preparedStepUp.kind!==`warm_session`)return null;let i=await ra({preparation:e.preparation,executor:e.executor}),a=Fa(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:i.walletSessionState,nowMs:Date.now()})),o=await Oi({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,activeClient:i.material.activeClient,walletSessionState:a,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:r,signingDigestB64u:await e.computeSigningDigestB64u(),intent:e.intent});return o?{resolved:i,started:o}:null}async function Ha(e,t,n=null){if(t.kind===`warm_session`){let r=n?.resolved??await ra({preparation:e.preparation,executor:e.executor});return{kind:`warm_session`,thresholdSessionId:r.thresholdSessionId,displayDigest:t.displayDigest,resolved:r,startedPrepare:n?.started}}return n&&ki(n.started),{kind:`operation_step_up`,thresholdSessionId:$i(t.material).thresholdSessionId,displayDigest:t.displayDigest,resolved:await Ia({label:e.label,material:t.material,prepared:t.prepared,displayDigest:t.displayDigest,authorization:t.stepUpAuthorization,emailOtpProof:t.proof.kind===`email_otp`?t.proof:null}),proof:t.proof,prepared:t.prepared,signingDigestB64u:t.signingDigestB64u}}async function Ua(e,t,n){let r=t.kind===`warm_session`?await e.computeSigningDigestB64u():Pa(e.label,t.signingDigestB64u),i=t.kind===`warm_session`?await Ei({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,sessionCoordinator:n,walletSessionState:Fa(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.resolved.walletSessionState,nowMs:Date.now()})),walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`reusable_wallet_session`},startedPrepare:t.startedPrepare}):await Ei({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,materialFacts:t.resolved.material.facts,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`operation_step_up`,prepared:t.prepared,proof:t.proof,issuedAuthorization:t.resolved.issuedAuthorization}});if(!i)throw Error(`[SigningEngine][near] Router A/B Ed25519 ${e.label} signing is unavailable`);return t.kind===`operation_step_up`&&i.authorization===`operation_step_up`&&ti({prepared:t.prepared,issuedAuthorization:i.issuedAuthorization}),{signingDigestB64u:r,signatureB64u:i.signatureB64u,signerPublicKey:i.signerPublicKey}}async function Wa(e,t){return await At({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,commandKind:Nt.Sign,execute:async()=>{try{return await t()}catch(e){throw e instanceof Error?e:Error(String(e))}}})}function $(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Ga(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey`;case`email_otp`:return`email_otp`;default:return Ka(e)}}function Ka(e){throw Error(`[SigningEngine][near] unsupported prepared step-up: ${String(e)}`)}async function qa({ctx:e,commandSubject:t,nearAccount:n,delegate:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:s,body:c,operationId:l,signerSlot:u,signingSessionCoordinator:d,forceFreshAuth:f,passkeyEd25519OperationStepUp:p,emailOtpEd25519StepUp:m,yaoSigningPreparation:h,yaoMaterialExecutor:g,selection:_}){let v=_.kind===`authorized`?_.selectedLane.auth:_.candidate.auth,y=_.kind===`authorized`?_.selectedLane.identity.signer.signerSlot:_.candidate.signerSlot,b=H(n.accountId),ee=e.relayerUrl,re={nearRpcUrl:i.nearRpcUrl||ne(bt.network.chains),nearAccountId:b},x=[],ie=e.touchConfirm;if(!ie)throw Error(`UiConfirm bridge not available for delegate signing`);let{signingAuthPlan:S,signingSessionPlan:C}=La({selection:_,commandSubject:t,forceFreshAuth:f,preparation:h});$(a,b,{phase:W.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:w}=await pr({materialExecutor:g,nearAccount:n,signerSlot:y,requestedSignerSlot:u,operationLabel:`delegate signing`,warnings:x}),T=Ja({nearAccountId:b,relayerUrl:ee,thresholdKeyMaterial:w,providedDelegatePublicKey:r.publicKey,warnings:x}),E=hr({nearAccountId:b,delegate:r,signingPublicKey:T.delegatePublicKeyStr}),D={...E.workerDelegate,actions:E.workerDelegate.actions.map((e,t)=>pe(e,`delegate.actions[${t}]`))},O={operationId:l,operationFingerprint:z.signingOperationFingerprint(await fe({nearAccountId:b,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:T.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:T.delegatePublicKeyStr,delegate:D})),intent:_e.TransactionSign},k={label:`delegate`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:b,auth:v,signingSessionPlan:C,signingOperation:O,thresholdKeyMaterial:T.threshold.thresholdKeyMaterial,preparation:h,executor:g,intent:{kind:`near_delegate_action_v1`,delegate:D},computeSigningDigestB64u:async()=>(await Pr({delegate:E.workerDelegate,workerCtx:e})).signingDigestB64u},A=await Ra(k,{signingAuthPlan:S,passkeyEd25519OperationStepUp:p,emailOtpEd25519StepUp:m}),j=A.preparedStepUp.confirmationAuthPayload;Et(j.signingAuthPlan)&&$(a,b,{phase:W.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:j.signingAuthPlan.thresholdSessionId,expiresAtMs:j.signingAuthPlan.expiresAtMs,remainingUses:j.signingAuthPlan.remainingUses}});let ae=await Va(k,A,d,await ot([{receiverId:E.confirmationDelegate.receiverId,actions:E.confirmationDelegate.actions.map(it)}])),oe=performance.now();$(a,b,{phase:W.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let M=await za(k,{touchConfirm:ie,signingAuthPlan:j.signingAuthPlan,nearPublicKeyStr:T.signingNearPublicKeyStr,onEvent:a,title:s,body:c,confirmationConfigOverride:o,request:{kind:`delegate`,delegate:E.confirmationDelegate,rpcCall:re}});G(String(l),`confirmation`,oe),$(a,b,{phase:W.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let N=Ba(k,A,M),P=await At({signingSessionPlan:C,signingOperation:O,commandKind:Nt.PreparePayload,execute:async()=>{$(a,b,{phase:W.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let e=await Ha(k,N,ae);return $(a,b,{phase:W.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Ga(A.preparedStepUp)}),$(a,b,{phase:W.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:e.thresholdSessionId,clientBaseSource:`yao_active_client`}}),e}}),F=await Wa(k,async()=>{$(a,b,{phase:W.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let t=await Ua(k,P,d),n=await di({ctx:e,delegate:E.workerDelegate,signingDigestB64u:t.signingDigestB64u,signatureB64u:t.signatureB64u});return{type:le.SignDelegateActionSuccess,payload:{success:!0,hash:n.hash,signedDelegate:n.signedDelegate,logs:[`Delegate action signed through Router A/B normal signing`],error:void 0}}});return $(a,b,{phase:W.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),$(a,b,{phase:W.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign_delegate`,hash:F.payload.hash}}),{signedDelegate:F.payload.signedDelegate,hash:F.payload.hash,nearAccountId:H(b),logs:[...F.payload.logs||[],...x]}}function Ja(e){let t=V(Jn(e.providedDelegatePublicKey)),n=e.thresholdKeyMaterial;if(!n)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let r=V(n.publicKey);if(!r)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(t&&t!==r&&e.warnings.push(`Delegate public key ${t} does not match threshold signer key; using ${r}`),!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=f(n.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:r,delegatePublicKeyStr:r,threshold:{thresholdKeyMaterial:n}}}async function Ya({ctx:e,commandSubject:t,nearAccount:n,signingSessionCoordinator:r,payload:i,forceFreshAuth:a,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:s,yaoSigningPreparation:c,yaoMaterialExecutor:l,selection:u,onEvent:d}){let f=u.kind===`authorized`?u.selectedLane.auth:u.candidate.auth,p=u.kind===`authorized`?u.selectedLane.identity.signer.signerSlot:u.candidate.signerSlot,g=i.operationId,_=performance.now(),v=e.relayerUrl,y=n.accountId,b=e.touchConfirm;if(!b)throw Error(`UiConfirm bridge not available for NEP-413 signing`);let{signingAuthPlan:ee,signingSessionPlan:ne}=La({selection:u,commandSubject:t,forceFreshAuth:a,preparation:c}),{thresholdKeyMaterial:re}=await pr({materialExecutor:l,nearAccount:n,signerSlot:p,requestedSignerSlot:i.signerSlot,operationLabel:`NEP-413 signing`}),x=Xa({nearAccountId:y,relayerUrl:v,thresholdKeyMaterial:re}),ie={operationId:g,operationFingerprint:z.signingOperationFingerprint(await de({nearAccountId:y,nearNetworkId:te(e.chains||bt.network.chains),relayerKeyId:x.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:x.threshold.thresholdKeyMaterial.publicKey,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl})),intent:_e.TransactionSign},S={label:`NEP-413`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:y,auth:f,signingSessionPlan:ne,signingOperation:ie,thresholdKeyMaterial:x.threshold.thresholdKeyMaterial,preparation:c,executor:l,intent:{kind:`nep413_message_v1`,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl},computeSigningDigestB64u:async()=>(await Nr({message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl,workerCtx:e})).signingDigestB64u},C=await Ra(S,{signingAuthPlan:ee,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:s}),w=await Va(S,C,r,await at({nearAccountId:y,recipient:i.recipient,message:i.message}));G(String(g),`pre_confirmation`,_);let T=performance.now(),E=await za(S,{touchConfirm:b,signingAuthPlan:C.preparedStepUp.confirmationAuthPayload.signingAuthPlan,nearPublicKeyStr:x.nearPublicKey,onEvent:d,title:i.title,body:i.body,confirmationConfigOverride:i.confirmationConfigOverride,request:{kind:`nep413`,message:i.message,recipient:i.recipient}});G(String(g),`confirmation`,T);let D=performance.now(),O=Ba(S,C,E),k=await At({signingSessionPlan:ne,signingOperation:ie,commandKind:Nt.PreparePayload,execute:async()=>await Ha(S,O,w)}),A=await Wa(S,async()=>{let e=await Ua(S,k,r);return{type:le.SignNep413MessageSuccess,payload:{accountId:y,publicKey:e.signerPublicKey,signature:m(h(e.signatureB64u)),state:i.state??void 0}}});return G(String(g),`confirmed_to_signed`,D),{success:!0,accountId:A.payload.accountId,publicKey:A.payload.publicKey,signature:A.payload.signature,state:A.payload.state}}function Xa(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let r=f(t.participants.map(e=>e.id));if(!r||r.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(r||[]).join(`,`)}])`);return{nearPublicKey:n,threshold:{thresholdKeyMaterial:t}}}async function Za(e){if(e.chain!==`near`)throw Error(`[NearSigningFlow] invalid chain`);return e.kind===`transactionWithActions`?(Qa(e.payload),await ya(e.payload)):e.kind===`delegateAction`?(eo(e.payload),await qa(e.payload)):e.kind===`nep413`?(to(e.payload),await Ya(e.payload)):e}function Qa(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);let n=e.transactions;Array.isArray(n)&&jr(n),$a(e.transaction,0)}function $a(e,t){if(!String(e?.receiverId||``).trim())throw Error(`[NearSigningFlow] transactions[${t}].receiverId is required`);let n=Array.isArray(e?.actions)?e.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] transactions[${t}].actions must be non-empty`);n.forEach(we)}function eo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);if(!String(e.delegate?.receiverId||``).trim())throw Error(`[NearSigningFlow] delegate.receiverId is required`);let n=Array.isArray(e.delegate?.actions)?e.delegate.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] delegate.actions must be non-empty`);n.forEach(e=>we(Se(e)))}function to(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required for NEP-413`);if(String(e.payload?.accountId||``).trim()!==t)throw Error(`[NearSigningFlow] payload.accountId must match nearAccount.accountId`);if(!String(e.payload?.recipient||``).trim())throw Error(`[NearSigningFlow] recipient is required for NEP-413`);if(!String(e.payload?.message||``).trim())throw Error(`[NearSigningFlow] message is required for NEP-413`)}var no=e({signDelegateAction:()=>Wo,signNear:()=>oo});function ro(e){if(!(e instanceof pt))return;let t=e.authorizationDecision;if(!(!t||t.kind!==`step_up_required`||!(`request_id`in t.step_up)))return{kind:`step_up_required`,reason:t.reason,step_up:t.step_up}}function io(e){let t=ro(e),n=ut(e);return t?lt(n??{kind:`exhausted`,source:`server_prepare`,detail:`Server requires owner operation step-up`}):n?.kind===`in_flight`?lt(n):null}async function ao(e){if(e.failure?.kind!==`expired`)return;let t=Tt({source:{kind:`ed25519`,laneIdentity:Je(e.lane)},expiresAtMs:e.expiresAtMs,detectedAtMs:Date.now()});if((await e.coordinator.invalidateExpiredWalletSession({state:t,source:Ae.serverRejection})).kind===`unavailable`)throw Error(`[SigningEngine][near] expired Wallet Session cleanup failed`)}async function oo(e,t){let n=e.getSignerWorkerContext(),r=t.kind===`transactionWithActions`?x(n.touchConfirm?.getContext().surfaceMeasurementBinding)??null:null;if(r&&r.assertPending(),e={...e,prepareNearEd25519YaoMaterialBoundary:so.bind(null,e.prepareNearEd25519YaoMaterialBoundary.bind(e),r),getSignerWorkerContext:r?Jo.bind(null,n,r.beforeSigning):e.getSignerWorkerContext},t.kind===`transactionWithActions`)return await Bo(e,t.args);if(t.kind===`delegateAction`)return await Wo(e,t.args);if(t.kind===`nep413`)return await qo(e,t.args);throw Error(`[SigningEngine] unsupported near signing intent: ${String(t.kind||``)}`)}function so(e,t,n){let r=L(n.materialIdentity?n.materialIdentity.auth:n.auth);if(r===`voiceid`&&!t)throw Error(`VoiceID requires a reviewed NEAR transfer.`);return t?.assertAuthMethodPolicy(r),e(n)}function co(e){return e.state===`missing`?{state:e.state,curve:e.curve,chain:e.chain}:{authMethod:L(e.auth),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,state:e.state,source:e.source||`unknown`,...e.authorizationState===`authorized`?{walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId}:{},thresholdSessionId:e.thresholdSessionId,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}}function lo(e){let t=e?.candidates.ed25519.near||[];return{generation:e?.generation||0,candidateCount:t.length,candidates:t.map(co)}}function uo(e,t,n){try{e?.(je({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function fo(e){if(qe(e.signingLane.identity)!==qe(e.transactionLane.identity))throw Error(`[SigningEngine][near] prepared signing lane drifted from selected transaction lane`)}function po(e,t){let n=e.identity.signer,r=t.identity.signer;return String(n.account.wallet.walletId)===String(r.account.wallet.walletId)&&String(n.account.nearAccountId)===String(r.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(r.nearEd25519SigningKeyId)&&n.signerSlot===r.signerSlot&&B(e.auth)===B(t.auth)}function mo(e){let t=e.readiness.status;return t===`ready`?{status:`ready`,remainingUses:Math.max(0,Math.floor(Number(e.readiness.remainingUses)||0)),expiresAtMs:Math.max(0,Math.floor(Number(e.readiness.expiresAtMs)||0))}:t===`expired`||t===`exhausted`||t===`status_unknown`?t===`status_unknown`?{status:t,reason:`trusted wallet budget status is unavailable`}:{status:t}:t===`auth_unavailable`||t===`status_unavailable`?{status:t,reason:t}:{status:`status_unavailable`,reason:t}}function ho(e){if(e.curve!==`ed25519`||e.keyKind!==`threshold_ed25519`)throw Error(`[SigningEngine][near] prepared signing lane is not Ed25519`);if(e.chainFamily!==`near`)throw Error(`[SigningEngine][near] prepared Ed25519 lane must target NEAR`);let t=String(e.thresholdSessionId||``).trim(),n=String(e.walletSessionId||``).trim(),r=String(e.quotaId||``).trim();if(!t||!n||!r)throw Error(`[SigningEngine][near] prepared Ed25519 lane is missing session identity`);return{...e,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,walletSessionId:z.walletSession(n),quotaId:z.walletSessionQuota(r),thresholdSessionId:z.thresholdEd25519Session(t)}}async function go(e){let t=e.preparedOperation,n=t.lane;nt(`near`,n,{reason:`near_transaction_auth_planning`});let r=e.commandSubject.nearAccount.accountId,i={accountId:r,intent:_e.TransactionSign,curve:`ed25519`},a=t.signingSessionPlan;if(a.kind===R.NotReady)throw console.warn(`[SigningEngine][near][ed25519] transaction auth planning not ready`,{nearAccountId:r,authMethod:L(n.auth),reason:a.reason,readiness:t.readiness.status,walletSessionId:n.walletSessionId,quotaId:n.quotaId,thresholdSessionId:n.thresholdSessionId,retention:n.retention,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs}),a.reason===`policy_blocked`?Error(`[SigningEngine] NEAR operation requires passkey authentication after Email OTP login`):Error(`[SigningEngine][near] signing session is not ready: ${a.reason}`);return{signingAuthPlan:Bt({plan:a,accountId:i.accountId,intent:i.intent,curve:i.curve,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses}),signingLane:n}}function _o(e){let t=String(e.providedThresholdSessionId||``).trim(),n=String(e.identity.thresholdSessionId||``).trim();if(t&&t!==n)throw Error(`[SigningEngine][near] transaction thresholdSessionId must match prepared Ed25519 identity`);return n}function vo(e){switch(e.authorization.kind){case`authorized`:return!1;case`authorization_required`:return!0;default:throw e.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function yo(e){if(e.authorization.kind!==`authorized`)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e.authorization.authorization.status.expiresAtMs}async function bo(e){let t={walletId:Ee(e.commandSubject.walletSession.walletId),nearAccountId:H(e.commandSubject.nearAccount.accountId)};return e.materialIdentity?await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,materialIdentity:e.materialIdentity}):await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,laneIdentity:e.selectedLane.identity,auth:e.selectedLane.auth})}function xo(e,t){return z.signingOperation(e.createSigningSessionId(`near-${t}-operation`))}function So(e){return{kind:`prepared_near_transaction_execution`,thresholdSessionId:e.thresholdSessionId,signingSessionPlan:e.preparedSigningSession.preparedOperation.signingSessionPlan,signingAuthPlan:e.preparedSigningSession.signingAuthPlan,signingLane:e.preparedSigningSession.signingLane,signingSessionCoordinator:e.signingSessionCoordinator,transactionOperation:e.preparedSigningSession.transactionOperation,passkeyEd25519OperationStepUp:e.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.emailOtpEd25519StepUp}}function Co(e){return ft({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.signingLane.walletSessionId),quotaId:String(e.prepared.signingLane.quotaId),projectionVersion:`server-owned`,authorityKey:B(e.prepared.signingLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function wo(e){if(e.prepared.kind!==`authorized`)throw Error(`[SigningEngine][near] deferred Ed25519 material has no reusable session`);return ft({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.selectedLane.walletSessionId),quotaId:String(e.prepared.selectedLane.quotaId),projectionVersion:`projection-unadmitted`,authorityKey:B(e.prepared.selectedLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function To(e){if(e.auth.kind!==`passkey`)return;let t=e.auth;return{prepare:async()=>{let n=e.signer,r=await Do({authorityRef:Eo(e.preparation),walletId:n.account.wallet.walletId,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u});return{thresholdSessionId:e.thresholdSessionId,authority:r}}}}function Eo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.hydration.authority;case`blocked`:throw Error(`[SigningEngine][near] blocked Passkey material has no authority`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Passkey material authority`)}}async function Do(e){let t=De({walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.authorityRef.walletAuthMethodId});if(!t)throw Error(`[SigningEngine][near] exact Passkey step-up authority is invalid`);let n=await Oe({authority:t});if(n.walletId!==e.authorityRef.walletId||n.walletAuthMethodId!==e.authorityRef.walletAuthMethodId||n.authorityDigest!==e.authorityRef.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey step-up authority changed`);return t}function Oo(e){if(e.auth.kind!==me.emailOtp||typeof e.deps.requestEmailOtpEd25519SigningChallenge!=`function`||!e.preparation.hydration.materialActivation)return;if(String(e.signer.account.wallet.walletId)!==String(e.commandSubject.walletSession.walletId)||String(e.signer.account.nearAccountId)!==String(e.commandSubject.nearAccount.accountId))throw Error(`[SigningEngine][near] Email OTP step-up lane changed subject`);let t=async t=>{let n=await e.deps.requestEmailOtpEd25519SigningChallenge({walletSession:e.commandSubject.walletSession,operationFingerprintDigest:t.operationFingerprintDigest});return uo(e.onEvent,e.commandSubject.nearAccount.accountId,{phase:W.STEP_06_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:n.emailHint,demoOtpCode:st(n.delivery)}}),n};return{prepare:t,resend:t}}async function ko(e){let t=qt({availableLanes:await Lo({deps:e.deps,commandSubject:e.commandSubject,authMethod:null}),intent:Po({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:1})});if(!t.ok)throw Error(`[SigningEngine][near] signature-only signing requires exact Ed25519 material`);if(t.kind===`authorization_required`){let n=t.candidate,r=Ye({walletId:n.walletId,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}),i={kind:`near_ed25519_material_identity`,signer:r,auth:n.auth,thresholdSessionId:z.thresholdEd25519Session(n.thresholdSessionId)},a=await bo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:i});return{kind:`authorization_required`,candidate:n,materialIdentity:i,forceFreshAuth:!0,passkeyEd25519OperationStepUp:To({auth:n.auth,signer:r,thresholdSessionId:i.thresholdSessionId,preparation:a.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:r,preparation:a.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:a.preparation,yaoMaterialExecutor:a.executor}}let n=t.lane,r=await bo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:n});return{kind:`authorized`,selectedLane:n,forceFreshAuth:e.attempt.forceFreshAuth||vo(r.preparation),passkeyEd25519OperationStepUp:To({auth:n.auth,signer:n.identity.signer,thresholdSessionId:n.identity.thresholdSessionId,preparation:r.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:n.identity.signer,preparation:r.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:r.preparation,yaoMaterialExecutor:r.executor}}async function Ao(e){let t=wt({materialActivation:e.materialActivation});return await e.deps.withThresholdEd25519CommitQueue({queueKey:t,nearAccountId:e.nearAccountId,enabled:!0,task:e.task})}async function jo(e){let t=e.availableLanes,n=qt({availableLanes:t,intent:Po({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:Ar(e.input.transaction)})});if(!n.ok||n.kind!==`authorization_required`)return null;let r=n.candidate,i=Ye({walletId:r.walletId,nearAccountId:r.nearAccountId,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,signerSlot:r.signerSlot}),a={kind:`near_ed25519_material_identity`,signer:i,auth:r.auth,thresholdSessionId:z.thresholdEd25519Session(r.thresholdSessionId)},o=await bo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:a});return{candidate:r,preparation:o.preparation,executor:o.executor,passkeyEd25519OperationStepUp:To({auth:r.auth,signer:i,thresholdSessionId:a.thresholdSessionId,preparation:o.preparation})||null,emailOtpEd25519StepUp:Oo({deps:e.deps,commandSubject:e.commandSubject,auth:r.auth,signer:i,preparation:o.preparation,onEvent:e.input.onEvent})||null}}function Mo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return e.hydration.materialActivation;case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired public material cannot enter the material commit queue`);case`blocked`:throw Error(`[SigningEngine][near] blocked material cannot enter the material commit queue: ${e.hydration.reason}`)}throw e.hydration,Error(`[SigningEngine][near] unsupported material hydration plan`)}function No(e){let t=e.authSelectionPolicy||null;if(!t)return null;let n=Ut(Ht(Wt(Po({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:t,operationUsesNeeded:e.operationUsesNeeded})),{availableLanes:e.availableLanes}));if(n.tag===`LaneSelected`){if(n.lane.curve!==`ed25519`||n.availableLane.curve!==`ed25519`)throw Error(`[SigningEngine][near] Ed25519 selector returned a non-Ed25519 lane`);return n}if(n.failure.kind===`no_candidate`)return null;throw Error(`[SigningEngine][near] Ed25519 transaction lane selection failed: ${n.failure.kind}`)}function Po(e){return{walletId:Ee(e.commandSubject.walletSession.walletId),curve:`ed25519`,chain:`near`,signerSelection:Fo({nearAccountId:e.commandSubject.nearAccount.accountId,signerSlot:e.signerSlot}),authSelectionPolicy:e.authSelectionPolicy,operationUsesNeeded:e.operationUsesNeeded}}function Fo(e){if(e.signerSlot===void 0)return{kind:`near_account`,nearAccountId:e.nearAccountId};let t=ke(e.signerSlot);if(t===null)throw Error(`[SigningEngine][near] signerSlot must be a positive safe integer`);return{kind:`signer_slot`,nearAccountId:e.nearAccountId,signerSlot:t}}function Io(e){return No({availableLanes:e.availableLanes,authSelectionPolicy:{kind:`any`},commandSubject:e.commandSubject,signerSlot:e.signerSlot,operationUsesNeeded:e.operationUsesNeeded})}async function Lo(e){let t=e.commandSubject.nearAccount.accountId,n=e.commandSubject.walletSession.walletId;if(typeof e.deps.readAvailableSigningLanesForSigning!=`function`)throw Error(`[SigningEngine][near] transaction signing requires available signing lanes reader`);let r=await e.deps.resolveOwnerLaneScope(n);return await e.deps.readAvailableSigningLanesForSigning({walletId:n,curve:`ed25519`,ownerScope:r,...e.authMethod?{authMethod:e.authMethod}:{}}).catch(e=>(console.warn(`[SigningEngine][near] available signing lanes read failed`,{nearAccountId:t,error:e instanceof Error?e.message:String(e||`unknown error`)}),null))}async function Ro(e){let t=e.commandSubject.nearAccount.accountId,n=Math.max(1,Math.floor(Number(e.operationUsesNeeded)||1)),r=e.selectedLane.lane,i=ka({commandSubject:e.commandSubject,selectedLane:r,preparation:e.preparation,forceFreshAuth:e.forceFreshAuth,requiredSignatureUses:n}),a=i.lane;fo({signingLane:a,transactionLane:e.selectedLane.lane});let o={readiness:i.coordinatorInput.readiness,expiresAtMs:i.coordinatorInput.expiresAtMs,remainingUses:i.coordinatorInput.remainingUses};r.auth.kind===`email_otp`&&o.readiness.status!==`ready`&&console.warn(`[SigningEngine][near][email-otp] Ed25519 pre-confirm readiness is not ready`,{nearAccountId:t,readiness:o.readiness.status,thresholdSessionId:r.thresholdSessionId,walletSessionId:r.walletSessionId,quotaId:r.quotaId,retention:a.retention,remainingUses:o.remainingUses,expiresAtMs:o.expiresAtMs,requiredSignatureUses:n}),tt(`near`,rt({event:`pre_confirm_readiness_checked`,lane:a,readinessStatus:o.readiness.status,phase:`pre_confirm`}));let s=Jt(e.selectedLane,mo({readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses})),c=Gt(s),l=ho(a),u={readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses};return{lane:a,transactionLane:e.selectedLane.lane,transactionIntent:e.selectedLane.intent,readiness:u,availableLanesGeneration:e.availableLanes?.generation||0,metadata:{transactionLane:e.selectedLane.lane,transactionOperation:c,transactionReadinessState:s,identity:l,availableLanesGeneration:e.availableLanes?.generation||0,readiness:u}}}async function zo(e){let t=e.commandSubject.nearAccount.accountId,n=Ar(e.input.transaction),r=e.availableLanes,i=Io({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!i)throw console.warn(`[SigningEngine][near][ed25519] exact transaction lane selection failed ${JSON.stringify({nearAccountId:t,signerSlot:e.input.signerSlot??null,requiredSignatureUses:n,availableLanes:lo(r)})}`),Error(`[SigningEngine][near] Ed25519 transaction signing requires an exact selected lane`);let a={kind:`account_class`,authMethod:L(i.lane.auth)},o=await bo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:i.lane});if(o.preparation.authorization.kind===`authorized`){let t=o.preparation.authorization.authorization;if(i.lane.walletSessionId!==t.operationCredential.walletSessionId||i.lane.quotaId!==t.session.quotaId){r=await Lo({deps:e.deps,commandSubject:e.commandSubject,authMethod:L(i.lane.auth)});let a=Io({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!a||!po(i.lane,a.lane)||a.lane.walletSessionId!==t.operationCredential.walletSessionId||a.lane.quotaId!==t.session.quotaId)throw Error(`[SigningEngine][near] material restoration changed the Wallet Session without an exact refreshed lane`);i=a}}let s=e.forceFreshAuth===!0||vo(o.preparation),c=await Kt({intent:Po({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:a,operationUsesNeeded:n}),coordinator:e.signingSessionCoordinator,forceFreshAuth:s,sensitiveOperationPolicy:e.input.sensitivePolicy||he.inheritSessionPolicy,onPlannerTrace:e=>et(`near`,e),lifecycleAdapter:{prepare:async()=>{let t=await Ro({deps:e.deps,commandSubject:e.commandSubject,signingSessionCoordinator:e.signingSessionCoordinator,availableLanes:r,selectedLane:i,preparation:o.preparation,forceFreshAuth:s,operationUsesNeeded:n});return{...t,metadata:t.metadata}}}}),l=c.thresholdOperation,u=c.transactionOperation,d=l.lane,f=u.lane,p=l.metadata.identity,{signingAuthPlan:m}=await go({commandSubject:e.commandSubject,preparedOperation:l});return{preparation:o.preparation,executor:o.executor,signingAuthPlan:m,signingLane:d,transactionLane:f,identity:p,thresholdSessionId:z.thresholdEd25519Session(_o({providedThresholdSessionId:e.input.thresholdSessionId,identity:p})),availableLanesGeneration:l.availableLanesGeneration,preparedOperation:l,transactionOperation:u}}async function Bo(e,t){let n=performance.now();await e.touchConfirm.openTransactionPreparationModal({chain:`near`,walletLabel:String(t.commandSubject.nearAccount.accountId),txSigningRequests:[t.transaction],model:qn({txSigningRequests:[t.transaction],signerAccount:String(t.commandSubject.nearAccount.accountId),title:t.title,subtitle:t.body}),confirmationConfigOverride:t.confirmationConfigOverride});try{let r=z.signingOperation(e.createSigningSessionId(`near-transaction-sign`));return G(String(r),`preparation_modal`,n),await Vo(e,t,{signingOperationState:jt({operationId:r})})}finally{e.touchConfirm.closeTransactionPreparationModal()}}async function Vo(e,t,n){let r=t.commandSubject.nearAccount,i=H(r.accountId),a={signerSlot:t.signerSlot,confirmationConfigOverride:t.confirmationConfigOverride,title:t.title,body:t.body,onEvent:t.onEvent},o=n.signingOperationState.operationId,s=n.signingSessionCoordinator||e.signingSessionCoordinator,c=performance.now(),l=await Lo({deps:e,commandSubject:t.commandSubject,authMethod:null}),u=await jo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,operationId:o});if(G(String(o),`authorization_probe`,c),u){let o=e.getSignerWorkerContext();return await Ao({deps:e,nearAccountId:i,materialActivation:Mo(u.preparation),task:async()=>await Za({chain:`near`,kind:`transactionWithActions`,payload:{ctx:o,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:s,selection:{kind:`authorization_required`,candidate:u.candidate},passkeyEd25519OperationStepUp:u.passkeyEd25519OperationStepUp||void 0,emailOtpEd25519StepUp:u.emailOtpEd25519StepUp||void 0,sensitivePolicy:t.sensitivePolicy,yaoSigningPreparation:u.preparation,yaoMaterialExecutor:u.executor}})})}let d=performance.now(),f=await zo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,signingSessionCoordinator:s,operationId:o,forceFreshAuth:n.forceFreshAuth===!0});G(String(o),`lane_preparation`,d);let p=performance.now(),m=f.preparation.authorization,h=f.signingAuthPlan,g=f.signingLane,_=f.transactionLane,v=f.thresholdSessionId;fo({signingLane:g,transactionLane:_});try{return await Ao({deps:e,nearAccountId:i,materialActivation:Mo(f.preparation),task:async()=>{let i=e.getSignerWorkerContext(),c=f,l=To({auth:_.auth,signer:_.identity.signer,thresholdSessionId:v,preparation:c.preparation}),u=Oo({deps:e,commandSubject:t.commandSubject,auth:_.auth,signer:_.identity.signer,preparation:c.preparation,onEvent:a.onEvent}),d=So({preparedSigningSession:f,thresholdSessionId:v,signingSessionCoordinator:s,passkeyEd25519OperationStepUp:l||null,emailOtpEd25519StepUp:u||null}),m={thresholdSessionId:d.thresholdSessionId,signingSessionPlan:d.signingSessionPlan,signingAuthPlan:d.signingAuthPlan,signingLane:d.signingLane},h={ctx:i,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:d.signingSessionCoordinator,selection:{kind:`authorized`,selectedLane:_},transactionOperation:d.transactionOperation,ed25519SigningBoundary:m,yaoSigningPreparation:c.preparation,yaoMaterialExecutor:c.executor,...d.passkeyEd25519OperationStepUp?{passkeyEd25519OperationStepUp:d.passkeyEd25519OperationStepUp}:{},...d.emailOtpEd25519StepUp?{emailOtpEd25519StepUp:d.emailOtpEd25519StepUp}:{}};return G(String(o),`execution_setup`,p),await Za({chain:`near`,kind:`transactionWithActions`,payload:h})}})}catch(r){let o=h.kind===kt.PasskeyReauth||h.kind===kt.EmailOtpReauth,c=ro(r),l=io(r),u=mt(r),d=c?.kind===`step_up_required`;if(!n.retryingFreshAuth&&!o&&m.kind===`authorized`&&(d||l)){if(l?.kind===`wait_and_retry_admission`)return await dt(l.retryAfterMs),await Vo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s});if(await ao({failure:u,coordinator:s,lane:f.transactionLane,expiresAtMs:m.authorization.status.expiresAtMs}),_.auth.kind===`voiceid`)throw Error(`Unlock with VoiceID again to renew the NEAR Wallet Session.`);let r=_.auth.kind===`email_otp`,o=c?.kind===`step_up_required`?c.reason:void 0,d=l?l.reason===`stale_projection`?`wallet_signing_budget_stale_projection`:`wallet_signing_budget_exhausted`:o===`wallet_session_missing`?`threshold_session_missing`:`threshold_session_expired`;if(uo(a.onEvent,i,{phase:r?W.STEP_06_AUTH_EMAIL_OTP_CHALLENGE_STARTED:W.STEP_09_THRESHOLD_SESSION_RECONNECT_STARTED,status:`running`,message:r?`Signing session needs reauthorization; requesting Email OTP`:`Signing session needs reauthorization; requesting passkey`,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,reason:d}}),l?.kind===`request_fresh_step_up`){let r=Co({walletId:t.commandSubject.walletSession.walletId,nearAccountId:i,prepared:f});return await s.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await Vo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s}),retryAfterRefresh:async()=>await Vo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s})})}return await Vo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s})}throw r}}async function Ho(e){return await Za({chain:`near`,kind:`delegateAction`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:e.input.commandSubject.nearAccount,delegate:e.input.delegate,rpcCall:e.normalizedRpcCall,signingSessionCoordinator:e.deps.signingSessionCoordinator,signerSlot:e.input.signerSlot,confirmationConfigOverride:e.input.confirmationConfigOverride,title:e.input.title,body:e.input.body,onEvent:e.input.onEvent,operationId:e.operationId,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor}})}async function Uo(e){let t=H(e.input.commandSubject.nearAccount.accountId),n=await ko({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt}),r={nearRpcUrl:e.input.rpcCall.nearRpcUrl||e.deps.nearRpcUrl,nearAccountId:t};try{return await Ao({deps:e.deps,nearAccountId:t,materialActivation:Mo(n.yaoSigningPreparation),task:Ho.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n,normalizedRpcCall:r})})}catch(r){let i=ro(r),a=io(r);if(e.attempt.kind===`initial`&&a){if(a.kind===`wait_and_retry_admission`)return await dt(a.retryAfterMs),await Uo(e);let r=wo({walletId:e.input.commandSubject.walletSession.walletId,nearAccountId:t,prepared:n});return await e.deps.signingSessionCoordinator.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await Uo({...e,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}}),retryAfterRefresh:async()=>await Uo({...e,attempt:{kind:`initial`,forceFreshAuth:!1}})})}let o=mt(r);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&i)return await ao({failure:o,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:yo(n.yaoSigningPreparation)}),await Uo({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw r}}async function Wo(e,t){try{return await Uo({deps:e,input:t,operationId:xo(e,`delegate`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){throw console.error(`[SigningEngine][delegate] failed`,e),e}}async function Go(e){let t=e.input.commandSubject.nearAccount;return await Za({chain:`near`,kind:`nep413`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:t,signingSessionCoordinator:e.deps.signingSessionCoordinator,onEvent:e.input.onEvent,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor,payload:{message:e.input.message,recipient:e.input.recipient,nonce:e.input.nonce,callbackUrl:e.input.callbackUrl,state:e.input.state,accountId:t.accountId,signerSlot:e.input.signerSlot,title:e.input.title,body:e.input.body,confirmationConfigOverride:e.input.confirmationConfigOverride,operationId:e.operationId}}})}async function Ko(e){let t=H(e.input.commandSubject.nearAccount.accountId),n=await ko({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt});try{return await Ao({deps:e.deps,nearAccountId:t,materialActivation:Mo(n.yaoSigningPreparation),task:Go.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n})})}catch(t){let r=ro(t),i=mt(t);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&r!==void 0)return await ao({failure:i,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:yo(n.yaoSigningPreparation)}),await Ko({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw t}}async function qo(e,t){try{return await Ko({deps:e,input:t,operationId:xo(e,`nep413`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){return console.error(`SigningEngine: NEP-413 signing error:`,e),{success:!1,error:e instanceof Error?e.message:String(e||`Unknown error`)}}}function Jo(e,t){return{...e,beforeSigning:t}}export{an as _,Qn as a,Rn as c,En as d,wn as f,mn as g,dn as h,ar as i,zn as l,un as m,no as n,Gn as o,Cn as p,fr as r,Kn as s,oo as t,Ln as u,nn as v};