@arkade-os/sdk 0.5.7 → 0.5.9

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 (106) hide show
  1. package/README.md +24 -6
  2. package/dist/adapters/expo.cjs +7 -7
  3. package/dist/adapters/expo.d.cts +2 -2
  4. package/dist/adapters/expo.d.ts +2 -2
  5. package/dist/adapters/expo.js +4 -4
  6. package/dist/{asyncStorageTaskQueue-B9byr6ij.d.cts → asyncStorageTaskQueue-B6rFkXzW.d.cts} +1 -1
  7. package/dist/{asyncStorageTaskQueue-XP4CCdRY.d.ts → asyncStorageTaskQueue-C0irgPwJ.d.ts} +1 -1
  8. package/dist/{chunk-MWEDDWFU.js → chunk-2657D67V.js} +9 -7
  9. package/dist/chunk-2657D67V.js.map +1 -0
  10. package/dist/{chunk-MWMO2ZQP.js → chunk-3KNSMZWD.js} +24 -13
  11. package/dist/chunk-3KNSMZWD.js.map +1 -0
  12. package/dist/{chunk-DNFTHG73.js → chunk-4DUTRRXF.js} +8 -6
  13. package/dist/chunk-4DUTRRXF.js.map +1 -0
  14. package/dist/{chunk-MQUATTIM.cjs → chunk-4PSM6ZUC.cjs} +55 -57
  15. package/dist/chunk-4PSM6ZUC.cjs.map +1 -0
  16. package/dist/{chunk-FDJ734CH.js → chunk-DPFD5KBK.js} +5 -2
  17. package/dist/chunk-DPFD5KBK.js.map +1 -0
  18. package/dist/{chunk-OMPDPBT5.cjs → chunk-DY24A73N.cjs} +296 -240
  19. package/dist/chunk-DY24A73N.cjs.map +1 -0
  20. package/dist/{chunk-VMVFRTF4.js → chunk-FUCKDTH7.js} +285 -234
  21. package/dist/chunk-FUCKDTH7.js.map +1 -0
  22. package/dist/{chunk-4AJRIM44.js → chunk-GUK33TNC.js} +9 -13
  23. package/dist/chunk-GUK33TNC.js.map +1 -0
  24. package/dist/{chunk-RLD7DRSZ.js → chunk-HT35HPXR.js} +19365 -18395
  25. package/dist/chunk-HT35HPXR.js.map +1 -0
  26. package/dist/{chunk-3NALVGMJ.cjs → chunk-ODLSVJRU.cjs} +38 -27
  27. package/dist/chunk-ODLSVJRU.cjs.map +1 -0
  28. package/dist/{chunk-X6ZI53DZ.cjs → chunk-OMZZQTDM.cjs} +28 -35
  29. package/dist/chunk-OMZZQTDM.cjs.map +1 -0
  30. package/dist/{chunk-V3ZLL5VY.js → chunk-PXEFYEKL.js} +22 -29
  31. package/dist/chunk-PXEFYEKL.js.map +1 -0
  32. package/dist/{chunk-JFJNB7ZH.cjs → chunk-UPIQZRNJ.cjs} +16 -14
  33. package/dist/chunk-UPIQZRNJ.cjs.map +1 -0
  34. package/dist/{chunk-V5WRO3P6.cjs → chunk-UPV4W423.cjs} +14 -18
  35. package/dist/chunk-UPV4W423.cjs.map +1 -0
  36. package/dist/{chunk-URGVQ5TQ.cjs → chunk-V2EU5QWF.cjs} +4583 -3610
  37. package/dist/chunk-V2EU5QWF.cjs.map +1 -0
  38. package/dist/{chunk-FLPWNMX3.cjs → chunk-WIZCF5IX.cjs} +5 -2
  39. package/dist/chunk-WIZCF5IX.cjs.map +1 -0
  40. package/dist/{chunk-MXCB6EVM.cjs → chunk-WZJJZGBT.cjs} +22 -20
  41. package/dist/chunk-WZJJZGBT.cjs.map +1 -0
  42. package/dist/{chunk-V2DDN4MV.js → chunk-Z6WDOZZI.js} +10 -12
  43. package/dist/chunk-Z6WDOZZI.js.map +1 -0
  44. package/dist/compiler.cjs +4 -4
  45. package/dist/compiler.d.cts +1 -1
  46. package/dist/compiler.d.ts +1 -1
  47. package/dist/compiler.js +3 -3
  48. package/dist/contracts/handlers/index.cjs +11 -11
  49. package/dist/contracts/handlers/index.d.cts +3 -4
  50. package/dist/contracts/handlers/index.d.ts +3 -4
  51. package/dist/contracts/handlers/index.js +4 -4
  52. package/dist/{index-18cDMayF.d.ts → index-Bq349_ly.d.cts} +2334 -101
  53. package/dist/{index-Ccfhdfvj.d.cts → index-D4ahI0W6.d.cts} +2 -3
  54. package/dist/{index-DDJFHfba.d.cts → index-Mn2POBPj.d.ts} +2334 -101
  55. package/dist/{index-B_kcptF8.d.ts → index-Yh5y9G4E.d.ts} +2 -3
  56. package/dist/index.cjs +362 -346
  57. package/dist/index.d.cts +1505 -1374
  58. package/dist/index.d.ts +1505 -1374
  59. package/dist/index.js +7 -7
  60. package/dist/{program-BARSNg3X.d.ts → program-38A2Twvj.d.ts} +4 -2
  61. package/dist/{program-znrWkxE4.d.cts → program-DPzf5qsk.d.cts} +4 -2
  62. package/dist/repositories/realm/index.cjs +40 -40
  63. package/dist/repositories/realm/index.d.cts +2 -2
  64. package/dist/repositories/realm/index.d.ts +2 -2
  65. package/dist/repositories/realm/index.js +8 -8
  66. package/dist/repositories/sqlite/index.cjs +38 -38
  67. package/dist/repositories/sqlite/index.d.cts +2 -2
  68. package/dist/repositories/sqlite/index.d.ts +2 -2
  69. package/dist/repositories/sqlite/index.js +8 -8
  70. package/dist/{taskRunner-DUafWu0o.d.ts → taskRunner-BYxEgwM5.d.ts} +1 -1
  71. package/dist/{taskRunner-JYHaLPne.d.cts → taskRunner-Z3LnHfgs.d.cts} +1 -1
  72. package/dist/wallet/expo/background.cjs +17 -17
  73. package/dist/wallet/expo/background.d.cts +3 -3
  74. package/dist/wallet/expo/background.d.ts +3 -3
  75. package/dist/wallet/expo/background.js +9 -9
  76. package/dist/wallet/expo/index.cjs +18 -18
  77. package/dist/wallet/expo/index.d.cts +3 -5
  78. package/dist/wallet/expo/index.d.ts +3 -5
  79. package/dist/wallet/expo/index.js +8 -8
  80. package/dist/worker/expo/index.cjs +12 -12
  81. package/dist/worker/expo/index.d.cts +4 -4
  82. package/dist/worker/expo/index.d.ts +4 -4
  83. package/dist/worker/expo/index.js +8 -8
  84. package/package.json +1 -1
  85. package/dist/chunk-3NALVGMJ.cjs.map +0 -1
  86. package/dist/chunk-4AJRIM44.js.map +0 -1
  87. package/dist/chunk-DNFTHG73.js.map +0 -1
  88. package/dist/chunk-FDJ734CH.js.map +0 -1
  89. package/dist/chunk-FLPWNMX3.cjs.map +0 -1
  90. package/dist/chunk-JFJNB7ZH.cjs.map +0 -1
  91. package/dist/chunk-MQUATTIM.cjs.map +0 -1
  92. package/dist/chunk-MWEDDWFU.js.map +0 -1
  93. package/dist/chunk-MWMO2ZQP.js.map +0 -1
  94. package/dist/chunk-MXCB6EVM.cjs.map +0 -1
  95. package/dist/chunk-OMPDPBT5.cjs.map +0 -1
  96. package/dist/chunk-RLD7DRSZ.js.map +0 -1
  97. package/dist/chunk-URGVQ5TQ.cjs.map +0 -1
  98. package/dist/chunk-V2DDN4MV.js.map +0 -1
  99. package/dist/chunk-V3ZLL5VY.js.map +0 -1
  100. package/dist/chunk-V5WRO3P6.cjs.map +0 -1
  101. package/dist/chunk-VMVFRTF4.js.map +0 -1
  102. package/dist/chunk-X6ZI53DZ.cjs.map +0 -1
  103. package/dist/delegate-gGkUnYpi.d.cts +0 -92
  104. package/dist/delegate-iyDum4fw.d.ts +0 -92
  105. package/dist/keyringDescriptorProvider-DL-jAiRO.d.ts +0 -2082
  106. package/dist/keyringDescriptorProvider-Dtv0JWrT.d.cts +0 -2082
package/dist/index.d.cts CHANGED
@@ -1,18 +1,15 @@
1
- import { a as Identity, ah as DescriptorProvider, a3 as Transaction, a4 as SignerSession, a5 as ReadonlyIdentity, aF as DescriptorSigningRequest, aG as IntentFeeConfig, aH as OffchainInput, aI as FeeAmount, aJ as OnchainInput, aK as FeeOutput, Y as BatchRegistrationRepository, Z as BatchRegistration, _ as BatchRegistrationPageFilter, P as PageRequest, D as PageResult, B as Outpoint, $ as VirtualTxRepository, a0 as VirtualTx, a1 as VtxoBranch, W as WalletRepository, Q as AtomicWalletState, z as ExtendedVirtualCoin, F as ScriptVtxoCursor, H as ScriptVtxoPageOptions, J as StoredVtxo, K as VtxoRepositoryKey, E as ExtendedCoin, L as TransactionHistoryPageFilter, M as TransactionHistoryPageCursor, g as ArkTransaction, U as WalletState, y as Contract, w as IndexerProvider, aL as ArkadeInfo, aj as OnchainProvider, i as Activity, C as ContractRepository, X as ContractFilter, I as IWallet, x as OperatorProvider, as as NetworkName, ay as SettlementConfig, aM as ContractWatcherConfig, aN as Asset, R as Recipient, aO as FeeInfo, n as SettlementEvent, N as NormalizedExtendedVirtualCoin, S as SettleParams, G as GetOperatorInfoOptions, aP as GetVtxosOptions, aQ as PaginationOptions, e as GetVtxosFilter, f as GetSpendableVtxosFilter, aR as CreateContractParams, aS as GetContractsFilter, V as VirtualCoin, aT as GetSpendablePathsOptions, aU as GetAllSpendingPathsOptions, k as GetNewAddressesOptions, aV as InputExpiryFloor, aW as IssuanceParams, aX as ReissuanceParams, aY as BurnParams, aZ as RenewVtxosOptions, p as SendOnchainParams, O as OperatorInfo, a_ as NormalizedVtxoPage, A as ArkadeReader, c as ArkadeBroadcaster, d as WalletBalance, ap as ContractSyncState, at as ContractWithVtxos, a$ as WatchedScript, b0 as PathSelection, l as NewAddress, b1 as ContractEvent, b2 as AssetDetails, b3 as IssuanceResult, b4 as DelegateInfo, b5 as MigrationGlobalSkipReason, b6 as MigrationLegSkipReason, b7 as SignerStatus, ai as IReadonlyWallet, h as ActivityRegistry, ao as IReadonlyAssetManager, b8 as StorageConfig, j as IContractManager, q as IAssetManager, o as SendParams, m as IDelegateManager, b9 as IVtxoManager, a6 as Network, av as Coin, ba as SendBitcoinParams, bb as ExplorerTransaction, aC as SignedProof, aD as Proof, bc as TreeNonces, bd as TreePartialSigs, T as TxNotificationEvent, be as PendingTx, bf as EmulatorProvider, bg as Status, bh as ChainTx, aa as TxTree, bi as ArkadeService, bj as ContractVtxoEvent, bk as ExtendedContractVtxo, bl as ResolvedArkadeService, bm as resolveArkadeService, bn as PathContext } from './index-DDJFHfba.cjs';
2
- export { bo as ActivityIntent, a7 as ActivityResolver, bp as ArkIntent, bq as ArkIntentState, v as ArkProvider, br as AssetMetadata, bs as BATCH_REGISTRATION_TERMINAL_STATES, bt as BITCOIN_EMULATOR_PUBKEY, bu as BaseWalletConfig, ae as BatchFailedEvent, ac as BatchFinalizationEvent, ad as BatchFinalizedEvent, bv as BatchInfo, bw as BatchRegistrationFilter, bx as BatchRegistrationState, by as BatchSignableIdentity, a8 as BatchStartedEvent, bz as CandidateDeps, bA as ChainTxType, a2 as ChainedTxType, bB as CommitmentTx, bC as ConnectorTreeNode, bD as ContractBalance, bE as ContractEventCallback, bF as ContractHandler, aw as ContractManager, ax as ContractManagerConfig, bG as ContractScope, bH as ContractState, bI as ContractVtxo, bJ as ContractWatcher, bK as ContractWatcherEventCallback, bL as DEFAULT_ARKADE_EMULATOR_URL, bM as DEFAULT_VTXO_PAGE_SIZE, bN as DelegateManagerImpl, bO as DelegateOptions, ak as DelegateProvider, bP as DeprecatedSignerMigrationReport, bQ as DeprecatedSignerReport, bR as DigestMismatchError, bS as Discoverable, bT as DiscoveredContract, bU as DiscoveryDeps, bV as ESPLORA_URL, bW as EmulatorInfo, ar as EsploraProvider, bX as EventSourceCapable, bY as EventSourceFactory, bZ as EventSourceLike, b_ as EventSourceUnavailableError, am as ExitCaptureMode, b$ as ExitChainResolver, an as ExitDataSource, c0 as GetArkadeInfoOptions, c1 as GetUtxosOptions, c2 as GroupMembership, c3 as HandlerError, c4 as INTENT_TERMINAL_STATES, c5 as IndexerTxType, c6 as IndexerUtxo, c7 as IndexerUtxosUnsupportedError, aB as Intent, c8 as IntentCoin, c9 as IntentFilter, ca as IntentPageFilter, cb as IntentRepository, cc as KnownMetadata, cd as MAX_PAGE_SIZE, ce as MUTINYNET_EMULATOR_PUBKEY, cf as MigrateDeprecatedSignerOptions, cg as MigrationLegReport, ch as MigrationVtxoRef, ci as NewAddressType, cj as Nonces, ck as OnchainCosignAmbiguousError, cl as OnchainCosignRejectedError, cm as OnchainCosignUnsupportedError, cn as Output, co as PageResponse, cp as PartialSig, cq as PrevTxSource, cr as PrevTxUnavailableError, cs as ProofInput, ct as ProviderClass, cu as REGTEST_EMULATOR_PUBKEY, cv as RawTxSource, al as ReadonlyWalletConfig, aq as RecipientArkadeAddressContext, cw as RenewalSplit, cx as RenewalSplitContext, cy as RestArkProvider, cz as RestDelegateProvider, cA as RestEmulatorProvider, s as RestIndexerProvider, r as RestOperatorProvider, cB as ScanContractsOptions, cC as ScanResult, cD as ScheduledSession, cE as SettlementEventType, cF as SignRequest, aA as SignedIntent, cG as SignerClassification, cH as SignerSet, t as SubscriptionEvent, cI as SubscriptionFilter, u as SubscriptionHeartbeat, cJ as SubscriptionResponse, cK as SweepTxNotification, cL as TapLeaves, aE as TimeHeight, ab as TreeNoncesEvent, ag as TreeSignatureEvent, cM as TreeSignerSession, a9 as TreeSigningStartedEvent, af as TreeTxEvent, cN as Tx, cO as TxHistoryRecord, cP as TxKey, cQ as TxNotification, cR as TxTag, cS as TxTreeNode, cT as TxType, cU as Vtxo, cV as VtxoChain, az as VtxoManager, cW as VtxoType, b as WalletConfig, cX as WalletMode, cY as WithPrevTx, cZ as assertAllowedSighashTypes, c_ as assertPageRequest, c$ as assertRecipientArkadeAddress, d0 as assetMintResolver, d1 as attachPrevArkTxs, d2 as attachPrevoutTxs, d3 as boardingResolver, d4 as canRecoverOnchain, d5 as canSpendOffchain, d6 as canSweepOnchain, d7 as classifyAgainstSignerSet, d8 as classifyContractSigner, d9 as collabExitResolver, da as collectBatchRegistrations, db as collectContracts, dc as collectIntents, dd as collectPages, de as collectScriptVtxos, df as collectTransactionHistory, dg as collectUtxos, dh as collectVtxos, di as configureEventSource, dj as createDefaultActivityRegistry, dk as createExitChainResolver, dl as defaultEmulatorPubkey, dm as getAllNormalizedVtxos, dn as getConfiguredEventSource, dp as getNetwork, dq as getNormalizedVtxos, dr as getRandomId, ds as hasCandidates, dt as isBatchSignable, du as isContractVtxoEvent, dv as isCooperativelyMigratable, dw as isDiscoverable, dx as isEventSourceUnavailableError, dy as isPastExpiry, dz as isSigningIdentity, dA as isSubdust, dB as isTerminalBatchRegistrationState, dC as isTerminalIntentState, dD as isVirtualCoin, dE as isVtxoExpiringSoon, dF as isVtxoSpent, dG as iteratePages, dH as networkFromArkadeInfo, dI as networkFromOperatorInfo, dJ as networks, dK as pageResult, dL as resolveEmulatorPubkey, dM as resolveEventSource, dN as resolvePrevTxs, dO as signerSetFromInfo, dP as toOffchainInputFeeParams, dQ as toXOnlySignerHex, dR as withPrevTxs } from './index-DDJFHfba.cjs';
3
- import { b as ArkadeCashTx, c as ArkadeCashRecord, d as ArkadeCashClaimResult, W as Wallet, R as ReadonlyWallet, e as ReceiveRotatorFactory, f as ReceiveRotatorBootOpts, g as ReceiveRotatorBoot, P as ProviderConnectionState, H as HDWalletCapable, a as HDAllocationCapable, A as AddressAllocationCapable, B as BatchExpiryPolicy, h as Batch } from './keyringDescriptorProvider-Dtv0JWrT.cjs';
4
- export { i as AbortError, j as ArkError, k as ArkErrorName, l as ArkadeCash, m as ArkadeCashAction, n as ArkadeCashCreateError, o as ArkadeCashOperatorMismatchError, p as ArkadeCashUnclaimedReason, q as ArkadeCashUnclaimedVtxo, r as ArkadeCashVtxoRef, s as BoardingUtxoGroup, D as DEFAULT_MIN_BATCH_EXPIRY_SECONDS, F as ForeignDescriptorError, I as IncomingFunds, t as IndexedDBWalletRepository, K as KeyringDescriptorProvider, M as MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, N as NotifiesIncomingFunds, u as ProviderKind, v as ProviderUnavailableError, w as REGTEST_MIN_BATCH_EXPIRY_SECONDS, x as ReadonlySingleKey, S as ServerInfoSource, y as ServerResponseMismatchError, z as SingleKey, V as VtxoReservation, C as VtxoReservedError, E as WaitForIncomingFundsOptions, G as WalletCannotAllocateAddressError, J as addArkadeCashRecord, L as arkadeCashId, O as arkadeCashResolver, Q as assertValidBatchExpiry, T as createArkadeCashTracker, U as defaultBatchExpiryPolicy, X as isAddressAllocationCapable, Y as isArkError, Z as isHDAllocationCapable, _ as isHDWalletCapable, $ as maybeArkError, a0 as mergeArkadeCashRecord, a1 as resolveBatchExpiryPolicy, a2 as resolveDescriptorSigner, a3 as selectVirtualCoins, a4 as signingDescriptorIndex, a5 as strictSigningDescriptorIndex, a6 as waitForIncomingFunds } from './keyringDescriptorProvider-Dtv0JWrT.cjs';
5
- import { T as TapLeafScript, E as EncodedVtxoScript, C as CSVMultisigTapscript, R as RelativeTimelock, V as VtxoScript } from './base-C-Y5t_0F.cjs';
1
+ import { b as Identity, a8 as DescriptorProvider, a9 as Transaction, aa as SignerSession, ab as ReadonlyIdentity, ac as DescriptorSigningRequest, ad as IntentFeeConfig, ae as OffchainInput, af as FeeAmount, ag as OnchainInput, ah as FeeOutput, ai as VtxoReservationRepository, aj as StoredVtxoReservation, a1 as BatchRegistrationRepository, a2 as BatchRegistration, a3 as BatchRegistrationPageFilter, J as PageRequest, L as PageResult, K as Outpoint, a4 as VirtualTxRepository, a5 as VirtualTx, a6 as VtxoBranch, W as WalletRepository, _ as AtomicWalletState, F as ExtendedVirtualCoin, M as ScriptVtxoCursor, Q as ScriptVtxoPageOptions, U as StoredVtxo, X as VtxoRepositoryKey, E as ExtendedCoin, Y as TransactionHistoryPageFilter, Z as TransactionHistoryPageCursor, j as ArkTransaction, $ as WalletState, D as Contract, ak as ArkadeCashTx, z as IndexerProvider, al as ArkadeInfo, am as OnchainProvider, an as ArkadeCashRecord, ao as ArkadeCashClaimResult, l as Activity, C as ContractRepository, a0 as ContractFilter, I as IWallet, S as SettleParams, G as GetOperatorInfoOptions, ap as GetVtxosOptions, aq as PaginationOptions, h as GetVtxosFilter, i as GetSpendableVtxosFilter, ar as CreateContractParams, as as GetContractsFilter, V as VirtualCoin, at as GetSpendablePathsOptions, au as GetAllSpendingPathsOptions, n as GetNewAddressesOptions, R as Recipient, av as InputExpiryFloor, aw as IssuanceParams, ax as ReissuanceParams, ay as BurnParams, az as RenewVtxosOptions, s as SendOnchainParams, q as SettlementEvent, O as OperatorInfo, aA as NormalizedVtxoPage, e as ArkadeReader, f as ArkadeBroadcaster, g as WalletBalance, P as ProviderConnectionState, aB as ContractSyncState, aC as ContractWithVtxos, aD as WatchedScript, aE as PathSelection, o as NewAddress, aF as ContractEvent, aG as AssetDetails, aH as IssuanceResult, aI as DelegateInfo, aJ as MigrationGlobalSkipReason, aK as MigrationLegSkipReason, aL as SignerStatus, aM as NetworkName, B as OperatorProvider, c as Wallet, aN as ReadonlyWallet, aO as SettlementConfig, aP as ContractWatcherConfig, aQ as Asset, aR as FeeInfo, N as NormalizedExtendedVirtualCoin, aS as ReceiveRotatorFactory, aT as ReceiveRotatorBootOpts, aU as ReceiveRotatorBoot, aV as IReadonlyWallet, k as ActivityRegistry, aW as IReadonlyAssetManager, aX as StorageConfig, m as IContractManager, H as HDWalletCapable, a as HDAllocationCapable, A as AddressAllocationCapable, t as IAssetManager, aY as VtxoReservation, r as SendParams, p as IDelegateManager, aZ as IVtxoManager, a_ as Network, a$ as Coin, b0 as SendBitcoinParams, b1 as ExplorerTransaction, b2 as SignedProof, b3 as Proof, b4 as TreeNonces, b5 as TreePartialSigs, T as TxNotificationEvent, b6 as PendingTx, b7 as EmulatorProvider, b8 as Status, b9 as BatchExpiryPolicy, ba as Batch, bb as ChainTx, bc as TxTree, bd as ArkadeService, be as ContractVtxoEvent, bf as ExtendedContractVtxo, bg as ResolvedArkadeService, bh as resolveArkadeService, bi as PathContext } from './index-Bq349_ly.cjs';
2
+ export { bj as AbortError, bk as ActivityIntent, bl as ActivityResolver, bm as ArkError, bn as ArkErrorName, bo as ArkIntent, bp as ArkIntentState, y as ArkProvider, bq as ArkadeCash, br as ArkadeCashAction, bs as ArkadeCashCreateError, bt as ArkadeCashOperatorMismatchError, bu as ArkadeCashUnclaimedReason, bv as ArkadeCashUnclaimedVtxo, bw as ArkadeCashVtxoRef, bx as AssetMetadata, by as BATCH_REGISTRATION_TERMINAL_STATES, bz as BITCOIN_EMULATOR_PUBKEY, bA as BaseWalletConfig, bB as BatchFailedEvent, bC as BatchFinalizationEvent, bD as BatchFinalizedEvent, bE as BatchInfo, bF as BatchRegistrationFilter, bG as BatchRegistrationState, bH as BatchSignableIdentity, bI as BatchStartedEvent, bJ as BoardingUtxoGroup, bK as CandidateDeps, bL as ChainTxType, a7 as ChainedTxType, bM as CommitmentTx, bN as ConnectorTreeNode, bO as ContractBalance, bP as ContractEventCallback, bQ as ContractHandler, bR as ContractManager, bS as ContractManagerConfig, bT as ContractScope, bU as ContractState, bV as ContractVtxo, bW as ContractWatcher, bX as ContractWatcherEventCallback, bY as DEFAULT_ARKADE_EMULATOR_URL, bZ as DEFAULT_MIN_BATCH_EXPIRY_SECONDS, b_ as DEFAULT_VTXO_PAGE_SIZE, b$ as DefaultVtxo, c0 as DelegateManagerImpl, c1 as DelegateOptions, c2 as DelegateProvider, c3 as DelegateVtxo, c4 as DeprecatedSignerMigrationReport, c5 as DeprecatedSignerReport, c6 as DigestMismatchError, c7 as Discoverable, c8 as DiscoveredContract, c9 as DiscoveryDeps, ca as ESPLORA_URL, cb as EmulatorInfo, cc as EsploraProvider, cd as EventSourceCapable, ce as EventSourceFactory, cf as EventSourceLike, cg as EventSourceUnavailableError, ch as ExitCaptureMode, ci as ExitChainResolver, cj as ExitDataSource, ck as ForeignDescriptorError, cl as GetArkadeInfoOptions, cm as GetUtxosOptions, cn as GroupMembership, co as HandlerError, cp as HttpResponseError, cq as INTENT_TERMINAL_STATES, cr as IncomingFunds, cs as IndexedDBWalletRepository, ct as IndexerTxType, cu as IndexerUtxo, cv as IndexerUtxosUnsupportedError, cw as Intent, cx as IntentCoin, cy as IntentFilter, cz as IntentPageFilter, cA as IntentRepository, cB as KeyringDescriptorProvider, cC as KnownMetadata, cD as MAX_PAGE_SIZE, cE as MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, cF as MUTINYNET_EMULATOR_PUBKEY, cG as MigrateDeprecatedSignerOptions, cH as MigrationLegReport, cI as MigrationVtxoRef, cJ as NewAddressType, cK as Nonces, cL as NotifiesIncomingFunds, cM as OnchainCosignAmbiguousError, cN as OnchainCosignRejectedError, cO as OnchainCosignUnsupportedError, cP as Output, cQ as PageResponse, cR as PartialSig, cS as PrevTxSource, cT as PrevTxUnavailableError, cU as ProofInput, cV as ProviderClass, cW as ProviderKind, cX as ProviderUnavailableError, cY as REGTEST_EMULATOR_PUBKEY, cZ as REGTEST_MIN_BATCH_EXPIRY_SECONDS, c_ as RawTxSource, c$ as ReadonlySingleKey, d0 as ReadonlyWalletConfig, d1 as RecipientArkadeAddressContext, d2 as RenewalSplit, d3 as RenewalSplitContext, d4 as RestArkProvider, d5 as RestDelegateProvider, d6 as RestEmulatorProvider, v as RestIndexerProvider, u as RestOperatorProvider, d7 as ScanContractsOptions, d8 as ScanResult, d9 as ScheduledSession, da as ServerInfoSource, db as ServerResponseMismatchError, dc as SettlementEventType, dd as SignRequest, de as SignedIntent, df as SignerClassification, dg as SignerSet, dh as SingleKey, w as SubscriptionEvent, di as SubscriptionFilter, x as SubscriptionHeartbeat, dj as SubscriptionResponse, dk as SweepTxNotification, dl as TapLeaves, dm as TimeHeight, dn as TreeNoncesEvent, dp as TreeSignatureEvent, dq as TreeSignerSession, dr as TreeSigningStartedEvent, ds as TreeTxEvent, dt as Tx, du as TxHistoryRecord, dv as TxKey, dw as TxNotification, dx as TxTag, dy as TxTreeNode, dz as TxType, dA as Vtxo, dB as VtxoChain, dC as VtxoManager, dD as VtxoReservedError, dE as VtxoType, dF as WaitForIncomingFundsOptions, dG as WalletCannotAllocateAddressError, d as WalletConfig, dH as WalletMode, dI as WithPrevTx, dJ as addArkadeCashRecord, dK as arkadeCashId, dL as arkadeCashResolver, dM as assertAllowedSighashTypes, dN as assertPageRequest, dO as assertRecipientArkadeAddress, dP as assertValidBatchExpiry, dQ as assetMintResolver, dR as attachPrevArkTxs, dS as attachPrevoutTxs, dT as boardingResolver, dU as canRecoverOnchain, dV as canSpendOffchain, dW as canSweepOnchain, dX as classifyAgainstSignerSet, dY as classifyContractSigner, dZ as collabExitResolver, d_ as collectBatchRegistrations, d$ as collectContracts, e0 as collectIntents, e1 as collectPages, e2 as collectScriptVtxos, e3 as collectTransactionHistory, e4 as collectUtxos, e5 as collectVtxos, e6 as configureEventSource, e7 as createArkadeCashTracker, e8 as createDefaultActivityRegistry, e9 as createExitChainResolver, ea as defaultBatchExpiryPolicy, eb as defaultEmulatorPubkey, ec as getAllNormalizedVtxos, ed as getConfiguredEventSource, ee as getNetwork, ef as getNormalizedVtxos, eg as getRandomId, eh as hasCandidates, ei as isAddressAllocationCapable, ej as isArkError, ek as isBatchSignable, el as isContractVtxoEvent, em as isCooperativelyMigratable, en as isDiscoverable, eo as isEventSourceUnavailableError, ep as isHDAllocationCapable, eq as isHDWalletCapable, er as isPastExpiry, es as isSigningIdentity, et as isSubdust, eu as isTerminalBatchRegistrationState, ev as isTerminalIntentState, ew as isVirtualCoin, ex as isVtxoExpiringSoon, ey as isVtxoSpent, ez as iteratePages, eA as maybeArkError, eB as mergeArkadeCashRecord, eC as networkFromArkadeInfo, eD as networkFromOperatorInfo, eE as networks, eF as pageResult, eG as resolveBatchExpiryPolicy, eH as resolveDescriptorSigner, eI as resolveEmulatorPubkey, eJ as resolveEventSource, eK as resolvePrevTxs, eL as selectVirtualCoins, eM as signerSetFromInfo, eN as signingDescriptorIndex, eO as strictSigningDescriptorIndex, eP as toOffchainInputFeeParams, eQ as toXOnlySignerHex, eR as waitForIncomingFunds, eS as withPrevTxs } from './index-Bq349_ly.cjs';
3
+ import { T as TapLeafScript, E as EncodedVtxoScript, C as CSVMultisigTapscript, V as VtxoScript, R as RelativeTimelock } from './base-C-Y5t_0F.cjs';
6
4
  export { A as ArkAddress, a as ArkTapscript, b as CLTVMultisigTapscript, c as ConditionCSVMultisigTapscript, d as ConditionMultisigTapscript, M as MultisigTapscript, e as TapTreeCoder, f as TapscriptType, g as decodeTapscript, h as getSequence, s as scriptFromTapLeafScript } from './base-C-Y5t_0F.cjs';
7
- export { A as ArkadeContractHandler, B as BoardingContractHandler, a as BoardingContractParams, D as DefaultContractHandler, b as DefaultContractParams, c as DelegateContractHandler, d as DelegateContractParams, V as VHTLC, e as VHTLCContractHandler, f as VHTLCContractParams, g as VHTLCV2ContractHandler, h as VHTLCV2ContractParams, i as contractHandlers } from './index-Ccfhdfvj.cjs';
8
- export { D as DefaultVtxo, a as DelegateVtxo } from './delegate-gGkUnYpi.cjs';
5
+ export { A as ArkadeContractHandler, B as BoardingContractHandler, a as BoardingContractParams, D as DefaultContractHandler, b as DefaultContractParams, c as DelegateContractHandler, d as DelegateContractParams, V as VHTLC, e as VHTLCContractHandler, f as VHTLCContractParams, g as VHTLCV2ContractHandler, h as VHTLCV2ContractParams, i as contractHandlers } from './index-D4ahI0W6.cjs';
9
6
  import { Bytes, BTC_NETWORK } from '@scure/btc-signer/utils.js';
10
7
  import { Transaction as Transaction$1, OP, Script, ScriptType } from '@scure/btc-signer';
11
8
  import { P2TR } from '@scure/btc-signer/payment.js';
12
9
  import { ElectrumWS } from 'ws-electrumx-client';
13
10
  import { TransactionOutput, TransactionInputUpdate } from '@scure/btc-signer/psbt.js';
14
11
  import * as P from 'micro-packed';
15
- import { P as Program, A as ArkadeArgValue, a as ArkadeProgramScript, b as ProgramKeys, c as ArkadeParamValue, d as ArkadeFunction, I as InputDef, e as ArkadeValueType, C as CompiledProgramFunction, S as SourceRange, f as ArkadeArgType, g as ArkadeContractParams, h as ArkadeSegment, i as AsmToken, j as InputRef, k as SUPPORTED_PROGRAM_VERSION, l as SignerRef, T as TapscriptSegment, m as TweakedSigner, U as UnsupportedProgramVersionError, W as WitnessRef, n as deserializeArkadeContractParams, p as parseArtifact, r as resolveAsm, s as serializeArkadeContractParams, o as stringifyArtifact, v as validateProgram, w as witnessRefToBytes } from './program-znrWkxE4.cjs';
12
+ import { P as Program, A as ArkadeArgValue, a as ArkadeProgramScript, b as ProgramKeys, c as ArkadeParamValue, d as ArkadeFunction, I as InputDef, e as ArkadeValueType, C as CompiledProgramFunction, S as SourceRange, f as ArkadeArgType, g as ArkadeContractParams, h as ArkadeSegment, i as AsmToken, j as InputRef, k as SUPPORTED_PROGRAM_VERSION, l as SignerRef, T as TapscriptSegment, m as TweakedSigner, U as UnsupportedProgramVersionError, W as WitnessRef, n as deserializeArkadeContractParams, p as parseArtifact, r as resolveAsm, s as serializeArkadeContractParams, o as stringifyArtifact, v as validateProgram, w as witnessRefToBytes } from './program-DPzf5qsk.cjs';
16
13
  import '@scure/btc-signer/transaction.js';
17
14
 
18
15
  /** Validate an optional millisecond duration; zero retains its caller-defined meaning. */
@@ -25,11 +22,18 @@ interface WebAuthnClient {
25
22
  create(options: CredentialCreationOptions): Promise<Credential | null>;
26
23
  get(options: CredentialRequestOptions): Promise<Credential | null>;
27
24
  }
25
+ /** Only `"unsupported"` (PRF reported off when the passkey was made, or no WebAuthn) means a passkey never gives
26
+ * a key; after the others it may still give one elsewhere, so a fallback tied to it can meet another wallet. */
27
+ type PrfUnavailableReason = "unsupported" | "unknown" | "no-secret" | "secret-changed" | "malformed" | "unconfirmed";
28
28
  /** The browser or the authenticator cannot return a PRF secret, so this passkey cannot derive a key. */
29
29
  declare class PrfUnavailable extends Error {
30
30
  name: string;
31
- /** Set when the passkey was created before this failure, so an app can still use it some other way. */
31
+ /** Set when the passkey was created before this failure; check `reason` before using it some other way. */
32
32
  credentialId?: Uint8Array;
33
+ readonly reason?: PrfUnavailableReason;
34
+ constructor(message?: string, options?: ErrorOptions & {
35
+ reason?: PrfUnavailableReason;
36
+ });
33
37
  }
34
38
  /** The user dismissed the passkey prompt. */
35
39
  declare class PasskeyCancelled extends Error {
@@ -42,6 +46,7 @@ declare class PasskeyCancelled extends Error {
42
46
  */
43
47
  declare class PasskeyUnconfirmed extends PrfUnavailable {
44
48
  name: string;
49
+ readonly reason = "unconfirmed";
45
50
  }
46
51
  /** The label of a passkey's first wallet, as in Breez's seedless-restore implementation. */
47
52
  declare const DEFAULT_PASSKEY_LABEL = "Default";
@@ -53,7 +58,7 @@ declare function prfSupport(): Promise<"yes" | "no" | "unknown">;
53
58
  * creation returns no PRF result there is nothing to compare that use against, so an authenticator
54
59
  * that changes its secret later is not caught here; it derives other words on the next sign-in.
55
60
  *
56
- * @throws PrfUnavailable when the authenticator cannot do PRF or gives another secret on reuse
61
+ * @throws PrfUnavailable when the authenticator cannot do PRF or gives another secret on reuse; `reason` says which
57
62
  * @throws PasskeyUnconfirmed when the passkey fails its first use right after creation, for any
58
63
  * reason (`cause` holds the error); this and PrfUnavailable carry the new passkey's
59
64
  * `credentialId`, since the passkey exists by then
@@ -313,6 +318,16 @@ declare class Estimator {
313
318
  evaluate(offchainInputs: OffchainInput[], onchainInputs: OnchainInput[], offchainOutputs: FeeOutput[], onchainOutputs: FeeOutput[]): FeeAmount;
314
319
  }
315
320
 
321
+ declare class IndexedDBVtxoReservationRepository implements VtxoReservationRepository, AsyncDisposable {
322
+ readonly version: 1;
323
+ private readonly connection;
324
+ constructor(dbName: string);
325
+ getReservations(): Promise<StoredVtxoReservation[]>;
326
+ saveReservation(reservation: StoredVtxoReservation): Promise<void>;
327
+ deleteReservation(id: string): Promise<void>;
328
+ [Symbol.asyncDispose](): Promise<void>;
329
+ }
330
+
316
331
  declare class InMemoryBatchRegistrationRepository implements BatchRegistrationRepository {
317
332
  readonly version: 1;
318
333
  private byId;
@@ -1072,1163 +1087,65 @@ declare function isDeterministicSigner(value: unknown): value is DeterministicSi
1072
1087
  */
1073
1088
  declare function adoptContractDescriptor(wallet: IWallet, descriptor: string): Promise<void>;
1074
1089
 
1075
- type RequestEnvelope = {
1076
- tag: string;
1077
- id: string;
1078
- broadcast?: boolean;
1090
+ declare class WalletNotInitializedError extends Error {
1091
+ constructor();
1092
+ }
1093
+ declare class ReadonlyWalletError extends Error {
1094
+ constructor();
1095
+ }
1096
+ declare class DelegateNotConfiguredError extends Error {
1097
+ constructor();
1098
+ }
1099
+ type RequestInitWallet = RequestEnvelope & {
1100
+ type: "INIT_WALLET";
1101
+ payload: {
1102
+ arkServerUrl: string;
1103
+ arkServerPublicKey?: string;
1104
+ lazyBoarding?: boolean;
1105
+ };
1079
1106
  };
1080
- type ResponseEnvelope = {
1081
- tag: string;
1082
- id?: string;
1083
- error?: Error;
1084
- /**
1085
- * `error.name`, carried beside the error as an ordinary string. The
1086
- * structured-clone algorithm serializes an Error's `name` only from the
1087
- * built-in whitelist (Error, TypeError, RangeError, …) — a custom name
1088
- * like `ProviderUnavailableError` reaches the page as `"Error"`. A plain
1089
- * property survives verbatim, so the page restores it before rejecting.
1090
- * Absent from workers built before it existed; the page then sees the
1091
- * clone-normalized name, exactly as it always did.
1092
- */
1093
- errorName?: string;
1094
- broadcast?: boolean;
1107
+ type ResponseInitWallet = ResponseEnvelope & {
1108
+ type: "WALLET_INITIALIZED";
1095
1109
  };
1096
- type MessageBusServices = {
1097
- arkProvider: OperatorProvider;
1098
- wallet?: Wallet;
1099
- readonlyWallet: ReadonlyWallet;
1110
+ type RequestSettle = RequestEnvelope & {
1111
+ type: "SETTLE";
1112
+ payload: {
1113
+ params?: SettleParams;
1114
+ };
1100
1115
  };
1101
- interface MessageHandler<REQ extends RequestEnvelope = RequestEnvelope, RES extends ResponseEnvelope = ResponseEnvelope> {
1102
- /**
1103
- * A unique identifier for the updater.
1104
- * This is used to route messages to the correct updater.
1105
- */
1106
- readonly messageTag: string;
1107
- /**
1108
- * Called once when the SW is starting up
1109
- * @param services - Providers and wallet instances available to the handler.
1110
- * @param repositories - Repositories available to the handler.
1111
- * @param channel - Push channel to clients, for responses that answer no
1112
- * request. Use it instead of holding events for the next {@link tick}.
1113
- * The channel is scoped to the generation it was handed out in: after a
1114
- * bus re-init or `stop()` it goes inert on its own, so retaining one past
1115
- * `stop()` cannot post.
1116
- **/
1117
- start(services: MessageBusServices, repositories: {
1118
- walletRepository: WalletRepository;
1119
- }, channel?: {
1120
- broadcast(response: RES): void;
1121
- }): Promise<void>;
1122
- /** Called once when the SW is shutting down */
1123
- stop(): Promise<void>;
1124
- /**
1125
- * Called by the scheduler to perform a tick.
1126
- * Can be used by the updater to perform periodic tasks or return
1127
- * delayed responses (eg: subscriptions).
1128
- * @param now The current time in milliseconds since the epoch.
1129
- **/
1130
- tick(now: number): Promise<RES[]>;
1131
- /**
1132
- * Handle routed messages from the clients
1133
- **/
1134
- handleMessage(message: REQ): Promise<RES | null>;
1135
- /**
1136
- * Optional opt-out from the bus-level message timeout.
1137
- *
1138
- * Long-running flows (e.g. settlement) surrender control to remote peers
1139
- * and can legitimately sit idle for longer than `messageTimeoutMs`. When
1140
- * this returns true, the bus awaits `handleMessage` without a deadline.
1141
- * Defaults to false.
1142
- */
1143
- isLongRunning?(message: REQ): boolean;
1144
- }
1145
- type Options = {
1146
- messageHandlers: MessageHandler[];
1147
- tickIntervalMs?: number;
1148
- messageTimeoutMs?: number;
1149
- /**
1150
- * Per-operation timeout overrides. Keys are either message types
1151
- * (e.g. "SETTLE") or handler tags (e.g. "WALLET_UPDATER"). Message-type
1152
- * matches take precedence over tag matches. Unspecified operations use
1153
- * `messageTimeoutMs`. These are treated as defaults: any map supplied
1154
- * via `INITIALIZE_MESSAGE_BUS` overrides per-key and is re-applied on
1155
- * every (re-)init.
1156
- */
1157
- messageTimeoutOverrides?: Record<string, number>;
1158
- /**
1159
- * Optional intent-lifecycle repository, handed to the worker's wallet as
1160
- * `storage.intentRepository`. Same opt-in as a main-thread wallet: without
1161
- * it the worker persists no settlement intent, reconciles none on restart,
1162
- * and counts intent-locked VTXOs as available. Pass the same repository the
1163
- * main thread uses so both sides read one intent state, but settle from one
1164
- * side only: reconciliation deletes from the server any pending intent the
1165
- * worker's wallet is not settling itself.
1166
- *
1167
- * Ignored when `buildServices` is supplied — that override owns `storage`.
1168
- */
1169
- intentRepository?: BatchRegistrationRepository;
1170
- /** The worker wallet's onchain provider, per network: an instance cannot cross `postMessage`.
1171
- * Called on every init and never closed, so return one instance per network. Defaults to
1172
- * Esplora; ignored when `buildServices` is supplied. */
1173
- onchainProvider?: (network: NetworkName) => OnchainProvider;
1174
- debug?: boolean;
1175
- buildServices?: (config: Initialize["config"]) => Promise<MessageBusServices>;
1116
+ type ResponseSettle = ResponseEnvelope & {
1117
+ type: "SETTLE_SUCCESS";
1118
+ payload: {
1119
+ txid: string;
1120
+ };
1176
1121
  };
1177
- type Initialize = {
1178
- type: "INITIALIZE_MESSAGE_BUS";
1179
- id: string;
1180
- config: {
1181
- wallet: SerializedIdentity;
1182
- arkServer: {
1183
- url: string;
1184
- publicKey?: string;
1185
- };
1186
- delegateUrl?: string;
1187
- settlementConfig?: SettlementConfig | false;
1188
- /** @see WalletConfig.concurrentSpending */
1189
- concurrentSpending?: boolean;
1190
- walletMode?: "auto" | "static" | "hd";
1191
- lazyInitialization?: boolean;
1192
- watcherConfig?: Partial<Omit<ContractWatcherConfig, "indexerProvider">>;
1193
- /** @see WalletConfig.lookAheadWindow */
1194
- lookAheadWindow?: number;
1195
- /** @see WalletConfig.oneShotSubmit */
1196
- oneShotSubmit?: boolean;
1197
- /** @see WalletConfig.minBatchExpirySeconds */
1198
- minBatchExpirySeconds?: bigint;
1199
- /**
1200
- * Page-supplied per-operation timeout map. Keys are message types
1201
- * (e.g. "SETTLE"). Overrides constructor-supplied
1202
- * `messageTimeoutOverrides` per-key; re-applied on every init.
1203
- */
1204
- messageTimeouts?: Record<string, number>;
1122
+ type RequestGetAddress = RequestEnvelope & {
1123
+ type: "GET_ADDRESS";
1124
+ };
1125
+ type ResponseGetAddress = ResponseEnvelope & {
1126
+ type: "ADDRESS";
1127
+ payload: {
1128
+ address: string;
1205
1129
  };
1206
1130
  };
1207
- declare class MessageBus {
1208
- private readonly walletRepository;
1209
- private readonly contractRepository;
1210
- private handlers;
1211
- private tickIntervalMs;
1212
- private messageTimeoutMs;
1213
- private readonly constructorTimeoutOverrides;
1214
- private messageTimeoutOverrides;
1215
- private lateDeliveries;
1216
- private running;
1217
- private tickTimeout;
1218
- private tickInProgress;
1219
- private debug;
1220
- private initialized;
1221
- /**
1222
- * FIFO chain that serializes `INITIALIZE_MESSAGE_BUS` handling. Each init
1223
- * runs to completion in enqueue order.
1224
- */
1225
- private initChain;
1226
- /**
1227
- * Number of inits accepted but not yet settled (queued or running). The
1228
- * bus refuses ordinary wallet messages while this is > 0.
1229
- */
1230
- private pendingInitCount;
1231
- private readonly buildServicesFn;
1232
- private readonly boundOnMessage;
1233
- private readonly intentRepository?;
1234
- private readonly onchainProvider?;
1235
- /** Pending broadcasts, drained FIFO by a single {@link drain} loop. */
1236
- private broadcastQueue;
1237
- private draining;
1238
- /** Bumped wherever the generation owning the queued broadcasts ends. */
1239
- private broadcastEpoch;
1240
- /** Create the service-worker message bus with repositories and handler configuration. */
1241
- constructor(walletRepository: WalletRepository, contractRepository: ContractRepository, { messageHandlers, tickIntervalMs, messageTimeoutMs, messageTimeoutOverrides, intentRepository, onchainProvider, debug, buildServices, }: Options);
1242
- /** Start the message bus and attach service-worker event listeners. */
1243
- start(): Promise<void>;
1244
- /** Stop the message bus, cancel ticks, and stop all registered handlers. */
1245
- stop(): Promise<void>;
1246
- /** Invalidate every broadcast belonging to the outgoing generation. */
1247
- private invalidateBroadcasts;
1248
- private broadcastToClients;
1249
- /**
1250
- * Single fan-out loop, so pushes and tick responses keep one FIFO order.
1251
- * A helper posting per response would race: `clients.matchAll()` gives no
1252
- * cross-call resolution order, and it would de-batch `runTick`.
1253
- */
1254
- private drain;
1255
- /**
1256
- * A dropped batch has no periodic recovery to fall back on now that events
1257
- * no longer ride the tick, so name the loss under {@link Options.debug}.
1258
- */
1259
- private logDroppedBroadcasts;
1260
- private scheduleNextTick;
1261
- private runTick;
1262
- /**
1263
- * Serialize init requests on {@link initChain}.
1264
- * Returns this init's own result.
1265
- */
1266
- private waitForInit;
1267
- /**
1268
- * The bus serves ordinary wallet messages only when it is initialized AND
1269
- * no init is in flight.
1270
- */
1271
- private acceptsWalletMessages;
1272
- private doInit;
1273
- private buildServices;
1274
- private onMessage;
1275
- private processMessage;
1276
- /**
1277
- * Race `promise` against a timeout. Note: this does NOT cancel the
1278
- * underlying work — the original promise keeps running. Call
1279
- * `attachLateDelivery` after catching the timeout to surface the
1280
- * eventual result so the message id does not go silent.
1281
- */
1282
- private withTimeout;
1283
- /**
1284
- * Extract the declared `type` from a request envelope (e.g. "SETTLE").
1285
- * Not every envelope carries a type (PING/INIT are special cased
1286
- * earlier), so this returns undefined for envelopes that lack one.
1287
- */
1288
- private extractMessageType;
1289
- /**
1290
- * Resolve the timeout for an operation. Message-type overrides take
1291
- * precedence over handler-tag overrides, with the bus-wide default
1292
- * (`messageTimeoutMs`) as the final fallback.
1293
- */
1294
- private resolveTimeoutMs;
1295
- /**
1296
- * Build a human-readable label for timeout errors. Format:
1297
- * `"<MESSAGE_TYPE> via <HANDLER_TAG>"` when both are known, else the
1298
- * handler tag alone. Used so timeout errors name the operation the
1299
- * client actually triggered (e.g. SETTLE) rather than just the
1300
- * handler that received it (e.g. WALLET_UPDATER).
1301
- */
1302
- private labelFor;
1303
- /**
1304
- * Post a response to the originating client. When `source` is null
1305
- * (client tab closed, detached frame, etc.) the response cannot be
1306
- * delivered; we log the drop in debug mode so it is not invisible.
1307
- */
1308
- private deliverResponse;
1309
- /**
1310
- * After a handler times out the client has already received a timeout
1311
- * error, but the handler keeps running. Attach a follow-up so the
1312
- * handler's eventual result (or error) is delivered under the same
1313
- * message id, or — if the handler never completes within
1314
- * {@link LATE_DELIVERY_GRACE_MS} — an "Operation abandoned" error is
1315
- * sent so the client's listener (if still attached) does not hang.
1316
- */
1317
- private attachLateDelivery;
1318
- /**
1319
- * Returns the registered SW for the path.
1320
- * It uses the functions in `service-worker-manager.ts` module.
1321
- * @param path
1322
- * @return the Service Worker
1323
- * @throws if not running in a browser environment
1324
- */
1325
- static getServiceWorker(path?: string): Promise<ServiceWorker>;
1326
- /**
1327
- * Set up and register the Service Worker, ensuring it's done once at most.
1328
- * It uses the functions in `service-worker-manager.ts` module.
1329
- * @param path
1330
- * @return the Service Worker
1331
- * @throws if not running in a browser environment
1332
- */
1333
- static setup(path: string): Promise<ServiceWorker>;
1334
- }
1335
-
1336
- /** A leaf node in the Taproot script tree, as consumed by `@scure/btc-signer`'s `p2tr`. */
1337
- interface TaprootLeaf {
1338
- script: Bytes;
1339
- leafVersion: number;
1340
- }
1341
- /** A `p2tr` tree node: a leaf, or a `[left, right]` branch tuple. */
1342
- type TaprootTreeNode = TaprootLeaf | [TaprootTreeNode, TaprootTreeNode];
1343
- /**
1344
- * Assemble a Taproot script tree with btcd's `txscript.AssembleTaprootScriptTree` algorithm
1345
- * (the one arkd uses).
1346
- *
1347
- * `@scure/btc-signer`'s `taprootListToTree` builds a Huffman tree instead; the two agree only for
1348
- * power-of-2 leaf counts. Any other count yields a different merkle root → different output key
1349
- * → arkd rejects spends with `INVALID_PSBT_INPUT`.
1350
- *
1351
- * @param scripts - Raw tapscript bytes per leaf, in TapTree PSBT field order.
1352
- * @returns The nested-tuple form `p2tr` accepts.
1353
- */
1354
- declare function assembleBtcdTaprootTree(scripts: Bytes[]): TaprootTreeNode;
1355
-
1356
- declare enum AssetInputType {
1357
- Unspecified = 0,
1358
- Local = 1,
1359
- /** @deprecated Use {@link AssetInputType.Proof}. */
1360
- Intent = 2,
1361
- Proof = 2
1362
- }
1363
- declare enum AssetRefType {
1364
- Unspecified = 0,
1365
- ByID = 1,
1366
- ByGroup = 2
1367
- }
1368
-
1369
- declare class BufferWriter {
1370
- private buffer;
1371
- write(data: Uint8Array): void;
1372
- writeByte(byte: number): void;
1373
- writeUint16LE(value: number): void;
1374
- writeVarUint(value: bigint | number): void;
1375
- writeVarSlice(data: Uint8Array): void;
1376
- writeCompactSize(value: number): void;
1377
- writeCompactSlice(data: Uint8Array): void;
1378
- toBytes(): Uint8Array;
1379
- }
1380
- declare class BufferReader {
1381
- private view;
1382
- private offset;
1383
- constructor(data: Uint8Array);
1384
- remaining(): number;
1385
- readByte(): number;
1386
- readSlice(size: number): Uint8Array;
1387
- readUint16LE(): number;
1388
- readVarUint(): bigint;
1389
- readVarSlice(): Uint8Array;
1390
- readCompactSize(): number;
1391
- readCompactSlice(): Uint8Array;
1392
- }
1393
-
1394
- /**
1395
- * AssetId identifies a specific asset.
1396
- *
1397
- * @remarks
1398
- * Asset ids are derived from the genesis transaction id plus the asset group index.
1399
- *
1400
- * @see AssetRef
1401
- *
1402
- * @example
1403
- * ```typescript
1404
- * const assetId = AssetId.create('00'.repeat(32), 0)
1405
- * const encoded = assetId.toString()
1406
- * const decoded = AssetId.fromString(encoded)
1407
- * ```
1408
- */
1409
- declare class AssetId {
1410
- readonly txid: Uint8Array;
1411
- readonly groupIndex: number;
1412
- private constructor();
1413
- /**
1414
- * Create a validated asset id from a genesis transaction id and group index.
1415
- *
1416
- * @param txid - Hex-encoded genesis transaction id
1417
- * @param groupIndex - Asset group index within the genesis transaction
1418
- * @throws Error if the txid is missing, malformed, or not 32 bytes long
1419
- * @see fromString
1420
- */
1421
- static create(txid: string, groupIndex: number): AssetId;
1422
- /**
1423
- * Decode an asset id from its hex string representation.
1424
- *
1425
- * @throws Error if the string is not valid hex or does not encode a valid asset id
1426
- * @see toString
1427
- */
1428
- static fromString(s: string): AssetId;
1429
- /**
1430
- * Decode an asset id from its serialized bytes.
1431
- *
1432
- * @throws Error if the buffer length is invalid
1433
- */
1434
- static fromBytes(buf: Uint8Array): AssetId;
1435
- /**
1436
- * Serialize the asset id to raw bytes.
1437
- *
1438
- * @see fromBytes
1439
- */
1440
- serialize(): Uint8Array;
1441
- /**
1442
- * Encode the asset id to a hex string.
1443
- *
1444
- * @see fromString
1445
- */
1446
- toString(): string;
1447
- /**
1448
- * Validate the asset id fields.
1449
- *
1450
- * @throws Error if the txid is empty or the group index is out of range
1451
- */
1452
- validate(): void;
1453
- /**
1454
- * Decode an asset id from a binary reader positioned at one.
1455
- *
1456
- * @throws Error if the reader does not contain enough bytes
1457
- */
1458
- static fromReader(reader: BufferReader): AssetId;
1459
- /**
1460
- * Serialize the asset id into an existing binary writer.
1461
- *
1462
- * @see serialize
1463
- */
1464
- serializeTo(writer: BufferWriter): void;
1465
- }
1466
-
1467
- type AssetRefByID = {
1468
- type: AssetRefType.ByID;
1469
- assetId: AssetId;
1131
+ type RequestGetBoardingAddress = RequestEnvelope & {
1132
+ type: "GET_BOARDING_ADDRESS";
1470
1133
  };
1471
- type AssetRefByGroup = {
1472
- type: AssetRefType.ByGroup;
1473
- groupIndex: number;
1134
+ type ResponseGetBoardingAddress = ResponseEnvelope & {
1135
+ type: "BOARDING_ADDRESS";
1136
+ payload: {
1137
+ address: string;
1138
+ };
1474
1139
  };
1475
- /**
1476
- * Reference to either an explicit asset id or another asset group in the same packet.
1477
- *
1478
- * @see AssetId
1479
- *
1480
- * @example
1481
- * ```typescript
1482
- * const refById = AssetRef.fromId(assetId)
1483
- * const refByGroup = AssetRef.fromGroupIndex(0)
1484
- * ```
1485
- */
1486
- declare class AssetRef {
1487
- readonly ref: AssetRefByID | AssetRefByGroup;
1488
- private constructor();
1489
- /** Reference type discriminator. */
1490
- get type(): AssetRefType;
1491
- /** Reference a specific asset id. @see fromGroupIndex */
1492
- static fromId(assetId: AssetId): AssetRef;
1493
- /**
1494
- * Reference another asset group in the packet.
1495
- *
1496
- * @param groupIndex - Zero-based asset group index in the packet
1497
- * @see fromId
1498
- */
1499
- static fromGroupIndex(groupIndex: number): AssetRef;
1500
- /**
1501
- * Decode an asset reference from hex.
1502
- *
1503
- * @throws Error if the string is not valid hex or does not encode a valid asset reference
1504
- * @see toString
1505
- */
1506
- static fromString(s: string): AssetRef;
1507
- /**
1508
- * Decode an asset reference from its serialized bytes.
1509
- *
1510
- * @throws Error if the buffer is empty or malformed
1511
- */
1512
- static fromBytes(buf: Uint8Array): AssetRef;
1513
- /** Serialize to raw bytes. @see fromBytes */
1514
- serialize(): Uint8Array;
1515
- /** Encode to hex. @see fromString */
1516
- toString(): string;
1517
- /**
1518
- * Decode an asset reference from a reader positioned at one.
1519
- *
1520
- * @throws Error if the type is unknown or the reader does not contain enough bytes
1521
- */
1522
- static fromReader(reader: BufferReader): AssetRef;
1523
- /** Append the serialized reference to `writer`. @see serialize */
1524
- serializeTo(writer: BufferWriter): void;
1525
- }
1526
-
1527
- type AssetInputLocal = {
1528
- type: AssetInputType.Local;
1529
- vin: number;
1530
- amount: bigint;
1140
+ type RequestGetOperatorInfo = RequestEnvelope & {
1141
+ type: "GET_OPERATOR_INFO" | "GET_ARKADE_INFO";
1142
+ payload?: GetOperatorInfoOptions;
1531
1143
  };
1532
- type AssetInputProof = Pick<AssetInputLocal, "vin" | "amount"> & {
1533
- type: AssetInputType.Proof;
1534
- txid: Uint8Array;
1535
- };
1536
- /**
1537
- * AssetInput represents an input of an asset group.
1538
- * a local input references a real transaction input and specify the amount in satoshis.
1539
- * a proof input references an external proof transaction. It is created by the operator to handle batch leaf transaction.
1540
- */
1541
- declare class AssetInput {
1542
- readonly input: AssetInputLocal | AssetInputProof;
1543
- private constructor();
1544
- /** Gets the transaction input index for an asset input, e.g. 0 */
1545
- get vin(): number;
1546
- /** Gets the amount for an input (in most cases, 330 sats) */
1547
- get amount(): bigint;
1548
- /** Create a local asset input that points at a transaction input index. */
1549
- static create(vin: number, amount: bigint | number): AssetInput;
1550
- /** Create a proof-backed asset input referencing an external proof transaction. */
1551
- static createProof(txid: string, vin: number, amount: bigint | number): AssetInput;
1552
- /** @deprecated Use {@link createProof}. */
1553
- static createIntent: typeof AssetInput.createProof;
1554
- /** Decode an asset input from its hex string form. */
1555
- static fromString(s: string): AssetInput;
1556
- /** Decode an asset input from its serialized bytes. */
1557
- static fromBytes(buf: Uint8Array): AssetInput;
1558
- /** Serialize the asset input to raw bytes. */
1559
- serialize(): Uint8Array;
1560
- /** Encode the asset input to a hex string. */
1561
- toString(): string;
1562
- /** Validate the asset input fields. */
1563
- validate(): void;
1564
- /** Decode an asset input from a buffer reader. */
1565
- static fromReader(reader: BufferReader): AssetInput;
1566
- /** Serialize the asset input into an existing buffer writer. */
1567
- serializeTo(writer: BufferWriter): void;
1568
- }
1569
- /**
1570
- * AssetInputs represents a list of asset inputs.
1571
- */
1572
- declare class AssetInputs {
1573
- readonly inputs: AssetInput[];
1574
- private constructor();
1575
- /** Create a validated list of asset inputs. */
1576
- static create(inputs: AssetInput[]): AssetInputs;
1577
- /** Decode an asset input list from its hex string form. */
1578
- static fromString(s: string): AssetInputs;
1579
- /** Serialize the asset input list to raw bytes. */
1580
- serialize(): Uint8Array;
1581
- /** Encode the asset input list to a hex string. */
1582
- toString(): string;
1583
- /** Validate the asset input list. */
1584
- validate(): void;
1585
- /** Decode an asset input list from a buffer reader. */
1586
- static fromReader(reader: BufferReader): AssetInputs;
1587
- /** Serialize the asset input list into an existing buffer writer. */
1588
- serializeTo(writer: BufferWriter): void;
1589
- }
1590
-
1591
- /**
1592
- * AssetOutput references a real transaction output and specify the amount in satoshis.
1593
- * it must be present in an AssetGroup.
1594
- *
1595
- * @param vout - the output index in the transaction
1596
- * @param amount - asset amount in satoshis
1597
- */
1598
- declare class AssetOutput {
1599
- readonly vout: number;
1600
- readonly amount: bigint;
1601
- static readonly TYPE_LOCAL = 1;
1602
- private constructor();
1603
- /** Create a local asset output referencing a transaction output index. */
1604
- static create(vout: number, amount: bigint | number): AssetOutput;
1605
- /** Decode an asset output from its hex string form. */
1606
- static fromString(s: string): AssetOutput;
1607
- /** Decode an asset output from its serialized bytes. */
1608
- static fromBytes(buf: Uint8Array): AssetOutput;
1609
- /** Serialize the asset output to raw bytes. */
1610
- serialize(): Uint8Array;
1611
- /** Encode the asset output to a hex string. */
1612
- toString(): string;
1613
- /** Validate the asset output fields. */
1614
- validate(): void;
1615
- /** Decode an asset output from a buffer reader. */
1616
- static fromReader(reader: BufferReader): AssetOutput;
1617
- /** Serialize the asset output into an existing buffer writer. */
1618
- serializeTo(writer: BufferWriter): void;
1619
- }
1620
- /**
1621
- * AssetOutputs is a list of AssetOutput references.
1622
- * it must be present in an AssetGroup.
1623
- *
1624
- * @param outputs - the list of asset outputs
1625
- */
1626
- declare class AssetOutputs {
1627
- readonly outputs: AssetOutput[];
1628
- private constructor();
1629
- /** Create a validated list of asset outputs. */
1630
- static create(outputs: AssetOutput[]): AssetOutputs;
1631
- /** Decode an asset output list from its hex string form. */
1632
- static fromString(s: string): AssetOutputs;
1633
- /** Serialize the asset output list to raw bytes. */
1634
- serialize(): Uint8Array;
1635
- /** Encode the asset output list to a hex string. */
1636
- toString(): string;
1637
- /** Validate the asset output list. */
1638
- validate(): void;
1639
- /** Decode an asset output list from a buffer reader. */
1640
- static fromReader(reader: BufferReader): AssetOutputs;
1641
- /** Serialize the asset output list into an existing buffer writer. */
1642
- serializeTo(writer: BufferWriter): void;
1643
- }
1644
-
1645
- /**
1646
- * Metadata represents a key-value pair.
1647
- * @param key - the key
1648
- * @param value - the value
1649
- */
1650
- declare class Metadata {
1651
- readonly key: Uint8Array;
1652
- readonly value: Uint8Array;
1653
- private constructor();
1654
- /** Create a metadata entry from raw key and value bytes. */
1655
- static create(key: Bytes, value: Bytes): Metadata;
1656
- /** Decode metadata from its hex string form. */
1657
- static fromString(s: string): Metadata;
1658
- /** Decode metadata from its serialized bytes. */
1659
- static fromBytes(buf: Uint8Array): Metadata;
1660
- /** Serialize metadata to raw bytes. */
1661
- serialize(): Uint8Array;
1662
- /** Encode metadata to a hex string. */
1663
- toString(): string;
1664
- get keyString(): string;
1665
- get valueString(): string;
1666
- /** Validate the metadata key and value. */
1667
- validate(): void;
1668
- /** Decode metadata from a buffer reader. */
1669
- static fromReader(reader: BufferReader): Metadata;
1670
- /** Serialize metadata into an existing buffer writer. */
1671
- serializeTo(writer: BufferWriter): void;
1672
- }
1673
- declare class MetadataList {
1674
- readonly items: Metadata[];
1675
- static readonly ARK_LEAF_TAG = "ArkadeAssetLeaf";
1676
- static readonly ARK_BRANCH_TAG = "ArkadeAssetBranch";
1677
- static readonly ARK_LEAF_VERSION = 0;
1678
- constructor(items: Metadata[]);
1679
- /** Create a metadata list from its hex string form. */
1680
- static fromString(s: string): MetadataList;
1681
- /** Decode a metadata list from its serialized bytes. */
1682
- static fromBytes(buf: Uint8Array): MetadataList;
1683
- /** Decode a metadata list from a buffer reader. */
1684
- static fromReader(reader: BufferReader): MetadataList;
1685
- /** Serialize the metadata list into an existing buffer writer. */
1686
- serializeTo(writer: BufferWriter): void;
1687
- /** Serialize the metadata list to raw bytes. */
1688
- serialize(): Uint8Array;
1689
- /** Iterate through metadata entries in insertion order. */
1690
- [Symbol.iterator](): Iterator<Metadata>;
1691
- get length(): number;
1692
- /** Compute the tagged Merkle root for the metadata list. */
1693
- hash(): Uint8Array;
1694
- }
1695
-
1696
- /**
1697
- * An asset group contains inputs, outputs, and all data related to a given asset id.
1698
- *
1699
- * @see Packet
1700
- * @see AssetId
1701
- * @see AssetRef
1702
- *
1703
- * @example
1704
- * ```typescript
1705
- * const group = AssetGroup.create(
1706
- * null, // asset ID: null for new issuance
1707
- * null, // control asset ID: null when reissuance not needed
1708
- * [], // asset inputs: empty for new issuance
1709
- * [AssetOutput.create(0, 1000)], // asset outputs: 1000 units at vout index 0
1710
- * [] // metadata: can be empty
1711
- * )
1712
- * ```
1713
- */
1714
- declare class AssetGroup {
1715
- readonly assetId: AssetId | null;
1716
- readonly controlAsset: AssetRef | null;
1717
- readonly inputs: AssetInput[];
1718
- readonly outputs: AssetOutput[];
1719
- private readonly metadataList;
1720
- /** @see create */
1721
- constructor(assetId: AssetId | null, controlAsset: AssetRef | null, inputs: AssetInput[], outputs: AssetOutput[], metadata: Metadata[]);
1722
- /**
1723
- * Create and validate an asset group.
1724
- *
1725
- * @param assetId - Asset id for this group, or `null` for fresh issuance
1726
- * @param controlAsset - Optional control asset reference for (re) issuance
1727
- * @param inputs - Asset inputs in the group
1728
- * @param outputs - Asset outputs in the group
1729
- * @param metadata - Metadata entries associated with the group
1730
- * @returns A validated asset group
1731
- * @throws Error if the group fails validation
1732
- * @see validate
1733
- */
1734
- static create(assetId: AssetId | null, controlAsset: AssetRef | null, inputs: AssetInput[], outputs: AssetOutput[], metadata: Metadata[]): AssetGroup;
1735
- /**
1736
- * Decode an asset group from its hex string form.
1737
- *
1738
- * @param s - Hex-encoded asset group
1739
- * @returns Decoded asset group
1740
- * @throws Error if the string is not valid hex or does not encode a valid asset group
1741
- * @see toString
1742
- */
1743
- static fromString(s: string): AssetGroup;
1744
- /**
1745
- * Decode an asset group from its serialized bytes.
1746
- *
1747
- * @param buf - Serialized asset group bytes
1748
- * @returns Decoded asset group
1749
- * @throws Error if the buffer is empty or malformed
1750
- */
1751
- static fromBytes(buf: Uint8Array): AssetGroup;
1752
- /**
1753
- * Return true when the group represents an issuance.
1754
- *
1755
- * @returns `true` when the group has no asset id
1756
- */
1757
- isIssuance(): boolean;
1758
- /**
1759
- * Return true when the group represents a reissuance.
1760
- *
1761
- * @returns `true` when the group has an asset id and outputs exceed local inputs
1762
- * @remarks
1763
- * Only local inputs contribute to the comparison; proof-backed inputs contribute `0` here.
1764
- */
1765
- isReissuance(): boolean;
1766
- /**
1767
- * Serialize the asset group to raw bytes.
1768
- *
1769
- * @returns Serialized asset group bytes
1770
- * @see fromBytes
1771
- */
1772
- serialize(): Uint8Array;
1773
- /**
1774
- * Validate the asset group and its child structures.
1775
- *
1776
- * @throws Error if the group is empty or violates issuance invariants
1777
- */
1778
- validate(): void;
1779
- /**
1780
- * Convert the group into its batch-leaf representation for the given proof txid.
1781
- *
1782
- * @param proofTxid - Proof transaction id used to build the leaf input reference
1783
- * @returns Batch-leaf asset group
1784
- * @see AssetInput.createProof
1785
- */
1786
- toBatchLeafAssetGroup(proofTxid: Uint8Array): AssetGroup;
1787
- /**
1788
- * Encode the asset group to a hex string.
1789
- *
1790
- * @returns Hex-encoded asset group
1791
- * @see fromString
1792
- */
1793
- toString(): string;
1794
- /**
1795
- * Decode an asset group from a binary reader.
1796
- *
1797
- * @param reader - Reader positioned at an asset group
1798
- * @returns Decoded asset group
1799
- * @throws Error if the encoded group is malformed
1800
- */
1801
- static fromReader(reader: BufferReader): AssetGroup;
1802
- /**
1803
- * Serialize the asset group into an existing binary writer.
1804
- *
1805
- * @param writer - Writer to append the asset group to
1806
- */
1807
- serializeTo(writer: BufferWriter): void;
1808
- }
1809
-
1810
- /**
1811
- * ExtensionPacket is the interface that all extension packets must implement.
1812
- * It mirrors the Go extension.Packet interface.
1813
- */
1814
- interface ExtensionPacket {
1815
- /** type returns the 1-byte packet type tag */
1816
- type(): number;
1817
- /** serialize returns the raw bytes of the packet (without type or length prefix) */
1818
- serialize(): Uint8Array;
1819
- }
1820
- /**
1821
- * UnknownPacket holds a packet whose type is not recognized by this implementation.
1822
- * It round-trips opaquely: the raw bytes are preserved as-is.
1823
- */
1824
- declare class UnknownPacket implements ExtensionPacket {
1825
- private readonly packetType;
1826
- private readonly data;
1827
- constructor(packetType: number, data: Uint8Array);
1828
- type(): number;
1829
- serialize(): Uint8Array;
1830
- }
1831
-
1832
- /**
1833
- * Packet represents a collection of asset groups.
1834
- * It encodes/decodes as raw bytes only — OP_RETURN framing is handled by the Extension module.
1835
- */
1836
- declare class Packet implements ExtensionPacket {
1837
- readonly groups: AssetGroup[];
1838
- /** PACKET_TYPE is the 1-byte TLV type tag used in the Extension envelope. */
1839
- static readonly PACKET_TYPE = 0;
1840
- private constructor();
1841
- /** Create a validated asset packet from a list of asset groups. */
1842
- static create(groups: AssetGroup[]): Packet;
1843
- /**
1844
- * fromBytes parses a Packet from raw bytes.
1845
- */
1846
- static fromBytes(buf: Uint8Array): Packet;
1847
- /**
1848
- * fromString parses a Packet from a raw hex string (not an OP_RETURN script).
1849
- */
1850
- static fromString(s: string): Packet;
1851
- /**
1852
- * type returns the TLV packet type tag. Implements ExtensionPacket interface.
1853
- */
1854
- type(): number;
1855
- /** Convert the packet into the batch-leaf form for a specific proof transaction id. */
1856
- leafTxPacket(proofTxid: Uint8Array): Packet;
1857
- /**
1858
- * serialize encodes the packet as raw bytes (varint group count + group data).
1859
- * Does NOT include OP_RETURN, Arkade magic bytes (`ARK`), or TLV type/length; those are
1860
- * added by the Extension module.
1861
- */
1862
- serialize(): Uint8Array;
1863
- /**
1864
- * toString returns the hex-encoded raw packet bytes.
1865
- */
1866
- toString(): string;
1867
- /** Validate packet structure and cross-group references. */
1868
- validate(): void;
1869
- private static fromReader;
1870
- }
1871
-
1872
- /**
1873
- * Cross-repo test vectors for the Arkade Asset ID encodings.
1874
- *
1875
- * @remarks
1876
- * Shipped from `src/` rather than `test/` so consumers outside this package can
1877
- * pin the same bytes: `lightning-swap-service` imports this value, while NArk
1878
- * and go-sdk vendor the backing `assetIdVectors.json` from a pinned revision of
1879
- * this repository. The encoding is implemented in seven places across three
1880
- * repos, and every disagreement fails silently (a flipped txid makes a covenant
1881
- * unsatisfiable, a flipped group index resolves to a different asset).
1882
- */
1883
- interface AssetIdVectors {
1884
- readonly version: number;
1885
- readonly note: string;
1886
- /** Genesis txid in display order — the 32 bytes an id's leading 64 hex chars carry. */
1887
- readonly txid_hex: string;
1888
- /** `txid_hex` reversed: serialization order, what the introspection opcodes match. */
1889
- readonly script_txid_hex: string;
1890
- readonly valid: ReadonlyArray<{
1891
- readonly label: string;
1892
- readonly group_index: number;
1893
- /** `txid_hex` with the group index appended little-endian. */
1894
- readonly asset_id_hex: string;
1895
- /**
1896
- * The group index as a stack item, after script-number encoding and
1897
- * before push framing. Not the raw u16: `65535` is `ffff00` here and
1898
- * `ffff` on the wire, and `0` is the empty item.
1899
- */
1900
- readonly script_group_index_item_hex: string;
1901
- }>;
1902
- /** Refused by the identity rule (`^[0-9a-f]{68}$`), though not necessarily by the decoder. */
1903
- readonly invalid_identity: ReadonlyArray<{
1904
- readonly label: string;
1905
- readonly value: string;
1906
- readonly why: string;
1907
- /** Present when the value still decodes: what `toString()` must return. */
1908
- readonly normalizes_to?: string;
1909
- }>;
1910
- /** Refused by {@link AssetId.fromString} / `fromBytes`. */
1911
- readonly invalid_decode: ReadonlyArray<{
1912
- readonly label: string;
1913
- readonly value: string;
1914
- /** Substring of the thrown message — normative for TS, advisory for other SDKs. */
1915
- readonly expected_error: string;
1916
- }>;
1917
- /** Refused by {@link AssetId.create} / `validate`. */
1918
- readonly invalid_construction: ReadonlyArray<{
1919
- readonly label: string;
1920
- readonly txid_hex: string;
1921
- readonly group_index: number;
1922
- readonly expected_error: string;
1923
- /** Set when the group index cannot be expressed by an SDK whose constructor takes a native u16. */
1924
- readonly outside_uint16?: boolean;
1925
- }>;
1926
- }
1927
- /**
1928
- * The asset-id test vectors, deeply frozen.
1929
- *
1930
- * @remarks
1931
- * Frozen all the way down: the module is a singleton, and one consumer mutating
1932
- * a nested entry would corrupt it for every other consumer in the process.
1933
- *
1934
- * @example
1935
- * ```typescript
1936
- * import { asset } from '@arkade-os/sdk'
1937
- * const { txid_hex, valid } = asset.ASSET_ID_VECTORS
1938
- * expect(AssetId.create(txid_hex, valid[0].group_index).toString()).toBe(valid[0].asset_id_hex)
1939
- * ```
1940
- */
1941
- declare const ASSET_ID_VECTORS: AssetIdVectors;
1942
-
1943
- declare const index$1_ASSET_ID_VECTORS: typeof ASSET_ID_VECTORS;
1944
- type index$1_AssetGroup = AssetGroup;
1945
- declare const index$1_AssetGroup: typeof AssetGroup;
1946
- type index$1_AssetId = AssetId;
1947
- declare const index$1_AssetId: typeof AssetId;
1948
- type index$1_AssetIdVectors = AssetIdVectors;
1949
- type index$1_AssetInput = AssetInput;
1950
- declare const index$1_AssetInput: typeof AssetInput;
1951
- type index$1_AssetInputType = AssetInputType;
1952
- declare const index$1_AssetInputType: typeof AssetInputType;
1953
- type index$1_AssetInputs = AssetInputs;
1954
- declare const index$1_AssetInputs: typeof AssetInputs;
1955
- type index$1_AssetOutput = AssetOutput;
1956
- declare const index$1_AssetOutput: typeof AssetOutput;
1957
- type index$1_AssetOutputs = AssetOutputs;
1958
- declare const index$1_AssetOutputs: typeof AssetOutputs;
1959
- type index$1_AssetRef = AssetRef;
1960
- declare const index$1_AssetRef: typeof AssetRef;
1961
- type index$1_AssetRefType = AssetRefType;
1962
- declare const index$1_AssetRefType: typeof AssetRefType;
1963
- type index$1_Metadata = Metadata;
1964
- declare const index$1_Metadata: typeof Metadata;
1965
- type index$1_MetadataList = MetadataList;
1966
- declare const index$1_MetadataList: typeof MetadataList;
1967
- type index$1_Packet = Packet;
1968
- declare const index$1_Packet: typeof Packet;
1969
- declare namespace index$1 {
1970
- export { index$1_ASSET_ID_VECTORS as ASSET_ID_VECTORS, index$1_AssetGroup as AssetGroup, index$1_AssetId as AssetId, type index$1_AssetIdVectors as AssetIdVectors, index$1_AssetInput as AssetInput, index$1_AssetInputType as AssetInputType, index$1_AssetInputs as AssetInputs, index$1_AssetOutput as AssetOutput, index$1_AssetOutputs as AssetOutputs, index$1_AssetRef as AssetRef, index$1_AssetRefType as AssetRefType, index$1_Metadata as Metadata, index$1_MetadataList as MetadataList, index$1_Packet as Packet };
1971
- }
1972
-
1973
- /**
1974
- * Creates an asset packet from asset inputs and receivers.
1975
- * Groups inputs and outputs by asset ID and creates the Packet object
1976
- * @param assetInputs - map input index -> assets
1977
- * @param receivers - array of recipients with their asset allocations
1978
- * @param changeReceiver - (optional) change receiver containing remaining assets
1979
- * @returns packet containing all asset groups
1980
- */
1981
- declare function createAssetPacket(assetInputs: Map<number, Asset[]>, receivers: Recipient[], changeReceiver?: Recipient): Packet;
1982
- /**
1983
- * Selects coins that contain a specific asset.
1984
- * Returns coins sorted by amount (smallest first for better coin selection).
1985
- */
1986
- declare function selectCoinsWithAsset(coins: ExtendedVirtualCoin[], assetId: string, requiredAmount: bigint): {
1987
- selected: ExtendedVirtualCoin[];
1988
- totalAssetAmount: bigint;
1989
- };
1990
-
1991
- /**
1992
- * Thrown when a collaborative-exit / offboard would leave a change VTXO below
1993
- * the dust threshold. Lets callers (e.g. wallet UI) react with appropriate UX
1994
- * — for instance, offering to exit the full balance — instead of forwarding a
1995
- * server-side dust rejection to the user.
1996
- */
1997
- declare class DustChangeError extends Error {
1998
- readonly change: bigint;
1999
- readonly dustAmount: bigint;
2000
- constructor(change: bigint, dustAmount: bigint);
2001
- }
2002
- /** Thrown when a collaborative exit's change VTXO is above the server's
2003
- * per-output ceiling, which arkd answers with `AMOUNT_TOO_HIGH`. */
2004
- declare class OversizedChangeError extends Error {
2005
- readonly change: bigint;
2006
- readonly maxAmount: bigint;
2007
- constructor(change: bigint, maxAmount: bigint);
2008
- }
2009
- /**
2010
- * Ramps is a class wrapping `settle` method to provide a more convenient interface for onboarding and offboarding operations.
2011
- *
2012
- * @see IWallet.settle
2013
- * @see onboard
2014
- * @see offboard
2015
- *
2016
- * @example
2017
- * ```typescript
2018
- * const ramps = new Ramps(wallet);
2019
- * const feeInfo = { intentFee: {}, txFeeRate: '1' };
2020
- * await ramps.onboard(feeInfo); // onboard all boarding inputs
2021
- * await ramps.offboard('bc1q...', feeInfo); // collaboratively exit all virtual outputs to an onchain address
2022
- * ```
2023
- */
2024
- declare class Ramps {
2025
- readonly wallet: IWallet;
2026
- /**
2027
- * Create convenience wrappers for onboarding and offboarding flows.
2028
- *
2029
- * @param wallet - Wallet used to query funds and execute settlement transactions
2030
- */
2031
- constructor(wallet: IWallet);
2032
- /**
2033
- * Onboard boarding inputs.
2034
- *
2035
- * @param feeInfo - The fee info to deduct from the onboard amount.
2036
- * @param boardingUtxos - Specific boarding inputs to onboard. If not provided, all boarding inputs will be used.
2037
- * @param amount - Amount to onboard. If not provided, the total amount of boarding inputs will be onboarded.
2038
- * @param eventCallback - Optional callback that receives settlement events
2039
- * @returns The Arkade transaction id created by settlement
2040
- * @throws Error if no boarding inputs remain after fee deduction or if `amount` exceeds available value
2041
- * @see IWallet.getBoardingUtxos
2042
- * @see IWallet.settle
2043
- * @example
2044
- * ```typescript
2045
- * const feeInfo = { intentFee: {}, txFeeRate: '1' };
2046
- * const ramps = new Ramps(wallet);
2047
- * await ramps.onboard(feeInfo);
2048
- * ```
2049
- */
2050
- onboard(feeInfo: FeeInfo, boardingUtxos?: ExtendedCoin[], amount?: bigint, eventCallback?: (event: SettlementEvent) => void): ReturnType<IWallet["settle"]>;
2051
- /**
2052
- * Offboard virtual outputs, or collaboratively exit them to an onchain address.
2053
- *
2054
- * @param destinationAddress - The destination address to offboard to.
2055
- * @param feeInfo - The fee info to deduct from the offboard amount.
2056
- * @param amount - The amount to offboard. If not provided, the total amount of virtual outputs will be offboarded.
2057
- * @param eventCallback - Optional callback that receives settlement events
2058
- * @param vtxos - Specific virtual outputs to spend, mirroring {@link onboard}'s
2059
- * `boardingUtxos`. Omitted, every spendable one is spent — merging the whole
2060
- * off-chain balance into a single change output. Taken as given like
2061
- * `settle({ inputs })`: an `amount` these cannot cover is an error, not a top-up.
2062
- * @returns The Arkade transaction id created by settlement
2063
- * @throws Error if no virtual outputs remain after fee deduction or the destination address cannot be decoded
2064
- * @see IWallet.getSpendableVtxos
2065
- * @see IWallet.settle
2066
- * @example
2067
- * ```typescript
2068
- * const feeInfo = { intentFee: {}, txFeeRate: '1' };
2069
- * const ramps = new Ramps(wallet);
2070
- * await ramps.offboard('bc1q...', feeInfo);
2071
- * ```
2072
- */
2073
- offboard(destinationAddress: string, feeInfo: FeeInfo, amount?: bigint, eventCallback?: (event: SettlementEvent) => void, vtxos?: NormalizedExtendedVirtualCoin[]): ReturnType<IWallet["settle"]>;
2074
- /**
2075
- * Collaboratively exit with the DESTINATION paid exactly `amount`, pricing the
2076
- * fee on that output rather than on a grossed-up figure. {@link offboard} keeps
2077
- * the other anchor, which needs `g - fee(g) = amount` solved — impossible for
2078
- * a program charging the whole output.
2079
- *
2080
- * Returns the onchain txid instead when onchain coins alone cover `amount`
2081
- * and were spent via arkd cosigning.
2082
- */
2083
- offboardExact(params: {
2084
- destinationAddress: string;
2085
- feeInfo: FeeInfo;
2086
- /** Sats the destination receives, exactly. */
2087
- amount: bigint;
2088
- eventCallback?: (event: SettlementEvent) => void;
2089
- vtxos?: NormalizedExtendedVirtualCoin[];
2090
- }): ReturnType<IWallet["settle"]>;
2091
- private tryCosign;
2092
- private offboardInputs;
2093
- /** Every candidate, or with `concurrentSpending` the shortest covering prefix in send order. */
2094
- private fundExit;
2095
- /** Re-runs an SDK-picked exit that lost a coin to a concurrent spend. */
2096
- private withRepick;
2097
- /** Fund the change output: pay its own fee, then judge it against both
2098
- * server-side bounds. `0n` in is `0n` out — no change output at all. */
2099
- private fundChange;
2100
- }
2101
-
2102
- /**
2103
- * HD-wallet {@link DescriptorProvider} that allocates a fresh signing descriptor on every call.
2104
- * A pure rotating allocator: which descriptor the wallet is bound to is answered by the contract
2105
- * repository, not this provider.
2106
- *
2107
- * State lives in `settings.hd` of the wallet state, so switching single-key → HD needs no schema
2108
- * migration. Allocation runs inside the shared per-repo `updateWalletState` mutex, so callers
2109
- * (even on separate instances over one repo) never observe the same index.
2110
- *
2111
- * @example
2112
- * ```ts
2113
- * const provider = await HDDescriptorProvider.create(identity, walletRepo);
2114
- * const descriptor = await provider.getNextSigningDescriptor();
2115
- * // descriptor: tr([fp/86'/0'/0']xpub/0/0)
2116
- * const next = await provider.getNextSigningDescriptor();
2117
- * // next: tr([fp/86'/0'/0']xpub/0/1)
2118
- * ```
2119
- */
2120
- declare class HDDescriptorProvider implements DescriptorProvider, ReceiveRotatorFactory {
2121
- private readonly identity;
2122
- private readonly walletRepository;
2123
- private constructor();
2124
- /**
2125
- * Construct an HDDescriptorProvider. No I/O: state is read lazily, so a descriptor-mismatch
2126
- * error surfaces on first use rather than here.
2127
- */
2128
- static create(identity: HDCapableIdentity, walletRepository: WalletRepository): Promise<HDDescriptorProvider>;
2129
- /** Allocate and return the next descriptor (index 0, 1, 2, …), atomically per repo. */
2130
- getNextSigningDescriptor(): Promise<string>;
2131
- /**
2132
- * Re-derive the descriptor `getNextSigningDescriptor` last returned, WITHOUT advancing;
2133
- * `undefined` if none was ever allocated. Lets boot keep the display address stable across
2134
- * restarts when no tagged display contract exists, instead of burning a new index.
2135
- */
2136
- getCurrentSigningDescriptor(): Promise<string | undefined>;
2137
- /** Read-only peek at the allocation watermark; `undefined` if nothing was ever allocated. */
2138
- getLastIndexUsed(): Promise<number | undefined>;
2139
- /**
2140
- * Monotonically advance the watermark past indices found by a restore scan; never rewinds.
2141
- * An invalid `index` (non-integer, negative, or >= 2^31) is ignored: persisting it would make
2142
- * `parseSettings()` throw, and a watermark at the hardened ceiling would fail every later
2143
- * allocation for the life of the repo.
2144
- */
2145
- advanceLastIndexUsed(index: number): Promise<void>;
2146
- /** Whether `descriptor` (HD or simple `tr(pubkey)`) is derivable from this wallet's seed. */
2147
- isOurs(descriptor: string): boolean;
2148
- /** Signs each request with its descriptor's derived key (the identity holds the seed). */
2149
- signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]>;
2150
- /** Signs a message using the key derived from `descriptor`. */
2151
- signMessageWithDescriptor(descriptor: string, message: Uint8Array, signatureType?: "schnorr" | "ecdsa"): Promise<Uint8Array>;
2152
- /** HD providers take part in receive rotation via {@link WalletReceiveRotator.defaultBoot}. */
2153
- createReceiveRotator(opts: ReceiveRotatorBootOpts): Promise<ReceiveRotatorBoot | undefined>;
2154
- /**
2155
- * Materialize the account template at `index` via the descriptors-scure parser (validates the
2156
- * ranged template and yields a canonical key expression) rather than string substitution.
2157
- * Pure: does NOT advance the watermark, so restore's gap-scan can peek arbitrary indices.
2158
- */
2159
- materializeDescriptorAt(index: number): string;
2160
- /**
2161
- * Read-modify-write HD settings inside the shared per-repo wallet-state mutex; `fn` mutates a
2162
- * validated snapshot that is persisted atomically. Reading inside the lock prevents races on a
2163
- * stale index.
2164
- */
2165
- private mutate;
2166
- /**
2167
- * Validate persisted HD settings (or init a fresh record) and return a mutable clone. Fails
2168
- * loud: a corrupt repo would otherwise derive `NaN` descriptors.
2169
- */
2170
- private parseSettings;
2171
- }
2172
-
2173
- declare class WalletNotInitializedError extends Error {
2174
- constructor();
2175
- }
2176
- declare class ReadonlyWalletError extends Error {
2177
- constructor();
2178
- }
2179
- declare class DelegateNotConfiguredError extends Error {
2180
- constructor();
2181
- }
2182
- type RequestInitWallet = RequestEnvelope & {
2183
- type: "INIT_WALLET";
2184
- payload: {
2185
- arkServerUrl: string;
2186
- arkServerPublicKey?: string;
2187
- lazyBoarding?: boolean;
2188
- };
2189
- };
2190
- type ResponseInitWallet = ResponseEnvelope & {
2191
- type: "WALLET_INITIALIZED";
2192
- };
2193
- type RequestSettle = RequestEnvelope & {
2194
- type: "SETTLE";
2195
- payload: {
2196
- params?: SettleParams;
2197
- };
2198
- };
2199
- type ResponseSettle = ResponseEnvelope & {
2200
- type: "SETTLE_SUCCESS";
2201
- payload: {
2202
- txid: string;
2203
- };
2204
- };
2205
- type RequestGetAddress = RequestEnvelope & {
2206
- type: "GET_ADDRESS";
2207
- };
2208
- type ResponseGetAddress = ResponseEnvelope & {
2209
- type: "ADDRESS";
2210
- payload: {
2211
- address: string;
2212
- };
2213
- };
2214
- type RequestGetBoardingAddress = RequestEnvelope & {
2215
- type: "GET_BOARDING_ADDRESS";
2216
- };
2217
- type ResponseGetBoardingAddress = ResponseEnvelope & {
2218
- type: "BOARDING_ADDRESS";
2219
- payload: {
2220
- address: string;
2221
- };
2222
- };
2223
- type RequestGetOperatorInfo = RequestEnvelope & {
2224
- type: "GET_OPERATOR_INFO" | "GET_ARKADE_INFO";
2225
- payload?: GetOperatorInfoOptions;
2226
- };
2227
- type ResponseGetOperatorInfo = ResponseEnvelope & {
2228
- type: "OPERATOR_INFO";
2229
- payload: {
2230
- info: OperatorInfo;
2231
- };
1144
+ type ResponseGetOperatorInfo = ResponseEnvelope & {
1145
+ type: "OPERATOR_INFO";
1146
+ payload: {
1147
+ info: OperatorInfo;
1148
+ };
2232
1149
  };
2233
1150
  type RequestIndexerGetVtxos = RequestEnvelope & {
2234
1151
  type: "INDEXER_GET_VTXOS";
@@ -2338,6 +1255,7 @@ type ResponseGetStatus = ResponseEnvelope & {
2338
1255
  payload: {
2339
1256
  walletInitialized: boolean;
2340
1257
  xOnlyPublicKey: Uint8Array | undefined;
1258
+ walletRequestBinding?: WalletRequestBinding;
2341
1259
  providerConnectionState?: ProviderConnectionState;
2342
1260
  };
2343
1261
  };
@@ -2668,6 +1586,29 @@ type ResponseContractEvent = ResponseEnvelope & {
2668
1586
  event: ContractEvent;
2669
1587
  };
2670
1588
  };
1589
+ type RequestReserveVtxos = RequestEnvelope & {
1590
+ type: "RESERVE_SCOPED_VTXOS";
1591
+ payload: {
1592
+ outpoints: Outpoint[];
1593
+ reservationId: string;
1594
+ scope: string;
1595
+ };
1596
+ };
1597
+ type ResponseReserveVtxos = ResponseEnvelope & {
1598
+ type: "VTXOS_RESERVED";
1599
+ };
1600
+ type RequestReleaseVtxos = RequestEnvelope & {
1601
+ type: "RELEASE_SCOPED_VTXOS";
1602
+ /** With `outpoints`, a no-op once the id names other inputs. */
1603
+ payload: {
1604
+ reservationId: string;
1605
+ scope: string;
1606
+ outpoints?: Outpoint[];
1607
+ };
1608
+ };
1609
+ type ResponseReleaseVtxos = ResponseEnvelope & {
1610
+ type: "VTXOS_RELEASED";
1611
+ };
2671
1612
  type RequestSend = RequestEnvelope & {
2672
1613
  type: "SEND";
2673
1614
  payload: {
@@ -2851,239 +1792,1370 @@ type ResponseGetExpiredBoardingUtxos = ResponseEnvelope & {
2851
1792
  type RequestSweepExpiredBoardingUtxos = RequestEnvelope & {
2852
1793
  type: "SWEEP_EXPIRED_BOARDING_UTXOS";
2853
1794
  };
2854
- type ResponseSweepExpiredBoardingUtxos = ResponseEnvelope & {
2855
- type: "SWEEP_EXPIRED_BOARDING_UTXOS_SUCCESS";
2856
- payload: {
2857
- txid: string;
2858
- };
1795
+ type ResponseSweepExpiredBoardingUtxos = ResponseEnvelope & {
1796
+ type: "SWEEP_EXPIRED_BOARDING_UTXOS_SUCCESS";
1797
+ payload: {
1798
+ txid: string;
1799
+ };
1800
+ };
1801
+ type RequestCosignOnchainTx = RequestEnvelope & {
1802
+ type: "COSIGN_ONCHAIN_TX";
1803
+ /** Base64 PSBT. */
1804
+ payload: {
1805
+ psbt: string;
1806
+ };
1807
+ };
1808
+ type ResponseCosignOnchainTx = ResponseEnvelope & {
1809
+ type: "COSIGN_ONCHAIN_TX_SUCCESS";
1810
+ payload: {
1811
+ txid: string;
1812
+ };
1813
+ };
1814
+ type RequestSendOnchain = RequestEnvelope & {
1815
+ type: "SEND_ONCHAIN";
1816
+ payload: SendOnchainParams;
1817
+ };
1818
+ type ResponseSendOnchain = ResponseEnvelope & {
1819
+ type: "SEND_ONCHAIN_SUCCESS";
1820
+ payload: {
1821
+ txid: string;
1822
+ };
1823
+ };
1824
+ type WireMigrationVtxoRef = {
1825
+ txid: string;
1826
+ vout: number;
1827
+ value: number;
1828
+ signerPubKey: string;
1829
+ cutoffDate?: string;
1830
+ };
1831
+ type WireDeprecatedSignerReport = {
1832
+ signerPubKey: string;
1833
+ status: SignerStatus;
1834
+ cutoffDate?: string;
1835
+ secondsUntilCutoff?: number;
1836
+ vtxoCount: number;
1837
+ totalValue: number;
1838
+ boardingCount: number;
1839
+ boardingValue: number;
1840
+ recoverableCount: number;
1841
+ recoverableValue: number;
1842
+ awaitingSweepCount: number;
1843
+ awaitingSweepValue: number;
1844
+ nextSweepEta?: number;
1845
+ };
1846
+ type WireMigrationLegReport = {
1847
+ txid?: string;
1848
+ migrated: WireMigrationVtxoRef[];
1849
+ skipped?: MigrationLegSkipReason;
1850
+ deferred?: number;
1851
+ oversized?: WireMigrationVtxoRef[];
1852
+ error?: string;
1853
+ };
1854
+ type WireDeprecatedSignerMigrationReport = {
1855
+ rotated: boolean;
1856
+ skipped?: MigrationGlobalSkipReason;
1857
+ vtxos?: WireMigrationLegReport;
1858
+ boarding?: WireMigrationLegReport;
1859
+ expired: WireMigrationVtxoRef[];
1860
+ signers: WireDeprecatedSignerReport[];
1861
+ };
1862
+ type RequestMigrateDeprecatedSignerVtxos = RequestEnvelope & {
1863
+ type: "MIGRATE_DEPRECATED_SIGNER_VTXOS";
1864
+ };
1865
+ type ResponseMigrateDeprecatedSignerVtxos = ResponseEnvelope & {
1866
+ type: "MIGRATE_DEPRECATED_SIGNER_VTXOS_SUCCESS";
1867
+ payload: {
1868
+ report: WireDeprecatedSignerMigrationReport;
1869
+ };
1870
+ };
1871
+ type RequestGetDeprecatedSignerStatus = RequestEnvelope & {
1872
+ type: "GET_DEPRECATED_SIGNER_STATUS";
1873
+ };
1874
+ type ResponseGetDeprecatedSignerStatus = ResponseEnvelope & {
1875
+ type: "DEPRECATED_SIGNER_STATUS";
1876
+ payload: {
1877
+ signers: WireDeprecatedSignerReport[];
1878
+ };
1879
+ };
1880
+ type RequestRestoreWallet = RequestEnvelope & {
1881
+ type: "RESTORE_WALLET";
1882
+ payload: {
1883
+ gapLimit?: number;
1884
+ };
1885
+ };
1886
+ type ResponseRestoreWallet = ResponseEnvelope & {
1887
+ type: "RESTORE_WALLET_SUCCESS";
1888
+ };
1889
+ type WalletRequest = RequestInitWallet | RequestSettle | RequestGetAddress | RequestGetBoardingAddress | RequestGetOperatorInfo | RequestIndexerGetVtxos | RequestIndexerGetVirtualTxs | RequestSubmitTx | RequestFinalizeTx | RequestGetBalance | RequestGetVtxos | RequestGetSpendableVtxos | RequestGetBoardingUtxos | RequestGetTransactionHistory | RequestGetStatus | RequestGetContractSyncState | RequestClear | RequestReloadWallet | RequestSignTransaction | RequestCreateContract | RequestGetContracts | RequestGetContractsWithVtxos | RequestGetStoredContractsWithVtxos | RequestWatchScript | RequestUnwatchScript | RequestGetWatchedScripts | RequestAnnotateVtxos | RequestUpdateContract | RequestDeleteContract | RequestGetSpendablePaths | RequestGetAllSpendingPaths | RequestGetUnsupportedContracts | RequestIsContractManagerWatching | RequestRefreshVtxos | RequestRefreshOutpoints | RequestGetCurrentSigningDescriptor | RequestGetNextSigningDescriptor | RequestGetNewAddresses | RequestGetUsedSigningDescriptors | RequestAdvanceSigningDescriptorWatermark | RequestSend | RequestReserveVtxos | RequestReleaseVtxos | RequestSendWithDeadline | RequestSendWithInputExpiryFloor | RequestGetAssetDetails | RequestIssue | RequestReissue | RequestBurn | RequestDelegate | RequestGetDelegateInfo | RequestRecoverVtxos | RequestGetRecoverableBalance | RequestGetExpiringVtxos | RequestRenewVtxos | RequestGetExpiredBoardingUtxos | RequestSweepExpiredBoardingUtxos | RequestCosignOnchainTx | RequestSendOnchain | RequestMigrateDeprecatedSignerVtxos | RequestGetDeprecatedSignerStatus | RequestRestoreWallet | RequestArkadeCash;
1890
+ type ScopedWalletRequest = RequestEnvelope & {
1891
+ type: "SCOPED_WALLET_REQUEST_V1";
1892
+ payload: {
1893
+ binding: WalletRequestBinding;
1894
+ request: WalletRequest;
1895
+ };
1896
+ };
1897
+ type WalletUpdaterRequest = WalletRequest | ScopedWalletRequest;
1898
+ type WalletUpdaterResponse = ResponseEnvelope & {
1899
+ walletRequestBinding?: WalletRequestBinding;
1900
+ } & (ResponseInitWallet | ResponseSettle | ResponseSettleEvent | ResponseGetAddress | ResponseGetBoardingAddress | ResponseGetOperatorInfo | ResponseIndexerGetVtxos | ResponseIndexerGetVirtualTxs | ResponseSubmitTx | ResponseFinalizeTx | ResponseGetBalance | ResponseGetVtxos | ResponseGetSpendableVtxos | ResponseGetBoardingUtxos | ResponseGetTransactionHistory | ResponseGetStatus | ResponseGetContractSyncState | ResponseClear | ResponseReloadWallet | ResponseUtxoUpdate | ResponseVtxoUpdate | ResponseSignTransaction | ResponseCreateContract | ResponseGetContracts | ResponseGetContractsWithVtxos | ResponseGetStoredContractsWithVtxos | ResponseWatchScript | ResponseUnwatchScript | ResponseGetWatchedScripts | ResponseAnnotateVtxos | ResponseUpdateContract | ResponseContractWatchStateSet | ResponseDeleteContract | ResponseGetSpendablePaths | ResponseGetAllSpendingPaths | ResponseGetUnsupportedContracts | ResponseIsContractManagerWatching | ResponseRefreshVtxos | ResponseRefreshOutpoints | ResponseGetCurrentSigningDescriptor | ResponseGetNextSigningDescriptor | ResponseGetNewAddresses | ResponseGetUsedSigningDescriptors | ResponseAdvanceSigningDescriptorWatermark | ResponseContractEvent | ResponseSend | ResponseReserveVtxos | ResponseReleaseVtxos | ResponseSendDeadlineExceeded | ResponseGetAssetDetails | ResponseIssue | ResponseReissue | ResponseBurn | ResponseDelegate | ResponseGetDelegateInfo | ResponseRecoverVtxos | ResponseRecoverVtxosEvent | ResponseGetRecoverableBalance | ResponseGetExpiringVtxos | ResponseRenewVtxos | ResponseRenewVtxosEvent | ResponseGetExpiredBoardingUtxos | ResponseSweepExpiredBoardingUtxos | ResponseCosignOnchainTx | ResponseSendOnchain | ResponseMigrateDeprecatedSignerVtxos | ResponseMigrateDeprecatedSignerVtxosEvent | ResponseGetDeprecatedSignerStatus | ResponseRestoreWallet | ResponseArkadeCash);
1901
+ declare class WalletMessageHandler implements MessageHandler<WalletUpdaterRequest, WalletUpdaterResponse> {
1902
+ readonly messageTag: string;
1903
+ private wallet;
1904
+ private readonlyWallet;
1905
+ private walletRequestBinding;
1906
+ private readonly inFlightOperations;
1907
+ private readonly longRunningOperations;
1908
+ /** Under the page's re-init retries (~9s) and CLEAR's 10s timeout. */
1909
+ private drainBudgetMs;
1910
+ private arkProvider;
1911
+ private indexerProvider;
1912
+ private walletRepository;
1913
+ private incomingFundsSubscription;
1914
+ private incomingFundsRegistrations;
1915
+ private contractEventsSubscription;
1916
+ private onNextTick;
1917
+ private channel;
1918
+ private incomingFundsEpoch;
1919
+ /**
1920
+ * Supersedes older initializers without touching `incomingFundsEpoch`, so a
1921
+ * re-init that fails before registering leaves the live subscription delivering.
1922
+ */
1923
+ private initEpoch;
1924
+ private contractEventsEpoch;
1925
+ private boardingEpoch;
1926
+ /** Per-request progress callbacks: ends with the handler, not with a re-init. */
1927
+ private requestEpoch;
1928
+ /**
1929
+ * Instantiate a new WalletUpdater.
1930
+ * Can override the default `messageTag` allowing more than one updater to run in parallel.
1931
+ * Note that the default ServiceWorkerWallet sends messages to the default WalletUpdater tag.
1932
+ */
1933
+ constructor(options?: {
1934
+ messageTag?: string;
1935
+ });
1936
+ start(...params: Parameters<MessageHandler<WalletUpdaterRequest, WalletUpdaterResponse>["start"]>): Promise<void>;
1937
+ stop(): Promise<void>;
1938
+ tick(_now: number): Promise<WalletUpdaterResponse[]>;
1939
+ private epochOf;
1940
+ private newGeneration;
1941
+ /**
1942
+ * A handle rather than a `broadcast(response, epoch)` call, because it can
1943
+ * only be written where the closure it guards is created — an epoch passed
1944
+ * at the call site reads identically whether it guards anything or not.
1945
+ */
1946
+ private newEmitter;
1947
+ private requireWallet;
1948
+ private captureRequestContext;
1949
+ private runOwnedOperation;
1950
+ private requireReservationWallet;
1951
+ private tagged;
1952
+ isLongRunning(message: WalletUpdaterRequest): boolean;
1953
+ getRequestType(message: WalletUpdaterRequest): string | undefined;
1954
+ handleMessage(message: WalletUpdaterRequest): Promise<WalletUpdaterResponse>;
1955
+ private dispatchOperation;
1956
+ private handleInitWallet;
1957
+ /** @see RequestInitWallet.payload.lazyBoarding */
1958
+ private lazyBoardingInit;
1959
+ /** Set once this session has actually fetched the boarding addresses. */
1960
+ private boardingLoaded;
1961
+ /**
1962
+ * The worker's own balance. Same bucketing rules as `Wallet.getBalance` —
1963
+ * both call {@link computeOffchainBalance} — but deliberately a different
1964
+ * freshness: this reads the repository directly, with no indexer sync, so a
1965
+ * polling UI never pays for a network round-trip. That rules out
1966
+ * `pendingRecoveryOutpoints()`, whose snapshot syncs; the same classification
1967
+ * runs over this method's local snapshot instead.
1968
+ */
1969
+ private handleGetBalance;
1970
+ private getBoardingUtxosForBalance;
1971
+ private onWalletInitialized;
1972
+ private registerIncomingFunds;
1973
+ /**
1974
+ * Refresh boarding inputs and transaction history. The virtual outputs come
1975
+ * from the contract manager, which runs before this. Shared by
1976
+ * onWalletInitialized (full bootstrap) and reloadWallet (post-refresh),
1977
+ * avoiding duplicate subscriptions and VtxoManager restarts.
1978
+ *
1979
+ * Both legs reach the onchain provider, so `lazyBoarding` moves them both
1980
+ * off the caller's path. @see RequestInitWallet.payload.lazyBoarding
1981
+ */
1982
+ private refreshCachedData;
1983
+ /** History rows plus the address they are stored under. Does not write. */
1984
+ private loadHistoryCache;
1985
+ private storeHistoryCache;
1986
+ /** @param gen - set by a background caller; the refresh is skipped once it goes stale. */
1987
+ private refreshBoardingCache;
1988
+ /**
1989
+ * Force a full VTXO refresh from the indexer, then refresh cached data.
1990
+ * Used by RELOAD_WALLET to ensure fresh data without re-subscribing
1991
+ * to incoming funds or restarting the VtxoManager.
1992
+ */
1993
+ private reloadWallet;
1994
+ private handleSettle;
1995
+ private handleSignTransaction;
1996
+ private handleDelegate;
1997
+ /**
1998
+ * Ungated repository read mirroring `Wallet.getVtxos`, the raw reporting read.
1999
+ */
2000
+ private handleGetVtxos;
2001
+ /** Tear down handler subscriptions, then delegate the full wipe to the wallet. */
2002
+ private clear;
2003
+ /**
2004
+ * Read all virtual outputs from the repository, aggregated across all contract
2005
+ * addresses and the wallet's primary address, with deduplication.
2006
+ *
2007
+ * Recovery-only contracts (imported by `claimCash` for operator-swept
2008
+ * arkcash) are excluded by default, mirroring {@link ReadonlyWallet.getVtxos}:
2009
+ * they are settled in their own isolated intent and must stay out of the
2010
+ * wallet's balance / VTXO / coin-selection / pending-tx views that read this.
2011
+ * Transaction history excludes them too, as does the non-worker
2012
+ * `getTransactionHistory`.
2013
+ */
2014
+ private getVtxosFromRepo;
2015
+ /**
2016
+ * The worker's equivalent of `ReadonlyWallet.contractSnapshot`: contracts
2017
+ * paired with the VTXOs the repository holds for them, plus the flat
2018
+ * deduplicated list. Purely local — unlike the main-thread snapshot it never
2019
+ * syncs against the indexer.
2020
+ *
2021
+ * One read of the contract rows serves both halves. Reading them twice
2022
+ * (once for the VTXO buckets, once for the gate) races the contract
2023
+ * manager's own writes: a contract registered between the two reads yields
2024
+ * VTXOs with no matching row in the gate, and `gatedContracts` lists only
2025
+ * what it knows is closed — so the coins of a just-registered escrowed
2026
+ * contract would count as available until the next poll.
2027
+ *
2028
+ * Recovery-only contracts are skipped (see {@link getVtxosFromRepo}).
2029
+ */
2030
+ private repoSnapshot;
2031
+ /**
2032
+ * Build transaction history from cached virtual outputs, hitting the indexer only for
2033
+ * uncached timestamps. Best-effort, like the plain Wallet path.
2034
+ *
2035
+ * Takes its own {@link repoSnapshot} rather than a caller-supplied VTXO
2036
+ * list: the coins and the gate that judges them have to come off one read
2037
+ * or they answer about different instants, and being the worker's only
2038
+ * history builder means neither caller can supply one without the other.
2039
+ * The snapshot and the boarding read are independent, so they run together
2040
+ * — the same pairing `handleGetBalance` makes.
2041
+ */
2042
+ private buildTransactionHistoryFromCache;
2043
+ private ensureContractEventBroadcasting;
2044
+ }
2045
+
2046
+ type WalletRequestBinding = {
2047
+ readonly scope: string;
2048
+ readonly network: NetworkName;
2049
+ };
2050
+
2051
+ type RequestEnvelope = {
2052
+ tag: string;
2053
+ id: string;
2054
+ broadcast?: boolean;
2859
2055
  };
2860
- type RequestCosignOnchainTx = RequestEnvelope & {
2861
- type: "COSIGN_ONCHAIN_TX";
2862
- /** Base64 PSBT. */
2863
- payload: {
2864
- psbt: string;
2865
- };
2056
+ type ResponseEnvelope = {
2057
+ tag: string;
2058
+ id?: string;
2059
+ error?: Error;
2060
+ /**
2061
+ * `error.name`, carried beside the error as an ordinary string. The
2062
+ * structured-clone algorithm serializes an Error's `name` only from the
2063
+ * built-in whitelist (Error, TypeError, RangeError, …) — a custom name
2064
+ * like `ProviderUnavailableError` reaches the page as `"Error"`. A plain
2065
+ * property survives verbatim, so the page restores it before rejecting.
2066
+ * Absent from workers built before it existed; the page then sees the
2067
+ * clone-normalized name, exactly as it always did.
2068
+ */
2069
+ errorName?: string;
2070
+ broadcast?: boolean;
2866
2071
  };
2867
- type ResponseCosignOnchainTx = ResponseEnvelope & {
2868
- type: "COSIGN_ONCHAIN_TX_SUCCESS";
2869
- payload: {
2870
- txid: string;
2871
- };
2072
+ type MessageBusServices = {
2073
+ arkProvider: OperatorProvider;
2074
+ wallet?: Wallet;
2075
+ readonlyWallet: ReadonlyWallet;
2076
+ vtxoReservationScope?: string;
2077
+ walletRequestBinding?: WalletRequestBinding;
2872
2078
  };
2873
- type RequestSendOnchain = RequestEnvelope & {
2874
- type: "SEND_ONCHAIN";
2875
- payload: SendOnchainParams;
2079
+ interface MessageHandler<REQ extends RequestEnvelope = RequestEnvelope, RES extends ResponseEnvelope = ResponseEnvelope> {
2080
+ /**
2081
+ * A unique identifier for the updater.
2082
+ * This is used to route messages to the correct updater.
2083
+ */
2084
+ readonly messageTag: string;
2085
+ /**
2086
+ * Called once when the SW is starting up
2087
+ * @param services - Providers and wallet instances available to the handler.
2088
+ * @param repositories - Repositories available to the handler.
2089
+ * @param channel - Push channel to clients, for responses that answer no
2090
+ * request. Use it instead of holding events for the next {@link tick}.
2091
+ * The channel is scoped to the generation it was handed out in: after a
2092
+ * bus re-init or `stop()` it goes inert on its own, so retaining one past
2093
+ * `stop()` cannot post.
2094
+ **/
2095
+ start(services: MessageBusServices, repositories: {
2096
+ walletRepository: WalletRepository;
2097
+ }, channel?: {
2098
+ broadcast(response: RES): void;
2099
+ }): Promise<void>;
2100
+ /** Called once when the SW is shutting down */
2101
+ stop(): Promise<void>;
2102
+ /**
2103
+ * Called by the scheduler to perform a tick.
2104
+ * Can be used by the updater to perform periodic tasks or return
2105
+ * delayed responses (eg: subscriptions).
2106
+ * @param now The current time in milliseconds since the epoch.
2107
+ **/
2108
+ tick(now: number): Promise<RES[]>;
2109
+ /**
2110
+ * Handle routed messages from the clients
2111
+ **/
2112
+ handleMessage(message: REQ): Promise<RES | null>;
2113
+ /**
2114
+ * Optional opt-out from the bus-level message timeout.
2115
+ *
2116
+ * Long-running flows (e.g. settlement) surrender control to remote peers
2117
+ * and can legitimately sit idle for longer than `messageTimeoutMs`. When
2118
+ * this returns true, the bus awaits `handleMessage` without a deadline.
2119
+ * Defaults to false.
2120
+ */
2121
+ isLongRunning?(message: REQ): boolean;
2122
+ /** Logical operation for timeout overrides when a handler uses a transport wrapper. */
2123
+ getRequestType?(message: REQ): string | undefined;
2124
+ }
2125
+ type Options = {
2126
+ messageHandlers: MessageHandler[];
2127
+ tickIntervalMs?: number;
2128
+ messageTimeoutMs?: number;
2129
+ /**
2130
+ * Per-operation timeout overrides. Keys are either message types
2131
+ * (e.g. "SETTLE") or handler tags (e.g. "WALLET_UPDATER"). Message-type
2132
+ * matches take precedence over tag matches. Unspecified operations use
2133
+ * `messageTimeoutMs`. These are treated as defaults: any map supplied
2134
+ * via `INITIALIZE_MESSAGE_BUS` overrides per-key and is re-applied on
2135
+ * every (re-)init.
2136
+ */
2137
+ messageTimeoutOverrides?: Record<string, number>;
2138
+ /**
2139
+ * Optional intent-lifecycle repository, handed to the worker's wallet as
2140
+ * `storage.intentRepository`. Same opt-in as a main-thread wallet: without
2141
+ * it the worker persists no settlement intent, reconciles none on restart,
2142
+ * and counts intent-locked VTXOs as available. Pass the same repository the
2143
+ * main thread uses so both sides read one intent state, but settle from one
2144
+ * side only: reconciliation deletes from the server any pending intent the
2145
+ * worker's wallet is not settling itself.
2146
+ *
2147
+ * Ignored when `buildServices` is supplied — that override owns `storage`.
2148
+ */
2149
+ intentRepository?: BatchRegistrationRepository;
2150
+ /** The worker wallet's onchain provider, per network: an instance cannot cross `postMessage`.
2151
+ * Called on every init and never closed, so return one instance per network. Defaults to
2152
+ * Esplora; ignored when `buildServices` is supplied. */
2153
+ onchainProvider?: (network: NetworkName) => OnchainProvider;
2154
+ debug?: boolean;
2155
+ buildServices?: (config: Initialize["config"]) => Promise<MessageBusServices>;
2876
2156
  };
2877
- type ResponseSendOnchain = ResponseEnvelope & {
2878
- type: "SEND_ONCHAIN_SUCCESS";
2879
- payload: {
2880
- txid: string;
2157
+ type Initialize = {
2158
+ type: "INITIALIZE_MESSAGE_BUS";
2159
+ id: string;
2160
+ config: {
2161
+ wallet: SerializedIdentity;
2162
+ arkServer: {
2163
+ url: string;
2164
+ publicKey?: string;
2165
+ };
2166
+ delegateUrl?: string;
2167
+ settlementConfig?: SettlementConfig | false;
2168
+ /** @see WalletConfig.concurrentSpending */
2169
+ concurrentSpending?: boolean;
2170
+ walletMode?: "auto" | "static" | "hd";
2171
+ lazyInitialization?: boolean;
2172
+ watcherConfig?: Partial<Omit<ContractWatcherConfig, "indexerProvider">>;
2173
+ /** @see WalletConfig.lookAheadWindow */
2174
+ lookAheadWindow?: number;
2175
+ /** @see WalletConfig.oneShotSubmit */
2176
+ oneShotSubmit?: boolean;
2177
+ /** @see WalletConfig.minBatchExpirySeconds */
2178
+ minBatchExpirySeconds?: bigint;
2179
+ /**
2180
+ * Page-supplied per-operation timeout map. Keys are message types
2181
+ * (e.g. "SETTLE"). Overrides constructor-supplied
2182
+ * `messageTimeoutOverrides` per-key; re-applied on every init.
2183
+ */
2184
+ messageTimeouts?: Record<string, number>;
2881
2185
  };
2882
2186
  };
2883
- type WireMigrationVtxoRef = {
2884
- txid: string;
2885
- vout: number;
2886
- value: number;
2887
- signerPubKey: string;
2888
- cutoffDate?: string;
2889
- };
2890
- type WireDeprecatedSignerReport = {
2891
- signerPubKey: string;
2892
- status: SignerStatus;
2893
- cutoffDate?: string;
2894
- secondsUntilCutoff?: number;
2895
- vtxoCount: number;
2896
- totalValue: number;
2897
- boardingCount: number;
2898
- boardingValue: number;
2899
- recoverableCount: number;
2900
- recoverableValue: number;
2901
- awaitingSweepCount: number;
2902
- awaitingSweepValue: number;
2903
- nextSweepEta?: number;
2904
- };
2905
- type WireMigrationLegReport = {
2906
- txid?: string;
2907
- migrated: WireMigrationVtxoRef[];
2908
- skipped?: MigrationLegSkipReason;
2909
- deferred?: number;
2910
- oversized?: WireMigrationVtxoRef[];
2911
- error?: string;
2912
- };
2913
- type WireDeprecatedSignerMigrationReport = {
2914
- rotated: boolean;
2915
- skipped?: MigrationGlobalSkipReason;
2916
- vtxos?: WireMigrationLegReport;
2917
- boarding?: WireMigrationLegReport;
2918
- expired: WireMigrationVtxoRef[];
2919
- signers: WireDeprecatedSignerReport[];
2920
- };
2921
- type RequestMigrateDeprecatedSignerVtxos = RequestEnvelope & {
2922
- type: "MIGRATE_DEPRECATED_SIGNER_VTXOS";
2923
- };
2924
- type ResponseMigrateDeprecatedSignerVtxos = ResponseEnvelope & {
2925
- type: "MIGRATE_DEPRECATED_SIGNER_VTXOS_SUCCESS";
2926
- payload: {
2927
- report: WireDeprecatedSignerMigrationReport;
2928
- };
2187
+ declare class MessageBus {
2188
+ private readonly walletRepository;
2189
+ private readonly contractRepository;
2190
+ private handlers;
2191
+ private tickIntervalMs;
2192
+ private messageTimeoutMs;
2193
+ private readonly constructorTimeoutOverrides;
2194
+ private messageTimeoutOverrides;
2195
+ private lateDeliveries;
2196
+ private running;
2197
+ private tickTimeout;
2198
+ private tickInProgress;
2199
+ private debug;
2200
+ private initialized;
2201
+ /**
2202
+ * FIFO chain that serializes `INITIALIZE_MESSAGE_BUS` handling. Each init
2203
+ * runs to completion in enqueue order.
2204
+ */
2205
+ private initChain;
2206
+ /**
2207
+ * Number of inits accepted but not yet settled (queued or running). The
2208
+ * bus refuses ordinary wallet messages while this is > 0.
2209
+ */
2210
+ private pendingInitCount;
2211
+ private readonly buildServicesFn;
2212
+ private readonly boundOnMessage;
2213
+ private readonly intentRepository?;
2214
+ private reservationStore?;
2215
+ private readonly onchainProvider?;
2216
+ /** Pending broadcasts, drained FIFO by a single {@link drain} loop. */
2217
+ private broadcastQueue;
2218
+ private draining;
2219
+ /** Bumped wherever the generation owning the queued broadcasts ends. */
2220
+ private broadcastEpoch;
2221
+ /** Create the service-worker message bus with repositories and handler configuration. */
2222
+ constructor(walletRepository: WalletRepository, contractRepository: ContractRepository, { messageHandlers, tickIntervalMs, messageTimeoutMs, messageTimeoutOverrides, intentRepository, onchainProvider, debug, buildServices, }: Options);
2223
+ /** Start the message bus and attach service-worker event listeners. */
2224
+ start(): Promise<void>;
2225
+ /** Stop the message bus, cancel ticks, and stop all registered handlers. */
2226
+ stop(): Promise<void>;
2227
+ /** Invalidate every broadcast belonging to the outgoing generation. */
2228
+ private invalidateBroadcasts;
2229
+ private broadcastToClients;
2230
+ /**
2231
+ * Single fan-out loop, so pushes and tick responses keep one FIFO order.
2232
+ * A helper posting per response would race: `clients.matchAll()` gives no
2233
+ * cross-call resolution order, and it would de-batch `runTick`.
2234
+ */
2235
+ private drain;
2236
+ /**
2237
+ * A dropped batch has no periodic recovery to fall back on now that events
2238
+ * no longer ride the tick, so name the loss under {@link Options.debug}.
2239
+ */
2240
+ private logDroppedBroadcasts;
2241
+ private scheduleNextTick;
2242
+ private runTick;
2243
+ /**
2244
+ * Serialize init requests on {@link initChain}.
2245
+ * Returns this init's own result.
2246
+ */
2247
+ private waitForInit;
2248
+ /**
2249
+ * The bus serves ordinary wallet messages only when it is initialized AND
2250
+ * no init is in flight.
2251
+ */
2252
+ private acceptsWalletMessages;
2253
+ private doInit;
2254
+ private buildServices;
2255
+ private onMessage;
2256
+ private processMessage;
2257
+ /**
2258
+ * Race `promise` against a timeout. Note: this does NOT cancel the
2259
+ * underlying work — the original promise keeps running. Call
2260
+ * `attachLateDelivery` after catching the timeout to surface the
2261
+ * eventual result so the message id does not go silent.
2262
+ */
2263
+ private withTimeout;
2264
+ /**
2265
+ * Extract the declared `type` from a request envelope (e.g. "SETTLE").
2266
+ * Not every envelope carries a type (PING/INIT are special cased
2267
+ * earlier), so this returns undefined for envelopes that lack one.
2268
+ */
2269
+ private extractMessageType;
2270
+ /**
2271
+ * Resolve the timeout for an operation. Message-type overrides take
2272
+ * precedence over handler-tag overrides, with the bus-wide default
2273
+ * (`messageTimeoutMs`) as the final fallback.
2274
+ */
2275
+ private resolveTimeoutMs;
2276
+ /**
2277
+ * Build a human-readable label for timeout errors. Format:
2278
+ * `"<MESSAGE_TYPE> via <HANDLER_TAG>"` when both are known, else the
2279
+ * handler tag alone. Used so timeout errors name the operation the
2280
+ * client actually triggered (e.g. SETTLE) rather than just the
2281
+ * handler that received it (e.g. WALLET_UPDATER).
2282
+ */
2283
+ private labelFor;
2284
+ /**
2285
+ * Post a response to the originating client. When `source` is null
2286
+ * (client tab closed, detached frame, etc.) the response cannot be
2287
+ * delivered; we log the drop in debug mode so it is not invisible.
2288
+ */
2289
+ private deliverResponse;
2290
+ /**
2291
+ * After a handler times out the client has already received a timeout
2292
+ * error, but the handler keeps running. Attach a follow-up so the
2293
+ * handler's eventual result (or error) is delivered under the same
2294
+ * message id, or — if the handler never completes within
2295
+ * {@link LATE_DELIVERY_GRACE_MS} — an "Operation abandoned" error is
2296
+ * sent so the client's listener (if still attached) does not hang.
2297
+ */
2298
+ private attachLateDelivery;
2299
+ /**
2300
+ * Returns the registered SW for the path.
2301
+ * It uses the functions in `service-worker-manager.ts` module.
2302
+ * @param path
2303
+ * @return the Service Worker
2304
+ * @throws if not running in a browser environment
2305
+ */
2306
+ static getServiceWorker(path?: string): Promise<ServiceWorker>;
2307
+ /**
2308
+ * Set up and register the Service Worker, ensuring it's done once at most.
2309
+ * It uses the functions in `service-worker-manager.ts` module.
2310
+ * @param path
2311
+ * @return the Service Worker
2312
+ * @throws if not running in a browser environment
2313
+ */
2314
+ static setup(path: string): Promise<ServiceWorker>;
2315
+ }
2316
+
2317
+ /** A leaf node in the Taproot script tree, as consumed by `@scure/btc-signer`'s `p2tr`. */
2318
+ interface TaprootLeaf {
2319
+ script: Bytes;
2320
+ leafVersion: number;
2321
+ }
2322
+ /** A `p2tr` tree node: a leaf, or a `[left, right]` branch tuple. */
2323
+ type TaprootTreeNode = TaprootLeaf | [TaprootTreeNode, TaprootTreeNode];
2324
+ /**
2325
+ * Assemble a Taproot script tree with btcd's `txscript.AssembleTaprootScriptTree` algorithm
2326
+ * (the one arkd uses).
2327
+ *
2328
+ * `@scure/btc-signer`'s `taprootListToTree` builds a Huffman tree instead; the two agree only for
2329
+ * power-of-2 leaf counts. Any other count yields a different merkle root → different output key
2330
+ * → arkd rejects spends with `INVALID_PSBT_INPUT`.
2331
+ *
2332
+ * @param scripts - Raw tapscript bytes per leaf, in TapTree PSBT field order.
2333
+ * @returns The nested-tuple form `p2tr` accepts.
2334
+ */
2335
+ declare function assembleBtcdTaprootTree(scripts: Bytes[]): TaprootTreeNode;
2336
+
2337
+ declare enum AssetInputType {
2338
+ Unspecified = 0,
2339
+ Local = 1,
2340
+ /** @deprecated Use {@link AssetInputType.Proof}. */
2341
+ Intent = 2,
2342
+ Proof = 2
2343
+ }
2344
+ declare enum AssetRefType {
2345
+ Unspecified = 0,
2346
+ ByID = 1,
2347
+ ByGroup = 2
2348
+ }
2349
+
2350
+ declare class BufferWriter {
2351
+ private buffer;
2352
+ write(data: Uint8Array): void;
2353
+ writeByte(byte: number): void;
2354
+ writeUint16LE(value: number): void;
2355
+ writeVarUint(value: bigint | number): void;
2356
+ writeVarSlice(data: Uint8Array): void;
2357
+ writeCompactSize(value: number): void;
2358
+ writeCompactSlice(data: Uint8Array): void;
2359
+ toBytes(): Uint8Array;
2360
+ }
2361
+ declare class BufferReader {
2362
+ private view;
2363
+ private offset;
2364
+ constructor(data: Uint8Array);
2365
+ remaining(): number;
2366
+ readByte(): number;
2367
+ readSlice(size: number): Uint8Array;
2368
+ readUint16LE(): number;
2369
+ readVarUint(): bigint;
2370
+ readVarSlice(): Uint8Array;
2371
+ readCompactSize(): number;
2372
+ readCompactSlice(): Uint8Array;
2373
+ }
2374
+
2375
+ /**
2376
+ * AssetId identifies a specific asset.
2377
+ *
2378
+ * @remarks
2379
+ * Asset ids are derived from the genesis transaction id plus the asset group index.
2380
+ *
2381
+ * @see AssetRef
2382
+ *
2383
+ * @example
2384
+ * ```typescript
2385
+ * const assetId = AssetId.create('00'.repeat(32), 0)
2386
+ * const encoded = assetId.toString()
2387
+ * const decoded = AssetId.fromString(encoded)
2388
+ * ```
2389
+ */
2390
+ declare class AssetId {
2391
+ readonly txid: Uint8Array;
2392
+ readonly groupIndex: number;
2393
+ private constructor();
2394
+ /**
2395
+ * Create a validated asset id from a genesis transaction id and group index.
2396
+ *
2397
+ * @param txid - Hex-encoded genesis transaction id
2398
+ * @param groupIndex - Asset group index within the genesis transaction
2399
+ * @throws Error if the txid is missing, malformed, or not 32 bytes long
2400
+ * @see fromString
2401
+ */
2402
+ static create(txid: string, groupIndex: number): AssetId;
2403
+ /**
2404
+ * Decode an asset id from its hex string representation.
2405
+ *
2406
+ * @throws Error if the string is not valid hex or does not encode a valid asset id
2407
+ * @see toString
2408
+ */
2409
+ static fromString(s: string): AssetId;
2410
+ /**
2411
+ * Decode an asset id from its serialized bytes.
2412
+ *
2413
+ * @throws Error if the buffer length is invalid
2414
+ */
2415
+ static fromBytes(buf: Uint8Array): AssetId;
2416
+ /**
2417
+ * Serialize the asset id to raw bytes.
2418
+ *
2419
+ * @see fromBytes
2420
+ */
2421
+ serialize(): Uint8Array;
2422
+ /**
2423
+ * Encode the asset id to a hex string.
2424
+ *
2425
+ * @see fromString
2426
+ */
2427
+ toString(): string;
2428
+ /**
2429
+ * Validate the asset id fields.
2430
+ *
2431
+ * @throws Error if the txid is empty or the group index is out of range
2432
+ */
2433
+ validate(): void;
2434
+ /**
2435
+ * Decode an asset id from a binary reader positioned at one.
2436
+ *
2437
+ * @throws Error if the reader does not contain enough bytes
2438
+ */
2439
+ static fromReader(reader: BufferReader): AssetId;
2440
+ /**
2441
+ * Serialize the asset id into an existing binary writer.
2442
+ *
2443
+ * @see serialize
2444
+ */
2445
+ serializeTo(writer: BufferWriter): void;
2446
+ }
2447
+
2448
+ type AssetRefByID = {
2449
+ type: AssetRefType.ByID;
2450
+ assetId: AssetId;
2929
2451
  };
2930
- type RequestGetDeprecatedSignerStatus = RequestEnvelope & {
2931
- type: "GET_DEPRECATED_SIGNER_STATUS";
2452
+ type AssetRefByGroup = {
2453
+ type: AssetRefType.ByGroup;
2454
+ groupIndex: number;
2932
2455
  };
2933
- type ResponseGetDeprecatedSignerStatus = ResponseEnvelope & {
2934
- type: "DEPRECATED_SIGNER_STATUS";
2935
- payload: {
2936
- signers: WireDeprecatedSignerReport[];
2937
- };
2456
+ /**
2457
+ * Reference to either an explicit asset id or another asset group in the same packet.
2458
+ *
2459
+ * @see AssetId
2460
+ *
2461
+ * @example
2462
+ * ```typescript
2463
+ * const refById = AssetRef.fromId(assetId)
2464
+ * const refByGroup = AssetRef.fromGroupIndex(0)
2465
+ * ```
2466
+ */
2467
+ declare class AssetRef {
2468
+ readonly ref: AssetRefByID | AssetRefByGroup;
2469
+ private constructor();
2470
+ /** Reference type discriminator. */
2471
+ get type(): AssetRefType;
2472
+ /** Reference a specific asset id. @see fromGroupIndex */
2473
+ static fromId(assetId: AssetId): AssetRef;
2474
+ /**
2475
+ * Reference another asset group in the packet.
2476
+ *
2477
+ * @param groupIndex - Zero-based asset group index in the packet
2478
+ * @see fromId
2479
+ */
2480
+ static fromGroupIndex(groupIndex: number): AssetRef;
2481
+ /**
2482
+ * Decode an asset reference from hex.
2483
+ *
2484
+ * @throws Error if the string is not valid hex or does not encode a valid asset reference
2485
+ * @see toString
2486
+ */
2487
+ static fromString(s: string): AssetRef;
2488
+ /**
2489
+ * Decode an asset reference from its serialized bytes.
2490
+ *
2491
+ * @throws Error if the buffer is empty or malformed
2492
+ */
2493
+ static fromBytes(buf: Uint8Array): AssetRef;
2494
+ /** Serialize to raw bytes. @see fromBytes */
2495
+ serialize(): Uint8Array;
2496
+ /** Encode to hex. @see fromString */
2497
+ toString(): string;
2498
+ /**
2499
+ * Decode an asset reference from a reader positioned at one.
2500
+ *
2501
+ * @throws Error if the type is unknown or the reader does not contain enough bytes
2502
+ */
2503
+ static fromReader(reader: BufferReader): AssetRef;
2504
+ /** Append the serialized reference to `writer`. @see serialize */
2505
+ serializeTo(writer: BufferWriter): void;
2506
+ }
2507
+
2508
+ type AssetInputLocal = {
2509
+ type: AssetInputType.Local;
2510
+ vin: number;
2511
+ amount: bigint;
2938
2512
  };
2939
- type RequestRestoreWallet = RequestEnvelope & {
2940
- type: "RESTORE_WALLET";
2941
- payload: {
2942
- gapLimit?: number;
2943
- };
2513
+ type AssetInputProof = Pick<AssetInputLocal, "vin" | "amount"> & {
2514
+ type: AssetInputType.Proof;
2515
+ txid: Uint8Array;
2944
2516
  };
2945
- type ResponseRestoreWallet = ResponseEnvelope & {
2946
- type: "RESTORE_WALLET_SUCCESS";
2517
+ /**
2518
+ * AssetInput represents an input of an asset group.
2519
+ * a local input references a real transaction input and specify the amount in satoshis.
2520
+ * a proof input references an external proof transaction. It is created by the operator to handle batch leaf transaction.
2521
+ */
2522
+ declare class AssetInput {
2523
+ readonly input: AssetInputLocal | AssetInputProof;
2524
+ private constructor();
2525
+ /** Gets the transaction input index for an asset input, e.g. 0 */
2526
+ get vin(): number;
2527
+ /** Gets the amount for an input (in most cases, 330 sats) */
2528
+ get amount(): bigint;
2529
+ /** Create a local asset input that points at a transaction input index. */
2530
+ static create(vin: number, amount: bigint | number): AssetInput;
2531
+ /** Create a proof-backed asset input referencing an external proof transaction. */
2532
+ static createProof(txid: string, vin: number, amount: bigint | number): AssetInput;
2533
+ /** @deprecated Use {@link createProof}. */
2534
+ static createIntent: typeof AssetInput.createProof;
2535
+ /** Decode an asset input from its hex string form. */
2536
+ static fromString(s: string): AssetInput;
2537
+ /** Decode an asset input from its serialized bytes. */
2538
+ static fromBytes(buf: Uint8Array): AssetInput;
2539
+ /** Serialize the asset input to raw bytes. */
2540
+ serialize(): Uint8Array;
2541
+ /** Encode the asset input to a hex string. */
2542
+ toString(): string;
2543
+ /** Validate the asset input fields. */
2544
+ validate(): void;
2545
+ /** Decode an asset input from a buffer reader. */
2546
+ static fromReader(reader: BufferReader): AssetInput;
2547
+ /** Serialize the asset input into an existing buffer writer. */
2548
+ serializeTo(writer: BufferWriter): void;
2549
+ }
2550
+ /**
2551
+ * AssetInputs represents a list of asset inputs.
2552
+ */
2553
+ declare class AssetInputs {
2554
+ readonly inputs: AssetInput[];
2555
+ private constructor();
2556
+ /** Create a validated list of asset inputs. */
2557
+ static create(inputs: AssetInput[]): AssetInputs;
2558
+ /** Decode an asset input list from its hex string form. */
2559
+ static fromString(s: string): AssetInputs;
2560
+ /** Serialize the asset input list to raw bytes. */
2561
+ serialize(): Uint8Array;
2562
+ /** Encode the asset input list to a hex string. */
2563
+ toString(): string;
2564
+ /** Validate the asset input list. */
2565
+ validate(): void;
2566
+ /** Decode an asset input list from a buffer reader. */
2567
+ static fromReader(reader: BufferReader): AssetInputs;
2568
+ /** Serialize the asset input list into an existing buffer writer. */
2569
+ serializeTo(writer: BufferWriter): void;
2570
+ }
2571
+
2572
+ /**
2573
+ * AssetOutput references a real transaction output and specify the amount in satoshis.
2574
+ * it must be present in an AssetGroup.
2575
+ *
2576
+ * @param vout - the output index in the transaction
2577
+ * @param amount - asset amount in satoshis
2578
+ */
2579
+ declare class AssetOutput {
2580
+ readonly vout: number;
2581
+ readonly amount: bigint;
2582
+ static readonly TYPE_LOCAL = 1;
2583
+ private constructor();
2584
+ /** Create a local asset output referencing a transaction output index. */
2585
+ static create(vout: number, amount: bigint | number): AssetOutput;
2586
+ /** Decode an asset output from its hex string form. */
2587
+ static fromString(s: string): AssetOutput;
2588
+ /** Decode an asset output from its serialized bytes. */
2589
+ static fromBytes(buf: Uint8Array): AssetOutput;
2590
+ /** Serialize the asset output to raw bytes. */
2591
+ serialize(): Uint8Array;
2592
+ /** Encode the asset output to a hex string. */
2593
+ toString(): string;
2594
+ /** Validate the asset output fields. */
2595
+ validate(): void;
2596
+ /** Decode an asset output from a buffer reader. */
2597
+ static fromReader(reader: BufferReader): AssetOutput;
2598
+ /** Serialize the asset output into an existing buffer writer. */
2599
+ serializeTo(writer: BufferWriter): void;
2600
+ }
2601
+ /**
2602
+ * AssetOutputs is a list of AssetOutput references.
2603
+ * it must be present in an AssetGroup.
2604
+ *
2605
+ * @param outputs - the list of asset outputs
2606
+ */
2607
+ declare class AssetOutputs {
2608
+ readonly outputs: AssetOutput[];
2609
+ private constructor();
2610
+ /** Create a validated list of asset outputs. */
2611
+ static create(outputs: AssetOutput[]): AssetOutputs;
2612
+ /** Decode an asset output list from its hex string form. */
2613
+ static fromString(s: string): AssetOutputs;
2614
+ /** Serialize the asset output list to raw bytes. */
2615
+ serialize(): Uint8Array;
2616
+ /** Encode the asset output list to a hex string. */
2617
+ toString(): string;
2618
+ /** Validate the asset output list. */
2619
+ validate(): void;
2620
+ /** Decode an asset output list from a buffer reader. */
2621
+ static fromReader(reader: BufferReader): AssetOutputs;
2622
+ /** Serialize the asset output list into an existing buffer writer. */
2623
+ serializeTo(writer: BufferWriter): void;
2624
+ }
2625
+
2626
+ /**
2627
+ * Metadata represents a key-value pair.
2628
+ * @param key - the key
2629
+ * @param value - the value
2630
+ */
2631
+ declare class Metadata {
2632
+ readonly key: Uint8Array;
2633
+ readonly value: Uint8Array;
2634
+ private constructor();
2635
+ /** Create a metadata entry from raw key and value bytes. */
2636
+ static create(key: Bytes, value: Bytes): Metadata;
2637
+ /** Decode metadata from its hex string form. */
2638
+ static fromString(s: string): Metadata;
2639
+ /** Decode metadata from its serialized bytes. */
2640
+ static fromBytes(buf: Uint8Array): Metadata;
2641
+ /** Serialize metadata to raw bytes. */
2642
+ serialize(): Uint8Array;
2643
+ /** Encode metadata to a hex string. */
2644
+ toString(): string;
2645
+ get keyString(): string;
2646
+ get valueString(): string;
2647
+ /** Validate the metadata key and value. */
2648
+ validate(): void;
2649
+ /** Decode metadata from a buffer reader. */
2650
+ static fromReader(reader: BufferReader): Metadata;
2651
+ /** Serialize metadata into an existing buffer writer. */
2652
+ serializeTo(writer: BufferWriter): void;
2653
+ }
2654
+ declare class MetadataList {
2655
+ readonly items: Metadata[];
2656
+ static readonly ARK_LEAF_TAG = "ArkadeAssetLeaf";
2657
+ static readonly ARK_BRANCH_TAG = "ArkadeAssetBranch";
2658
+ static readonly ARK_LEAF_VERSION = 0;
2659
+ constructor(items: Metadata[]);
2660
+ /** Create a metadata list from its hex string form. */
2661
+ static fromString(s: string): MetadataList;
2662
+ /** Decode a metadata list from its serialized bytes. */
2663
+ static fromBytes(buf: Uint8Array): MetadataList;
2664
+ /** Decode a metadata list from a buffer reader. */
2665
+ static fromReader(reader: BufferReader): MetadataList;
2666
+ /** Serialize the metadata list into an existing buffer writer. */
2667
+ serializeTo(writer: BufferWriter): void;
2668
+ /** Serialize the metadata list to raw bytes. */
2669
+ serialize(): Uint8Array;
2670
+ /** Iterate through metadata entries in insertion order. */
2671
+ [Symbol.iterator](): Iterator<Metadata>;
2672
+ get length(): number;
2673
+ /** Compute the tagged Merkle root for the metadata list. */
2674
+ hash(): Uint8Array;
2675
+ }
2676
+
2677
+ /**
2678
+ * An asset group contains inputs, outputs, and all data related to a given asset id.
2679
+ *
2680
+ * @see Packet
2681
+ * @see AssetId
2682
+ * @see AssetRef
2683
+ *
2684
+ * @example
2685
+ * ```typescript
2686
+ * const group = AssetGroup.create(
2687
+ * null, // asset ID: null for new issuance
2688
+ * null, // control asset ID: null when reissuance not needed
2689
+ * [], // asset inputs: empty for new issuance
2690
+ * [AssetOutput.create(0, 1000)], // asset outputs: 1000 units at vout index 0
2691
+ * [] // metadata: can be empty
2692
+ * )
2693
+ * ```
2694
+ */
2695
+ declare class AssetGroup {
2696
+ readonly assetId: AssetId | null;
2697
+ readonly controlAsset: AssetRef | null;
2698
+ readonly inputs: AssetInput[];
2699
+ readonly outputs: AssetOutput[];
2700
+ private readonly metadataList;
2701
+ /** @see create */
2702
+ constructor(assetId: AssetId | null, controlAsset: AssetRef | null, inputs: AssetInput[], outputs: AssetOutput[], metadata: Metadata[]);
2703
+ /**
2704
+ * Create and validate an asset group.
2705
+ *
2706
+ * @param assetId - Asset id for this group, or `null` for fresh issuance
2707
+ * @param controlAsset - Optional control asset reference for (re) issuance
2708
+ * @param inputs - Asset inputs in the group
2709
+ * @param outputs - Asset outputs in the group
2710
+ * @param metadata - Metadata entries associated with the group
2711
+ * @returns A validated asset group
2712
+ * @throws Error if the group fails validation
2713
+ * @see validate
2714
+ */
2715
+ static create(assetId: AssetId | null, controlAsset: AssetRef | null, inputs: AssetInput[], outputs: AssetOutput[], metadata: Metadata[]): AssetGroup;
2716
+ /**
2717
+ * Decode an asset group from its hex string form.
2718
+ *
2719
+ * @param s - Hex-encoded asset group
2720
+ * @returns Decoded asset group
2721
+ * @throws Error if the string is not valid hex or does not encode a valid asset group
2722
+ * @see toString
2723
+ */
2724
+ static fromString(s: string): AssetGroup;
2725
+ /**
2726
+ * Decode an asset group from its serialized bytes.
2727
+ *
2728
+ * @param buf - Serialized asset group bytes
2729
+ * @returns Decoded asset group
2730
+ * @throws Error if the buffer is empty or malformed
2731
+ */
2732
+ static fromBytes(buf: Uint8Array): AssetGroup;
2733
+ /**
2734
+ * Return true when the group represents an issuance.
2735
+ *
2736
+ * @returns `true` when the group has no asset id
2737
+ */
2738
+ isIssuance(): boolean;
2739
+ /**
2740
+ * Return true when the group represents a reissuance.
2741
+ *
2742
+ * @returns `true` when the group has an asset id and outputs exceed local inputs
2743
+ * @remarks
2744
+ * Only local inputs contribute to the comparison; proof-backed inputs contribute `0` here.
2745
+ */
2746
+ isReissuance(): boolean;
2747
+ /**
2748
+ * Serialize the asset group to raw bytes.
2749
+ *
2750
+ * @returns Serialized asset group bytes
2751
+ * @see fromBytes
2752
+ */
2753
+ serialize(): Uint8Array;
2754
+ /**
2755
+ * Validate the asset group and its child structures.
2756
+ *
2757
+ * @throws Error if the group is empty or violates issuance invariants
2758
+ */
2759
+ validate(): void;
2760
+ /**
2761
+ * Convert the group into its batch-leaf representation for the given proof txid.
2762
+ *
2763
+ * @param proofTxid - Proof transaction id used to build the leaf input reference
2764
+ * @returns Batch-leaf asset group
2765
+ * @see AssetInput.createProof
2766
+ */
2767
+ toBatchLeafAssetGroup(proofTxid: Uint8Array): AssetGroup;
2768
+ /**
2769
+ * Encode the asset group to a hex string.
2770
+ *
2771
+ * @returns Hex-encoded asset group
2772
+ * @see fromString
2773
+ */
2774
+ toString(): string;
2775
+ /**
2776
+ * Decode an asset group from a binary reader.
2777
+ *
2778
+ * @param reader - Reader positioned at an asset group
2779
+ * @returns Decoded asset group
2780
+ * @throws Error if the encoded group is malformed
2781
+ */
2782
+ static fromReader(reader: BufferReader): AssetGroup;
2783
+ /**
2784
+ * Serialize the asset group into an existing binary writer.
2785
+ *
2786
+ * @param writer - Writer to append the asset group to
2787
+ */
2788
+ serializeTo(writer: BufferWriter): void;
2789
+ }
2790
+
2791
+ /**
2792
+ * ExtensionPacket is the interface that all extension packets must implement.
2793
+ * It mirrors the Go extension.Packet interface.
2794
+ */
2795
+ interface ExtensionPacket {
2796
+ /** type returns the 1-byte packet type tag */
2797
+ type(): number;
2798
+ /** serialize returns the raw bytes of the packet (without type or length prefix) */
2799
+ serialize(): Uint8Array;
2800
+ }
2801
+ /**
2802
+ * UnknownPacket holds a packet whose type is not recognized by this implementation.
2803
+ * It round-trips opaquely: the raw bytes are preserved as-is.
2804
+ */
2805
+ declare class UnknownPacket implements ExtensionPacket {
2806
+ private readonly packetType;
2807
+ private readonly data;
2808
+ constructor(packetType: number, data: Uint8Array);
2809
+ type(): number;
2810
+ serialize(): Uint8Array;
2811
+ }
2812
+
2813
+ /**
2814
+ * Packet represents a collection of asset groups.
2815
+ * It encodes/decodes as raw bytes only — OP_RETURN framing is handled by the Extension module.
2816
+ */
2817
+ declare class Packet implements ExtensionPacket {
2818
+ readonly groups: AssetGroup[];
2819
+ /** PACKET_TYPE is the 1-byte TLV type tag used in the Extension envelope. */
2820
+ static readonly PACKET_TYPE = 0;
2821
+ private constructor();
2822
+ /** Create a validated asset packet from a list of asset groups. */
2823
+ static create(groups: AssetGroup[]): Packet;
2824
+ /**
2825
+ * fromBytes parses a Packet from raw bytes.
2826
+ */
2827
+ static fromBytes(buf: Uint8Array): Packet;
2828
+ /**
2829
+ * fromString parses a Packet from a raw hex string (not an OP_RETURN script).
2830
+ */
2831
+ static fromString(s: string): Packet;
2832
+ /**
2833
+ * type returns the TLV packet type tag. Implements ExtensionPacket interface.
2834
+ */
2835
+ type(): number;
2836
+ /** Convert the packet into the batch-leaf form for a specific proof transaction id. */
2837
+ leafTxPacket(proofTxid: Uint8Array): Packet;
2838
+ /**
2839
+ * serialize encodes the packet as raw bytes (varint group count + group data).
2840
+ * Does NOT include OP_RETURN, Arkade magic bytes (`ARK`), or TLV type/length; those are
2841
+ * added by the Extension module.
2842
+ */
2843
+ serialize(): Uint8Array;
2844
+ /**
2845
+ * toString returns the hex-encoded raw packet bytes.
2846
+ */
2847
+ toString(): string;
2848
+ /** Validate packet structure and cross-group references. */
2849
+ validate(): void;
2850
+ private static fromReader;
2851
+ }
2852
+
2853
+ /**
2854
+ * Cross-repo test vectors for the Arkade Asset ID encodings.
2855
+ *
2856
+ * @remarks
2857
+ * Shipped from `src/` rather than `test/` so consumers outside this package can
2858
+ * pin the same bytes: `lightning-swap-service` imports this value, while NArk
2859
+ * and go-sdk vendor the backing `assetIdVectors.json` from a pinned revision of
2860
+ * this repository. The encoding is implemented in seven places across three
2861
+ * repos, and every disagreement fails silently (a flipped txid makes a covenant
2862
+ * unsatisfiable, a flipped group index resolves to a different asset).
2863
+ */
2864
+ interface AssetIdVectors {
2865
+ readonly version: number;
2866
+ readonly note: string;
2867
+ /** Genesis txid in display order — the 32 bytes an id's leading 64 hex chars carry. */
2868
+ readonly txid_hex: string;
2869
+ /** `txid_hex` reversed: serialization order, what the introspection opcodes match. */
2870
+ readonly script_txid_hex: string;
2871
+ readonly valid: ReadonlyArray<{
2872
+ readonly label: string;
2873
+ readonly group_index: number;
2874
+ /** `txid_hex` with the group index appended little-endian. */
2875
+ readonly asset_id_hex: string;
2876
+ /**
2877
+ * The group index as a stack item, after script-number encoding and
2878
+ * before push framing. Not the raw u16: `65535` is `ffff00` here and
2879
+ * `ffff` on the wire, and `0` is the empty item.
2880
+ */
2881
+ readonly script_group_index_item_hex: string;
2882
+ }>;
2883
+ /** Refused by the identity rule (`^[0-9a-f]{68}$`), though not necessarily by the decoder. */
2884
+ readonly invalid_identity: ReadonlyArray<{
2885
+ readonly label: string;
2886
+ readonly value: string;
2887
+ readonly why: string;
2888
+ /** Present when the value still decodes: what `toString()` must return. */
2889
+ readonly normalizes_to?: string;
2890
+ }>;
2891
+ /** Refused by {@link AssetId.fromString} / `fromBytes`. */
2892
+ readonly invalid_decode: ReadonlyArray<{
2893
+ readonly label: string;
2894
+ readonly value: string;
2895
+ /** Substring of the thrown message — normative for TS, advisory for other SDKs. */
2896
+ readonly expected_error: string;
2897
+ }>;
2898
+ /** Refused by {@link AssetId.create} / `validate`. */
2899
+ readonly invalid_construction: ReadonlyArray<{
2900
+ readonly label: string;
2901
+ readonly txid_hex: string;
2902
+ readonly group_index: number;
2903
+ readonly expected_error: string;
2904
+ /** Set when the group index cannot be expressed by an SDK whose constructor takes a native u16. */
2905
+ readonly outside_uint16?: boolean;
2906
+ }>;
2907
+ }
2908
+ /**
2909
+ * The asset-id test vectors, deeply frozen.
2910
+ *
2911
+ * @remarks
2912
+ * Frozen all the way down: the module is a singleton, and one consumer mutating
2913
+ * a nested entry would corrupt it for every other consumer in the process.
2914
+ *
2915
+ * @example
2916
+ * ```typescript
2917
+ * import { asset } from '@arkade-os/sdk'
2918
+ * const { txid_hex, valid } = asset.ASSET_ID_VECTORS
2919
+ * expect(AssetId.create(txid_hex, valid[0].group_index).toString()).toBe(valid[0].asset_id_hex)
2920
+ * ```
2921
+ */
2922
+ declare const ASSET_ID_VECTORS: AssetIdVectors;
2923
+
2924
+ declare const index$1_ASSET_ID_VECTORS: typeof ASSET_ID_VECTORS;
2925
+ type index$1_AssetGroup = AssetGroup;
2926
+ declare const index$1_AssetGroup: typeof AssetGroup;
2927
+ type index$1_AssetId = AssetId;
2928
+ declare const index$1_AssetId: typeof AssetId;
2929
+ type index$1_AssetIdVectors = AssetIdVectors;
2930
+ type index$1_AssetInput = AssetInput;
2931
+ declare const index$1_AssetInput: typeof AssetInput;
2932
+ type index$1_AssetInputType = AssetInputType;
2933
+ declare const index$1_AssetInputType: typeof AssetInputType;
2934
+ type index$1_AssetInputs = AssetInputs;
2935
+ declare const index$1_AssetInputs: typeof AssetInputs;
2936
+ type index$1_AssetOutput = AssetOutput;
2937
+ declare const index$1_AssetOutput: typeof AssetOutput;
2938
+ type index$1_AssetOutputs = AssetOutputs;
2939
+ declare const index$1_AssetOutputs: typeof AssetOutputs;
2940
+ type index$1_AssetRef = AssetRef;
2941
+ declare const index$1_AssetRef: typeof AssetRef;
2942
+ type index$1_AssetRefType = AssetRefType;
2943
+ declare const index$1_AssetRefType: typeof AssetRefType;
2944
+ type index$1_Metadata = Metadata;
2945
+ declare const index$1_Metadata: typeof Metadata;
2946
+ type index$1_MetadataList = MetadataList;
2947
+ declare const index$1_MetadataList: typeof MetadataList;
2948
+ type index$1_Packet = Packet;
2949
+ declare const index$1_Packet: typeof Packet;
2950
+ declare namespace index$1 {
2951
+ export { index$1_ASSET_ID_VECTORS as ASSET_ID_VECTORS, index$1_AssetGroup as AssetGroup, index$1_AssetId as AssetId, type index$1_AssetIdVectors as AssetIdVectors, index$1_AssetInput as AssetInput, index$1_AssetInputType as AssetInputType, index$1_AssetInputs as AssetInputs, index$1_AssetOutput as AssetOutput, index$1_AssetOutputs as AssetOutputs, index$1_AssetRef as AssetRef, index$1_AssetRefType as AssetRefType, index$1_Metadata as Metadata, index$1_MetadataList as MetadataList, index$1_Packet as Packet };
2952
+ }
2953
+
2954
+ /**
2955
+ * Creates an asset packet from asset inputs and receivers.
2956
+ * Groups inputs and outputs by asset ID and creates the Packet object
2957
+ * @param assetInputs - map input index -> assets
2958
+ * @param receivers - array of recipients with their asset allocations
2959
+ * @param changeReceiver - (optional) change receiver containing remaining assets
2960
+ * @returns packet containing all asset groups
2961
+ */
2962
+ declare function createAssetPacket(assetInputs: Map<number, Asset[]>, receivers: Recipient[], changeReceiver?: Recipient): Packet;
2963
+ /**
2964
+ * Selects coins that contain a specific asset.
2965
+ * Returns coins sorted by amount (smallest first for better coin selection).
2966
+ */
2967
+ declare function selectCoinsWithAsset(coins: ExtendedVirtualCoin[], assetId: string, requiredAmount: bigint): {
2968
+ selected: ExtendedVirtualCoin[];
2969
+ totalAssetAmount: bigint;
2947
2970
  };
2948
- type WalletUpdaterRequest = RequestInitWallet | RequestSettle | RequestGetAddress | RequestGetBoardingAddress | RequestGetOperatorInfo | RequestIndexerGetVtxos | RequestIndexerGetVirtualTxs | RequestSubmitTx | RequestFinalizeTx | RequestGetBalance | RequestGetVtxos | RequestGetSpendableVtxos | RequestGetBoardingUtxos | RequestGetTransactionHistory | RequestGetStatus | RequestGetContractSyncState | RequestClear | RequestReloadWallet | RequestSignTransaction | RequestCreateContract | RequestGetContracts | RequestGetContractsWithVtxos | RequestGetStoredContractsWithVtxos | RequestWatchScript | RequestUnwatchScript | RequestGetWatchedScripts | RequestAnnotateVtxos | RequestUpdateContract | RequestDeleteContract | RequestGetSpendablePaths | RequestGetAllSpendingPaths | RequestGetUnsupportedContracts | RequestIsContractManagerWatching | RequestRefreshVtxos | RequestRefreshOutpoints | RequestGetCurrentSigningDescriptor | RequestGetNextSigningDescriptor | RequestGetNewAddresses | RequestGetUsedSigningDescriptors | RequestAdvanceSigningDescriptorWatermark | RequestSend | RequestSendWithDeadline | RequestSendWithInputExpiryFloor | RequestGetAssetDetails | RequestIssue | RequestReissue | RequestBurn | RequestDelegate | RequestGetDelegateInfo | RequestRecoverVtxos | RequestGetRecoverableBalance | RequestGetExpiringVtxos | RequestRenewVtxos | RequestGetExpiredBoardingUtxos | RequestSweepExpiredBoardingUtxos | RequestCosignOnchainTx | RequestSendOnchain | RequestMigrateDeprecatedSignerVtxos | RequestGetDeprecatedSignerStatus | RequestRestoreWallet | RequestArkadeCash;
2949
- type WalletUpdaterResponse = ResponseEnvelope & (ResponseInitWallet | ResponseSettle | ResponseSettleEvent | ResponseGetAddress | ResponseGetBoardingAddress | ResponseGetOperatorInfo | ResponseIndexerGetVtxos | ResponseIndexerGetVirtualTxs | ResponseSubmitTx | ResponseFinalizeTx | ResponseGetBalance | ResponseGetVtxos | ResponseGetSpendableVtxos | ResponseGetBoardingUtxos | ResponseGetTransactionHistory | ResponseGetStatus | ResponseGetContractSyncState | ResponseClear | ResponseReloadWallet | ResponseUtxoUpdate | ResponseVtxoUpdate | ResponseSignTransaction | ResponseCreateContract | ResponseGetContracts | ResponseGetContractsWithVtxos | ResponseGetStoredContractsWithVtxos | ResponseWatchScript | ResponseUnwatchScript | ResponseGetWatchedScripts | ResponseAnnotateVtxos | ResponseUpdateContract | ResponseContractWatchStateSet | ResponseDeleteContract | ResponseGetSpendablePaths | ResponseGetAllSpendingPaths | ResponseGetUnsupportedContracts | ResponseIsContractManagerWatching | ResponseRefreshVtxos | ResponseRefreshOutpoints | ResponseGetCurrentSigningDescriptor | ResponseGetNextSigningDescriptor | ResponseGetNewAddresses | ResponseGetUsedSigningDescriptors | ResponseAdvanceSigningDescriptorWatermark | ResponseContractEvent | ResponseSend | ResponseSendDeadlineExceeded | ResponseGetAssetDetails | ResponseIssue | ResponseReissue | ResponseBurn | ResponseDelegate | ResponseGetDelegateInfo | ResponseRecoverVtxos | ResponseRecoverVtxosEvent | ResponseGetRecoverableBalance | ResponseGetExpiringVtxos | ResponseRenewVtxos | ResponseRenewVtxosEvent | ResponseGetExpiredBoardingUtxos | ResponseSweepExpiredBoardingUtxos | ResponseCosignOnchainTx | ResponseSendOnchain | ResponseMigrateDeprecatedSignerVtxos | ResponseMigrateDeprecatedSignerVtxosEvent | ResponseGetDeprecatedSignerStatus | ResponseRestoreWallet | ResponseArkadeCash);
2950
- declare class WalletMessageHandler implements MessageHandler<WalletUpdaterRequest, WalletUpdaterResponse> {
2951
- readonly messageTag: string;
2952
- private wallet;
2953
- private readonlyWallet;
2954
- private arkProvider;
2955
- private indexerProvider;
2956
- private walletRepository;
2957
- private incomingFundsSubscription;
2958
- private incomingFundsRegistrations;
2959
- private contractEventsSubscription;
2960
- private onNextTick;
2961
- private channel;
2962
- private incomingFundsEpoch;
2971
+
2972
+ /**
2973
+ * Thrown when a collaborative-exit / offboard would leave a change VTXO below
2974
+ * the dust threshold. Lets callers (e.g. wallet UI) react with appropriate UX
2975
+ * — for instance, offering to exit the full balance — instead of forwarding a
2976
+ * server-side dust rejection to the user.
2977
+ */
2978
+ declare class DustChangeError extends Error {
2979
+ readonly change: bigint;
2980
+ readonly dustAmount: bigint;
2981
+ constructor(change: bigint, dustAmount: bigint);
2982
+ }
2983
+ /** Thrown when a collaborative exit's change VTXO is above the server's
2984
+ * per-output ceiling, which arkd answers with `AMOUNT_TOO_HIGH`. */
2985
+ declare class OversizedChangeError extends Error {
2986
+ readonly change: bigint;
2987
+ readonly maxAmount: bigint;
2988
+ constructor(change: bigint, maxAmount: bigint);
2989
+ }
2990
+ /**
2991
+ * Ramps is a class wrapping `settle` method to provide a more convenient interface for onboarding and offboarding operations.
2992
+ *
2993
+ * @see IWallet.settle
2994
+ * @see onboard
2995
+ * @see offboard
2996
+ *
2997
+ * @example
2998
+ * ```typescript
2999
+ * const ramps = new Ramps(wallet);
3000
+ * const feeInfo = { intentFee: {}, txFeeRate: '1' };
3001
+ * await ramps.onboard(feeInfo); // onboard all boarding inputs
3002
+ * await ramps.offboard('bc1q...', feeInfo); // collaboratively exit all virtual outputs to an onchain address
3003
+ * ```
3004
+ */
3005
+ declare class Ramps {
3006
+ readonly wallet: IWallet;
2963
3007
  /**
2964
- * Supersedes older initializers without touching `incomingFundsEpoch`, so a
2965
- * re-init that fails before registering leaves the live subscription delivering.
3008
+ * Create convenience wrappers for onboarding and offboarding flows.
3009
+ *
3010
+ * @param wallet - Wallet used to query funds and execute settlement transactions
2966
3011
  */
2967
- private initEpoch;
2968
- private contractEventsEpoch;
2969
- private boardingEpoch;
2970
- /** Per-request progress callbacks: ends with the handler, not with a re-init. */
2971
- private requestEpoch;
3012
+ constructor(wallet: IWallet);
2972
3013
  /**
2973
- * Instantiate a new WalletUpdater.
2974
- * Can override the default `messageTag` allowing more than one updater to run in parallel.
2975
- * Note that the default ServiceWorkerWallet sends messages to the default WalletUpdater tag.
3014
+ * Onboard boarding inputs.
3015
+ *
3016
+ * @param feeInfo - The fee info to deduct from the onboard amount.
3017
+ * @param boardingUtxos - Specific boarding inputs to onboard. If not provided, all boarding inputs will be used.
3018
+ * @param amount - Amount to onboard. If not provided, the total amount of boarding inputs will be onboarded.
3019
+ * @param eventCallback - Optional callback that receives settlement events
3020
+ * @returns The Arkade transaction id created by settlement
3021
+ * @throws Error if no boarding inputs remain after fee deduction or if `amount` exceeds available value
3022
+ * @see IWallet.getBoardingUtxos
3023
+ * @see IWallet.settle
3024
+ * @example
3025
+ * ```typescript
3026
+ * const feeInfo = { intentFee: {}, txFeeRate: '1' };
3027
+ * const ramps = new Ramps(wallet);
3028
+ * await ramps.onboard(feeInfo);
3029
+ * ```
2976
3030
  */
2977
- constructor(options?: {
2978
- messageTag?: string;
2979
- });
2980
- start(...params: Parameters<MessageHandler<WalletUpdaterRequest, WalletUpdaterResponse>["start"]>): Promise<void>;
2981
- stop(): Promise<void>;
2982
- tick(_now: number): Promise<WalletUpdaterResponse[]>;
2983
- private epochOf;
2984
- private newGeneration;
3031
+ onboard(feeInfo: FeeInfo, boardingUtxos?: ExtendedCoin[], amount?: bigint, eventCallback?: (event: SettlementEvent) => void): ReturnType<IWallet["settle"]>;
2985
3032
  /**
2986
- * A handle rather than a `broadcast(response, epoch)` call, because it can
2987
- * only be written where the closure it guards is created — an epoch passed
2988
- * at the call site reads identically whether it guards anything or not.
3033
+ * Offboard virtual outputs, or collaboratively exit them to an onchain address.
3034
+ *
3035
+ * @param destinationAddress - The destination address to offboard to.
3036
+ * @param feeInfo - The fee info to deduct from the offboard amount.
3037
+ * @param amount - The amount to offboard. If not provided, the total amount of virtual outputs will be offboarded.
3038
+ * @param eventCallback - Optional callback that receives settlement events
3039
+ * @param vtxos - Specific virtual outputs to spend, mirroring {@link onboard}'s
3040
+ * `boardingUtxos`. Omitted, every spendable one is spent — merging the whole
3041
+ * off-chain balance into a single change output. Taken as given like
3042
+ * `settle({ inputs })`: an `amount` these cannot cover is an error, not a top-up.
3043
+ * @returns The Arkade transaction id created by settlement
3044
+ * @throws Error if no virtual outputs remain after fee deduction or the destination address cannot be decoded
3045
+ * @see IWallet.getSpendableVtxos
3046
+ * @see IWallet.settle
3047
+ * @example
3048
+ * ```typescript
3049
+ * const feeInfo = { intentFee: {}, txFeeRate: '1' };
3050
+ * const ramps = new Ramps(wallet);
3051
+ * await ramps.offboard('bc1q...', feeInfo);
3052
+ * ```
2989
3053
  */
2990
- private newEmitter;
2991
- private requireWallet;
2992
- private tagged;
2993
- isLongRunning(message: WalletUpdaterRequest): boolean;
2994
- handleMessage(message: WalletUpdaterRequest): Promise<WalletUpdaterResponse>;
2995
- private handleInitWallet;
2996
- /** @see RequestInitWallet.payload.lazyBoarding */
2997
- private lazyBoardingInit;
2998
- /** Set once this session has actually fetched the boarding addresses. */
2999
- private boardingLoaded;
3054
+ offboard(destinationAddress: string, feeInfo: FeeInfo, amount?: bigint, eventCallback?: (event: SettlementEvent) => void, vtxos?: NormalizedExtendedVirtualCoin[]): ReturnType<IWallet["settle"]>;
3000
3055
  /**
3001
- * The worker's own balance. Same bucketing rules as `Wallet.getBalance` —
3002
- * both call {@link computeOffchainBalance} — but deliberately a different
3003
- * freshness: this reads the repository directly, with no indexer sync, so a
3004
- * polling UI never pays for a network round-trip. That rules out
3005
- * `pendingRecoveryOutpoints()`, whose snapshot syncs; the same classification
3006
- * runs over this method's local snapshot instead.
3056
+ * Collaboratively exit with the DESTINATION paid exactly `amount`, pricing the
3057
+ * fee on that output rather than on a grossed-up figure. {@link offboard} keeps
3058
+ * the other anchor, which needs `g - fee(g) = amount` solved — impossible for
3059
+ * a program charging the whole output.
3060
+ *
3061
+ * Returns the onchain txid instead when onchain coins alone cover `amount`
3062
+ * and were spent via arkd cosigning.
3007
3063
  */
3008
- private handleGetBalance;
3009
- private getBoardingUtxosForBalance;
3010
- private onWalletInitialized;
3011
- private registerIncomingFunds;
3064
+ offboardExact(params: {
3065
+ destinationAddress: string;
3066
+ feeInfo: FeeInfo;
3067
+ /** Sats the destination receives, exactly. */
3068
+ amount: bigint;
3069
+ eventCallback?: (event: SettlementEvent) => void;
3070
+ vtxos?: NormalizedExtendedVirtualCoin[];
3071
+ }): ReturnType<IWallet["settle"]>;
3072
+ private tryCosign;
3073
+ private offboardInputs;
3074
+ /** Every candidate, or with `concurrentSpending` the shortest covering prefix in send order. */
3075
+ private fundExit;
3076
+ /** Re-runs an SDK-picked exit that lost a coin to a concurrent spend. */
3077
+ private withRepick;
3078
+ /** Fund the change output: pay its own fee, then judge it against both
3079
+ * server-side bounds. `0n` in is `0n` out — no change output at all. */
3080
+ private fundChange;
3081
+ }
3082
+
3083
+ /**
3084
+ * HD-wallet {@link DescriptorProvider} that allocates a fresh signing descriptor on every call.
3085
+ * A pure rotating allocator: which descriptor the wallet is bound to is answered by the contract
3086
+ * repository, not this provider.
3087
+ *
3088
+ * State lives in `settings.hd` of the wallet state, so switching single-key → HD needs no schema
3089
+ * migration. Allocation runs inside the shared per-repo `updateWalletState` mutex, so callers
3090
+ * (even on separate instances over one repo) never observe the same index.
3091
+ *
3092
+ * @example
3093
+ * ```ts
3094
+ * const provider = await HDDescriptorProvider.create(identity, walletRepo);
3095
+ * const descriptor = await provider.getNextSigningDescriptor();
3096
+ * // descriptor: tr([fp/86'/0'/0']xpub/0/0)
3097
+ * const next = await provider.getNextSigningDescriptor();
3098
+ * // next: tr([fp/86'/0'/0']xpub/0/1)
3099
+ * ```
3100
+ */
3101
+ declare class HDDescriptorProvider implements DescriptorProvider, ReceiveRotatorFactory {
3102
+ private readonly identity;
3103
+ private readonly walletRepository;
3104
+ private constructor();
3012
3105
  /**
3013
- * Refresh boarding inputs and transaction history. The virtual outputs come
3014
- * from the contract manager, which runs before this. Shared by
3015
- * onWalletInitialized (full bootstrap) and reloadWallet (post-refresh),
3016
- * avoiding duplicate subscriptions and VtxoManager restarts.
3017
- *
3018
- * Both legs reach the onchain provider, so `lazyBoarding` moves them both
3019
- * off the caller's path. @see RequestInitWallet.payload.lazyBoarding
3106
+ * Construct an HDDescriptorProvider. No I/O: state is read lazily, so a descriptor-mismatch
3107
+ * error surfaces on first use rather than here.
3020
3108
  */
3021
- private refreshCachedData;
3022
- /** History rows plus the address they are stored under. Does not write. */
3023
- private loadHistoryCache;
3024
- private storeHistoryCache;
3025
- /** @param gen - set by a background caller; the refresh is skipped once it goes stale. */
3026
- private refreshBoardingCache;
3109
+ static create(identity: HDCapableIdentity, walletRepository: WalletRepository): Promise<HDDescriptorProvider>;
3110
+ /** Allocate and return the next descriptor (index 0, 1, 2, …), atomically per repo. */
3111
+ getNextSigningDescriptor(): Promise<string>;
3027
3112
  /**
3028
- * Force a full VTXO refresh from the indexer, then refresh cached data.
3029
- * Used by RELOAD_WALLET to ensure fresh data without re-subscribing
3030
- * to incoming funds or restarting the VtxoManager.
3113
+ * Re-derive the descriptor `getNextSigningDescriptor` last returned, WITHOUT advancing;
3114
+ * `undefined` if none was ever allocated. Lets boot keep the display address stable across
3115
+ * restarts when no tagged display contract exists, instead of burning a new index.
3031
3116
  */
3032
- private reloadWallet;
3033
- private handleSettle;
3034
- private handleSignTransaction;
3035
- private handleDelegate;
3117
+ getCurrentSigningDescriptor(): Promise<string | undefined>;
3118
+ /** Read-only peek at the allocation watermark; `undefined` if nothing was ever allocated. */
3119
+ getLastIndexUsed(): Promise<number | undefined>;
3036
3120
  /**
3037
- * Ungated repository read mirroring `Wallet.getVtxos`, the raw reporting read.
3121
+ * Monotonically advance the watermark past indices found by a restore scan; never rewinds.
3122
+ * An invalid `index` (non-integer, negative, or >= 2^31) is ignored: persisting it would make
3123
+ * `parseSettings()` throw, and a watermark at the hardened ceiling would fail every later
3124
+ * allocation for the life of the repo.
3038
3125
  */
3039
- private handleGetVtxos;
3040
- /** Tear down handler subscriptions, then delegate the full wipe to the wallet. */
3041
- private clear;
3126
+ advanceLastIndexUsed(index: number): Promise<void>;
3127
+ /** Whether `descriptor` (HD or simple `tr(pubkey)`) is derivable from this wallet's seed. */
3128
+ isOurs(descriptor: string): boolean;
3129
+ /** Signs each request with its descriptor's derived key (the identity holds the seed). */
3130
+ signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]>;
3131
+ /** Signs a message using the key derived from `descriptor`. */
3132
+ signMessageWithDescriptor(descriptor: string, message: Uint8Array, signatureType?: "schnorr" | "ecdsa"): Promise<Uint8Array>;
3133
+ /** HD providers take part in receive rotation via {@link WalletReceiveRotator.defaultBoot}. */
3134
+ createReceiveRotator(opts: ReceiveRotatorBootOpts): Promise<ReceiveRotatorBoot | undefined>;
3042
3135
  /**
3043
- * Read all virtual outputs from the repository, aggregated across all contract
3044
- * addresses and the wallet's primary address, with deduplication.
3045
- *
3046
- * Recovery-only contracts (imported by `claimCash` for operator-swept
3047
- * arkcash) are excluded by default, mirroring {@link ReadonlyWallet.getVtxos}:
3048
- * they are settled in their own isolated intent and must stay out of the
3049
- * wallet's balance / VTXO / coin-selection / pending-tx views that read this.
3050
- * Transaction history excludes them too, as does the non-worker
3051
- * `getTransactionHistory`.
3136
+ * Materialize the account template at `index` via the descriptors-scure parser (validates the
3137
+ * ranged template and yields a canonical key expression) rather than string substitution.
3138
+ * Pure: does NOT advance the watermark, so restore's gap-scan can peek arbitrary indices.
3052
3139
  */
3053
- private getVtxosFromRepo;
3140
+ materializeDescriptorAt(index: number): string;
3054
3141
  /**
3055
- * The worker's equivalent of `ReadonlyWallet.contractSnapshot`: contracts
3056
- * paired with the VTXOs the repository holds for them, plus the flat
3057
- * deduplicated list. Purely local — unlike the main-thread snapshot it never
3058
- * syncs against the indexer.
3059
- *
3060
- * One read of the contract rows serves both halves. Reading them twice
3061
- * (once for the VTXO buckets, once for the gate) races the contract
3062
- * manager's own writes: a contract registered between the two reads yields
3063
- * VTXOs with no matching row in the gate, and `gatedContracts` lists only
3064
- * what it knows is closed — so the coins of a just-registered escrowed
3065
- * contract would count as available until the next poll.
3066
- *
3067
- * Recovery-only contracts are skipped (see {@link getVtxosFromRepo}).
3142
+ * Read-modify-write HD settings inside the shared per-repo wallet-state mutex; `fn` mutates a
3143
+ * validated snapshot that is persisted atomically. Reading inside the lock prevents races on a
3144
+ * stale index.
3068
3145
  */
3069
- private repoSnapshot;
3146
+ private mutate;
3070
3147
  /**
3071
- * Build transaction history from cached virtual outputs, hitting the indexer only for
3072
- * uncached timestamps. Best-effort, like the plain Wallet path.
3073
- *
3074
- * Takes its own {@link repoSnapshot} rather than a caller-supplied VTXO
3075
- * list: the coins and the gate that judges them have to come off one read
3076
- * or they answer about different instants, and being the worker's only
3077
- * history builder means neither caller can supply one without the other.
3078
- * The snapshot and the boarding read are independent, so they run together
3079
- * — the same pairing `handleGetBalance` makes.
3148
+ * Validate persisted HD settings (or init a fresh record) and return a mutable clone. Fails
3149
+ * loud: a corrupt repo would otherwise derive `NaN` descriptors.
3080
3150
  */
3081
- private buildTransactionHistoryFromCache;
3082
- private ensureContractEventBroadcasting;
3151
+ private parseSettings;
3083
3152
  }
3084
3153
 
3085
3154
  type RequestType = WalletUpdaterRequest["type"];
3086
3155
  type MessageTimeouts = Partial<Record<RequestType, number>>;
3156
+ type WalletUpdate = Extract<WalletUpdaterResponse, {
3157
+ type: "CONTRACT_EVENT" | "VTXO_UPDATE" | "UTXO_UPDATE";
3158
+ }>;
3087
3159
  type ServiceWorkerWalletMode = "auto" | "static" | "hd";
3088
3160
  declare const DEFAULT_MESSAGE_TIMEOUTS: Readonly<Record<RequestType, number>>;
3089
3161
  /**
@@ -3133,6 +3205,8 @@ interface ServiceWorkerWalletOptions {
3133
3205
  storage?: StorageConfig;
3134
3206
  /** Identity used to derive addresses and optionally sign operations. */
3135
3207
  identity: ReadonlyIdentity | Identity;
3208
+ /** Refuse a worker on another network before exposing a usable proxy. */
3209
+ expectedNetwork?: NetworkName;
3136
3210
  /** Optional delegation service URL. */
3137
3211
  delegateUrl?: string;
3138
3212
  /**
@@ -3230,6 +3304,9 @@ declare class ServiceWorkerReadonlyWallet implements IReadonlyWallet {
3230
3304
  readonly activity: ActivityRegistry;
3231
3305
  private readonly _readonlyAssetManager;
3232
3306
  protected initConfig: MessageBusInitConfig | null;
3307
+ protected expectedWalletScope?: string;
3308
+ protected expectedNetwork?: NetworkName;
3309
+ protected walletRequestBinding?: WalletRequestBinding;
3233
3310
  protected initWalletPayload: RequestInitWallet["payload"] | null;
3234
3311
  protected messageBusTimeoutMs?: number;
3235
3312
  protected messageTimeouts: Record<RequestType, number>;
@@ -3273,6 +3350,7 @@ declare class ServiceWorkerReadonlyWallet implements IReadonlyWallet {
3273
3350
  onEvent: (response: WalletUpdaterResponse) => void;
3274
3351
  isComplete: (response: WalletUpdaterResponse) => boolean;
3275
3352
  }): Promise<WalletUpdaterResponse>;
3353
+ private scopeRequest;
3276
3354
  /** The init config cached by `create()`; manually constructed wallets have none. */
3277
3355
  protected buildInitConfig(): Promise<MessageBusInitConfig>;
3278
3356
  protected buildInitWalletPayload(): RequestInitWallet["payload"];
@@ -3339,6 +3417,8 @@ declare class ServiceWorkerReadonlyWallet implements IReadonlyWallet {
3339
3417
  * @returns `true` when the wallet was reloaded
3340
3418
  */
3341
3419
  reload(): Promise<boolean>;
3420
+ /** Subscribe to contract and coin updates bound to this proxy's wallet. */
3421
+ onWalletUpdate(callback: (update: WalletUpdate) => void): () => void;
3342
3422
  getContractManager(): Promise<IContractManager>;
3343
3423
  }
3344
3424
  declare class ServiceWorkerWallet extends ServiceWorkerReadonlyWallet implements IWallet, HDWalletCapable, HDAllocationCapable, AddressAllocationCapable {
@@ -3436,6 +3516,11 @@ declare class ServiceWorkerWallet extends ServiceWorkerReadonlyWallet implements
3436
3516
  gapLimit?: number;
3437
3517
  }): Promise<void>;
3438
3518
  private _restoreWorkerWallet;
3519
+ /**
3520
+ * Durable across tabs and worker restarts. Persist the application operation id before calling;
3521
+ * release only after proving settlement or non-submission. SDK sends cannot spend this hold.
3522
+ */
3523
+ reserveVtxos(outpoints: readonly Outpoint[], reservationId: string): Promise<VtxoReservation>;
3439
3524
  send(...args: [SendParams] | [Recipient, ...Recipient[]]): Promise<string>;
3440
3525
  cosignOnchainTx(psbt: string | Transaction$1): Promise<string>;
3441
3526
  sendOnchain(params: SendOnchainParams): Promise<string>;
@@ -3911,8 +3996,6 @@ declare class ElectrumOnchainProvider implements OnchainProvider {
3911
3996
  * the orphaned chain's median.
3912
3997
  */
3913
3998
  private medianTimePast;
3914
- /** Degrades to the tip's `nTime` rather than throwing — a caller that
3915
- * cannot read the tip at all is worse off. */
3916
3999
  private readMedianTimePast;
3917
4000
  watchAddresses(addresses: string[], eventCallback: (txs: ExplorerTransaction[]) => void): Promise<() => void>;
3918
4001
  /** Close the underlying WebSocket connection. */
@@ -3983,6 +4066,33 @@ type OffchainTx = {
3983
4066
  */
3984
4067
  declare function buildOffchainTx(inputs: ArkTxInput[], outputs: TransactionOutput[], serverUnrollScript: CSVMultisigTapscript.Type): OffchainTx;
3985
4068
  declare function hasBoardingTxExpired(coin: ExtendedCoin, boardingTimelock: RelativeTimelock, chainTipHeight?: number, chainTipMedianTime?: number, confirmationParentMedianTime?: number): boolean;
4069
+ /**
4070
+ * The CSV exit path of the boarding address a coin sits on, decoded from the coin's own
4071
+ * `tapTree`. Its timelock can differ from the wallet's current boarding delay (a signer rotation
4072
+ * may change it), so expiry and the sweep must read it from the coin, not from the wallet.
4073
+ *
4074
+ * @returns `undefined` when the tree is undecodable or has no CSV leaf.
4075
+ */
4076
+ declare function decodeBoardingExit(coin: ExtendedCoin): {
4077
+ script: VtxoScript;
4078
+ leaf: TapLeafScript;
4079
+ timelock: RelativeTimelock;
4080
+ } | undefined;
4081
+ type BoardingExpiry = {
4082
+ expired: ExtendedCoin[];
4083
+ unknown: ExtendedCoin[];
4084
+ };
4085
+ /**
4086
+ * Splits out the confirmed coins whose own boarding timelock has elapsed, so they can no longer be
4087
+ * settled and leave through the unilateral exit. Seconds-based CSV uses the MTP of the block before
4088
+ * confirmation and the current tip MTP, as required by BIP 68. A coin whose expiry cannot be
4089
+ * established (no block height, no provider MTP lookup, a failed lookup) is `unknown`: callers
4090
+ * must neither settle nor sweep it, but the other coins are still judged.
4091
+ */
4092
+ declare function classifyBoardingExpiry(coins: ExtendedCoin[], getChainTip: () => Promise<{
4093
+ height: number;
4094
+ time: number;
4095
+ }>, getMedianTimePast?: (height: number) => Promise<number>): Promise<BoardingExpiry>;
3986
4096
  /**
3987
4097
  * Verify tapscript signatures on a transaction input
3988
4098
  * @param tx Transaction to verify
@@ -4770,7 +4880,7 @@ type ExitOptions = {
4770
4880
  onchainWallet: OnchainWallet;
4771
4881
  /** Destination for the exited funds. */
4772
4882
  sweepAddress: string;
4773
- /** sat/vB; defaults to the onchain provider estimate, floored at MIN_FEE_RATE. */
4883
+ /** sat/vB, rounded up; 0 or unset: provider rate, floored at MIN_FEE_RATE, capped at 1,000. */
4774
4884
  feeRate?: number;
4775
4885
  /** Defaults to all spendable VTXOs. */
4776
4886
  vtxos?: Outpoint[];
@@ -5513,9 +5623,11 @@ declare namespace bignum {
5513
5623
  * handler: pass a `contractManager` to {@link Arkade.connect} and call
5514
5624
  * {@link ArkadeContract.register} to persist and watch a contract.
5515
5625
  *
5516
- * Functions are typed from the program's literal shape (`inputs: [{ name: "preimage", type:
5517
- * "bytes" }]` → `functions.claim(preimage: Uint8Array)`). For a program stored in a variable use
5518
- * `satisfies Program`; a `: Program` annotation widens the literal type away. Typed `params`
5626
+ * Functions are typed from the program's literal shape (`tapscript.inputs: [{ name: "preimage",
5627
+ * type: "bytes" }]` → `functions.claim({ tapscript: [preimage: Uint8Array] })`). Each segment's
5628
+ * `witness` names its own `inputs`, and the call passes them under that segment's key. For a
5629
+ * program stored in a variable use `satisfies Program`; a `: Program` annotation widens the
5630
+ * literal type away. Typed `params`
5519
5631
  * descriptors `{ name, type }` make the list authoritative (every param bound, every `$name`
5520
5632
  * declared, values type-checked).
5521
5633
  *
@@ -5535,8 +5647,12 @@ declare namespace bignum {
5535
5647
  * ],
5536
5648
  * functions: {
5537
5649
  * claim: {
5538
- * inputs: [{ name: "preimage", type: "bytes" }],
5539
- * tapscript: { signers: ["$server"], asm: ["HASH160", "$hash", "EQUAL"], witness: ["preimage"] },
5650
+ * tapscript: {
5651
+ * signers: ["$server"],
5652
+ * asm: ["HASH160", "$hash", "EQUAL"],
5653
+ * inputs: [{ name: "preimage", type: "bytes" }],
5654
+ * witness: ["preimage"],
5655
+ * },
5540
5656
  * arkadeScript: { asm: payTo, witness: [0] },
5541
5657
  * },
5542
5658
  * },
@@ -5546,7 +5662,7 @@ declare namespace bignum {
5546
5662
  * // `server` is declared in `params`, so it defaults to the client's operator key.
5547
5663
  * const htlc = arkade.contract(htlcProgram, { hash, receiver, amount: 10_000n });
5548
5664
  * // `preimage` is typed Uint8Array; calling `claim()` with no args is a type error.
5549
- * const { txid } = await htlc.functions.claim(preimage).to(receiver, 10_000n).send();
5665
+ * const { txid } = await htlc.functions.claim({ tapscript: [preimage] }).to(receiver, 10_000n).send();
5550
5666
  * ```
5551
5667
  *
5552
5668
  * @module arkade/contract
@@ -5562,14 +5678,24 @@ type ArgsTuple<I extends readonly InputDef[]> = {
5562
5678
  [K in keyof I]: ArkadeValueType[I[K]["type"]];
5563
5679
  };
5564
5680
  /**
5565
- * The call signature arguments for one function (nullary when `inputs` is absent). Dotted input
5566
- * names group into one struct or array argument at runtime; dotted or widened names stay loose.
5681
+ * One segment's call arguments, one per source parameter (none when it declares no `inputs`).
5682
+ * Dotted input names group into one struct or array argument at runtime; dotted or widened names
5683
+ * stay loose.
5567
5684
  */
5568
- type FnArgs<F extends ArkadeFunction> = F extends {
5685
+ type SegmentArgs<S> = S extends {
5569
5686
  inputs: infer I extends readonly InputDef[];
5570
5687
  } ? string extends I[number]["name"] ? ArkadeNestedValue[] : Extract<I[number]["name"], `${string}.${string}`> extends never ? ArgsTuple<I> : ArkadeNestedValue[] : [];
5688
+ type WitnessSegment = "tapscript" | "arkadeScript";
5689
+ /** A function's call argument: one key for each segment that declares non-empty `inputs`. */
5690
+ type CallArgs<F extends ArkadeFunction> = {
5691
+ [K in WitnessSegment as SegmentArgs<F[K]> extends readonly [] ? never : K]: SegmentArgs<F[K]>;
5692
+ };
5693
+ /** The call argument of a function of a widened {@link Program}. */
5694
+ type LooseCallArgs = Partial<Record<WitnessSegment, readonly ArkadeNestedValue[]>>;
5695
+ /** The call signature arguments for one function: nullary when no segment declares inputs. */
5696
+ type FnArgs<F extends ArkadeFunction> = keyof CallArgs<F> extends never ? [] : [args: CallArgs<F>];
5571
5697
  /** A contract's functions returning `R`: typed per function for a literal program, else loose. */
5572
- type FunctionMap<P extends Program, R> = string extends keyof P["functions"] ? Record<string, (...args: ArkadeNestedValue[]) => R> : {
5698
+ type FunctionMap<P extends Program, R> = string extends keyof P["functions"] ? Record<string, (args?: LooseCallArgs) => R> : {
5573
5699
  [K in keyof P["functions"]]: (...args: FnArgs<P["functions"][K]>) => R;
5574
5700
  };
5575
5701
  /**
@@ -5620,7 +5746,8 @@ interface Utxo {
5620
5746
  interface ArkadeUnlocker {
5621
5747
  readonly contract: ArkadeContract<any>;
5622
5748
  readonly fn: CompiledProgramFunction;
5623
- readonly args: Record<string, ArkadeArgValue>;
5749
+ /** Bound call inputs, by the segment whose witness names them. */
5750
+ readonly args: Readonly<Record<WitnessSegment, Record<string, ArkadeArgValue>>>;
5624
5751
  }
5625
5752
  /**
5626
5753
  * An asset-group transfer attached to a spend: which inputs supply the asset and
@@ -5653,7 +5780,7 @@ interface ArkadeSpendResult {
5653
5780
  signedCheckpointTxs: string[];
5654
5781
  }
5655
5782
  /** The callable spending paths of a contract. */
5656
- type CallableFunctions = Record<string, (...args: ArkadeNestedValue[]) => ArkadeTransactionBuilder>;
5783
+ type CallableFunctions = Record<string, (args?: LooseCallArgs) => ArkadeTransactionBuilder>;
5657
5784
  /** What {@link Arkade} needs from the operator; see {@link ArkadeConnectOptions.arkade}. */
5658
5785
  type ArkadeServerProvider = Pick<OperatorProvider, "getInfo"> & Partial<ArkadeBroadcaster & Pick<OperatorProvider, "cosignOnchainTx">>;
5659
5786
  /** Fields shared by both forms of {@link ArkadeConnectOptions}. */
@@ -5848,7 +5975,10 @@ declare class ArkadeContract<P extends Program = Program> {
5848
5975
  get address(): string;
5849
5976
  /** Taproot output script. */
5850
5977
  get pkScript(): Uint8Array;
5851
- /** Callable spending paths: `functions.<name>(...args)` (see {@link ContractFunctions}). */
5978
+ /**
5979
+ * Callable spending paths: `functions.<name>({ tapscript: [...], arkadeScript: [...] })`
5980
+ * (see {@link ContractFunctions}).
5981
+ */
5852
5982
  get functions(): ContractFunctions<P>;
5853
5983
  /** Spending paths bound to their arguments, for `.from(coins, contract.unlock.<name>(...))`. */
5854
5984
  get unlock(): ContractUnlockers<P>;
@@ -6555,9 +6685,10 @@ declare function sequenceToTimelock(sequence: number): RelativeTimelock;
6555
6685
  */
6556
6686
  declare function toXOnly(key: Uint8Array, label?: string): Uint8Array;
6557
6687
 
6558
- declare const buildVersion = "0.9.9";
6559
6688
  /** The SDK's own version string, sourced from package.json */
6560
6689
  declare const sdkVersion: string;
6690
+
6691
+ declare const buildVersion = "0.9.9";
6561
6692
  /**
6562
6693
  * Wraps a transport-level `fetch` rejection (DNS failure, connection refused,
6563
6694
  * TLS or CORS error) with the request method and URL, preserving the original
@@ -6768,4 +6899,4 @@ declare class AssetManager extends ReadonlyAssetManager implements IAssetManager
6768
6899
  private burnWith;
6769
6900
  }
6770
6901
 
6771
- export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, ASSET_CARRIER_SATS, Activity, ActivityRegistry, AddressAllocationCapable, AmbiguousRouteError, type AnchorBumper, ArkNote, type ArkPsbtFieldCoder, ArkPsbtFieldKey, ArkPsbtFieldKeyType, ArkTransaction, type ArkTxInput, Arkade, type ArkadeBatchInput, ArkadeBroadcaster, ArkadeCashClaimResult, ArkadeCashRecord, type ArkadeCashRequest, type ArkadeCashResponse, type ArkadeCashStatus, type ArkadeCashStatusReport, ArkadeCashTx, ArkadeContractParams, type ArkadeExtendedCoin, type ArkadeExtendedVirtualCoin, ArkadeInfo, ArkadeReader, ArkadeService, Asset, AssetDetails, AssetManager, AtomicWalletState, BIP21, BIP21Error, type BIP21Params, type BIP21ParseResult, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, BatchExpiryPolicy, BatchRegistration, BatchRegistrationPageFilter, BatchRegistrationRepository, BurnParams, CSVMultisigTapscript, CachingArkProvider, CachingOperatorProvider, ChainTx, Coin, ConditionWitness, ConnectionDisposedError, Contract, ContractEvent, ContractFilter, ContractRepository, ContractSyncState, ContractVtxoEvent, ContractWatcherConfig, ContractWithVtxos, CosignerPublicKey, CreateContractParams, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_PASSKEY_LABEL, DatabaseUpgradeBlockedError, DelegateInfo, DelegateNotConfiguredError, DescriptorIdentity, type DescriptorIdentityOptions, type DescriptorOptions, DescriptorProvider, type DescriptorSigner, DescriptorSigningProviderMissingError, DescriptorSigningRequest, type DeterministicSigner, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, type BlockHeader as ElectrumBlockHeader, ElectrumOnchainProvider, type TransactionHistory as ElectrumTransactionHistory, type Unspent as ElectrumUnspent, type EmulatorEntry, EmulatorPacket, EmulatorProvider, EncodedVtxoScript, Estimator, type ExcludableVtxo, type ExecutorEvent, type ExecutorOptions, type ExitDelay, type ExitFeeWallet, type ExitMode, type ExitOptions, type ExitPackage, type ExitQuote, type ExitStep, type ExitTotals, type ExitVtxoInfo, ExplorerTransaction, ExtendedCoin, ExtendedContractVtxo, ExtendedVirtualCoin, Extension, ExtensionNotFoundError, type ExtensionPacket, FeeAmount, FeeInfo, FeeOutput, FetchError, GetNewAddressesOptions, GetOperatorInfoOptions, GetSpendableVtxosFilter, GetVtxosFilter, GetVtxosOptions, HDAllocationCapable, HDDescriptorProvider, type HDDeterministicSignCapable, HDWalletCapable, IAssetManager, IContractManager, IDelegateManager, IReadonlyAssetManager, IReadonlyWallet, IVtxoManager, IWallet, Identity, InMemoryBatchRegistrationRepository, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBBatchRegistrationRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexerProvider, InputExpiryFloor, IntentFeeConfig, IssuanceParams, IssuanceResult, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, type ManagedConnection, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, type MessageHandler, type MessageTimeouts, MigrationGlobalSkipReason, MigrationLegSkipReason, MissingSigningDescriptorError, MnemonicIdentity, type MnemonicOptions, Network, NetworkName, type NetworkOptions, NewAddress, NormalizedExtendedVirtualCoin, NormalizedVtxoPage, OffchainInput, type OffchainTx, type OnExitObserved, OnchainCosignPreflightError, OnchainInput, OnchainProvider, OnchainWallet, OperatorInfo, OperatorProvider, Outpoint, OversizedChangeError, P2A, PageRequest, PageResult, PaginationOptions, type ParsedArkContract, PasskeyCancelled, type PasskeyMnemonic, type PasskeySource, PasskeyUnconfirmed, PathContext, PathSelection, type PaymentHandle, type PaymentOption, type PaymentRail, type PaymentRequest, PaymentRouter, type PaymentStatus, PrevArkTxField, PrevoutTxField, PrfUnavailable, Proof, ProviderConnectionState, type ProvisionedClaimSecret, type ProvisionedKey, READ_TIMEOUT_MS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlyIdentity, ReadonlyWallet, ReadonlyWalletError, Recipient, ReissuanceParams, RelativeTimelock, RenewVtxosOptions, type RequestEnvelope, type ResponseEnvelope, type RouteQuote, type RouteResult, type RouterContext, type RouterPreferences, ScriptVtxoCursor, ScriptVtxoPageOptions, SeedIdentity, type SeedIdentityOptions, SendBitcoinParams, SendDeadlineExceededError, SendOnchainParams, SendParams, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, type ServiceWorkerWalletMode, SettleParams, SettlementConfig, SettlementEvent, SignedProof, SignerSession, SignerStatus, StaticDescriptorProvider, Status, StorageConfig, StoredVtxo, TapLeafScript, Transaction, TransactionHistoryPageCursor, TransactionHistoryPageFilter, TreeNonces, TreePartialSigs, TxNotificationEvent, TxTree, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, UnsupportedProgramVersionError, type VSize, type VerifyServerSignatures, VirtualCoin, VirtualTx, VirtualTxRepository, VtxoBranch, type VtxoExclusion, VtxoScript, VtxoTaprootTree, VtxoTreeExpiry, Wallet, WalletBalance, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WalletRepository, type WalletRestoreHook, WatchedScript, type WebAuthnClient, WsElectrumChainSource, adoptContractDescriptor, arkAssetRail, arkRail, arkTarget, index as arkade, assembleBtcdTaprootTree, assertFinalCommitmentMatchesValidated, assertNoAssets, assertNoSelection, assertNonNegativeMs, assertSendDeadline, assertSendableAmount, assertSubmittedArkTxid, assertTimerMs, assertValidServerUnrollScript, index$1 as asset, assetsOf, awaitTransaction, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, buildVersion, captureSendDeadline, claimWithPreimageIdentity, closeDatabase, combineTapscriptSigs, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createAssetPacket, createDefaultPaymentRouter, createManagedConnection, createPrfPasskey, decodeArkContract, deleteByIndex, deriveDescriptorLeafCompressedPubKey, deriveDescriptorLeafPubKey, deserializeExitPackage, encodeArkContract, evaluatePrf, exitObserverFor, gateExclusion, gatedContracts, getAllByIndexValues, getArkPsbtFields, hasBoardingTxExpired, identityDescriptor, invoiceTarget, isArkContract, isBtcAddress, isCltvSatisfied, isContractGenericallySpendable, isCosignFallback, isCsvSpendable, isDeterministicSigner, isHDDeterministicSignCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isRetryableProviderError, isValidArkAddress, logExcludedVtxos, makeHandle, matchServerCheckpoints, mnemonicFromPrf, normalizeToDescriptor, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, parseHDDescriptor, prfSupport, promisifyRequest, provisionClaimSecret, provisionRefundKey, readArkadeCash, registerWalletRestoreHook, resolveAssetAmount, resolveSendAmount, sdkVersion, selectCoinsWithAsset, selectionOf, sequenceToTimelock, serializeExitPackage, setArkPsbtField, setupServiceWorker, signAndSubmitOffchainTx, submitViaEmulator, timelockToSequence, toXOnly, tryResolveSendAmount, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, walletFeeSource };
6902
+ export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, ASSET_CARRIER_SATS, Activity, ActivityRegistry, AddressAllocationCapable, AmbiguousRouteError, type AnchorBumper, ArkNote, type ArkPsbtFieldCoder, ArkPsbtFieldKey, ArkPsbtFieldKeyType, ArkTransaction, type ArkTxInput, Arkade, type ArkadeBatchInput, ArkadeBroadcaster, ArkadeCashClaimResult, ArkadeCashRecord, type ArkadeCashRequest, type ArkadeCashResponse, type ArkadeCashStatus, type ArkadeCashStatusReport, ArkadeCashTx, ArkadeContractParams, type ArkadeExtendedCoin, type ArkadeExtendedVirtualCoin, ArkadeInfo, ArkadeReader, ArkadeService, Asset, AssetDetails, AssetManager, AtomicWalletState, BIP21, BIP21Error, type BIP21Params, type BIP21ParseResult, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, BatchExpiryPolicy, BatchRegistration, BatchRegistrationPageFilter, BatchRegistrationRepository, type BoardingExpiry, BurnParams, CSVMultisigTapscript, CachingArkProvider, CachingOperatorProvider, ChainTx, Coin, ConditionWitness, ConnectionDisposedError, Contract, ContractEvent, ContractFilter, ContractRepository, ContractSyncState, ContractVtxoEvent, ContractWatcherConfig, ContractWithVtxos, CosignerPublicKey, CreateContractParams, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_PASSKEY_LABEL, DatabaseUpgradeBlockedError, DelegateInfo, DelegateNotConfiguredError, DescriptorIdentity, type DescriptorIdentityOptions, type DescriptorOptions, DescriptorProvider, type DescriptorSigner, DescriptorSigningProviderMissingError, DescriptorSigningRequest, type DeterministicSigner, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, type BlockHeader as ElectrumBlockHeader, ElectrumOnchainProvider, type TransactionHistory as ElectrumTransactionHistory, type Unspent as ElectrumUnspent, type EmulatorEntry, EmulatorPacket, EmulatorProvider, EncodedVtxoScript, Estimator, type ExcludableVtxo, type ExecutorEvent, type ExecutorOptions, type ExitDelay, type ExitFeeWallet, type ExitMode, type ExitOptions, type ExitPackage, type ExitQuote, type ExitStep, type ExitTotals, type ExitVtxoInfo, ExplorerTransaction, ExtendedCoin, ExtendedContractVtxo, ExtendedVirtualCoin, Extension, ExtensionNotFoundError, type ExtensionPacket, FeeAmount, FeeInfo, FeeOutput, FetchError, GetNewAddressesOptions, GetOperatorInfoOptions, GetSpendableVtxosFilter, GetVtxosFilter, GetVtxosOptions, HDAllocationCapable, HDDescriptorProvider, type HDDeterministicSignCapable, HDWalletCapable, IAssetManager, IContractManager, IDelegateManager, IReadonlyAssetManager, IReadonlyWallet, IVtxoManager, IWallet, Identity, InMemoryBatchRegistrationRepository, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBBatchRegistrationRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexedDBVtxoReservationRepository, IndexerProvider, InputExpiryFloor, IntentFeeConfig, IssuanceParams, IssuanceResult, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, type ManagedConnection, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, type MessageHandler, type MessageTimeouts, MigrationGlobalSkipReason, MigrationLegSkipReason, MissingSigningDescriptorError, MnemonicIdentity, type MnemonicOptions, Network, NetworkName, type NetworkOptions, NewAddress, NormalizedExtendedVirtualCoin, NormalizedVtxoPage, OffchainInput, type OffchainTx, type OnExitObserved, OnchainCosignPreflightError, OnchainInput, OnchainProvider, OnchainWallet, OperatorInfo, OperatorProvider, Outpoint, OversizedChangeError, P2A, PageRequest, PageResult, PaginationOptions, type ParsedArkContract, PasskeyCancelled, type PasskeyMnemonic, type PasskeySource, PasskeyUnconfirmed, PathContext, PathSelection, type PaymentHandle, type PaymentOption, type PaymentRail, type PaymentRequest, PaymentRouter, type PaymentStatus, PrevArkTxField, PrevoutTxField, PrfUnavailable, type PrfUnavailableReason, Proof, ProviderConnectionState, type ProvisionedClaimSecret, type ProvisionedKey, READ_TIMEOUT_MS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlyIdentity, ReadonlyWallet, ReadonlyWalletError, Recipient, ReissuanceParams, RelativeTimelock, RenewVtxosOptions, type RequestEnvelope, type ResponseEnvelope, type RouteQuote, type RouteResult, type RouterContext, type RouterPreferences, ScriptVtxoCursor, ScriptVtxoPageOptions, SeedIdentity, type SeedIdentityOptions, SendBitcoinParams, SendDeadlineExceededError, SendOnchainParams, SendParams, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, type ServiceWorkerWalletMode, SettleParams, SettlementConfig, SettlementEvent, SignedProof, SignerSession, SignerStatus, StaticDescriptorProvider, Status, StorageConfig, StoredVtxo, StoredVtxoReservation, TapLeafScript, Transaction, TransactionHistoryPageCursor, TransactionHistoryPageFilter, TreeNonces, TreePartialSigs, TxNotificationEvent, TxTree, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, UnsupportedProgramVersionError, type VSize, type VerifyServerSignatures, VirtualCoin, VirtualTx, VirtualTxRepository, VtxoBranch, type VtxoExclusion, VtxoReservation, VtxoReservationRepository, VtxoScript, VtxoTaprootTree, VtxoTreeExpiry, Wallet, WalletBalance, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WalletRepository, type WalletRestoreHook, type WalletUpdate, WatchedScript, type WebAuthnClient, WsElectrumChainSource, adoptContractDescriptor, arkAssetRail, arkRail, arkTarget, index as arkade, assembleBtcdTaprootTree, assertFinalCommitmentMatchesValidated, assertNoAssets, assertNoSelection, assertNonNegativeMs, assertSendDeadline, assertSendableAmount, assertSubmittedArkTxid, assertTimerMs, assertValidServerUnrollScript, index$1 as asset, assetsOf, awaitTransaction, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, buildVersion, captureSendDeadline, claimWithPreimageIdentity, classifyBoardingExpiry, closeDatabase, combineTapscriptSigs, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createAssetPacket, createDefaultPaymentRouter, createManagedConnection, createPrfPasskey, decodeArkContract, decodeBoardingExit, deleteByIndex, deriveDescriptorLeafCompressedPubKey, deriveDescriptorLeafPubKey, deserializeExitPackage, encodeArkContract, evaluatePrf, exitObserverFor, gateExclusion, gatedContracts, getAllByIndexValues, getArkPsbtFields, hasBoardingTxExpired, identityDescriptor, invoiceTarget, isArkContract, isBtcAddress, isCltvSatisfied, isContractGenericallySpendable, isCosignFallback, isCsvSpendable, isDeterministicSigner, isHDDeterministicSignCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isRetryableProviderError, isValidArkAddress, logExcludedVtxos, makeHandle, matchServerCheckpoints, mnemonicFromPrf, normalizeToDescriptor, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, parseHDDescriptor, prfSupport, promisifyRequest, provisionClaimSecret, provisionRefundKey, readArkadeCash, registerWalletRestoreHook, resolveAssetAmount, resolveSendAmount, sdkVersion, selectCoinsWithAsset, selectionOf, sequenceToTimelock, serializeExitPackage, setArkPsbtField, setupServiceWorker, signAndSubmitOffchainTx, submitViaEmulator, timelockToSequence, toXOnly, tryResolveSendAmount, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, walletFeeSource };