@arkade-os/sdk 0.4.28 → 0.4.30

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 (82) hide show
  1. package/README.md +14 -16
  2. package/dist/adapters/expo.cjs +5 -5
  3. package/dist/adapters/expo.d.cts +4 -4
  4. package/dist/adapters/expo.d.ts +4 -4
  5. package/dist/adapters/expo.js +3 -3
  6. package/dist/adapters/indexedDB.cjs +5 -5
  7. package/dist/adapters/indexedDB.js +4 -4
  8. package/dist/{ark-TZ1gXAXU.d.cts → ark-C0TMXvwO.d.cts} +92 -63
  9. package/dist/{ark-TZ1gXAXU.d.ts → ark-C0TMXvwO.d.ts} +92 -63
  10. package/dist/{asyncStorageTaskQueue-EFqSmYTg.d.cts → asyncStorageTaskQueue-DHOoNvRy.d.cts} +2 -2
  11. package/dist/{asyncStorageTaskQueue-Cb1F_Z9s.d.ts → asyncStorageTaskQueue-Iip3xMF_.d.ts} +2 -2
  12. package/dist/{chunk-ADV27S4N.cjs → chunk-6FLL2Q36.cjs} +8 -8
  13. package/dist/chunk-6FLL2Q36.cjs.map +1 -0
  14. package/dist/{chunk-ZBUDLTBO.js → chunk-6NWNOLL3.js} +5 -5
  15. package/dist/chunk-6NWNOLL3.js.map +1 -0
  16. package/dist/{chunk-BQLHADL7.js → chunk-6NY27WL6.js} +341 -183
  17. package/dist/chunk-6NY27WL6.js.map +1 -0
  18. package/dist/{chunk-CFZMTDWI.js → chunk-ABWRLTX5.js} +6 -5
  19. package/dist/chunk-ABWRLTX5.js.map +1 -0
  20. package/dist/{chunk-FG5ACJJW.cjs → chunk-GIGILVVP.cjs} +11 -10
  21. package/dist/chunk-GIGILVVP.cjs.map +1 -0
  22. package/dist/{chunk-A3EMF7RN.js → chunk-GRJKJNBO.js} +3 -3
  23. package/dist/{chunk-A3EMF7RN.js.map → chunk-GRJKJNBO.js.map} +1 -1
  24. package/dist/{chunk-I3DGUUCT.cjs → chunk-IEO3XDKI.cjs} +28 -28
  25. package/dist/{chunk-I3DGUUCT.cjs.map → chunk-IEO3XDKI.cjs.map} +1 -1
  26. package/dist/{chunk-IPX2R7FR.cjs → chunk-PCEE6DRL.cjs} +7 -7
  27. package/dist/{chunk-IPX2R7FR.cjs.map → chunk-PCEE6DRL.cjs.map} +1 -1
  28. package/dist/{chunk-HW3JJ323.js → chunk-TU3LVAPX.js} +32 -31
  29. package/dist/chunk-TU3LVAPX.js.map +1 -0
  30. package/dist/{chunk-5PG7DV7A.cjs → chunk-WMIPYZSB.cjs} +34 -36
  31. package/dist/chunk-WMIPYZSB.cjs.map +1 -0
  32. package/dist/{chunk-ZLO6NETT.cjs → chunk-XWJFOP5G.cjs} +505 -337
  33. package/dist/chunk-XWJFOP5G.cjs.map +1 -0
  34. package/dist/{chunk-T64LAI7L.js → chunk-YA4G7RFB.js} +3 -3
  35. package/dist/{chunk-T64LAI7L.js.map → chunk-YA4G7RFB.js.map} +1 -1
  36. package/dist/contracts/handlers/index.cjs +6 -6
  37. package/dist/contracts/handlers/index.d.cts +3 -3
  38. package/dist/contracts/handlers/index.d.ts +3 -3
  39. package/dist/contracts/handlers/index.js +2 -2
  40. package/dist/{delegate-aaVGfWsV.d.ts → delegate-CEk9RHVj.d.cts} +2 -2
  41. package/dist/{delegate-BFZs69hp.d.cts → delegate-Ds4Hi7Xy.d.ts} +2 -2
  42. package/dist/{index-NDla_UoJ.d.ts → index-DA9r_7Vg.d.ts} +2 -2
  43. package/dist/{index-B22cA64m.d.cts → index-WIAY0DDn.d.cts} +2 -2
  44. package/dist/index.cjs +161 -137
  45. package/dist/index.d.cts +144 -17
  46. package/dist/index.d.ts +144 -17
  47. package/dist/index.js +4 -4
  48. package/dist/repositories/realm/index.cjs +13 -13
  49. package/dist/repositories/realm/index.d.cts +2 -2
  50. package/dist/repositories/realm/index.d.ts +2 -2
  51. package/dist/repositories/realm/index.js +4 -4
  52. package/dist/repositories/sqlite/index.cjs +13 -13
  53. package/dist/repositories/sqlite/index.d.cts +1 -1
  54. package/dist/repositories/sqlite/index.d.ts +1 -1
  55. package/dist/repositories/sqlite/index.js +4 -4
  56. package/dist/{taskRunner-C6Ff4OaU.d.cts → taskRunner-CdEVYgoP.d.cts} +2 -2
  57. package/dist/{taskRunner-yvPN8Z0K.d.ts → taskRunner-JNjIWWJi.d.ts} +2 -2
  58. package/dist/wallet/expo/background.cjs +14 -14
  59. package/dist/wallet/expo/background.d.cts +3 -3
  60. package/dist/wallet/expo/background.d.ts +3 -3
  61. package/dist/wallet/expo/background.js +6 -6
  62. package/dist/wallet/expo/index.cjs +19 -15
  63. package/dist/wallet/expo/index.cjs.map +1 -1
  64. package/dist/wallet/expo/index.d.cts +9 -7
  65. package/dist/wallet/expo/index.d.ts +9 -7
  66. package/dist/wallet/expo/index.js +11 -7
  67. package/dist/wallet/expo/index.js.map +1 -1
  68. package/dist/{wallet-D9NBRqvC.d.ts → wallet-BGL6SzKQ.d.ts} +19 -15
  69. package/dist/{wallet-AF-p-OWj.d.cts → wallet-CMgzKP0o.d.cts} +19 -15
  70. package/dist/worker/expo/index.cjs +9 -9
  71. package/dist/worker/expo/index.d.cts +4 -4
  72. package/dist/worker/expo/index.d.ts +4 -4
  73. package/dist/worker/expo/index.js +5 -5
  74. package/package.json +1 -1
  75. package/dist/chunk-5PG7DV7A.cjs.map +0 -1
  76. package/dist/chunk-ADV27S4N.cjs.map +0 -1
  77. package/dist/chunk-BQLHADL7.js.map +0 -1
  78. package/dist/chunk-CFZMTDWI.js.map +0 -1
  79. package/dist/chunk-FG5ACJJW.cjs.map +0 -1
  80. package/dist/chunk-HW3JJ323.js.map +0 -1
  81. package/dist/chunk-ZBUDLTBO.js.map +0 -1
  82. package/dist/chunk-ZLO6NETT.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/musig2/nonces.ts","../src/musig2/keys.ts","../src/musig2/sign.ts","../src/tree/signingSession.ts","../src/identity/singleKey.ts","../src/identity/seedIdentity.ts","../src/identity/serialize.ts","../src/identity/hdCapableIdentity.ts","../src/identity/index.ts","../src/worker/browser/service-worker-manager.ts","../src/providers/delegator.ts","../src/networks.ts","../src/providers/onchain.ts","../src/utils/anchor.ts","../src/forfeit.ts","../src/tree/validation.ts","../src/extension/packet.ts","../src/extension/index.ts","../src/wallet/validation.ts","../src/wallet/asset.ts","../src/utils/arkTransaction.ts","../src/utils/txSizeEstimator.ts","../src/arkfee/celenv.ts","../src/arkfee/types.ts","../src/arkfee/estimator.ts","../src/wallet/vtxo-manager.ts","../src/arknote/index.ts","../src/wallet/utils.ts","../src/tree/txTree.ts","../src/wallet/batch.ts","../src/utils/transactionHistory.ts","../src/wallet/asset-manager.ts","../src/wallet/delegator.ts","../src/contracts/vtxoOwnership.ts","../src/repositories/inMemory/walletRepository.ts","../src/repositories/inMemory/contractRepository.ts","../src/repositories/scriptFromAddress.ts","../src/repositories/indexedDB/schema.ts","../src/repositories/serialization.ts","../src/repositories/indexedDB/manager.ts","../src/worker/browser/utils.ts","../src/repositories/indexedDB/contractRepository.ts","../src/repositories/indexedDB/walletRepository.ts","../src/repositories/migrations/walletRepositoryImpl.ts","../src/repositories/migrations/fromStorageAdapter.ts","../src/repositories/migrations/contractRepositoryImpl.ts","../src/contracts/types.ts","../src/contracts/contractWatcher.ts","../src/utils/syncCursors.ts","../src/contracts/contractManager.ts","../src/wallet/hdDescriptorProvider.ts","../src/wallet/walletReceiveRotator.ts","../src/wallet/signingErrors.ts","../src/wallet/inputSignerRouter.ts","../src/wallet/wallet.ts","../src/worker/errors.ts","../src/worker/messageBus.ts","../src/wallet/ramps.ts","../src/wallet/serviceWorker/wallet-message-handler.ts","../src/wallet/serviceWorker/wallet.ts","../src/wallet/onchain.ts","../src/providers/electrum.ts","../src/bip322/index.ts","../src/wallet/unroll.ts","../src/contracts/arkcontract.ts"],"names":["musig","musig3","schnorr","SigHash","Script","randomPrivateKeyBytes","hex","ALL_SIGHASH","pubSchnorr","pubECDSA","signAsync","networks","txKey","Transaction","equalBytes","Address","OutScript","base64","Batch","Step","vtxos","fee","initDatabase","normalizeOptions","serializeVtxo","serializeTapLeaf","serializeUtxo","deserializeVtxo","deserializeTapLeaf","deserializeUtxo","TaprootControlBlock","window","expand","info","Wallet","sha256","tapLeafHash","identity","updater","label","timeoutMs","handlerPromise","context","i","BIP322","sign","p2tr","secp256k1","buf","Unroll","StepType","Session"],"mappings":";;;;;;;;;;;;;;;;;;AAeO,SAAS,eAAe,SAAA,EAA+B;AAC1D,EAAA,MAAM,MAAA,GAAeA,gBAAS,SAAS,CAAA;AACvC,EAAA,OAAO,EAAE,QAAA,EAAU,MAAA,CAAO,MAAA,EAAQ,QAAA,EAAU,OAAO,MAAA,EAAO;AAC9D;AAEO,SAAS,gBAAgB,SAAA,EAAqC;AACjE,EAAA,OAAaA,sBAAe,SAAS,CAAA;AACzC;ACTO,SAAS,aAAA,CACZ,UAAA,EACA,IAAA,EACA,OAAA,GAAkC,EAAC,EACvB;AACZ,EAAU;AACN,IAAA,UAAA,GAAmB,gBAAS,UAAU,CAAA;AAAA,EAC1C;AAEA,EAAA,MAAM,EAAE,YAAA,EAAc,aAAA,EAAc,GAAU,oBAAa,UAAU,CAAA;AAErE,EAAA,IAAI,CAAC,QAAQ,YAAA,EAAc;AACvB,IAAA,OAAO;AAAA,MACH,aAAA,EAAe,aAAA,CAAc,OAAA,CAAQ,IAAI,CAAA;AAAA,MACzC,QAAA,EAAU,aAAA,CAAc,OAAA,CAAQ,IAAI;AAAA,KACxC;AAAA,EACJ;AAEA,EAAA,MAAM,UAAA,GAAa,QAAQ,KAAA,CAAM,UAAA;AAAA,IAC7B,UAAA;AAAA,IACA,aAAA,CAAc,OAAA,CAAQ,IAAI,CAAA,CAAE,SAAS,CAAC,CAAA;AAAA,IACtC,OAAA,CAAQ,YAAA,IAAgB,IAAI,UAAA,CAAW,CAAC;AAAA,GAC5C;AAEA,EAAA,MAAM,EAAE,YAAA,EAAc,QAAA,EAAS,GAAU,MAAA,CAAA,YAAA,CAAa,U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AA,CAAO,IAAA;AAAA,IACb,MAAA;AAAA,IACA,KAAA,EAAO,QAAQ,KAAA,IAAS,QAAA;AAAA,IACxB,SAAA,EAAW,KAAK,GAAA,EAAI;AAAA,IACpB,UAAU,OAAA,CAAQ;AAAA,GACtB;AACJ;AAWO,SAAS,mCACZ,OAAA,EACA,YAAA,EACA,gBAAwB,kBAAA,EACxB,OAAA,GAII,EAAC,EACG;AACR,EAAA,MAAM,MAAA,GAAS,kBAAkB,OAAO,CAAA;AACxC,EAAA,MAAM,OAAA,GAAU,gBAAA,CAAiB,UAAA,CAAW,MAAA,CAAO,IAAI,CAAA;AAEvD,EAAA,MAAM,SAAS,MAAA,CAAO,IAAA;AACtB,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,YAAA,CAAa,MAAM,CAAA;AAE9C,EAAA,OAAO;AAAA,IACH,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,MAAA;AAAA,IACA,MAAA,EAAQ5B,GAAAA,CAAI,MAAA,CAAO,UAAA,CAAW,QAAQ,CAAA;AAAA,IACtC,SAAS,UAAA,CAAW,OAAA,CAAQ,aAAA,EAAe,YAAY,EAAE,MAAA,EAAO;AAAA,IAChE,KAAA,EAAO,QAAQ,KAAA,IAAS,QAAA;AAAA,IACxB,SAAA,EAAW,KAAK,GAAA,EAAI;AAAA,IACpB,UAAU,OAAA,CAAQ;AAAA,GACtB;AACJ;AAKO,SAAS,cAAc,GAAA,EAAsB;AAChD,EAAA,OAAO,GAAA,CAAI,UAAA,CAAW,kBAAA,GAAqB,GAAG,CAAA;AAClD","file":"chunk-BQLHADL7.js","sourcesContent":["import * as musig from \"@scure/btc-signer/musig2.js\";\n\n/**\n * MuSig2 nonce pair containing public and secret values.\n * Public nonces are two compressed points (33 bytes each).\n * Secret nonces are the corresponding private scalars plus pubkey.\n */\nexport type Nonces = {\n pubNonce: Uint8Array;\n secNonce: Uint8Array;\n};\n\n/**\n * Generates a pair of public and secret nonces for MuSig2 signing\n */\nexport function generateNonces(publicKey: Uint8Array): Nonces {\n const nonces = musig.nonceGen(publicKey);\n return { secNonce: nonces.secret, pubNonce: nonces.public };\n}\n\nexport function aggregateNonces(pubNonces: Uint8Array[]): Uint8Array {\n return musig.nonceAggregate(pubNonces);\n}\n","import * as musig from \"@scure/btc-signer/musig2.js\";\nimport { schnorr } from \"@noble/curves/secp256k1.js\";\n\ninterface KeyAggOptions {\n taprootTweak?: Uint8Array;\n}\n\nexport interface AggregateKey {\n preTweakedKey: Uint8Array; // 33-byte compressed point\n finalKey: Uint8Array; // 33-byte compressed point\n}\n\n// Aggregates multiple public keys according to the MuSig2 algorithm\nexport function aggregateKeys(\n publicKeys: Uint8Array[],\n sort: boolean,\n options: Partial<KeyAggOptions> = {},\n): AggregateKey {\n if (sort) {\n publicKeys = musig.sortKeys(publicKeys);\n }\n\n const { aggPublicKey: preTweakedKey } = musig.keyAggregate(publicKeys);\n\n if (!options.taprootTweak) {\n return {\n preTweakedKey: preTweakedKey.toBytes(true),\n finalKey: preTweakedKey.toBytes(true),\n };\n }\n\n const tweakBytes = schnorr.utils.taggedHash(\n \"TapTweak\",\n preTweakedKey.toBytes(true).subarray(1),\n options.taprootTweak ?? new Uint8Array(0),\n );\n\n const { aggPublicKey: finalKey } = musig.keyAggregate(publicKeys, [tweakBytes], [true]);\n\n return {\n preTweakedKey: preTweakedKey.toBytes(true),\n finalKey: finalKey.toBytes(true),\n };\n}\n","import * as musig from \"@scure/btc-signer/musig2.js\";\nimport { bytesToNumberBE } from \"@noble/curves/utils.js\";\nimport { Point } from \"@noble/secp256k1\";\nimport { aggregateKeys } from \"./keys\";\nimport { schnorr } from \"@noble/curves/secp256k1.js\";\n\n// Add this error type for decode failures\nexport class PartialSignatureError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PartialSignatureError\";\n }\n}\n\ninterface SignOptions {\n sortKeys?: boolean;\n taprootTweak?: Uint8Array;\n}\n\n// Implement a concrete class for PartialSignature\nexport class PartialSig {\n constructor(\n public s: Uint8Array,\n public R: Uint8Array,\n ) {\n if (s.length !== 32) {\n throw new PartialSignatureError(\"Invalid s length\");\n }\n if (R.length !== 33) {\n throw new PartialSignatureError(\"Invalid R length\");\n }\n }\n\n /**\n * Encodes the partial signature into bytes\n * Returns a 32-byte array containing just the s value\n */\n encode(): Uint8Array {\n // Return copy of s bytes\n return new Uint8Array(this.s);\n }\n\n /**\n * Decodes a partial signature from bytes\n * @param bytes - 32-byte array containing s value\n */\n static decode(bytes: Uint8Array): PartialSig {\n if (bytes.length !== 32) {\n throw new PartialSignatureError(\"Invalid partial signature length\");\n }\n\n // Verify s is less than curve order\n const s = bytesToNumberBE(bytes);\n if (s >= Point.CURVE().n) {\n throw new PartialSignatureError(\"s value overflows curve order\");\n }\n\n // For decode we don't have R, so we'll need to compute it later\n const R = new Uint8Array(33); // Zero R for now\n\n return new PartialSig(bytes, R);\n }\n}\n\n/**\n * Generates a MuSig2 partial signature\n */\nexport function sign(\n secNonce: Uint8Array,\n privateKey: Uint8Array,\n combinedNonce: Uint8Array,\n publicKeys: Uint8Array[],\n message: Uint8Array,\n options?: SignOptions,\n): PartialSig {\n let tweakBytes: Uint8Array | undefined;\n\n if (options?.taprootTweak !== undefined) {\n const { preTweakedKey } = aggregateKeys(\n options?.sortKeys ? musig.sortKeys(publicKeys) : publicKeys,\n true,\n );\n\n tweakBytes = schnorr.utils.taggedHash(\n \"TapTweak\",\n preTweakedKey.subarray(1),\n options.taprootTweak,\n );\n }\n\n const session = new musig.Session(\n combinedNonce,\n options?.sortKeys ? musig.sortKeys(publicKeys) : publicKeys,\n message,\n tweakBytes ? [tweakBytes] : undefined,\n tweakBytes ? [true] : undefined,\n );\n const partialSig = session.sign(secNonce, privateKey);\n return PartialSig.decode(partialSig);\n}\n","import * as musig2 from \"../musig2\";\nimport { Script } from \"@scure/btc-signer/script.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { hex } from \"@scure/base\";\nimport { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { randomPrivateKeyBytes } from \"@scure/btc-signer/utils.js\";\nimport { CosignerPublicKey, getArkPsbtFields } from \"../utils/unknownFields\";\nimport { TxTree } from \"./txTree\";\n\nexport const ErrMissingVtxoGraph = new Error(\"missing vtxo graph\");\nexport const ErrMissingAggregateKey = new Error(\"missing aggregate key\");\n\nexport type Musig2PublicNonce = Pick<musig2.Nonces, \"pubNonce\">;\nexport type TreeNonces = Map<string, Musig2PublicNonce>;\nexport type TreePartialSigs = Map<string, musig2.PartialSig>;\n\n// Signer session defines the methods to participate in a cooperative signing process\n// with participants of a settlement. It holds the state of the musig2 nonces and allows to\n// create the partial signatures for each transaction in the virtual output tree\nexport interface SignerSession {\n getPublicKey(): Promise<Uint8Array>;\n init(tree: TxTree, scriptRoot: Uint8Array, rootInputAmount: bigint): Promise<void>;\n getNonces(): Promise<TreeNonces>;\n aggregatedNonces(txid: string, noncesByPubkey: TreeNonces): Promise<{ hasAllNonces: boolean }>;\n sign(): Promise<TreePartialSigs>;\n}\n\nexport class TreeSignerSession implements SignerSession {\n static NOT_INITIALIZED = new Error(\"session not initialized, call init method\");\n\n private myNonces: Map<string, musig2.Nonces> | null = null;\n private aggregateNonces: TreeNonces | null = null;\n private graph: TxTree | null = null;\n private scriptRoot: Uint8Array | null = null;\n private rootSharedOutputAmount: bigint | null = null;\n\n constructor(private secretKey: Uint8Array) {}\n\n static random(): TreeSignerSession {\n const secretKey = randomPrivateKeyBytes();\n return new TreeSignerSession(secretKey);\n }\n\n async init(tree: TxTree, scriptRoot: Uint8Array, rootInputAmount: bigint): Promise<void> {\n this.graph = tree;\n this.scriptRoot = scriptRoot;\n this.rootSharedOutputAmount = rootInputAmount;\n }\n\n async getPublicKey(): Promise<Uint8Array> {\n return secp256k1.getPublicKey(this.secretKey);\n }\n\n async getNonces(): Promise<TreeNonces> {\n if (!this.graph) throw ErrMissingVtxoGraph;\n if (!this.myNonces) {\n this.myNonces = this.generateNonces();\n }\n\n const publicNonces: TreeNonces = new Map();\n\n for (const [txid, nonces] of this.myNonces) {\n publicNonces.set(txid, { pubNonce: nonces.pubNonce });\n }\n\n return publicNonces;\n }\n\n async aggregatedNonces(\n txid: string,\n noncesByPubkey: TreeNonces,\n ): Promise<{ hasAllNonces: boolean }> {\n if (!this.graph) throw ErrMissingVtxoGraph;\n if (!this.aggregateNonces) {\n this.aggregateNonces = new Map();\n }\n if (!this.myNonces) {\n await this.getNonces(); // generate nonces if not generated yet\n }\n if (this.aggregateNonces.has(txid)) {\n return {\n hasAllNonces: this.aggregateNonces.size === this.myNonces?.size,\n };\n }\n\n const myNonce = this.myNonces!.get(txid);\n if (!myNonce) throw new Error(`missing nonce for txid ${txid}`);\n\n const myPublicKey = await this.getPublicKey();\n // set my nonce to not rely on server\n noncesByPubkey.set(hex.encode(myPublicKey.subarray(1)), myNonce);\n\n const tx = this.graph.find(txid);\n if (!tx) throw new Error(`missing tx for txid ${txid}`);\n\n const cosigners = getArkPsbtFields(tx.root, 0, CosignerPublicKey).map(\n (c) => hex.encode(c.key.subarray(1)), // xonly pubkey\n );\n\n const pubNonces: Uint8Array[] = [];\n for (const cosigner of cosigners) {\n const nonce = noncesByPubkey.get(cosigner);\n if (!nonce) {\n throw new Error(`missing nonce for cosigner ${cosigner}`);\n }\n pubNonces.push(nonce.pubNonce);\n }\n\n const aggregateNonce = musig2.aggregateNonces(pubNonces);\n this.aggregateNonces.set(txid, { pubNonce: aggregateNonce });\n\n return {\n hasAllNonces: this.aggregateNonces.size === this.myNonces?.size,\n };\n }\n\n async sign(): Promise<TreePartialSigs> {\n if (!this.graph) throw ErrMissingVtxoGraph;\n if (!this.aggregateNonces) throw new Error(\"nonces not set\");\n if (!this.myNonces) throw new Error(\"nonces not generated\");\n\n const sigs: TreePartialSigs = new Map();\n\n for (const g of this.graph.iterator()) {\n const sig = this.signPartial(g);\n sigs.set(g.txid, sig);\n }\n\n return sigs;\n }\n\n private generateNonces(): Map<string, musig2.Nonces> {\n if (!this.graph) throw ErrMissingVtxoGraph;\n\n const myNonces: Map<string, musig2.Nonces> = new Map();\n\n const publicKey = secp256k1.getPublicKey(this.secretKey);\n\n for (const g of this.graph.iterator()) {\n const nonces = musig2.generateNonces(publicKey);\n myNonces.set(g.txid, nonces);\n }\n\n return myNonces;\n }\n\n private signPartial(g: TxTree): musig2.PartialSig {\n if (!this.graph || !this.scriptRoot || !this.rootSharedOutputAmount) {\n throw TreeSignerSession.NOT_INITIALIZED;\n }\n\n if (!this.myNonces || !this.aggregateNonces) {\n throw new Error(\"session not properly initialized\");\n }\n\n const myNonce = this.myNonces.get(g.txid);\n if (!myNonce) throw new Error(\"missing private nonce\");\n\n const aggNonce = this.aggregateNonces.get(g.txid);\n if (!aggNonce) throw new Error(\"missing aggregate nonce\");\n const prevoutAmounts: bigint[] = [];\n const prevoutScripts: Uint8Array[] = [];\n\n const cosigners = getArkPsbtFields(g.root, 0, CosignerPublicKey).map((c) => c.key);\n\n const { finalKey } = musig2.aggregateKeys(cosigners, true, {\n taprootTweak: this.scriptRoot,\n });\n\n for (let inputIndex = 0; inputIndex < g.root.inputsLength; inputIndex++) {\n const prevout = getPrevOutput(\n finalKey,\n this.graph,\n this.rootSharedOutputAmount,\n g.root,\n );\n prevoutAmounts.push(prevout.amount);\n prevoutScripts.push(prevout.script);\n }\n\n const message = g.root.preimageWitnessV1(\n 0, // always first input\n prevoutScripts,\n SigHash.DEFAULT,\n prevoutAmounts,\n );\n\n return musig2.sign(\n myNonce.secNonce,\n this.secretKey,\n aggNonce.pubNonce,\n cosigners,\n message,\n {\n taprootTweak: this.scriptRoot,\n sortKeys: true,\n },\n );\n }\n}\n\n// Helper function to validate tree signatures\nexport async function validateTreeSigs(\n finalAggregatedKey: Uint8Array,\n sharedOutputAmount: bigint,\n vtxoTree: TxTree,\n): Promise<void> {\n // Iterate through each level of the tree\n for (const g of vtxoTree.iterator()) {\n // Parse the transaction\n const input = g.root.getInput(0);\n\n // Check if input has signature\n if (!input.tapKeySig) {\n throw new Error(\"unsigned tree input\");\n }\n\n // Get the previous output information\n const prevout = getPrevOutput(finalAggregatedKey, vtxoTree, sharedOutputAmount, g.root);\n\n // Calculate the message that was signed\n const message = g.root.preimageWitnessV1(\n 0, // always first input\n [prevout.script],\n SigHash.DEFAULT,\n [prevout.amount],\n );\n\n // Verify the signature\n const isValid = schnorr.verify(input.tapKeySig, message, finalAggregatedKey);\n\n if (!isValid) {\n throw new Error(\"invalid signature\");\n }\n }\n}\n\ninterface PrevOutput {\n script: Uint8Array;\n amount: bigint;\n}\n\nfunction getPrevOutput(\n finalKey: Uint8Array,\n graph: TxTree,\n sharedOutputAmount: bigint,\n tx: Transaction,\n): PrevOutput {\n // generate P2TR script from musig2 final key\n const pkScript = Script.encode([\"OP_1\", finalKey.slice(1)]);\n\n // if the input is the root input, return the shared output amount\n if (tx.id === graph.txid) {\n return {\n amount: sharedOutputAmount,\n script: pkScript,\n };\n }\n\n // find the parent transaction\n const parentInput = tx.getInput(0);\n if (!parentInput.txid) throw new Error(\"missing parent input txid\");\n const parentTxid = hex.encode(parentInput.txid);\n const parent = graph.find(parentTxid);\n if (!parent) throw new Error(\"parent tx not found\");\n\n if (parentInput.index === undefined) throw new Error(\"missing input index\");\n const parentOutput = parent.root.getOutput(parentInput.index);\n if (!parentOutput) throw new Error(\"parent output not found\");\n if (!parentOutput.amount) throw new Error(\"parent output amount not found\");\n\n return {\n amount: parentOutput.amount,\n script: pkScript,\n };\n}\n","import { pubECDSA, pubSchnorr, randomPrivateKeyBytes } from \"@scure/btc-signer/utils.js\";\nimport { SigHash } from \"@scure/btc-signer\";\nimport { hex } from \"@scure/base\";\nimport { Identity, ReadonlyIdentity } from \".\";\nimport { Transaction } from \"../utils/transaction\";\nimport { SignerSession, TreeSignerSession } from \"../tree/signingSession\";\nimport { schnorr, signAsync } from \"@noble/secp256k1\";\n\nconst ALL_SIGHASH = Object.values(SigHash).filter((x) => typeof x === \"number\");\n\n/**\n * In-memory single key implementation for Bitcoin transaction signing.\n *\n * @example\n * ```typescript\n * // Create from hex string\n * const key = SingleKey.fromHex('your_private_key_hex');\n *\n * // Create from raw bytes\n * const key = SingleKey.fromPrivateKey(privateKeyBytes);\n *\n * // Create random key\n * const randomKey = SingleKey.fromRandomBytes();\n *\n * // Sign a transaction\n * const signedTx = await key.sign(transaction);\n * ```\n */\nexport class SingleKey implements Identity {\n private key: Uint8Array;\n\n private constructor(key: Uint8Array | undefined) {\n this.key = key || randomPrivateKeyBytes();\n }\n\n /** Create a signing identity from raw private key bytes. */\n static fromPrivateKey(privateKey: Uint8Array): SingleKey {\n return new SingleKey(privateKey);\n }\n\n /** Create a signing identity from a hex-encoded private key. */\n static fromHex(privateKeyHex: string): SingleKey {\n return new SingleKey(hex.decode(privateKeyHex));\n }\n\n /** Create a signing identity with a freshly generated random private key. */\n static fromRandomBytes(): SingleKey {\n return new SingleKey(randomPrivateKeyBytes());\n }\n\n /**\n * Export the private key as a hex string.\n *\n * @returns The private key as a hex string\n */\n toHex(): string {\n return hex.encode(this.key);\n }\n\n async sign(tx: Transaction, inputIndexes?: number[]): Promise<Transaction> {\n const txCpy = tx.clone();\n\n if (!inputIndexes) {\n try {\n if (!txCpy.sign(this.key, ALL_SIGHASH)) {\n throw new Error(\"Failed to sign transaction\");\n }\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No inputs signed\")) {\n // ignore\n } else {\n throw e;\n }\n }\n return txCpy;\n }\n\n for (const inputIndex of inputIndexes) {\n if (!txCpy.signIdx(this.key, inputIndex, ALL_SIGHASH)) {\n throw new Error(`Failed to sign input #${inputIndex}`);\n }\n }\n\n return txCpy;\n }\n\n compressedPublicKey(): Promise<Uint8Array> {\n return Promise.resolve(pubECDSA(this.key, true));\n }\n\n xOnlyPublicKey(): Promise<Uint8Array> {\n return Promise.resolve(pubSchnorr(this.key));\n }\n\n signerSession(): SignerSession {\n return TreeSignerSession.random();\n }\n\n async signMessage(\n message: Uint8Array,\n signatureType: \"schnorr\" | \"ecdsa\" = \"schnorr\",\n ): Promise<Uint8Array> {\n if (signatureType === \"ecdsa\") return signAsync(message, this.key, { prehash: false });\n return schnorr.signAsync(message, this.key);\n }\n\n async toReadonly(): Promise<ReadonlySingleKey> {\n return new ReadonlySingleKey(await this.compressedPublicKey());\n }\n}\n\nexport class ReadonlySingleKey implements ReadonlyIdentity {\n /** Create a readonly identity from a compressed public key. */\n constructor(private readonly publicKey: Uint8Array) {\n if (publicKey.length !== 33) {\n throw new Error(\"Invalid public key length\");\n }\n }\n\n /**\n * Create a ReadonlySingleKey from a compressed public key.\n *\n * @param publicKey - 33-byte compressed public key (02/03 prefix + 32-byte x coordinate)\n * @returns A new ReadonlySingleKey instance\n * @example\n * ```typescript\n * const pubkey = new Uint8Array(33); // your compressed public key\n * const readonlyKey = ReadonlySingleKey.fromPublicKey(pubkey);\n * ```\n */\n static fromPublicKey(publicKey: Uint8Array): ReadonlySingleKey {\n return new ReadonlySingleKey(publicKey);\n }\n\n xOnlyPublicKey(): Promise<Uint8Array> {\n return Promise.resolve(this.publicKey.slice(1));\n }\n compressedPublicKey(): Promise<Uint8Array> {\n return Promise.resolve(this.publicKey);\n }\n}\n","import { validateMnemonic, mnemonicToSeedSync } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\nimport { pubECDSA, pubSchnorr } from \"@scure/btc-signer/utils.js\";\nimport { SigHash } from \"@scure/btc-signer\";\nimport { hex } from \"@scure/base\";\nimport { Transaction } from \"../utils/transaction\";\nimport { SignerSession, TreeSignerSession } from \"../tree/signingSession\";\nimport { schnorr, signAsync } from \"@noble/secp256k1\";\nimport {\n HDKey,\n expand,\n networks,\n scriptExpressions,\n type KeyInfo,\n} from \"@bitcoinerlab/descriptors-scure\";\nimport type { SerializedSigningIdentity, SerializedReadonlyIdentity } from \"./serialize\";\nimport { DescriptorSigningRequest } from \"./descriptorProvider\";\nimport { HDCapableIdentity, ReadonlyHDCapableIdentity } from \"./hdCapableIdentity\";\nimport { descriptorIsOurs, isMainnetDescriptor } from \"./descriptor\";\n\nconst ALL_SIGHASH = Object.values(SigHash).filter((x) => typeof x === \"number\");\n\n/**\n * Secret-bearing state for seed-backed identities, held off the public\n * instance surface. Accessed only by the SDK-internal serializer helpers\n * below; application code cannot read these via ordinary field access.\n *\n * Using a module-private WeakMap (rather than `private` / `protected`)\n * matters because TypeScript visibility is a compile-time boundary only:\n * JavaScript consumers could still read public fields. A WeakMap removes\n * that enumeration path entirely.\n */\nconst seedBytes = new WeakMap<SeedIdentity, Uint8Array>();\nconst mnemonicMeta = new WeakMap<MnemonicIdentity, { mnemonic: string; passphrase?: string }>();\n\n/** Used for default BIP86 derivation with network selection. */\nexport interface NetworkOptions {\n /**\n * Mainnet (coin type 0) or testnet (coin type 1).\n *\n * @defaultValue `true`\n */\n isMainnet?: boolean;\n}\n\n/** Used for a caller-supplied account-descriptor template. */\nexport interface DescriptorOptions {\n /**\n * Account-descriptor *template* — must end with the BIP-32 wildcard\n * suffix `/*)`. Stored as-is on {@link SeedIdentity.descriptor} and\n * read by HD providers to rotate through derivation indices.\n */\n descriptor: string;\n}\n\n/** Either default BIP86 derivation (with optional network selection) or a caller-supplied template. */\nexport type SeedIdentityOptions = NetworkOptions | DescriptorOptions;\n\n/** Used for deriving an identity from a BIP39 mnemonic. */\nexport type MnemonicOptions = SeedIdentityOptions & {\n /** Optional BIP39 passphrase for additional seed entropy. */\n passphrase?: string;\n};\n\n/**\n * Seed-based identity derived from a raw seed and an account descriptor\n * *template*.\n *\n * This is the recommended identity type for most applications. It uses\n * standard BIP86 (Taproot) derivation by default; callers that need a\n * different path supply the wildcard template directly.\n *\n * Prefer this (or @see MnemonicIdentity) over `SingleKey` for new\n * integrations — `SingleKey` exists for backward compatibility with\n * raw nsec-style keys.\n *\n * The identity holds the wildcard *template* (e.g.\n * `tr([fp/86'/0'/0']xpub/0/*)`) on its public {@link descriptor}\n * field. HD rotation reads it directly; consumers that need a\n * concrete descriptor at a specific index materialize it themselves\n * (see `HDDescriptorProvider` in the wallet layer).\n *\n * Exposes seed-level primitives (signing, derivation, the template)\n * but is deliberately NOT a `DescriptorProvider`. Wrap it explicitly\n * to get one:\n * - `HDDescriptorProvider` for rotating receive addresses.\n * - {@link StaticDescriptorProvider} for legacy, single-key behaviour.\n *\n * The split prevents a SeedIdentity from being silently used as a\n * concrete descriptor source, which would defeat HD rotation without\n * any compile-time signal that something was wrong.\n *\n * @example\n * ```typescript\n * const seed = mnemonicToSeedSync(mnemonic);\n *\n * // Testnet (BIP86 wildcard descriptor m/86'/1'/0'/0/*)\n * const identity = SeedIdentity.fromSeed(seed, { isMainnet: false });\n *\n * // Mainnet (BIP86 wildcard descriptor m/86'/0'/0'/0/*)\n * const identity = SeedIdentity.fromSeed(seed, { isMainnet: true });\n *\n * // Caller-supplied wildcard descriptor (must end in `/*)`).\n * const identity = SeedIdentity.fromSeed(seed, { descriptor });\n * ```\n */\nexport class SeedIdentity implements HDCapableIdentity {\n private readonly derivedKey: Uint8Array;\n /**\n * Wildcard account-descriptor template (e.g.\n * `tr([fp/86'/0'/0']xpub/0/*)`). The canonical thing to pass\n * through the system; consumers materialize a concrete descriptor\n * at a specific index themselves (see `HDDescriptorProvider` in\n * the wallet layer for the rotating-counter use case).\n */\n readonly descriptor: string;\n\n /**\n * Constructs a SeedIdentity from a 64-byte seed and either a\n * caller-supplied wildcard descriptor (`{ descriptor }`) or the\n * default BIP86 path at the requested network (`{ isMainnet }`).\n * Prefer the {@link fromSeed} factory for symmetry with\n * {@link MnemonicIdentity.fromMnemonic}.\n *\n * Throws on a non-wildcard descriptor, an xpub mismatch with the\n * seed, or a missing derivation path.\n */\n constructor(seed: Uint8Array, opts: SeedIdentityOptions = {}) {\n if (seed.length !== 64) {\n throw new Error(\"Seed must be 64 bytes\");\n }\n\n // Resolve the descriptor: caller-supplied wins; otherwise build\n // the BIP86 default at the requested network via the library.\n let descriptor: string;\n let network: typeof networks.bitcoin;\n if (\"descriptor\" in opts && typeof opts.descriptor === \"string\") {\n descriptor = opts.descriptor;\n network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n } else {\n network =\n ((opts as NetworkOptions).isMainnet ?? true) ? networks.bitcoin : networks.testnet;\n descriptor = scriptExpressions.trBIP32({\n masterNode: HDKey.fromMasterSeed(seed, network.bip32),\n network,\n account: 0,\n change: 0,\n index: \"*\",\n });\n }\n\n // Parse the descriptor, substituting the wildcard at index 0.\n // The library raises \"index passed for non-ranged descriptor\"\n // if the input isn't a wildcard template, which we re-wrap so\n // the caller sees what they actually got wrong.\n let expansion;\n try {\n expansion = expand({ descriptor, network, index: 0 });\n } catch (e) {\n throw new Error(\n `SeedIdentity requires a wildcard descriptor template (must end in \"/*)\"); ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const keyInfo = expansion.expansionMap?.[\"@0\"];\n\n // Defensive copy: `derivedKey` and `descriptor` are computed eagerly\n // from the bytes we're about to stash, so a later mutation of the\n // caller's buffer must not drift the serialized `seed` out of sync\n // with the live identity state.\n seedBytes.set(this, new Uint8Array(seed));\n this.descriptor = descriptor;\n\n if (!keyInfo?.originPath) {\n throw new Error(\"Descriptor must include a key origin path\");\n }\n\n // Verify the xpub in the descriptor matches our seed (validates\n // that the descriptor was generated from this seed; we don't\n // need to keep the xpub around afterwards — `isOurs` re-derives\n // it from `this.descriptor` on demand).\n const masterNode = HDKey.fromMasterSeed(seed, network.bip32);\n const accountNode = masterNode.derive(`m${keyInfo.originPath}`);\n if (accountNode.publicExtendedKey !== keyInfo.bip32?.toBase58()) {\n throw new Error(\"xpub mismatch: derived key does not match descriptor\");\n }\n\n // Derive the private key for index 0 using the full path\n if (!keyInfo.path) {\n throw new Error(\"Descriptor must specify a full derivation path\");\n }\n const derivedNode = masterNode.derive(keyInfo.path);\n if (!derivedNode.privateKey) {\n throw new Error(\"Failed to derive private key\");\n }\n this.derivedKey = derivedNode.privateKey;\n }\n\n /**\n * Creates a SeedIdentity from a raw 64-byte seed.\n *\n * Pass `{ isMainnet }` for default BIP86 derivation, or\n * `{ descriptor }` for a caller-supplied account-descriptor\n * template (the option's value must end with `/*)`).\n *\n * @param seed - 64-byte seed (typically from mnemonicToSeedSync)\n * @param opts - Network selection or descriptor template.\n */\n static fromSeed(seed: Uint8Array, opts: SeedIdentityOptions = {}): SeedIdentity {\n return new SeedIdentity(seed, opts);\n }\n\n async xOnlyPublicKey(): Promise<Uint8Array> {\n return pubSchnorr(this.derivedKey);\n }\n\n async compressedPublicKey(): Promise<Uint8Array> {\n return pubECDSA(this.derivedKey, true);\n }\n\n async sign(tx: Transaction, inputIndexes?: number[]): Promise<Transaction> {\n return this.signTxWithKey(tx, this.derivedKey, inputIndexes);\n }\n\n async signMessage(\n message: Uint8Array,\n signatureType: \"schnorr\" | \"ecdsa\" = \"schnorr\",\n ): Promise<Uint8Array> {\n return this.signMessageWithKey(this.derivedKey, message, signatureType);\n }\n\n signerSession(): SignerSession {\n return TreeSignerSession.random();\n }\n\n /**\n * Converts to a watch-only identity that cannot sign. Carries the\n * template forward, so the readonly side stays HD-capable (can\n * derive descriptors at any index without seed access).\n */\n async toReadonly(): Promise<ReadonlyDescriptorIdentity> {\n return ReadonlyDescriptorIdentity.fromDescriptor(this.descriptor);\n }\n\n /**\n * Returns true when `descriptor` is derived from this identity's seed.\n * HD descriptors match by account xpub; bare `tr(pubkey)` descriptors\n * match by raw pubkey. See {@link descriptorIsOurs}.\n *\n * @deprecated Prefer `DescriptorProvider.isOurs()` via\n * `HDDescriptorProvider` for rotating HD wallets or\n * `StaticDescriptorProvider` for legacy single-key wallets.\n */\n isOurs(descriptor: string): boolean {\n return descriptorIsOurs(descriptor, this.descriptor, pubSchnorr(this.derivedKey));\n }\n\n /**\n * Signs each request with the key derived from its descriptor.\n * Each descriptor must share this identity's seed ({@link isOurs}).\n *\n * @deprecated Prefer `DescriptorProvider.signWithDescriptor()` via\n * `HDDescriptorProvider` or `StaticDescriptorProvider`. Identities keep\n * this method only as backing implementation for descriptor providers.\n */\n async signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]> {\n return requests.map((request) => {\n if (!this.isOurs(request.descriptor)) {\n throw new Error(\n `Descriptor ${request.descriptor} does not belong to this identity`,\n );\n }\n const key = this.derivePrivateKeyForDescriptor(request.descriptor);\n return this.signTxWithKey(request.tx, key, request.inputIndexes);\n });\n }\n\n /**\n * Signs a message with the key derived from `descriptor`.\n *\n * @deprecated Prefer `DescriptorProvider.signMessageWithDescriptor()` via\n * `HDDescriptorProvider` or `StaticDescriptorProvider`. Identities keep\n * this method only as backing implementation for descriptor providers.\n */\n async signMessageWithDescriptor(\n descriptor: string,\n message: Uint8Array,\n signatureType: \"schnorr\" | \"ecdsa\" = \"schnorr\",\n ): Promise<Uint8Array> {\n if (!this.isOurs(descriptor)) {\n throw new Error(`Descriptor ${descriptor} does not belong to this identity`);\n }\n const key = this.derivePrivateKeyForDescriptor(descriptor);\n return this.signMessageWithKey(key, message, signatureType);\n }\n\n // ── internal helpers ─────────────────────────────────────────────\n\n private derivePrivateKeyForDescriptor(descriptor: string): Uint8Array {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n const expansion = expand({ descriptor, network });\n if (expansion.isRanged) {\n throw new Error(\n \"Cannot sign with a wildcard descriptor; derive a concrete index first\",\n );\n }\n const keyInfo = expansion.expansionMap?.[\"@0\"];\n if (!keyInfo?.path) {\n throw new Error(\"Descriptor must specify a full derivation path for signing\");\n }\n const seed = seedBytes.get(this);\n if (!seed) {\n throw new Error(\"Seed bytes not available for descriptor signing\");\n }\n const masterNode = HDKey.fromMasterSeed(seed, network.bip32);\n const node = masterNode.derive(keyInfo.path);\n if (!node.privateKey) {\n throw new Error(\"Failed to derive private key for descriptor\");\n }\n return node.privateKey;\n }\n\n private signTxWithKey(tx: Transaction, key: Uint8Array, inputIndexes?: number[]): Transaction {\n const txCpy = tx.clone();\n\n if (!inputIndexes) {\n try {\n if (!txCpy.sign(key, ALL_SIGHASH)) {\n throw new Error(\"Failed to sign transaction\");\n }\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No inputs signed\")) {\n // ignore\n } else {\n throw e;\n }\n }\n } else {\n for (const idx of inputIndexes) {\n if (!txCpy.signIdx(key, idx, ALL_SIGHASH)) {\n throw new Error(`Failed to sign input #${idx}`);\n }\n }\n }\n\n return txCpy;\n }\n\n private signMessageWithKey(\n key: Uint8Array,\n message: Uint8Array,\n signatureType: \"schnorr\" | \"ecdsa\",\n ): Promise<Uint8Array> {\n if (signatureType === \"ecdsa\") return signAsync(message, key, { prehash: false });\n return schnorr.signAsync(message, key);\n }\n}\n\n/**\n * Mnemonic-based identity derived from a BIP39 phrase.\n *\n * This is the most user-friendly identity type — recommended for wallet\n * applications where users manage their own backup phrase. Extends\n * @see SeedIdentity with mnemonic validation and optional passphrase\n * support.\n *\n * @example\n * ```typescript\n * const identity = MnemonicIdentity.fromMnemonic(\n * 'abandon abandon abandon ...',\n * { isMainnet: true, passphrase: 'secret' }\n * );\n * ```\n */\nexport class MnemonicIdentity extends SeedIdentity {\n private constructor(phrase: string, opts: MnemonicOptions) {\n const { passphrase } = opts;\n super(mnemonicToSeedSync(phrase, passphrase), opts);\n mnemonicMeta.set(this, { mnemonic: phrase, passphrase });\n }\n\n /**\n * Creates a MnemonicIdentity from a BIP39 mnemonic phrase.\n *\n * Pass `{ isMainnet }` for default BIP86 derivation, or\n * `{ descriptor }` for a caller-supplied account-descriptor\n * template (the option's value must end with `/*)`).\n *\n * @param phrase - BIP39 mnemonic phrase (12 or 24 words)\n * @param opts - Network selection or descriptor template, plus optional passphrase\n */\n static fromMnemonic(phrase: string, opts: MnemonicOptions = {}): MnemonicIdentity {\n if (!validateMnemonic(phrase, wordlist)) {\n throw new Error(\"Invalid mnemonic\");\n }\n return new MnemonicIdentity(phrase, opts);\n }\n}\n\n/**\n * Watch-only HD identity from a descriptor *template*.\n *\n * Can derive public keys but cannot sign transactions. Use this for\n * watch-only wallets — given just an xpub-based template, the readonly\n * side still rotates through HD indices.\n *\n * Constructed from a wildcard template (e.g.\n * `tr([fp/86'/0'/0']xpub.../0/*)`); the {@link descriptor} field\n * holds it for HD providers to consume.\n *\n * @example\n * ```typescript\n * const ro = ReadonlyDescriptorIdentity.fromDescriptor(\n * \"tr([fp/86'/0'/0']xpub.../0/*)\"\n * );\n * ro.descriptor;\n * // => \"tr([fp/86'/0'/0']xpub.../0/*)\" — the template\n * ```\n */\nexport class ReadonlyDescriptorIdentity implements ReadonlyHDCapableIdentity {\n /**\n * Index-0 expansion of {@link descriptor}. Both the x-only pubkey\n * (taproot, returned by the library as 32 bytes) and the compressed\n * pubkey (derived through the bip32 node when needed) are read off\n * this on demand — no separate caches.\n */\n private readonly indexZero: KeyInfo;\n /**\n * Wildcard account-descriptor template (e.g.\n * `tr([fp/86'/0'/0']xpub/0/*)`). HD rotation consumers materialize\n * a concrete descriptor at a specific index themselves.\n */\n readonly descriptor: string;\n\n private constructor(descriptor: string) {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n // Library substitutes the wildcard at index 0 and raises\n // \"index passed for non-ranged descriptor\" if `descriptor` isn't\n // actually a wildcard template — re-wrap so the caller sees\n // the higher-level invariant they violated.\n let expansion;\n try {\n expansion = expand({ descriptor, network, index: 0 });\n } catch (e) {\n throw new Error(\n `ReadonlyDescriptorIdentity requires a wildcard descriptor template (must end in \"/*)\"); ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const keyInfo = expansion.expansionMap?.[\"@0\"];\n\n if (!keyInfo?.pubkey) {\n throw new Error(\"Failed to derive public key from descriptor\");\n }\n if (!keyInfo.bip32) {\n throw new Error(\"Cannot determine compressed public key parity from descriptor\");\n }\n\n this.descriptor = descriptor;\n this.indexZero = keyInfo;\n }\n\n /**\n * Creates a ReadonlyDescriptorIdentity from an account-descriptor\n * *template* (must end with the BIP-32 wildcard suffix `/*)`).\n *\n * @param descriptor - Wildcard-suffixed Taproot template\n * (`tr([fp/path']xpub.../child/*)`).\n */\n static fromDescriptor(descriptor: string): ReadonlyDescriptorIdentity {\n return new ReadonlyDescriptorIdentity(descriptor);\n }\n\n async xOnlyPublicKey(): Promise<Uint8Array> {\n // Validated non-null in the constructor.\n return this.indexZero.pubkey!;\n }\n\n async compressedPublicKey(): Promise<Uint8Array> {\n const { bip32, keyPath } = this.indexZero;\n // bip32 validated non-null in the constructor; derivePath\n // returns a fresh node so this is a read of the index-0\n // compressed pubkey, not a mutation of the stored one.\n if (keyPath) {\n // Strip leading \"/\" — the library's derivePath prepends \"m/\" itself\n return bip32!.derivePath(keyPath.replace(/^\\//, \"\")).publicKey;\n }\n return bip32!.publicKey;\n }\n\n /**\n * Returns true when `descriptor` derives from this identity's xpub.\n * HD descriptors match by account xpub; bare `tr(pubkey)` descriptors\n * fall back to comparing against the index-0 x-only pubkey. See\n * {@link descriptorIsOurs}.\n *\n * @deprecated Prefer `DescriptorProvider.isOurs()` via\n * `HDDescriptorProvider` for rotating HD wallets or\n * `StaticDescriptorProvider` for legacy single-key wallets.\n */\n isOurs(descriptor: string): boolean {\n return descriptorIsOurs(descriptor, this.descriptor, this.indexZero.pubkey!);\n }\n}\n\n/**\n * Serialize a seed-backed signing identity into a\n * {@link SerializedSigningIdentity} envelope without exposing the\n * underlying secret material on the public instance surface.\n *\n * Called by {@link serializeSigningIdentity}; application code should\n * prefer that public dispatcher instead of calling this directly. This\n * helper is deliberately kept out of the `src/identity` barrel so it is\n * not part of the package's public export surface.\n *\n * Secret-surface trade-off: the resulting envelope carries master-seed\n * material — the BIP39 mnemonic (+ optional passphrase) for\n * `MnemonicIdentity` or the raw 64-byte seed for `SeedIdentity`. A party\n * that reads this envelope can derive any key under the HD tree, not\n * just the key currently in use. The pre-change `SingleKey` flow only\n * shipped one derived private key and therefore had a smaller blast\n * radius. This is an intentional design trade to preserve class and\n * descriptor identity across the page / service-worker boundary; the\n * page already holds the same material so that it can re-initialize a\n * killed worker. Transport is same-origin `postMessage` only. See the\n * threat-model note in `src/worker/browser/README.md`.\n *\n * @internal\n */\nexport function serializeSeedOwnedSigningIdentity(\n identity: SeedIdentity,\n): SerializedSigningIdentity {\n if (identity instanceof MnemonicIdentity) {\n const meta = mnemonicMeta.get(identity);\n if (!meta) {\n throw new Error(\n \"MnemonicIdentity is missing internal secret state; was it constructed via MnemonicIdentity.fromMnemonic()?\",\n );\n }\n const envelope: SerializedSigningIdentity = {\n type: \"mnemonic\",\n mnemonic: meta.mnemonic,\n descriptor: identity.descriptor,\n };\n if (meta.passphrase !== undefined) {\n envelope.passphrase = meta.passphrase;\n }\n return envelope;\n }\n const seed = seedBytes.get(identity);\n if (!seed) {\n throw new Error(\n \"SeedIdentity is missing internal secret state; was it constructed via SeedIdentity.fromSeed() or the class constructor?\",\n );\n }\n return {\n type: \"seed\",\n seed: hex.encode(seed),\n descriptor: identity.descriptor,\n };\n}\n\n/**\n * Downgrade a seed-backed or descriptor-backed identity into a readonly\n * descriptor envelope. Always produces a descriptor-only shape — secret\n * material never crosses this path, even if the input is a signing\n * identity.\n *\n * Deliberately kept out of the `src/identity` barrel; consumers should go\n * through {@link serializeReadonlyIdentity}.\n *\n * @internal\n */\nexport function serializeSeedOwnedReadonlyIdentity(\n identity: SeedIdentity | ReadonlyDescriptorIdentity,\n): SerializedReadonlyIdentity {\n return {\n type: \"readonly-descriptor\",\n descriptor: identity.descriptor,\n };\n}\n","import { hex } from \"@scure/base\";\nimport type { Identity, ReadonlyIdentity } from \".\";\nimport { SingleKey, ReadonlySingleKey } from \"./singleKey\";\nimport {\n SeedIdentity,\n MnemonicIdentity,\n ReadonlyDescriptorIdentity,\n serializeSeedOwnedSigningIdentity,\n serializeSeedOwnedReadonlyIdentity,\n} from \"./seedIdentity\";\n\n/**\n * Tagged envelope for a signing identity transported across the\n * service-worker boundary. All variants are structured-clone safe\n * (plain strings only — no functions or prototypes).\n *\n * `descriptor` carries the wildcard *template* (e.g.\n * `tr([fp/86'/0'/0']xpub.../0/*)`), not a concrete index — the\n * receiving factories require a template, and storing it directly\n * means nothing here has to convert concrete → template on rehydrate.\n *\n * Adding a new variant is a source change in every worker build; keep\n * old variants around until all deployed workers handle them.\n */\nexport type SerializedSigningIdentity =\n | { type: \"single-key\"; privateKey: string }\n | { type: \"seed\"; seed: string; descriptor: string }\n | {\n type: \"mnemonic\";\n mnemonic: string;\n descriptor: string;\n passphrase?: string;\n };\n\n/**\n * Tagged envelope for a readonly identity transported across the\n * service-worker boundary. All variants are structured-clone safe.\n * `descriptor` is the wildcard template (see\n * {@link SerializedSigningIdentity}).\n */\nexport type SerializedReadonlyIdentity =\n | { type: \"readonly-single-key\"; publicKey: string }\n | { type: \"readonly-descriptor\"; descriptor: string };\n\nexport type SerializedIdentity = SerializedSigningIdentity | SerializedReadonlyIdentity;\n\n/** Type guard — true for signing envelopes, false for readonly envelopes. */\nexport function isSigningSerialized(s: SerializedIdentity): s is SerializedSigningIdentity {\n return s.type === \"single-key\" || s.type === \"seed\" || s.type === \"mnemonic\";\n}\n\n/** Identity that can expose a raw 32-byte private key via `toHex()`. */\ntype HexExportableIdentity = Identity & { toHex(): string };\n\nfunction hasToHex(identity: Identity): identity is HexExportableIdentity {\n return typeof (identity as { toHex?: unknown }).toHex === \"function\";\n}\n\n/**\n * Serialize a signing identity into a structured-clone safe envelope for\n * transport across the service-worker boundary.\n *\n * Supports SDK-owned signing identities directly. For custom identities, a\n * duck-typed `toHex()` fallback preserves compatibility with existing\n * `SingleKey`-like implementations.\n */\nexport function serializeSigningIdentity(identity: Identity): SerializedSigningIdentity {\n // Seed-backed identities (including MnemonicIdentity, which extends\n // SeedIdentity) delegate to the colocated helper so secret material\n // stays behind the WeakMap-backed internal state in seedIdentity.ts.\n if (identity instanceof SeedIdentity) {\n return serializeSeedOwnedSigningIdentity(identity);\n }\n if (identity instanceof SingleKey) {\n return { type: \"single-key\", privateKey: identity.toHex() };\n }\n if (hasToHex(identity)) {\n return { type: \"single-key\", privateKey: identity.toHex() };\n }\n throw new Error(\"Unsupported signing identity: cannot serialize for service-worker transport\");\n}\n\n/**\n * Serialize a readonly identity into a structured-clone safe envelope.\n *\n * Works for any `ReadonlyIdentity` via `compressedPublicKey()`. When called\n * with a signing identity, produces a readonly envelope (never ships signing\n * material) — callers that need to preserve signing capability across the\n * boundary must use {@link serializeSigningIdentity}.\n */\nexport async function serializeReadonlyIdentity(\n identity: ReadonlyIdentity,\n): Promise<SerializedReadonlyIdentity> {\n if (identity instanceof SeedIdentity || identity instanceof ReadonlyDescriptorIdentity) {\n return serializeSeedOwnedReadonlyIdentity(identity);\n }\n return {\n type: \"readonly-single-key\",\n publicKey: hex.encode(await identity.compressedPublicKey()),\n };\n}\n\n/**\n * Rehydrate a serialized identity envelope back into an identity instance.\n * The return type is the union of signing and readonly; use\n * {@link isSigningSerialized} on the envelope before hydration if the caller\n * needs to know which side it ends up on.\n *\n * Envelopes store the wildcard template directly (see\n * `serializeSeedOwnedSigningIdentity` / `serializeSeedOwnedReadonlyIdentity`),\n * so the `descriptor` field is passed straight through to the\n * template-only factories.\n */\nexport function hydrateIdentity(s: SerializedIdentity): Identity | ReadonlyIdentity {\n switch (s.type) {\n case \"single-key\":\n return SingleKey.fromHex(s.privateKey);\n case \"readonly-single-key\":\n return ReadonlySingleKey.fromPublicKey(hex.decode(s.publicKey));\n case \"seed\":\n return SeedIdentity.fromSeed(hex.decode(s.seed), {\n descriptor: s.descriptor,\n });\n case \"mnemonic\":\n return MnemonicIdentity.fromMnemonic(s.mnemonic, {\n descriptor: s.descriptor,\n passphrase: s.passphrase,\n });\n case \"readonly-descriptor\":\n return ReadonlyDescriptorIdentity.fromDescriptor(s.descriptor);\n default:\n // Belt-and-suspenders: `normalizeSerializedIdentity` already\n // rejects unknown `type` values at the wire boundary. Without\n // this throw, an unknown type would fall through and return\n // undefined, which callers would then cast to Identity and\n // crash downstream with an opaque error.\n throw new Error(\n `Unknown serialized identity type: ${String((s as { type: unknown }).type)}`,\n );\n }\n}\n\n/**\n * Legacy untagged shape emitted by page builds prior to the tagged\n * SerializedIdentity envelope. Retained so newer workers can still accept\n * older pages during a rolling upgrade. Slated for removal in the next major.\n *\n * @deprecated Use {@link SerializedIdentity}.\n */\nexport type LegacySerializedIdentity = { privateKey: string } | { publicKey: string };\n\nlet warnedLegacyShape = false;\n\n/**\n * Accept either a modern {@link SerializedIdentity} envelope or a legacy\n * `{ privateKey }` / `{ publicKey }` shape and normalize to a\n * {@link SerializedIdentity}. Emits a one-time deprecation warning when a\n * legacy shape is seen.\n *\n * Intended for the worker-side boundary; new page builds always emit tagged\n * envelopes via {@link serializeSigningIdentity} /\n * {@link serializeReadonlyIdentity}.\n */\nexport function normalizeSerializedIdentity(\n shape: SerializedIdentity | LegacySerializedIdentity,\n): SerializedIdentity {\n if (\"type\" in shape) {\n assertValidSerializedIdentity(shape);\n return shape;\n }\n if (!warnedLegacyShape) {\n warnedLegacyShape = true;\n console.warn(\n \"[ts-sdk] Received legacy serialized identity shape \" +\n \"(privateKey/publicKey). Upgrade the page build to the latest \" +\n \"@arkade-os/sdk — this compatibility path will be removed in \" +\n \"the next major.\",\n );\n }\n if (\"privateKey\" in shape && typeof shape.privateKey === \"string\") {\n return { type: \"single-key\", privateKey: shape.privateKey };\n }\n if (\"publicKey\" in shape && typeof shape.publicKey === \"string\") {\n return { type: \"readonly-single-key\", publicKey: shape.publicKey };\n }\n throw new Error(\"Unrecognized serialized identity shape\");\n}\n\n/**\n * Runtime-validate that a tagged envelope carries the fields its variant\n * requires. The SDK's own serializer produces well-formed envelopes; this\n * guard exists so a malformed message (older SDK version mismatch,\n * hand-built config, etc.) fails loudly at the wire boundary rather than\n * with an opaque `\"Cannot read properties of undefined\"` deep inside a\n * hydrator.\n */\nfunction assertValidSerializedIdentity(s: { type: unknown }): asserts s is SerializedIdentity {\n const kind = s.type;\n const bad = (field: string, expected: string): never => {\n throw new Error(\n `Malformed serialized identity ({ type: ${JSON.stringify(kind)} }): ` +\n `missing or invalid \"${field}\" (expected ${expected})`,\n );\n };\n const asStr = (key: string): string => {\n const v = (s as Record<string, unknown>)[key];\n return typeof v === \"string\" ? v : bad(key, \"string\");\n };\n switch (kind) {\n case \"single-key\":\n asStr(\"privateKey\");\n return;\n case \"readonly-single-key\":\n asStr(\"publicKey\");\n return;\n case \"seed\":\n asStr(\"seed\");\n asStr(\"descriptor\");\n return;\n case \"mnemonic\": {\n asStr(\"mnemonic\");\n asStr(\"descriptor\");\n const passphrase = (s as Record<string, unknown>).passphrase;\n if (passphrase !== undefined && typeof passphrase !== \"string\") {\n bad(\"passphrase\", \"string | undefined\");\n }\n return;\n }\n case \"readonly-descriptor\":\n asStr(\"descriptor\");\n return;\n default:\n throw new Error(`Unknown serialized identity type: ${String(kind)}`);\n }\n}\n","import { Identity, ReadonlyIdentity } from \".\";\nimport { DescriptorSigningRequest } from \"./descriptorProvider\";\nimport { Transaction } from \"../utils/transaction\";\n\n/**\n * Read-side HD capability marker. Exposes the wildcard-suffixed account\n * descriptor *template* and the descriptor-membership predicate, but no\n * signing primitives — suitable for watch-only identities backed by an\n * xpub.\n *\n * Extracted from {@link HDCapableIdentity} so that\n * `ReadonlyDescriptorIdentity` can stand in for an HD wallet's read-only\n * surface (template-aware, derives pubkeys at any index) without having\n * to claim signing capability it cannot honour.\n */\nexport interface ReadonlyHDCapableIdentity extends ReadonlyIdentity {\n /**\n * The wildcard-suffixed account descriptor template\n * (e.g. `tr([fp/86'/0'/0']xpub/0/*)`). Consumers materialize a\n * concrete descriptor by replacing the `*` with a derivation index.\n */\n readonly descriptor: string;\n\n /**\n * True iff `descriptor` derives from this identity's xpub/seed.\n *\n * @deprecated Prefer `DescriptorProvider.isOurs()` via\n * `HDDescriptorProvider` for rotating HD wallets or\n * `StaticDescriptorProvider` for legacy single-key wallets.\n */\n isOurs(descriptor: string): boolean;\n}\n\n/**\n * Capability marker for identities that can be rotated through an HD\n * derivation tree AND can sign at each rotated index.\n *\n * Deliberately does NOT extend `DescriptorProvider`: if an HD-capable\n * identity were silently usable as a concrete descriptor source, callers\n * could bypass receive rotation and unknowingly reuse a single address\n * forever. To use this identity as a wallet's descriptor source, wrap\n * it explicitly:\n *\n * - `HDDescriptorProvider` — rotating, recommended for new wallets.\n * - `StaticDescriptorProvider` — pinned to a single key, for legacy or\n * explicitly-non-rotating use cases.\n */\nexport interface HDCapableIdentity extends ReadonlyHDCapableIdentity, Identity {\n /**\n * Signs each request with the key derived from its descriptor.\n *\n * @deprecated Prefer `DescriptorProvider.signWithDescriptor()` via\n * `HDDescriptorProvider` or `StaticDescriptorProvider`. Identities keep\n * this method only as backing implementation for descriptor providers.\n */\n signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]>;\n\n /**\n * Signs a message using the key derived from `descriptor`.\n *\n * @deprecated Prefer `DescriptorProvider.signMessageWithDescriptor()` via\n * `HDDescriptorProvider` or `StaticDescriptorProvider`. Identities keep\n * this method only as backing implementation for descriptor providers.\n */\n signMessageWithDescriptor(\n descriptor: string,\n message: Uint8Array,\n signatureType?: \"schnorr\" | \"ecdsa\",\n ): Promise<Uint8Array>;\n}\n\n/**\n * Structural type guard for {@link HDCapableIdentity}. Returns `true`\n * when the value exposes the four members the HD wallet flow relies on:\n * `descriptor`, `isOurs`, `signWithDescriptor`, and\n * `signMessageWithDescriptor`. Used by callers that need to opt into\n * the HD path (e.g. installing an `HDDescriptorProvider`) without\n * coupling to a concrete identity class.\n */\nexport function isHDCapableIdentity(value: unknown): value is HDCapableIdentity {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.descriptor === \"string\" &&\n typeof v.isOurs === \"function\" &&\n typeof v.signWithDescriptor === \"function\" &&\n typeof v.signMessageWithDescriptor === \"function\"\n );\n}\n","import { Transaction } from \"../utils/transaction\";\nimport { SignerSession } from \"../tree/signingSession\";\n\nexport interface Identity extends ReadonlyIdentity {\n /** Returns a signer session used for musig2 tree signing flows. */\n signerSession(): SignerSession;\n\n /** Sign an arbitrary message using the requested signature type. */\n signMessage(message: Uint8Array, signatureType: \"schnorr\" | \"ecdsa\"): Promise<Uint8Array>;\n\n /**\n * Sign the provided transaction inputs.\n *\n * @param tx - Transaction to sign\n * @param inputIndexes - Optional input indexes to sign. When omitted, the implementation should sign every signable input.\n */\n sign(tx: Transaction, inputIndexes?: number[]): Promise<Transaction>;\n}\n\nexport interface ReadonlyIdentity {\n /** Returns the x-only public key used by Taproot scripts. */\n xOnlyPublicKey(): Promise<Uint8Array>;\n\n /** Returns the compressed public key for this identity. */\n compressedPublicKey(): Promise<Uint8Array>;\n}\n\n/** A single PSBT signing request within a batch. */\nexport interface SignRequest {\n tx: Transaction;\n inputIndexes?: number[];\n}\n\n/**\n * Identity that supports signing multiple PSBTs in a single wallet interaction.\n * Browser wallet providers that support batch signing (e.g. Xverse, UniSat, OKX)\n * should implement this interface to reduce the number of confirmation popups\n * from N+1 to 1 during Arkade send transactions.\n *\n * Contract: implementations MUST return exactly one `Transaction` per request,\n * in the same order as the input array. The SDK validates this at runtime and\n * will throw if the lengths do not match.\n */\nexport interface BatchSignableIdentity extends Identity {\n /**\n * Sign multiple transactions in a single wallet interaction.\n *\n * @param requests - Transactions and optional input indexes to sign\n * @returns Signed transactions in the same order as the input requests\n */\n signMultiple(requests: SignRequest[]): Promise<Transaction[]>;\n}\n\n/** Type guard for identities that support batch signing. */\nexport function isBatchSignable(identity: Identity): identity is BatchSignableIdentity {\n return (\n \"signMultiple\" in identity &&\n typeof (identity as BatchSignableIdentity).signMultiple === \"function\"\n );\n}\n\nexport * from \"./singleKey\";\n// Explicit named re-export so the barrel stays a documented public surface.\n// `serializeSeedOwnedSigningIdentity` and `serializeSeedOwnedReadonlyIdentity`\n// are deliberately omitted — they are SDK-internal helpers consumed only by\n// `./serialize`, per Appendix A of the plan.\nexport type {\n NetworkOptions,\n DescriptorOptions,\n SeedIdentityOptions,\n MnemonicOptions,\n} from \"./seedIdentity\";\nexport { SeedIdentity, MnemonicIdentity, ReadonlyDescriptorIdentity } from \"./seedIdentity\";\nexport * from \"./serialize\";\n\n// Descriptor utilities\nexport {\n isDescriptor,\n normalizeToDescriptor,\n extractPubKey,\n parseHDDescriptor,\n} from \"./descriptor\";\nexport type { ParsedHDDescriptor } from \"./descriptor\";\n\n// Descriptor provider interface\nexport type { DescriptorProvider, DescriptorSigningRequest } from \"./descriptorProvider\";\n\n// HD capability markers — readonly (xpub-only) and signing variants\nexport type { HDCapableIdentity, ReadonlyHDCapableIdentity } from \"./hdCapableIdentity\";\nexport { isHDCapableIdentity } from \"./hdCapableIdentity\";\n\n// Static descriptor provider (wrapper for legacy Identity)\nexport { StaticDescriptorProvider } from \"./staticDescriptorProvider\";\n","type SetupServiceWorkerOptions = {\n path: string;\n updateViaCache?: ServiceWorkerUpdateViaCache;\n autoReload?: boolean;\n onNeedRefresh?: () => void;\n onUpdated?: () => void;\n debug?: boolean;\n activationTimeoutMs?: number;\n};\n\nconst registrations = new Map<string, Promise<ServiceWorkerRegistration>>();\nlet handshakes = new WeakSet<ServiceWorkerRegistration>();\n\nfunction ensureServiceWorkerSupport() {\n if (!(\"serviceWorker\" in navigator)) {\n throw new Error(\"Service workers are not supported in this browser\");\n }\n}\n\nfunction debugLog(debug: boolean | undefined, ...args: unknown[]) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.debug(...args);\n }\n}\n\nfunction normalizeOptions(\n pathOrOptions: string | SetupServiceWorkerOptions,\n): Required<Omit<SetupServiceWorkerOptions, \"onNeedRefresh\" | \"onUpdated\">> &\n Pick<SetupServiceWorkerOptions, \"onNeedRefresh\" | \"onUpdated\"> {\n if (typeof pathOrOptions === \"string\") {\n return {\n path: pathOrOptions,\n updateViaCache: \"none\",\n autoReload: true,\n debug: false,\n activationTimeoutMs: 10_000,\n };\n }\n\n return {\n path: pathOrOptions.path,\n updateViaCache: pathOrOptions.updateViaCache ?? \"none\",\n autoReload: pathOrOptions.autoReload ?? true,\n onNeedRefresh: pathOrOptions.onNeedRefresh,\n onUpdated: pathOrOptions.onUpdated,\n debug: pathOrOptions.debug ?? false,\n activationTimeoutMs: pathOrOptions.activationTimeoutMs ?? 10_000,\n };\n}\n\nfunction sendSkipWaiting(worker: ServiceWorker | null | undefined, debug?: boolean) {\n if (!worker) return;\n try {\n worker.postMessage({ type: \"SKIP_WAITING\" });\n debugLog(debug, \"Sent SKIP_WAITING to waiting service worker\");\n } catch (error) {\n console.warn(\"Failed to post SKIP_WAITING to service worker\", error);\n }\n}\n\nfunction attachUpdateHandlers(\n registration: ServiceWorkerRegistration,\n options: ReturnType<typeof normalizeOptions>,\n) {\n // Guard: only the first caller per registration attaches handlers.\n // Subsequent calls with different options are silently ignored.\n if (handshakes.has(registration)) return;\n handshakes.add(registration);\n\n const { autoReload, onNeedRefresh, onUpdated, activationTimeoutMs, debug } = options;\n\n let reloadTriggered = false;\n\n const maybeReload = () => {\n if (reloadTriggered) return;\n reloadTriggered = true;\n debugLog(debug, \"Service worker controller change detected\");\n onUpdated?.();\n if (\n autoReload &&\n typeof window !== \"undefined\" &&\n typeof window.location?.reload === \"function\"\n ) {\n window.location.reload();\n }\n };\n\n const handleWaiting = (worker: ServiceWorker | null | undefined) => {\n if (!worker) return;\n onNeedRefresh?.();\n sendSkipWaiting(worker, debug);\n\n if (activationTimeoutMs > 0 && typeof window !== \"undefined\") {\n window.setTimeout(() => {\n if (registration.waiting) {\n debugLog(debug, \"Waiting worker still pending; re-sending SKIP_WAITING\");\n sendSkipWaiting(registration.waiting, debug);\n registration\n .update()\n .catch(() =>\n debugLog(debug, \"Service worker update retry failed (timeout path)\"),\n );\n }\n }, activationTimeoutMs);\n }\n };\n\n // Handle an already waiting worker at startup.\n if (registration.waiting) {\n handleWaiting(registration.waiting);\n }\n\n // Listen for newly installed workers becoming waiting.\n registration.addEventListener(\"updatefound\", () => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n if (installing.state === \"installed\") {\n handleWaiting(registration.waiting);\n }\n });\n });\n\n // Reload (or callback) once the new controller takes over.\n navigator.serviceWorker.addEventListener(\"controllerchange\", maybeReload, {\n once: true,\n });\n}\n\nfunction registerOnce(\n options: ReturnType<typeof normalizeOptions>,\n): Promise<ServiceWorkerRegistration> {\n const { path, updateViaCache } = options;\n\n if (!registrations.has(path)) {\n const registrationPromise = navigator.serviceWorker\n .register(path, { updateViaCache })\n .then(async (registration) => {\n try {\n await registration.update();\n } catch (error) {\n console.warn(\n \"Service worker update failed; continuing with registration\",\n error,\n );\n }\n return registration;\n })\n .catch((error) => {\n // delete failed registration to allow retrials\n registrations.delete(path);\n throw error;\n });\n registrations.set(path, registrationPromise);\n }\n\n return registrations.get(path)!.then((registration) => {\n attachUpdateHandlers(registration, options);\n return registration;\n });\n}\n\n/**\n * Registers a service worker for the given path only once, attaches an\n * update/activation handshake (SKIP_WAITING + controllerchange reload), and\n * caches the registration promise for subsequent calls.\n *\n * @param pathOrOptions - Service worker script path or a configuration object.\n * @throws if service workers are not supported or registration fails.\n */\nexport async function setupServiceWorkerOnce(\n pathOrOptions: string | SetupServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration> {\n ensureServiceWorkerSupport();\n const options = normalizeOptions(pathOrOptions);\n return registerOnce(options);\n}\n\n/**\n * Returns an active service worker instance, optionally ensuring a specific\n * script path is registered before resolving.\n *\n * @param path - Optional service worker script path to register and prefer.\n * @throws if service workers are not supported or no active worker is available.\n */\nexport async function getActiveServiceWorker(path?: string): Promise<ServiceWorker> {\n ensureServiceWorkerSupport();\n const registration: ServiceWorkerRegistration = path\n ? await registerOnce(normalizeOptions(path))\n : await navigator.serviceWorker.ready;\n let serviceWorker =\n registration.active ||\n registration.waiting ||\n registration.installing ||\n navigator.serviceWorker.controller;\n\n if (!serviceWorker && path) {\n const readyRegistration = await navigator.serviceWorker.ready;\n serviceWorker =\n readyRegistration.active ||\n readyRegistration.waiting ||\n readyRegistration.installing ||\n navigator.serviceWorker.controller;\n }\n\n if (!serviceWorker) {\n throw new Error(\"Service worker not ready yet\");\n }\n return serviceWorker;\n}\n\n/**\n * Clears the cached registration promises.\n * Intended for tests to reset state between runs.\n */\nexport const __resetServiceWorkerManager = () => {\n registrations.clear();\n handshakes = new WeakSet<ServiceWorkerRegistration>();\n};\n","import { Intent } from \"../intent\";\nimport { SignedIntent } from \"./ark\";\n\n/**\n * Delegate identity and fee information returned by `getDelegateInfo`.\n */\nexport interface DelegateInfo {\n /** Delegate public key. */\n pubkey: string;\n /** Delegate fee amount or expression returned by the delegation service. */\n fee: string;\n /**\n * Address controlled by the delegation service.\n * Naming is confusing: should be thought of as a \"delegate address\".\n */\n delegatorAddress: string;\n}\n\n/**\n * Optional delegate behavior flags.\n */\nexport interface DelegateOptions {\n /**\n * Instruct the delegate not to replace an existing delegation\n * (meaning a signed register intent and its forfeit transactions)\n * that already includes at least one virtual output from this request.\n *\n * @defaultValue `false`\n */\n rejectReplace?: boolean;\n}\n\n/**\n * Provider interface for remote delegation services.\n */\nexport interface DelegatorProvider {\n /**\n * Request delegation for a signed register intent and its forfeit transactions.\n *\n * @param intent - Signed register intent to delegate\n * @param forfeitTxs - Forfeit transactions associated with the delegation request\n * @param options - Optional delegate behavior flags\n */\n delegate(\n intent: SignedIntent<Intent.RegisterMessage>,\n forfeitTxs: string[],\n options?: DelegateOptions,\n ): Promise<void>;\n\n /**\n * Fetch delegate metadata such as pubkey, fee, and delegate address.\n *\n * @returns Delegate identity and fee information\n */\n getDelegateInfo(): Promise<DelegateInfo>;\n}\n\n/**\n * REST-based delegation provider implementation.\n * @example\n * ```typescript\n * const provider = new RestDelegatorProvider('https://delegator.example.com');\n * const info = await provider.getDelegateInfo();\n * await provider.delegate(intent, forfeitTxs);\n * ```\n */\nexport class RestDelegatorProvider implements DelegatorProvider {\n /**\n * Create a REST delegation provider targeting the given base URL.\n *\n * @param url - Base URL of the delegation service\n */\n constructor(public url: string) {}\n\n /**\n * Submit a delegation request to the remote delegation service.\n *\n * @param intent - Signed register intent to delegate\n * @param forfeitTxs - Forfeit transactions associated with the delegation request\n * @param options - Optional delegate behavior flags\n * @throws Error if the remote service rejects the request\n */\n async delegate(\n intent: SignedIntent<Intent.RegisterMessage>,\n forfeitTxs: string[],\n options?: DelegateOptions,\n ): Promise<void> {\n const url = `${this.url}/v1/delegate`;\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n intent: {\n message: Intent.encodeMessage(intent.message),\n proof: intent.proof,\n },\n forfeit_txs: forfeitTxs,\n reject_replace: options?.rejectReplace ?? false,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delegate: ${errorText}`);\n }\n }\n\n /**\n * Fetch delegate metadata exposed by the remote delegation service.\n *\n * @returns Delegate identity and fee information\n * @throws Error if the remote service returns invalid data\n */\n async getDelegateInfo(): Promise<DelegateInfo> {\n const url = `${this.url}/v1/delegator/info`;\n const response = await fetch(url);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get delegate info: ${errorText}`);\n }\n\n const data = await response.json();\n if (!isDelegateInfo(data)) {\n throw new Error(\"Invalid delegate info\");\n }\n return data;\n }\n}\n\nfunction isDelegateInfo(data: unknown): data is DelegateInfo {\n return (\n !!data &&\n typeof data === \"object\" &&\n \"pubkey\" in data &&\n \"fee\" in data &&\n \"delegatorAddress\" in data &&\n typeof (data as DelegateInfo).pubkey === \"string\" &&\n typeof (data as DelegateInfo).fee === \"string\" &&\n typeof (data as DelegateInfo).delegatorAddress === \"string\" &&\n (data as DelegateInfo).pubkey !== \"\" &&\n (data as DelegateInfo).fee !== \"\" &&\n (data as DelegateInfo).delegatorAddress !== \"\"\n );\n}\n","import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n\nexport type NetworkName = \"bitcoin\" | \"testnet\" | \"signet\" | \"mutinynet\" | \"regtest\";\n\nexport interface Network {\n hrp: string;\n bech32: string;\n pubKeyHash: number;\n scriptHash: number;\n wif: number;\n}\nexport const getNetwork = (network: NetworkName): Network => {\n return networks[network];\n};\n\nexport const networks = {\n bitcoin: withArkPrefix(NETWORK, \"ark\"),\n testnet: withArkPrefix(TEST_NETWORK, \"tark\"),\n signet: withArkPrefix(TEST_NETWORK, \"tark\"),\n mutinynet: withArkPrefix(TEST_NETWORK, \"tark\"),\n regtest: withArkPrefix(\n {\n ...TEST_NETWORK,\n bech32: \"bcrt\",\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n },\n \"tark\",\n ),\n};\n\nfunction withArkPrefix(network: Omit<Network, \"hrp\">, prefix: string): Network {\n return {\n ...network,\n hrp: prefix,\n };\n}\n","import type { NetworkName } from \"../networks\";\nimport { Coin } from \"../wallet\";\n\n/**\n * The default base URLs for esplora API providers.\n *\n * Mainnet, mutinynet, and signet point at Ark Labs–operated\n * mempool deployments (mempool.space-compatible esplora API).\n * Testnet falls back to the public mempool.space deployment\n * because Ark doesn't host it. Regtest assumes a local nigiri\n * stack on the standard port.\n */\nexport const ESPLORA_URL: Record<NetworkName, string> = {\n bitcoin: \"https://mempool.arkade.sh/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.signet.arkade.sh/api\",\n mutinynet: \"https://mempool.mutinynet.arkade.sh/api\",\n regtest: \"http://localhost:3000\",\n};\n\nexport type ExplorerTransaction = {\n txid: string;\n vout: {\n scriptpubkey_address: string;\n value: string;\n }[];\n status: {\n confirmed: boolean;\n block_time: number;\n };\n};\n\nexport interface OnchainProvider {\n /**\n * Fetch spendable onchain outputs for an address.\n *\n * @param address - Bitcoin address to query\n * @returns Spendable onchain outputs for the address\n * @see Coin\n */\n getCoins(address: string): Promise<Coin[]>;\n\n /**\n * Fetch the current fastest fee rate estimate.\n *\n * @returns Fee rate in sats/vB, if available\n * @remarks\n * Implementations may return `undefined` when the backing service does not expose\n * a usable fee estimate.\n */\n getFeeRate(): Promise<number | undefined>;\n\n /**\n * Broadcast a single transaction or a 1P1C package.\n *\n * @param txs - One or more raw transaction hex strings\n * @returns Broadcast transaction id\n * @throws Error if the broadcast request fails or the package shape is invalid\n */\n broadcastTransaction(...txs: string[]): Promise<string>;\n\n /**\n * Fetch outspend information for every output in a transaction.\n *\n * @param txid - Transaction id to inspect\n * @returns Per-output spend status information\n * @see getTxStatus\n */\n getTxOutspends(txid: string): Promise<{ spent: boolean; txid: string }[]>;\n\n /**\n * Fetch transactions associated with an address.\n *\n * @param address - Bitcoin address to query\n * @returns Transactions involving the address\n * @see ExplorerTransaction\n */\n getTransactions(address: string): Promise<ExplorerTransaction[]>;\n\n /**\n * Fetch confirmation status for a transaction.\n *\n * @param txid - Transaction id to inspect\n * @returns Confirmation status and block metadata when confirmed\n * @see getTxOutspends\n */\n getTxStatus(\n txid: string,\n ): Promise<{ confirmed: false } | { confirmed: true; blockTime: number; blockHeight: number }>;\n /**\n * Fetch the current chain tip.\n *\n * @returns Current chain height, block time, and block hash\n */\n getChainTip(): Promise<{\n height: number;\n time: number;\n hash: string;\n }>;\n\n /**\n * Watch a set of addresses and invoke the callback when transactions are observed.\n *\n * @param addresses - Addresses to monitor\n * @param eventCallback - Callback invoked when matching transactions are seen\n * @returns Stop function that cancels the watch\n * @remarks\n * Implementations may use websockets, server-sent events, polling, or a hybrid strategy.\n * @see getTransactions\n */\n watchAddresses(\n addresses: string[],\n eventCallback: (txs: ExplorerTransaction[]) => void,\n ): Promise<() => void>;\n}\n\n/**\n * Implementation of the onchain provider interface for esplora REST API.\n *\n * @see https://mempool.space/docs/api/rest\n * @example\n * ```typescript\n * const provider = new EsploraProvider(\"https://mempool.space/api\");\n * const outputs = await provider.getCoins(\"bcrt1q679zsd45msawvr7782r0twvmukns3drlstjt77\");\n * ```\n */\nexport class EsploraProvider implements OnchainProvider {\n readonly pollingInterval: number;\n readonly forcePolling: boolean;\n\n constructor(\n private baseUrl: string,\n opts?: {\n /** Polling interval in milliseconds. */\n pollingInterval?: number;\n\n /** Force polling even when websocket transport is available. */\n forcePolling?: boolean;\n },\n ) {\n this.pollingInterval = opts?.pollingInterval ?? 15_000;\n this.forcePolling = opts?.forcePolling ?? false;\n }\n\n async getCoins(address: string): Promise<Coin[]> {\n const response = await fetch(`${this.baseUrl}/address/${address}/utxo`);\n if (!response.ok) {\n throw new Error(`Failed to fetch UTXOs: ${response.statusText}`);\n }\n return response.json();\n }\n\n async getFeeRate(): Promise<number | undefined> {\n const response = await fetch(`${this.baseUrl}/fee-estimates`);\n if (!response.ok) {\n throw new Error(`Failed to fetch fee rate: ${response.statusText}`);\n }\n const fees = (await response.json()) as Record<string, number>;\n return fees[\"1\"] ?? undefined;\n }\n\n async broadcastTransaction(...txs: string[]): Promise<string> {\n switch (txs.length) {\n case 1:\n return this.broadcastTx(txs[0]);\n case 2:\n return this.broadcastPackage(txs[0], txs[1]);\n default:\n throw new Error(\"Only 1 or 1C1P package can be broadcast\");\n }\n }\n\n async getTxOutspends(txid: string): Promise<{ spent: boolean; txid: string }[]> {\n const response = await fetch(`${this.baseUrl}/tx/${txid}/outspends`);\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to get transaction outspends: ${error}`);\n }\n\n return response.json();\n }\n\n async getTransactions(address: string): Promise<ExplorerTransaction[]> {\n const response = await fetch(`${this.baseUrl}/address/${address}/txs`);\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to get transactions: ${error}`);\n }\n\n return response.json();\n }\n\n async getTxStatus(txid: string): Promise<\n | {\n confirmed: false;\n }\n | {\n confirmed: true;\n blockTime: number;\n blockHeight: number;\n }\n > {\n // make sure tx exists in mempool or in block\n const txresponse = await fetch(`${this.baseUrl}/tx/${txid}`);\n if (!txresponse.ok) {\n throw new Error(txresponse.statusText);\n }\n\n const tx = await txresponse.json();\n if (!tx.status.confirmed) {\n return { confirmed: false };\n }\n\n const response = await fetch(`${this.baseUrl}/tx/${txid}/status`);\n if (!response.ok) {\n throw new Error(`Failed to get transaction status: ${response.statusText}`);\n }\n\n const data = await response.json();\n if (!data.confirmed) {\n return { confirmed: false };\n }\n\n return {\n confirmed: data.confirmed,\n blockTime: data.block_time,\n blockHeight: data.block_height,\n };\n }\n\n async watchAddresses(\n addresses: string[],\n callback: (txs: ExplorerTransaction[]) => void,\n ): Promise<() => void> {\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const wsUrl = this.baseUrl.replace(/^http(s)?:/, \"ws$1:\") + \"/v1/ws\";\n\n const poll = async () => {\n const getAllTxs = async () => {\n const txArrays = await Promise.all(\n addresses.map((address) => this.getTransactions(address)),\n );\n return txArrays.flat();\n };\n\n // initial fetch to get existing transactions\n const initialTxs = await getAllTxs();\n\n // we use block_time in key to also notify when a transaction is confirmed\n const txKey = (tx: ExplorerTransaction) => `${tx.txid}_${tx.status.block_time}`;\n\n // create a set of existing transactions to avoid duplicates\n const existingTxs = new Set(initialTxs.map(txKey));\n\n // polling for new transactions\n intervalId = setInterval(async () => {\n try {\n // get current transactions\n // we will compare with initialTxs to find new ones\n const currentTxs = await getAllTxs();\n\n // filter out transactions that are already in initialTxs\n const newTxs = currentTxs.filter((tx) => !existingTxs.has(txKey(tx)));\n\n if (newTxs.length > 0) {\n // Update the tracking set instead of growing the array\n newTxs.forEach((tx) => existingTxs.add(txKey(tx)));\n callback(newTxs);\n }\n } catch (error) {\n console.error(\"Error in polling mechanism:\", error);\n }\n }, this.pollingInterval);\n };\n\n let ws: WebSocket | null = null;\n\n const stopFunc = () => {\n if (ws) ws.close();\n if (intervalId) clearInterval(intervalId);\n };\n\n if (this.forcePolling) {\n await poll();\n return stopFunc;\n }\n\n try {\n ws = new WebSocket(wsUrl);\n ws.addEventListener(\"open\", () => {\n // subscribe to address updates\n const subscribeMsg: SubscribeMessage = {\n \"track-addresses\": addresses,\n };\n ws!.send(JSON.stringify(subscribeMsg));\n });\n\n ws.addEventListener(\"message\", (event: MessageEvent) => {\n try {\n const newTxs: ExplorerTransaction[] = [];\n const message: WebSocketMessage = JSON.parse(event.data.toString());\n if (!message[\"multi-address-transactions\"]) return;\n const aux = message[\"multi-address-transactions\"];\n\n for (const address in aux) {\n for (const type of [\"mempool\", \"confirmed\", \"removed\"] as const) {\n if (!aux[address][type]) continue;\n newTxs.push(...aux[address][type].filter(isExplorerTransaction));\n }\n }\n // callback with new transactions\n if (newTxs.length > 0) callback(newTxs);\n } catch (error) {\n console.error(\"Failed to process WebSocket message:\", error);\n }\n });\n\n ws.addEventListener(\"error\", async () => {\n // if websocket is not available, fallback to polling\n await poll();\n });\n } catch {\n if (intervalId) clearInterval(intervalId);\n // if websocket is not available, fallback to polling\n await poll();\n }\n\n return stopFunc;\n }\n\n async getChainTip(): Promise<{\n height: number;\n time: number;\n hash: string;\n }> {\n const tipBlocks = await fetch(`${this.baseUrl}/blocks/tip`);\n if (!tipBlocks.ok) {\n throw new Error(`Failed to get chain tip: ${tipBlocks.statusText}`);\n }\n\n const tip = await tipBlocks.json();\n if (!isValidBlocksTip(tip)) {\n throw new Error(`Invalid chain tip: ${JSON.stringify(tip)}`);\n }\n\n if (tip.length === 0) {\n throw new Error(\"No chain tip found\");\n }\n\n const hash = tip[0].id;\n return {\n height: tip[0].height,\n time: tip[0].mediantime,\n hash,\n };\n }\n\n private async broadcastPackage(parent: string, child: string): Promise<string> {\n const response = await fetch(`${this.baseUrl}/txs/package`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify([parent, child]),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to broadcast package: ${error}`);\n }\n\n return response.json();\n }\n\n private async broadcastTx(tx: string): Promise<string> {\n const response = await fetch(`${this.baseUrl}/tx`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n body: tx,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to broadcast transaction: ${error}`);\n }\n\n return response.text();\n }\n}\n\nfunction isValidBlocksTip(tip: any): tip is { id: string; height: number; mediantime: number }[] {\n return (\n Array.isArray(tip) &&\n tip.every((t) => {\n return (\n t &&\n typeof t === \"object\" &&\n typeof t.id === \"string\" &&\n t.id.length > 0 &&\n typeof t.height === \"number\" &&\n t.height >= 0 &&\n typeof t.mediantime === \"number\" &&\n t.mediantime > 0\n );\n })\n );\n}\n\nconst isExplorerTransaction = (tx: any): tx is ExplorerTransaction => {\n return (\n typeof tx.txid === \"string\" &&\n Array.isArray(tx.vout) &&\n tx.vout.every(\n (vout: any) =>\n typeof vout.scriptpubkey_address === \"string\" && typeof vout.value === \"number\",\n ) &&\n typeof tx.status === \"object\" &&\n typeof tx.status.confirmed === \"boolean\"\n );\n};\n\ninterface SubscribeMessage {\n \"track-addresses\": string[];\n}\n\ninterface WebSocketMessage {\n \"multi-address-transactions\"?: Record<\n string,\n {\n mempool: ExplorerTransaction[];\n confirmed: ExplorerTransaction[];\n removed: ExplorerTransaction[];\n }\n >;\n}\n","import { hex } from \"@scure/base\";\nimport { Transaction } from \"@scure/btc-signer\";\nimport { TransactionInputUpdate } from \"@scure/btc-signer/psbt.js\";\n\nexport const ANCHOR_VALUE = 0n;\nexport const ANCHOR_PKSCRIPT = new Uint8Array([0x51, 0x02, 0x4e, 0x73]);\n\n/**\n * A zero-value anchor output.\n */\nexport const P2A = {\n script: ANCHOR_PKSCRIPT,\n amount: ANCHOR_VALUE,\n};\n\nconst hexP2Ascript = hex.encode(P2A.script);\n\n/**\n * search for anchor in the given transaction.\n * @throws {Error} if the anchor is not found or has the wrong amount\n */\nexport function findP2AOutput(tx: Transaction): TransactionInputUpdate {\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n if (output.script && hex.encode(output.script) === hexP2Ascript) {\n if (output.amount !== P2A.amount) {\n throw new Error(\n `P2A output has wrong amount, expected ${P2A.amount} got ${output.amount}`,\n );\n }\n\n return {\n txid: tx.id,\n index: i,\n witnessUtxo: P2A,\n };\n }\n }\n\n throw new Error(\"P2A output not found\");\n}\n\nexport interface AnchorBumper {\n // bumpP2A creates a new transaction spending the P2A output from the given transaction\n // it returns the package to broadcast [parent, child] in order to get the tx confirmed\n bumpP2A(parent: Transaction): Promise<[string, string]>;\n}\n","import { Transaction } from \"./utils/transaction\";\nimport { TransactionInputUpdate, TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport { P2A } from \"./utils/anchor\";\n\n/**\n * Build a forfeit transaction that spends the provided inputs to a single forfeit output.\n *\n * @param inputs - Inputs to include in the forfeit transaction\n * @param forfeitPkScript - ScriptPubKey for the forfeit output\n * @param txLocktime - Optional locktime to apply to the transaction\n */\nexport function buildForfeitTx(\n inputs: TransactionInputUpdate[],\n forfeitPkScript: Uint8Array,\n txLocktime?: number,\n): Transaction {\n let amount = 0n;\n for (const input of inputs) {\n if (!input.witnessUtxo) {\n throw new Error(\"input needs witness utxo\");\n }\n amount += input.witnessUtxo.amount;\n }\n\n return buildForfeitTxWithOutput(\n inputs,\n {\n script: forfeitPkScript,\n amount,\n },\n txLocktime,\n );\n}\n\n/**\n * Build a forfeit transaction using an explicit output descriptor (used for delegated renewals)\n *\n * @param inputs - Inputs to include in the forfeit transaction\n * @param output - Primary transaction output\n * @param txLocktime - Optional locktime to apply to the transaction\n */\nexport function buildForfeitTxWithOutput(\n inputs: TransactionInputUpdate[],\n output: TransactionOutput,\n txLocktime?: number,\n): Transaction {\n const tx = new Transaction({\n version: 3,\n lockTime: txLocktime,\n });\n for (const input of inputs) {\n tx.addInput(input);\n }\n tx.addOutput(output);\n tx.addOutput(P2A);\n return tx;\n}\n","import { hex } from \"@scure/base\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { base64 } from \"@scure/base\";\nimport { aggregateKeys } from \"../musig2\";\nimport { TxTree } from \"./txTree\";\nimport { CosignerPublicKey, getArkPsbtFields } from \"../utils/unknownFields\";\n\nexport const ErrInvalidSettlementTx = (tx: string) =>\n new Error(`invalid settlement transaction: ${tx}`);\nexport const ErrInvalidSettlementTxOutputs = new Error(\"invalid settlement transaction outputs\");\nexport const ErrEmptyTree = new Error(\"empty tree\");\nexport const ErrNumberOfInputs = new Error(\"invalid number of inputs\");\nexport const ErrWrongSettlementTxid = new Error(\"wrong settlement txid\");\nexport const ErrInvalidAmount = new Error(\"invalid amount\");\nexport const ErrNoLeaves = new Error(\"no leaves\");\nexport const ErrInvalidTaprootScript = new Error(\"invalid taproot script\");\nexport const ErrInvalidRoundTxOutputs = new Error(\"invalid round transaction outputs\");\nexport const ErrWrongCommitmentTxid = new Error(\"wrong commitment txid\");\nexport const ErrMissingCosignersPublicKeys = new Error(\"missing cosigners public keys\");\n\nconst BATCH_OUTPUT_VTXO_INDEX = 0;\nconst BATCH_OUTPUT_CONNECTORS_INDEX = 1;\n\nexport function validateConnectorsTxGraph(settlementTxB64: string, connectorsGraph: TxTree): void {\n connectorsGraph.validate();\n\n if (connectorsGraph.root.inputsLength !== 1) throw ErrNumberOfInputs;\n\n const rootInput = connectorsGraph.root.getInput(0);\n\n const settlementTx = Transaction.fromPSBT(base64.decode(settlementTxB64));\n if (settlementTx.outputsLength <= BATCH_OUTPUT_CONNECTORS_INDEX)\n throw ErrInvalidSettlementTxOutputs;\n\n const expectedRootTxid = settlementTx.id;\n\n if (!rootInput.txid) throw ErrWrongSettlementTxid;\n\n if (hex.encode(rootInput.txid) !== expectedRootTxid) throw ErrWrongSettlementTxid;\n\n if (rootInput.index !== BATCH_OUTPUT_CONNECTORS_INDEX) throw ErrWrongSettlementTxid;\n}\n\n// ValidateVtxoTxGraph checks if the given virtual output tx graph is valid.\n// The function validates:\n// - the number of nodes\n// - the number of leaves\n// - children coherence with parent.\n// - every control block and taproot output scripts.\n// - input and output amounts.\nexport function validateVtxoTxGraph(\n graph: TxTree,\n roundTransaction: Transaction,\n sweepTapTreeRoot: Uint8Array,\n): void {\n if (roundTransaction.outputsLength < BATCH_OUTPUT_VTXO_INDEX + 1) {\n throw ErrInvalidRoundTxOutputs;\n }\n\n const batchOutputAmount = roundTransaction.getOutput(BATCH_OUTPUT_VTXO_INDEX)?.amount;\n if (!batchOutputAmount) {\n throw ErrInvalidRoundTxOutputs;\n }\n\n if (!graph.root) {\n throw ErrEmptyTree;\n }\n\n const rootInput = graph.root.getInput(0);\n const commitmentTxid = roundTransaction.id;\n\n if (\n !rootInput.txid ||\n hex.encode(rootInput.txid) !== commitmentTxid ||\n rootInput.index !== BATCH_OUTPUT_VTXO_INDEX\n ) {\n throw ErrWrongCommitmentTxid;\n }\n\n let sumRootValue = 0n;\n for (let i = 0; i < graph.root.outputsLength; i++) {\n const output = graph.root.getOutput(i);\n if (output?.amount) {\n sumRootValue += output.amount;\n }\n }\n\n if (sumRootValue !== batchOutputAmount) {\n throw ErrInvalidAmount;\n }\n\n const leaves = graph.leaves();\n if (leaves.length === 0) {\n throw ErrNoLeaves;\n }\n\n // validate the graph structure\n graph.validate();\n\n // iterates over all the nodes of the graph to verify that cosigners public keys are corresponding to the parent output\n for (const g of graph.iterator()) {\n for (const [childIndex, child] of g.children) {\n const parentOutput = g.root.getOutput(childIndex);\n if (!parentOutput?.script) {\n throw new Error(`parent output ${childIndex} not found`);\n }\n\n const previousScriptKey = parentOutput.script.slice(2);\n if (previousScriptKey.length !== 32) {\n throw new Error(`parent output ${childIndex} has invalid script`);\n }\n\n const cosigners = getArkPsbtFields(child.root, 0, CosignerPublicKey);\n\n if (cosigners.length === 0) {\n throw ErrMissingCosignersPublicKeys;\n }\n\n const cosignerKeys = cosigners.map((c) => c.key);\n\n const { finalKey } = aggregateKeys(cosignerKeys, true, {\n taprootTweak: sweepTapTreeRoot,\n });\n\n if (!finalKey || hex.encode(finalKey.slice(1)) !== hex.encode(previousScriptKey)) {\n throw ErrInvalidTaprootScript;\n }\n }\n }\n}\n","/**\n * ExtensionPacket is the interface that all extension packets must implement.\n * It mirrors the Go extension.Packet interface.\n */\nexport interface ExtensionPacket {\n /** type returns the 1-byte packet type tag */\n type(): number;\n /** serialize returns the raw bytes of the packet (without type or length prefix) */\n serialize(): Uint8Array;\n}\n\n/**\n * UnknownPacket holds a packet whose type is not recognized by this implementation.\n * It round-trips opaquely: the raw bytes are preserved as-is.\n */\nexport class UnknownPacket implements ExtensionPacket {\n constructor(\n private readonly packetType: number,\n private readonly data: Uint8Array,\n ) {}\n\n type(): number {\n return this.packetType;\n }\n\n serialize(): Uint8Array {\n return this.data;\n }\n}\n","import { hex } from \"@scure/base\";\nimport { Script } from \"@scure/btc-signer\";\nimport { equalBytes } from \"@scure/btc-signer/utils.js\";\nimport { Packet } from \"./asset/packet\";\nimport { BufferReader } from \"./asset/utils\";\nimport { ExtensionPacket, UnknownPacket } from \"./packet\";\nimport type { TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport type { Transaction } from \"../utils/transaction\";\n\nexport type { ExtensionPacket } from \"./packet\";\nexport { UnknownPacket } from \"./packet\";\n\n/**\n * ArkadeMagic is the 3-byte magic prefix (\"ARK\") that identifies an OP_RETURN\n * output as an Arkade extension blob.\n */\nexport const ARKADE_MAGIC = new Uint8Array([0x41, 0x52, 0x4b]); // \"ARK\"\n\n/**\n * ErrExtensionNotFound is thrown when no extension output is found in a transaction.\n */\nexport class ExtensionNotFoundError extends Error {\n constructor() {\n super(\"no extension output found in transaction\");\n this.name = \"ExtensionNotFoundError\";\n }\n}\n\n/**\n * Extension is a set of typed packets encoded in an OP_RETURN output.\n *\n * Wire format:\n * OP_RETURN | <push> | ARK(3B) | [type(1B) | varint_len | data]...\n */\nexport class Extension {\n private constructor(private readonly packets: ExtensionPacket[]) {}\n\n static create(packets: ExtensionPacket[]): Extension {\n if (packets.length === 0) {\n throw new Error(\"missing packets\");\n }\n const seen = new Set<number>();\n for (const p of packets) {\n if (seen.has(p.type())) {\n throw new Error(`duplicate packet type ${p.type()}`);\n }\n seen.add(p.type());\n }\n return new Extension(packets);\n }\n\n /**\n * isExtension returns true if the script is an OP_RETURN whose push data\n * begins with the ARK magic bytes.\n */\n static isExtension(script: Uint8Array): boolean {\n try {\n const decoded = Script.decode(script);\n if (decoded.length < 2 || decoded[0] !== \"RETURN\") return false;\n const data = decoded[1];\n if (!(data instanceof Uint8Array)) return false;\n return (\n data.length >= ARKADE_MAGIC.length &&\n equalBytes(data.slice(0, ARKADE_MAGIC.length), ARKADE_MAGIC)\n );\n } catch {\n return false;\n }\n }\n\n /**\n * fromBytes parses an Extension from a raw OP_RETURN script.\n */\n static fromBytes(script: Uint8Array): Extension {\n if (!script || script.length === 0) {\n throw new Error(\"missing OP_RETURN\");\n }\n\n let decoded: ReturnType<typeof Script.decode>;\n try {\n decoded = Script.decode(script);\n } catch {\n throw new Error(\"expected OP_RETURN\");\n }\n\n if (decoded.length === 0 || decoded[0] !== \"RETURN\") {\n throw new Error(\"expected OP_RETURN\");\n }\n\n const dataPushes = decoded.slice(1).filter((x): x is Uint8Array => x instanceof Uint8Array);\n if (dataPushes.length === 0) {\n throw new Error(\"missing magic prefix: EOF\");\n }\n\n // Concatenate all data pushes (handles OP_PUSHDATA1/2/4)\n const payload = new Uint8Array(dataPushes.reduce((acc, d) => acc + d.length, 0));\n let offset = 0;\n for (const d of dataPushes) {\n payload.set(d, offset);\n offset += d.length;\n }\n\n // Check ARK magic\n if (\n payload.length < ARKADE_MAGIC.length ||\n !equalBytes(payload.slice(0, ARKADE_MAGIC.length), ARKADE_MAGIC)\n ) {\n throw new Error(\n `expected magic prefix ${hex.encode(ARKADE_MAGIC)}, got ${hex.encode(payload.slice(0, Math.min(payload.length, ARKADE_MAGIC.length)))}`,\n );\n }\n\n // Parse TLV records\n const reader = new BufferReader(payload.slice(ARKADE_MAGIC.length));\n const packets: ExtensionPacket[] = [];\n\n while (reader.remaining() > 0) {\n const packetType = reader.readByte();\n let data: Uint8Array;\n try {\n data = reader.readVarSlice();\n } catch {\n throw new Error(\"missing packet data\");\n }\n packets.push(parsePacket(packetType, data));\n }\n\n if (packets.length === 0) {\n throw new Error(\"missing packets\");\n }\n\n // Reject duplicate packet types\n const seen = new Set<number>();\n for (const p of packets) {\n if (seen.has(p.type())) {\n throw new Error(`duplicate packet type ${p.type()}`);\n }\n seen.add(p.type());\n }\n\n return new Extension(packets);\n }\n\n /**\n * fromTx searches the transaction outputs for an extension blob and parses it.\n * Throws ExtensionNotFoundError if none is found.\n */\n static fromTx(tx: Transaction): Extension {\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n if (!output?.script) continue;\n if (Extension.isExtension(output.script)) {\n return Extension.fromBytes(output.script);\n }\n }\n throw new ExtensionNotFoundError();\n }\n\n /**\n * serialize encodes the extension as an OP_RETURN script.\n *\n * Layout: OP_RETURN | <push> | ARK | [type | varint_len | data]...\n */\n serialize(): Uint8Array {\n // Build payload: ARK magic + TLV records\n const parts: Uint8Array[] = [ARKADE_MAGIC];\n\n for (const p of this.packets) {\n const data = p.serialize();\n // type (1 byte)\n const typeByte = new Uint8Array([p.type()]);\n // varint length prefix + data\n const lengthBuf = encodeVarUint(data.length);\n parts.push(typeByte, lengthBuf, data);\n }\n\n const totalLen = parts.reduce((acc, p) => acc + p.length, 0);\n const payload = new Uint8Array(totalLen);\n let off = 0;\n for (const p of parts) {\n payload.set(p, off);\n off += p.length;\n }\n\n return buildOpReturnScript(payload);\n }\n\n /**\n * txOut returns the extension as a zero-value OP_RETURN transaction output.\n */\n txOut(): Required<Pick<TransactionOutput, \"script\" | \"amount\">> {\n return {\n script: this.serialize(),\n amount: 0n,\n };\n }\n\n /**\n * getAssetPacket returns the embedded Packet, or null if not present.\n */\n getAssetPacket(): Packet | null {\n for (const p of this.packets) {\n if (p instanceof Packet) {\n return p;\n }\n }\n return null;\n }\n}\n\n/**\n * parsePacket dispatches to a known packet type or falls back to UnknownPacket.\n */\nfunction parsePacket(packetType: number, data: Uint8Array): ExtensionPacket {\n if (packetType === Packet.PACKET_TYPE) {\n return Packet.fromBytes(data);\n }\n return new UnknownPacket(packetType, data);\n}\n\n/**\n * encodeVarUint encodes a non-negative integer as a LEB128 unsigned varint.\n */\nfunction encodeVarUint(value: number): Uint8Array {\n const bytes: number[] = [];\n let remaining = value;\n do {\n let byte = remaining & 0x7f;\n remaining >>>= 7;\n if (remaining > 0) byte |= 0x80;\n bytes.push(byte);\n } while (remaining > 0);\n return new Uint8Array(bytes);\n}\n\n/**\n * buildOpReturnScript builds an OP_RETURN script with an arbitrary-length data push.\n * Manually constructed to avoid the 520-byte cap in some script builders.\n *\n * Opcodes: 0x6a=OP_RETURN, 0x4c=OP_PUSHDATA1, 0x4d=OP_PUSHDATA2, 0x4e=OP_PUSHDATA4\n */\nfunction buildOpReturnScript(data: Uint8Array): Uint8Array {\n const n = data.length;\n let script: Uint8Array;\n\n if (n <= 75) {\n script = new Uint8Array(2 + n);\n script[0] = 0x6a; // OP_RETURN\n script[1] = n;\n script.set(data, 2);\n } else if (n <= 255) {\n script = new Uint8Array(3 + n);\n script[0] = 0x6a;\n script[1] = 0x4c; // OP_PUSHDATA1\n script[2] = n;\n script.set(data, 3);\n } else if (n <= 65535) {\n script = new Uint8Array(4 + n);\n script[0] = 0x6a;\n script[1] = 0x4d; // OP_PUSHDATA2\n new DataView(script.buffer).setUint16(2, n, true);\n script.set(data, 4);\n } else {\n script = new Uint8Array(6 + n);\n script[0] = 0x6a;\n script[1] = 0x4e; // OP_PUSHDATA4\n new DataView(script.buffer).setUint32(2, n, true);\n script.set(data, 6);\n }\n\n return script;\n}\n","import { equalBytes } from \"@scure/btc-signer/utils.js\";\nimport { Recipient, Asset } from \".\";\nimport { ArkAddress } from \"../script/address\";\nimport { Transaction } from \"../utils/transaction\";\nimport { Packet } from \"../extension/asset\";\nimport { Extension } from \"../extension\";\nimport { Address, OutScript } from \"@scure/btc-signer\";\nimport type { Network } from \"../networks\";\n\nexport const ErrOffchainOutputNotFound = (address: string) =>\n new Error(`offchain send output not found: ${address}`);\nexport const ErrInvalidAssetOutputAmount = (got: bigint, want: bigint, assetId: string) =>\n new Error(`invalid asset output amount for ${assetId}: got ${got}, want ${want}`);\nexport const ErrAssetGroupNotFound = (assetId: string) =>\n new Error(`asset group not found in batch leaf: ${assetId}`);\nexport const ErrAssetOutputNotFound = (assetId: string, outputIndex: number) =>\n new Error(`asset output not found in asset group ${assetId} at index ${outputIndex}`);\nexport const ErrInvalidOnchainOutputAmount = (address: string) =>\n new Error(`invalid onchain output amount: ${address}`);\nexport const ErrInvalidOnchainOutputAssets = (address: string) =>\n new Error(`onchain output ${address} cannot have assets`);\nexport const ErrOnchainOutputNotFound = (address: string) =>\n new Error(`onchain output not found: ${address}`);\nexport const ErrInvalidOffchainOutputAmount = (address: string) =>\n new Error(`invalid offchain output ${address}, missing amount`);\n\n/**\n * Validates both offchain and onchain recipients.\n * Offchain recipients are checked against vtxo tree leaves for correct amounts and assets.\n * Onchain recipients are validated against the round transaction outputs (amounts and scripts)\n * via validateOnchainRecipient.\n *\n * @param commitmentTx - The commitment transaction to validate against\n * @param vtxoTreeLeaves - The vtxo tree leaves to validate against\n * @param recipients - The expected recipients to validate (both offchain and onchain)\n * @param network - Network for decoding onchain addresses (e.g. mainnet, testnet)\n * @throws {Error} if a recipient is not present or invalid in the vtxo tree or commitment tx\n */\nexport function validateBatchRecipients(\n commitmentTx: Transaction,\n vtxoTreeLeaves: Transaction[],\n recipients: Recipient[],\n network: Network,\n): void {\n // usedOutputs is used to track which outputs are validated to handle\n // duplicate recipients in the list\n const usedOutputs = new Set<string>();\n const usedOnchainOutputs = new Set<number>();\n for (const recipient of recipients) {\n let arkAddress: ArkAddress;\n try {\n arkAddress = ArkAddress.decode(recipient.address);\n } catch {\n validateOnchainRecipient(commitmentTx, recipient, network, usedOnchainOutputs);\n continue;\n }\n\n validateOffchainRecipient(vtxoTreeLeaves, arkAddress, recipient, usedOutputs);\n }\n}\n\n// validateOnchainRecipient verifies the given recipient is present in the commitment tx outputs list\nfunction validateOnchainRecipient(\n commitmentTx: Transaction,\n recipient: Recipient,\n network: Network,\n usedOutputs: Set<number>,\n): void {\n const addr = Address(network).decode(recipient.address);\n const expectedPkScript = OutScript.encode(addr);\n\n if (!recipient.amount) {\n throw ErrInvalidOnchainOutputAmount(recipient.address);\n }\n if (recipient.assets && recipient.assets.length > 0) {\n throw ErrInvalidOnchainOutputAssets(recipient.address);\n }\n\n for (let i = 0; i < commitmentTx.outputsLength; i++) {\n if (usedOutputs.has(i)) {\n continue;\n }\n\n const output = commitmentTx.getOutput(i);\n if (!output?.script || output.script.length === 0) {\n continue;\n }\n\n if (equalBytes(output.script, expectedPkScript)) {\n if (output.amount !== BigInt(recipient.amount)) {\n continue; // if amount does not match, continue\n }\n\n // we found the right output, recipient is valid, return\n usedOutputs.add(i);\n return;\n }\n }\n\n // if we get here, the recipient is not present in the commitment tx outputs list\n throw ErrOnchainOutputNotFound(recipient.address);\n}\n\n// validate the offchain recipient is present in one of the leaf output\n// also verify the asset packet is here, and point the same output index\nfunction validateOffchainRecipient(\n leaves: Transaction[],\n arkAddress: ArkAddress,\n recipient: Recipient,\n usedOutputs: Set<string>, // leafIndex:outputIndex\n): void {\n const expectedPkScript = arkAddress.pkScript;\n if (!recipient.amount) {\n throw ErrInvalidOffchainOutputAmount(recipient.address);\n }\n const expectedAmount = BigInt(recipient.amount);\n\n let found = false;\n\n for (let leafIdx = 0; leafIdx < leaves.length; leafIdx++) {\n const leaf = leaves[leafIdx];\n for (let outputIndex = 0; outputIndex < leaf.outputsLength; outputIndex++) {\n const output = leaf.getOutput(outputIndex);\n if (!output?.script || output.script.length === 0) {\n continue;\n }\n\n if (!equalBytes(output.script, expectedPkScript)) {\n continue;\n }\n\n if (output.amount !== expectedAmount) {\n continue;\n }\n\n const key = `${leafIdx}:${outputIndex}`;\n if (usedOutputs.has(key)) {\n continue;\n }\n\n usedOutputs.add(key);\n found = true;\n\n // if assets, validate the asset packet\n if (recipient.assets && recipient.assets.length > 0) {\n validateAssetOutputs(leaf, outputIndex, recipient.assets);\n }\n break;\n }\n\n if (found) {\n break;\n }\n }\n\n if (!found) {\n throw ErrOffchainOutputNotFound(recipient.address);\n }\n}\n\nfunction validateAssetOutputs(\n leafTx: Transaction,\n outputIndex: number,\n expectedAssets: Asset[],\n): void {\n const ext = Extension.fromTx(leafTx);\n const assetPacket = ext.getAssetPacket();\n if (!assetPacket) {\n throw new Error(\"no asset packet found in extension\");\n }\n\n for (const { assetId, amount } of expectedAssets) {\n validateAssetGroupOutput(assetPacket, outputIndex, assetId, amount);\n }\n}\n\nfunction validateAssetGroupOutput(\n packet: Packet,\n outputIndex: number,\n assetId: string,\n expectedAmount: bigint,\n): void {\n const assetGroup = packet.groups.find((group) => {\n if (group.isIssuance()) return false;\n return group.assetId!.toString() === assetId;\n });\n\n if (!assetGroup) {\n throw ErrAssetGroupNotFound(assetId);\n }\n\n // find the output at the expected index\n const assetOutput = assetGroup.outputs.find((output) => output.vout === outputIndex);\n\n if (!assetOutput) {\n throw ErrAssetOutputNotFound(assetId, outputIndex);\n }\n\n if (assetOutput.amount !== expectedAmount) {\n throw ErrInvalidAssetOutputAmount(assetOutput.amount, expectedAmount, assetId);\n }\n}\n","import { AssetGroup, AssetId, AssetRef, AssetInput, AssetOutput, Packet } from \"../extension/asset\";\nimport { Asset, ExtendedVirtualCoin, Recipient, VirtualCoin } from \"./index\";\n\n/**\n * Creates an asset packet from asset inputs and receivers.\n * Groups inputs and outputs by asset ID and creates the Packet object\n * @param assetInputs - map input index -> assets\n * @param receivers - array of recipients with their asset allocations\n * @param changeReceiver - (optional) change receiver containing remaining assets\n * @returns packet containing all asset groups\n */\nexport function createAssetPacket(\n assetInputs: Map<number, Asset[]>,\n receivers: Recipient[],\n changeReceiver?: Recipient,\n): Packet {\n // map inputs by asset id\n const inputsByAssetId = new Map<string, AssetInput[]>();\n\n for (const [inputIndex, assets] of assetInputs) {\n for (const asset of assets) {\n const existing = inputsByAssetId.get(asset.assetId);\n inputsByAssetId.set(asset.assetId, [\n ...(existing ?? []),\n AssetInput.create(inputIndex, asset.amount),\n ]);\n }\n }\n\n // map outputs by asset id\n const outputsByAssetId = new Map<string, AssetOutput[]>();\n\n // track tx output index\n let outputIndex = 0;\n\n for (const receiver of receivers) {\n if (receiver.assets) {\n for (const asset of receiver.assets) {\n const existing = outputsByAssetId.get(asset.assetId);\n outputsByAssetId.set(asset.assetId, [\n ...(existing ?? []),\n AssetOutput.create(outputIndex, asset.amount),\n ]);\n }\n }\n outputIndex++;\n }\n\n // add change receiver assets if present\n if (changeReceiver?.assets) {\n for (const asset of changeReceiver.assets) {\n const existing = outputsByAssetId.get(asset.assetId);\n outputsByAssetId.set(asset.assetId, [\n ...(existing ?? []),\n AssetOutput.create(outputIndex, asset.amount),\n ]);\n }\n }\n\n const groups: AssetGroup[] = [];\n\n // get all unique asset ids from both inputs and outputs\n const allAssetIds = new Set([...inputsByAssetId.keys(), ...outputsByAssetId.keys()]);\n\n for (const assetIdStr of allAssetIds) {\n const inputs = inputsByAssetId.get(assetIdStr);\n const outputs = outputsByAssetId.get(assetIdStr);\n\n const assetId = AssetId.fromString(assetIdStr);\n\n const group = AssetGroup.create(assetId, null, inputs ?? [], outputs ?? [], []);\n\n groups.push(group);\n }\n\n return Packet.create(groups);\n}\n\n/**\n * Selects coins that contain a specific asset.\n * Returns coins sorted by amount (smallest first for better coin selection).\n */\nexport function selectCoinsWithAsset(\n coins: ExtendedVirtualCoin[],\n assetId: string,\n requiredAmount: bigint,\n): { selected: ExtendedVirtualCoin[]; totalAssetAmount: bigint } {\n // filter only coins that have the specified asset\n const coinsWithAsset = coins.filter((coin) => coin.assets?.some((a) => a.assetId === assetId));\n\n // sort by asset amount (smallest first for better selection)\n coinsWithAsset.sort((a, b) => {\n const amountA = a.assets?.find((asset) => asset.assetId === assetId)?.amount ?? 0n;\n const amountB = b.assets?.find((asset) => asset.assetId === assetId)?.amount ?? 0n;\n // Array.sort callback returns number; reduce the bigint diff to\n // -1/0/1 (the only thing sort actually consults).\n return amountA < amountB ? -1 : amountA > amountB ? 1 : 0;\n });\n\n const selected: ExtendedVirtualCoin[] = [];\n let totalAssetAmount = 0n;\n\n for (const coin of coinsWithAsset) {\n if (totalAssetAmount >= requiredAmount) break;\n\n selected.push(coin);\n const assetAmount = coin.assets?.find((a) => a.assetId === assetId)?.amount ?? 0n;\n totalAssetAmount += assetAmount;\n }\n\n if (totalAssetAmount < requiredAmount) {\n throw new Error(\n `Insufficient asset balance: have ${totalAssetAmount}, need ${requiredAmount}`,\n );\n }\n\n return { selected, totalAssetAmount };\n}\n\nexport function computeAssetChange(\n inputAssets: Map<string, bigint>,\n outputAssets: Map<string, bigint>,\n): Map<string, bigint> {\n const change = new Map<string, bigint>();\n\n for (const [assetId, inputAmount] of inputAssets) {\n const outputAmount = outputAssets.get(assetId) ?? 0n;\n const changeAmount = inputAmount - outputAmount;\n if (changeAmount > 0n) {\n change.set(assetId, changeAmount);\n }\n }\n\n return change;\n}\n\nexport function selectedCoinsToAssetInputs(selectedCoins: VirtualCoin[]): Map<number, Asset[]> {\n const assetInputs = new Map<number, Asset[]>();\n\n for (let inputIndex = 0; inputIndex < selectedCoins.length; inputIndex++) {\n const coin = selectedCoins[inputIndex];\n if (!coin.assets || coin.assets.length === 0) {\n continue;\n }\n assetInputs.set(inputIndex, coin.assets);\n }\n\n return assetInputs;\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { hex } from \"@scure/base\";\nimport { DEFAULT_SEQUENCE, Script, SigHash } from \"@scure/btc-signer\";\nimport { tapLeafHash } from \"@scure/btc-signer/payment.js\";\nimport { TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport { ExtendedCoin, VirtualCoin } from \"../wallet\";\nimport { CLTVMultisigTapscript, decodeTapscript, RelativeTimelock } from \"../script/tapscript\";\nimport {\n EncodedVtxoScript,\n scriptFromTapLeafScript,\n TapLeafScript,\n VtxoScript,\n} from \"../script/base\";\nimport { P2A } from \"./anchor\";\nimport { CSVMultisigTapscript } from \"../script/tapscript\";\nimport { setArkPsbtField, VtxoTaprootTree } from \"./unknownFields\";\nimport { Transaction } from \"./transaction\";\nimport { ArkAddress } from \"../script/address\";\nimport { Extension } from \"../extension\";\n\nexport type ArkTxInput = {\n // the script used to spend the virtual output\n tapLeafScript: TapLeafScript;\n} & EncodedVtxoScript &\n Pick<VirtualCoin, \"txid\" | \"vout\" | \"value\">;\n\nexport type OffchainTx = {\n arkTx: Transaction;\n checkpoints: Transaction[];\n};\n\n/**\n * Builds an offchain transaction with checkpoint transactions.\n *\n * Creates one checkpoint transaction per input and a virtual transaction that\n * combines all the checkpoints, sending to the specified outputs. This is the\n * core function for creating Arkade transactions.\n *\n * @param inputs - Array of virtual transaction inputs\n * @param outputs - Array of transaction outputs\n * @param serverUnrollScript - Server unroll script for checkpoint transactions\n * @returns Object containing the virtual transaction and checkpoint transactions\n */\nexport function buildOffchainTx(\n inputs: ArkTxInput[],\n outputs: TransactionOutput[],\n serverUnrollScript: CSVMultisigTapscript.Type,\n): OffchainTx {\n // TODO: use arkd /info\n const MAX_OP_RETURN = 2;\n\n let countOpReturn = 0;\n let hasExtensionOutput = false;\n for (const [index, output] of outputs.entries()) {\n if (!output.script) throw new Error(`missing output script ${index}`);\n const isExtension = Extension.isExtension(output.script);\n const isOpReturn = isExtension || Script.decode(output.script)[0] === \"RETURN\";\n if (isOpReturn) {\n countOpReturn++;\n }\n if (!isExtension) continue;\n if (hasExtensionOutput) throw new Error(\"multiple extension outputs\");\n hasExtensionOutput = true;\n }\n\n if (countOpReturn > MAX_OP_RETURN) {\n throw new Error(`too many OP_RETURN outputs: ${countOpReturn} > ${MAX_OP_RETURN}`);\n }\n\n const checkpoints = inputs.map((input) => buildCheckpointTx(input, serverUnrollScript));\n\n const arkTx = buildVirtualTx(\n checkpoints.map((c) => c.input),\n outputs,\n );\n\n return {\n arkTx,\n checkpoints: checkpoints.map((c) => c.tx),\n };\n}\n\nfunction buildVirtualTx(inputs: ArkTxInput[], outputs: TransactionOutput[]) {\n let lockTime = 0n;\n for (const input of inputs) {\n const tapscript = decodeTapscript(scriptFromTapLeafScript(input.tapLeafScript));\n if (CLTVMultisigTapscript.is(tapscript)) {\n if (lockTime !== 0n) {\n // if a locktime is already set, check if the new locktime is in the same unit\n if (isSeconds(lockTime) !== isSeconds(tapscript.params.absoluteTimelock)) {\n throw new Error(\"cannot mix seconds and blocks locktime\");\n }\n }\n\n if (tapscript.params.absoluteTimelock > lockTime) {\n lockTime = tapscript.params.absoluteTimelock;\n }\n }\n }\n\n const tx = new Transaction({\n version: 3,\n lockTime: Number(lockTime),\n });\n\n for (const [i, input] of inputs.entries()) {\n tx.addInput({\n txid: input.txid,\n index: input.vout,\n sequence: lockTime ? DEFAULT_SEQUENCE - 1 : undefined,\n witnessUtxo: {\n script: VtxoScript.decode(input.tapTree).pkScript,\n amount: BigInt(input.value),\n },\n tapLeafScript: [input.tapLeafScript],\n });\n\n setArkPsbtField(tx, i, VtxoTaprootTree, input.tapTree);\n }\n\n for (const output of outputs) {\n tx.addOutput(output);\n }\n\n // add the anchor output\n tx.addOutput(P2A);\n\n return tx;\n}\n\nfunction buildCheckpointTx(\n vtxo: ArkTxInput,\n serverUnrollScript: CSVMultisigTapscript.Type,\n): { tx: Transaction; input: ArkTxInput } {\n // create the checkpoint virtual output script from collaborative closure\n const collaborativeClosure = decodeTapscript(scriptFromTapLeafScript(vtxo.tapLeafScript));\n\n // create the checkpoint virtual output script combining collaborative closure and server unroll script\n const checkpointVtxoScript = new VtxoScript([\n serverUnrollScript.script,\n collaborativeClosure.script,\n ]);\n\n // build the checkpoint virtual tx\n const checkpointTx = buildVirtualTx(\n [vtxo],\n [\n {\n amount: BigInt(vtxo.value),\n script: checkpointVtxoScript.pkScript,\n },\n ],\n );\n\n // get the collaborative leaf proof\n const collaborativeLeafProof = checkpointVtxoScript.findLeaf(\n hex.encode(collaborativeClosure.script),\n );\n\n // create the checkpoint input that will be used as input of the virtual tx\n const checkpointInput = {\n txid: checkpointTx.id,\n vout: 0,\n value: vtxo.value,\n tapLeafScript: collaborativeLeafProof,\n tapTree: checkpointVtxoScript.encode(),\n };\n\n return {\n tx: checkpointTx,\n input: checkpointInput,\n };\n}\n\nconst nLocktimeMinSeconds = 500_000_000n;\n\nfunction isSeconds(locktime: bigint): boolean {\n return locktime >= nLocktimeMinSeconds;\n}\n\nexport function hasBoardingTxExpired(\n coin: ExtendedCoin,\n boardingTimelock: RelativeTimelock,\n chainTipHeight?: number,\n) {\n if (!coin.status.block_time) return false;\n if (boardingTimelock.value === 0n) return true;\n\n if (boardingTimelock.type === \"blocks\") {\n if (chainTipHeight === undefined || !coin.status.block_height) return false;\n return BigInt(chainTipHeight - coin.status.block_height) >= boardingTimelock.value;\n }\n\n // validate expiry in terms of seconds\n const now = BigInt(Math.floor(Date.now() / 1000));\n const blockTime = BigInt(Math.floor(coin.status.block_time));\n return blockTime + boardingTimelock.value <= now;\n}\n\n/**\n * Formats a sighash type as a hex string (e.g., 0x01)\n */\nfunction formatSighash(type: number): string {\n return `0x${type.toString(16).padStart(2, \"0\")}`;\n}\n\n/**\n * Verify tapscript signatures on a transaction input\n * @param tx Transaction to verify\n * @param inputIndex Index of the input to verify\n * @param requiredSigners List of required signer pubkeys (hex encoded)\n * @param excludePubkeys List of pubkeys to exclude from verification (hex encoded, e.g., server key not yet signed)\n * @param allowedSighashTypes List of allowed sighash types (defaults to [SigHash.DEFAULT])\n * @throws Error if verification fails\n */\nexport function verifyTapscriptSignatures(\n tx: Transaction,\n inputIndex: number,\n requiredSigners: string[],\n excludePubkeys: string[] = [],\n allowedSighashTypes: number[] = [SigHash.DEFAULT],\n): void {\n const input = tx.getInput(inputIndex);\n\n // Collect prevout scripts and amounts for ALL inputs (required for preimageWitnessV1)\n const prevoutScripts: Uint8Array[] = [];\n const prevoutAmounts: bigint[] = [];\n\n for (let i = 0; i < tx.inputsLength; i++) {\n const inp = tx.getInput(i);\n if (!inp.witnessUtxo) {\n throw new Error(`Input ${i} is missing witnessUtxo`);\n }\n prevoutScripts.push(inp.witnessUtxo.script);\n prevoutAmounts.push(inp.witnessUtxo.amount);\n }\n\n // Verify tapScriptSig signatures\n if (!input.tapScriptSig || input.tapScriptSig.length === 0) {\n throw new Error(`Input ${inputIndex} is missing tapScriptSig`);\n }\n\n // Verify each signature in tapScriptSig\n for (const [tapScriptSigData, signature] of input.tapScriptSig) {\n const pubKey = tapScriptSigData.pubKey;\n const pubKeyHex = hex.encode(pubKey);\n\n // Skip verification for excluded pubkeys\n if (excludePubkeys.includes(pubKeyHex)) {\n continue;\n }\n\n // Extract sighash type from signature\n // Schnorr signatures are 64 bytes, with optional 1-byte sighash appended\n const sighashType = signature.length === 65 ? signature[64] : SigHash.DEFAULT;\n const sig = signature.subarray(0, 64);\n\n // Verify sighash type is allowed\n if (!allowedSighashTypes.includes(sighashType)) {\n const sighashName = formatSighash(sighashType);\n throw new Error(\n `Unallowed sighash type ${sighashName} for input ${inputIndex}, pubkey ${pubKeyHex}.`,\n );\n }\n\n // Find the tapLeafScript that matches this signature's leafHash\n if (!input.tapLeafScript || input.tapLeafScript.length === 0) {\n throw new Error();\n }\n\n // Search for the leaf that matches the leafHash in tapScriptSigData\n const leafHash = tapScriptSigData.leafHash;\n const leafHashHex = hex.encode(leafHash);\n let matchingScript: Uint8Array | undefined;\n let matchingVersion: number | undefined;\n\n for (const [_, scriptWithVersion] of input.tapLeafScript) {\n const script = scriptWithVersion.subarray(0, -1);\n const version = scriptWithVersion[scriptWithVersion.length - 1];\n\n // Compute the leaf hash for this script and compare as hex strings\n const computedLeafHash = tapLeafHash(script, version);\n const computedHex = hex.encode(computedLeafHash);\n\n if (computedHex === leafHashHex) {\n matchingScript = script;\n matchingVersion = version;\n break;\n }\n }\n\n if (!matchingScript || matchingVersion === undefined) {\n throw new Error(\n `Input ${inputIndex}: No tapLeafScript found matching leafHash ${hex.encode(leafHash)}`,\n );\n }\n\n // Reconstruct the message that was signed\n // Note: preimageWitnessV1 requires ALL input prevout scripts and amounts\n const message = tx.preimageWitnessV1(\n inputIndex,\n prevoutScripts,\n sighashType,\n prevoutAmounts,\n undefined,\n matchingScript,\n matchingVersion,\n );\n\n // Verify the schnorr signature\n const isValid = schnorr.verify(sig, message, pubKey);\n\n if (!isValid) {\n throw new Error(`Invalid signature for input ${inputIndex}, pubkey ${pubKeyHex}`);\n }\n }\n\n // Verify we have signatures from all required signers (excluding those we're skipping)\n const signedPubkeys = input.tapScriptSig.map(([data]) => hex.encode(data.pubKey));\n const requiredNotExcluded = requiredSigners.filter((pk) => !excludePubkeys.includes(pk));\n const missingSigners = requiredNotExcluded.filter((pk) => !signedPubkeys.includes(pk));\n\n if (missingSigners.length > 0) {\n throw new Error(\n `Missing signatures from: ${missingSigners.map((pk) => pk.slice(0, 16)).join(\", \")}...`,\n );\n }\n}\n\n/**\n * Merges the signed transaction with the original transaction\n * @param signedTx signed transaction\n * @param originalTx original transaction\n */\nexport function combineTapscriptSigs(signedTx: Transaction, originalTx: Transaction) {\n for (let i = 0; i < signedTx.inputsLength; i++) {\n const input = originalTx.getInput(i);\n const signedInput = signedTx.getInput(i);\n if (!input.tapScriptSig) throw new Error(\"No tapScriptSig\");\n originalTx.updateInput(i, {\n tapScriptSig: input.tapScriptSig?.concat(signedInput.tapScriptSig!),\n });\n }\n return originalTx;\n}\n\n/**\n * Validates if a given string is a valid Arkade address by attempting to decode it.\n * @param address The Arkade address to validate.\n * @returns True if the address is valid, false otherwise.\n */\nexport function isValidArkAddress(address: string): boolean {\n try {\n ArkAddress.decode(address);\n return true;\n } catch (e) {\n return false;\n }\n}\n","import { Address, OutScript } from \"@scure/btc-signer\";\nimport { Network } from \"../networks\";\n\nexport type VSize = {\n value: bigint;\n fee(feeRate: bigint): bigint;\n};\n\n/**\n * Calculates the byte size required to store a variable-length integer (VarInt).\n * Bitcoin uses VarInts to compact integer data (like array lengths).\n *\n * @param n - The integer value to check\n * @returns The size in bytes (1, 3, 5, or 9)\n */\nconst getVarIntSize = (n: number): number => {\n if (n < 0xfd) return 1;\n if (n <= 0xffff) return 3;\n if (n <= 0xffffffff) return 5;\n return 9;\n};\n\nexport class TxWeightEstimator {\n static readonly P2PKH_SCRIPT_SIG_SIZE = 1 + 73 + 1 + 33;\n static readonly INPUT_SIZE = 32 + 4 + 1 + 4;\n static readonly BASE_CONTROL_BLOCK_SIZE = 1 + 32;\n static readonly OUTPUT_SIZE = 8 + 1;\n static readonly P2WPKH_OUTPUT_SIZE = 1 + 1 + 20;\n static readonly BASE_TX_SIZE = 8 + 2; // Version + LockTime\n static readonly WITNESS_HEADER_SIZE = 2; // Flag + Marker\n static readonly WITNESS_SCALE_FACTOR = 4;\n static readonly P2TR_OUTPUT_SIZE = 1 + 1 + 32;\n\n public hasWitness: boolean;\n public inputCount: number;\n public outputCount: number;\n public inputSize: number;\n public inputWitnessSize: number;\n public outputSize: number;\n\n private constructor(\n hasWitness: boolean,\n inputCount: number,\n outputCount: number,\n inputSize: number,\n inputWitnessSize: number,\n outputSize: number,\n ) {\n this.hasWitness = hasWitness;\n this.inputCount = inputCount;\n this.outputCount = outputCount;\n this.inputSize = inputSize;\n this.inputWitnessSize = inputWitnessSize;\n this.outputSize = outputSize;\n }\n\n static create(): TxWeightEstimator {\n return new TxWeightEstimator(false, 0, 0, 0, 0, 0);\n }\n\n addP2AInput(): TxWeightEstimator {\n this.inputCount++;\n this.inputSize += TxWeightEstimator.INPUT_SIZE;\n return this;\n }\n\n addKeySpendInput(isDefault: boolean = true): TxWeightEstimator {\n this.inputCount++;\n this.inputWitnessSize += 64 + 1 + (isDefault ? 0 : 1);\n this.inputSize += TxWeightEstimator.INPUT_SIZE;\n this.hasWitness = true;\n return this;\n }\n\n addP2PKHInput(): TxWeightEstimator {\n this.inputCount++;\n this.inputWitnessSize++;\n this.inputSize += TxWeightEstimator.INPUT_SIZE + TxWeightEstimator.P2PKH_SCRIPT_SIG_SIZE;\n return this;\n }\n\n addTapscriptInput(\n leafWitnessSize: number,\n leafScriptSize: number,\n leafControlBlockSize: number,\n ): TxWeightEstimator {\n const controlBlockWitnessSize =\n 1 +\n TxWeightEstimator.BASE_CONTROL_BLOCK_SIZE +\n 1 +\n leafScriptSize +\n 1 +\n leafControlBlockSize;\n\n this.inputCount++;\n this.inputWitnessSize += leafWitnessSize + 1 + controlBlockWitnessSize;\n this.inputSize += TxWeightEstimator.INPUT_SIZE;\n this.hasWitness = true;\n return this;\n }\n\n addP2WPKHOutput(): TxWeightEstimator {\n this.outputCount++;\n this.outputSize += TxWeightEstimator.OUTPUT_SIZE + TxWeightEstimator.P2WPKH_OUTPUT_SIZE;\n return this;\n }\n\n addP2TROutput(): TxWeightEstimator {\n this.outputCount++;\n this.outputSize += TxWeightEstimator.OUTPUT_SIZE + TxWeightEstimator.P2TR_OUTPUT_SIZE;\n return this;\n }\n\n /**\n * Adds an output given a raw script.\n * Cost = 8 bytes (amount) + varint(scriptLen) + scriptLen\n */\n addOutputScript(script: Uint8Array): TxWeightEstimator {\n this.outputCount++;\n this.outputSize += 8 + getVarIntSize(script.length) + script.length;\n return this;\n }\n\n /**\n * Adds an output by decoding the address to get the exact script size.\n */\n addOutputAddress(address: string, network: Network): TxWeightEstimator {\n const payment = Address(network).decode(address);\n const script = OutScript.encode(payment);\n return this.addOutputScript(script);\n }\n\n vsize(): VSize {\n const inputCount = getVarIntSize(this.inputCount);\n const outputCount = getVarIntSize(this.outputCount);\n\n // Calculate the size of the transaction without witness data\n const txSizeStripped =\n TxWeightEstimator.BASE_TX_SIZE +\n inputCount +\n this.inputSize +\n outputCount +\n this.outputSize;\n\n // Calculate the total weight\n let weight = txSizeStripped * TxWeightEstimator.WITNESS_SCALE_FACTOR;\n\n // Add witness data if present\n if (this.hasWitness) {\n weight += TxWeightEstimator.WITNESS_HEADER_SIZE + this.inputWitnessSize;\n }\n\n // Convert weight to vsize (weight / 4, rounded up)\n return vsize(weight);\n }\n}\n\nconst vsize = (weight: number): VSize => {\n const value = BigInt(Math.ceil(weight / TxWeightEstimator.WITNESS_SCALE_FACTOR));\n return {\n value,\n fee: (feeRate: bigint) => feeRate * value,\n };\n};\n","import { Environment } from \"@marcbachmann/cel-js\";\n\n/**\n * Variable names used in CEL expressions\n */\nexport const AmountVariableName = \"amount\";\nexport const ExpiryVariableName = \"expiry\";\nexport const BirthVariableName = \"birth\";\nexport const WeightVariableName = \"weight\";\nexport const InputTypeVariableName = \"inputType\";\nexport const OutputScriptVariableName = \"script\";\n\nconst nowFunction = {\n signature: \"now(): double\",\n implementation: () => Math.floor(Date.now() / 1000),\n};\n\n/**\n * IntentOutputEnv is the CEL environment for output fee calculation\n * Variables: amount, script\n */\nexport const IntentOutputEnv = new Environment()\n .registerVariable(AmountVariableName, \"double\")\n .registerVariable(OutputScriptVariableName, \"string\")\n .registerFunction(nowFunction.signature, nowFunction.implementation);\n\n/**\n * IntentOffchainInputEnv is the CEL environment for offchain input fee calculation\n * Variables: amount, expiry, birth, weight, inputType\n */\nexport const IntentOffchainInputEnv = new Environment()\n .registerVariable(AmountVariableName, \"double\")\n .registerVariable(ExpiryVariableName, \"double\")\n .registerVariable(BirthVariableName, \"double\")\n .registerVariable(WeightVariableName, \"double\")\n .registerVariable(InputTypeVariableName, \"string\")\n .registerFunction(nowFunction.signature, nowFunction.implementation);\n\n/**\n * IntentOnchainInputEnv is the CEL environment for onchain input fee calculation\n * Variables: amount\n */\nexport const IntentOnchainInputEnv = new Environment()\n .registerVariable(AmountVariableName, \"double\")\n .registerFunction(nowFunction.signature, nowFunction.implementation);\n","/**\n * FeeAmount is a wrapper around a number that represents a fee amount in satoshis floating point.\n * @param value - The fee amount in floating point.\n * @example\n * const fee = new FeeAmount(1.23456789);\n * console.log(fee.value); // 1.23456789\n * console.log(fee.satoshis); // 2\n */\nexport class FeeAmount {\n static ZERO = new FeeAmount(0);\n\n constructor(readonly value: number) {}\n\n /** Returns the fee amount rounded up to whole satoshis. */\n get satoshis(): number {\n return this.value ? Math.ceil(this.value) : 0;\n }\n\n /** Add two fee amounts together. */\n add(other: FeeAmount): FeeAmount {\n return new FeeAmount(this.value + other.value);\n }\n}\n\nexport interface IntentFeeConfig {\n offchainInput?: string;\n onchainInput?: string;\n offchainOutput?: string;\n onchainOutput?: string;\n}\n\nexport type VtxoType = \"recoverable\" | \"vtxo\" | \"note\";\n\nexport interface OffchainInput {\n amount: bigint;\n expiry?: Date;\n birth?: Date;\n type: VtxoType;\n weight: number;\n}\n\nexport interface OnchainInput {\n amount: bigint;\n}\n\nexport interface FeeOutput {\n amount: bigint;\n script: string;\n}\n","import { Environment, ParseResult } from \"@marcbachmann/cel-js\";\nimport { IntentOffchainInputEnv, IntentOnchainInputEnv, IntentOutputEnv } from \"./celenv.js\";\nimport { IntentFeeConfig, OffchainInput, OnchainInput, FeeOutput, FeeAmount } from \"./types.js\";\n\ninterface Program {\n program: ParseResult;\n text: string;\n}\n\n/**\n * Estimator evaluates CEL expressions to calculate fees for Arkade intents\n */\nexport class Estimator {\n private intentOffchainInput?: Program;\n private intentOnchainInput?: Program;\n private intentOffchainOutput?: Program;\n private intentOnchainOutput?: Program;\n\n /**\n * Creates a new Estimator with the given config\n * @param config - Configuration containing CEL programs for fee calculation\n */\n constructor(readonly config: IntentFeeConfig) {\n this.intentOffchainInput = config.offchainInput\n ? parseProgram(config.offchainInput, IntentOffchainInputEnv)\n : undefined;\n\n this.intentOnchainInput = config.onchainInput\n ? parseProgram(config.onchainInput, IntentOnchainInputEnv)\n : undefined;\n\n this.intentOffchainOutput = config.offchainOutput\n ? parseProgram(config.offchainOutput, IntentOutputEnv)\n : undefined;\n this.intentOnchainOutput = config.onchainOutput\n ? parseProgram(config.onchainOutput, IntentOutputEnv)\n : undefined;\n }\n\n /**\n * Evaluates the fee for a given vtxo input\n * @param input - The offchain input to evaluate\n * @returns The fee amount for this input\n */\n evalOffchainInput(input: OffchainInput): FeeAmount {\n if (!this.intentOffchainInput) {\n return FeeAmount.ZERO;\n }\n\n const args = inputToArgs(input);\n return new FeeAmount(this.intentOffchainInput.program(args));\n }\n\n /**\n * Evaluates the fee for a given boarding input\n * @param input - The onchain input to evaluate\n * @returns The fee amount for this input\n */\n evalOnchainInput(input: OnchainInput): FeeAmount {\n if (!this.intentOnchainInput) {\n return FeeAmount.ZERO;\n }\n\n const args = {\n amount: Number(input.amount),\n };\n return new FeeAmount(this.intentOnchainInput.program(args));\n }\n\n /**\n * Evaluates the fee for a given vtxo output\n * @param output - The output to evaluate\n * @returns The fee amount for this output\n */\n evalOffchainOutput(output: FeeOutput): FeeAmount {\n if (!this.intentOffchainOutput) {\n return FeeAmount.ZERO;\n }\n\n const args = outputToArgs(output);\n return new FeeAmount(this.intentOffchainOutput.program(args));\n }\n\n /**\n * Evaluates the fee for a given collaborative exit output\n * @param output - The output to evaluate\n * @returns The fee amount for this output\n */\n evalOnchainOutput(output: FeeOutput): FeeAmount {\n if (!this.intentOnchainOutput) {\n return FeeAmount.ZERO;\n }\n\n const args = outputToArgs(output);\n return new FeeAmount(this.intentOnchainOutput.program(args));\n }\n\n /**\n * Evaluates the fee for a given set of inputs and outputs\n * @param offchainInputs - Array of offchain inputs to evaluate\n * @param onchainInputs - Array of onchain inputs to evaluate\n * @param offchainOutputs - Array of offchain outputs to evaluate\n * @param onchainOutputs - Array of onchain outputs to evaluate\n * @returns The total fee amount\n */\n eval(\n offchainInputs: OffchainInput[],\n onchainInputs: OnchainInput[],\n offchainOutputs: FeeOutput[],\n onchainOutputs: FeeOutput[],\n ): FeeAmount {\n let fee = FeeAmount.ZERO;\n\n for (const input of offchainInputs) {\n fee = fee.add(this.evalOffchainInput(input));\n }\n\n for (const input of onchainInputs) {\n fee = fee.add(this.evalOnchainInput(input));\n }\n\n for (const output of offchainOutputs) {\n fee = fee.add(this.evalOffchainOutput(output));\n }\n\n for (const output of onchainOutputs) {\n fee = fee.add(this.evalOnchainOutput(output));\n }\n\n return fee;\n }\n}\n\nfunction inputToArgs(input: OffchainInput): Record<string, any> {\n const args: Record<string, any> = {\n amount: Number(input.amount),\n inputType: input.type,\n weight: input.weight,\n };\n\n if (input.expiry) {\n args.expiry = Math.floor(input.expiry.getTime() / 1000);\n }\n\n if (input.birth) {\n args.birth = Math.floor(input.birth.getTime() / 1000);\n }\n\n return args;\n}\n\nfunction outputToArgs(output: FeeOutput): Record<string, any> {\n return {\n amount: Number(output.amount),\n script: output.script,\n };\n}\n\n/**\n * Parses a CEL program and validates its return type\n * @param text - The CEL program text to parse\n * @param env - The CEL environment to use\n * @returns parsed and validated program\n */\nfunction parseProgram(text: string, env: Environment): Program {\n const program = env.parse(text);\n\n // Type check the program\n const checkResult = program.check();\n if (!checkResult.valid) {\n throw new Error(`type check failed: ${checkResult.error?.message ?? \"unknown error\"}`);\n }\n\n // Verify return type is double\n if (checkResult.type !== \"double\") {\n throw new Error(`expected return type double, got ${checkResult.type}`);\n }\n\n return { program, text };\n}\n","import {\n ExtendedCoin,\n ExtendedVirtualCoin,\n IWallet,\n IReadonlyWallet,\n isExpired,\n isRecoverable,\n isSpendable,\n isSubdust,\n Outpoint,\n} from \".\";\nimport { ArkProvider, SettlementEvent } from \"../providers/ark\";\nimport { maybeArkError } from \"../providers/errors\";\nimport { hasBoardingTxExpired } from \"../utils/arkTransaction\";\nimport { CSVMultisigTapscript } from \"../script/tapscript\";\nimport { hex } from \"@scure/base\";\nimport { getSequence } from \"../script/base\";\nimport { Transaction } from \"../utils/transaction\";\nimport { TxWeightEstimator } from \"../utils/txSizeEstimator\";\nimport { Estimator } from \"../arkfee\";\nimport { ArkAddress } from \"../script/address\";\nimport type { OnchainProvider } from \"../providers/onchain\";\nimport type { Network } from \"../networks\";\nimport type { DefaultVtxo } from \"../script/default\";\n\n/**\n * Extended wallet interface for boarding input sweep operations.\n * These properties exist on the concrete Wallet class but not on IWallet.\n */\ninterface SweepCapableWallet extends IReadonlyWallet {\n boardingTapscript: DefaultVtxo.Script;\n onchainProvider: OnchainProvider;\n arkProvider: ArkProvider;\n network: Network;\n}\n\n/**\n * Return whether a wallet exposes the properties required for boarding input sweep operations.\n *\n * @param wallet - Wallet to inspect\n * @returns `true` when the wallet supports boarding input sweep operations.\n */\nfunction isSweepCapable(wallet: IWallet): wallet is IWallet & SweepCapableWallet {\n return (\n \"boardingTapscript\" in wallet &&\n \"onchainProvider\" in wallet &&\n \"arkProvider\" in wallet &&\n \"network\" in wallet\n );\n}\n\n/**\n * Assert that the wallet supports boarding input sweep operations.\n *\n * @param wallet - Wallet to inspect\n * @throws Error if the wallet does not support boarding input sweep operations.\n */\nfunction assertSweepCapable(wallet: IWallet): asserts wallet is IWallet & SweepCapableWallet {\n if (!isSweepCapable(wallet)) {\n throw new Error(\n \"Boarding UTXO sweep requires a Wallet instance with boardingTapscript, onchainProvider, arkProvider, and network\",\n );\n }\n}\n\n/**\n * Web Locks name used to serialize boarding-poll work across same-origin\n * browser contexts (tabs, service worker). Static because the goal is to\n * deduplicate polls for the *same* wallet — two distinct wallets on the\n * same origin will take turns, which is acceptable.\n */\nconst BOARDING_POLL_LOCK_NAME = \"arkade-boarding-poll\";\n\n/**\n * Run `fn` under an exclusive Web Lock when the runtime provides one\n * (browser main thread, service worker). In environments without\n * `navigator.locks` (Node, React Native) the callback runs immediately\n * with no coordination.\n *\n * Uses `ifAvailable: true`: if another context already holds the lock,\n * skip this cycle entirely rather than queueing — the other context will\n * do the work and the next poll will re-check.\n */\nasync function runWithCrossInstanceLock(name: string, fn: () => Promise<void>): Promise<void> {\n const locks =\n typeof globalThis !== \"undefined\" && typeof globalThis.navigator !== \"undefined\"\n ? globalThis.navigator.locks\n : undefined;\n if (!locks) {\n await fn();\n return;\n }\n await locks.request(name, { ifAvailable: true, mode: \"exclusive\" }, async (lock) => {\n if (lock === null) return;\n await fn();\n });\n}\n\n/** Default renewal threshold in seconds (3 days). */\nexport const DEFAULT_THRESHOLD_SECONDS = 3 * 24 * 60 * 60;\n\n/**\n * Default renewal threshold in milliseconds (3 days).\n */\nexport const DEFAULT_THRESHOLD_MS = DEFAULT_THRESHOLD_SECONDS * 1000;\n\n/**\n * Configuration options for automatic virtual output renewal\n *\n * @see DEFAULT_RENEWAL_CONFIG\n * @deprecated Leave `renewalConfig` undefined and use `settlementConfig` instead.\n * @see SettlementConfig\n */\nexport interface RenewalConfig {\n /**\n * Enable automatic renewal monitoring\n *\n * @defaultValue `false`\n * @deprecated Explicitly set `settlementConfig` to `false` to disable VTXO renewal.\n */\n enabled?: boolean;\n\n /**\n * Threshold in milliseconds to use as threshold for renewal\n * E.g., 86_400_000 means renew when 24 hours until expiry remains\n *\n * @defaultValue `259_200_000` (3 days).\n * @deprecated Use `SettlementConfig.vtxoThreshold` (in seconds) instead.\n */\n thresholdMs?: number;\n}\n\n/**\n * Configuration for automatic settlement and renewal.\n *\n * Controls two behaviors:\n * 1. **VTXO renewal**: Automatically renew virtual outputs that are close to expiry\n * 2. **Boarding UTXO sweep**: Sweep expired boarding inputs back to a fresh boarding address\n * via the unilateral exit path (onchain self-spend to restart the timelock)\n *\n * Enabled by default when no config is provided.\n * Pass `false` to explicitly disable all settlement behavior.\n *\n * @remarks\n * VTXO renewal and boarding UTXO sweep are both coordinated by `VtxoManager`, which periodically\n * inspects wallet virtual outputs and boarding inputs and decides whether action is needed.\n *\n * @see DEFAULT_SETTLEMENT_CONFIG\n *\n * @example\n * ```typescript\n * // Default behavior: virtual output renewal at 3 days, boarding sweep enabled, polling every minute\n * const wallet = await Wallet.create({\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),\n * arkServerUrl: 'https://arkade.computer',\n * });\n *\n * // Custom expiry threshold of 24 hours\n * const wallet = await Wallet.create({\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: {\n * vtxoThreshold: 60 * 60 * 24, // 24 hours in seconds\n * },\n * });\n *\n * // Explicitly disable\n * const wallet = await Wallet.create({\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: false,\n * });\n * ```\n */\nexport interface SettlementConfig {\n /**\n * Seconds before virtual output expiry to trigger renewal.\n *\n * @defaultValue `259_200` (3 days)\n */\n vtxoThreshold?: number;\n\n /**\n * Sweep expired boarding inputs back to a fresh boarding address\n * via the unilateral exit path (onchain self-spend to restart the timelock).\n *\n * When enabled, expired boarding inputs are batched into a single onchain\n * transaction with multiple inputs and one output.\n *\n * A dust check ensures the sweep is only performed when the output\n * after fees is above dust.\n *\n * @defaultValue `true`\n */\n boardingUtxoSweep?: boolean;\n\n /**\n * Polling interval in milliseconds for checking boarding inputs.\n * The poll loop auto-settles new boarding inputs into Arkade and\n * sweeps expired ones (when boardingUtxoSweep is enabled).\n *\n * @defaultValue `60_000` (1 minute)\n */\n pollIntervalMs?: number;\n}\n\n/**\n * Default renewal configuration values.\n *\n * @see RenewalConfig\n * @deprecated Leave `renewalConfig` undefined and use `settlementConfig` instead.\n * @see SettlementConfig\n */\nexport const DEFAULT_RENEWAL_CONFIG: Required<Omit<RenewalConfig, \"enabled\">> = {\n thresholdMs: DEFAULT_THRESHOLD_MS, // 3 days\n};\n\n/**\n * Default settlement configuration values.\n *\n * @see SettlementConfig\n *\n * @example\n * ```typescript\n * const wallet = await Wallet.create({\n * identity,\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: DEFAULT_SETTLEMENT_CONFIG,\n * })\n * ```\n */\nexport const DEFAULT_SETTLEMENT_CONFIG: Required<SettlementConfig> = {\n vtxoThreshold: DEFAULT_THRESHOLD_SECONDS,\n boardingUtxoSweep: true,\n pollIntervalMs: 60_000,\n};\n\n/** Extracts the dust amount from the wallet, defaulting to 330 sats. */\nfunction getDustAmount(wallet: IWallet): bigint {\n return \"dustAmount\" in wallet ? (wallet.dustAmount as bigint) : 330n;\n}\n\n/**\n * Filter virtual outputs that are recoverable (swept and still spendable, or preconfirmed subdust)\n *\n * Recovery strategy:\n * - Always recover swept virtual outputs (they've been taken by the server)\n * - Only recover subdust preconfirmed virtual outputs (to avoid locking liquidity on settled virtual outputs with long expiry)\n *\n * @param vtxos - Array of virtual outputs to check\n * @param dustAmount - Dust threshold to identify subdust\n * @returns Array of recoverable virtual outputs\n */\nfunction getRecoverableVtxos(\n vtxos: ExtendedVirtualCoin[],\n dustAmount: bigint,\n): ExtendedVirtualCoin[] {\n return vtxos.filter((vtxo) => {\n // Always recover swept virtual outputs\n if (isRecoverable(vtxo)) {\n return true;\n }\n\n // also include virtual outputs that are not swept but expired\n if (isSpendable(vtxo) && isExpired(vtxo)) {\n return true;\n }\n\n // Recover preconfirmed subdust to consolidate small amounts\n if (vtxo.virtualStatus.state === \"preconfirmed\" && isSubdust(vtxo, dustAmount)) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Get recoverable virtual outputs including subdust outputs if the total value exceeds dust threshold.\n *\n * Decision is based on the combined total of ALL recoverable virtual outputs (regular + subdust),\n * not just the subdust portion alone.\n *\n * @param vtxos - Array of virtual outputs to check\n * @param dustAmount - Dust threshold amount in satoshis\n * @returns Object containing recoverable virtual outputs and whether subdust should be included\n */\nfunction getRecoverableWithSubdust(\n vtxos: ExtendedVirtualCoin[],\n dustAmount: bigint,\n): {\n vtxosToRecover: ExtendedVirtualCoin[];\n includesSubdust: boolean;\n totalAmount: bigint;\n} {\n const recoverableVtxos = getRecoverableVtxos(vtxos, dustAmount);\n\n // Separate subdust from regular recoverable\n const subdust: ExtendedVirtualCoin[] = [];\n const regular: ExtendedVirtualCoin[] = [];\n\n for (const vtxo of recoverableVtxos) {\n if (isSubdust(vtxo, dustAmount)) {\n subdust.push(vtxo);\n } else {\n regular.push(vtxo);\n }\n }\n\n // Calculate totals\n const regularTotal = regular.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);\n const subdustTotal = subdust.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);\n const combinedTotal = regularTotal + subdustTotal;\n\n // Include subdust only if the combined total exceeds dust threshold\n const shouldIncludeSubdust = combinedTotal >= dustAmount;\n const vtxosToRecover = shouldIncludeSubdust ? recoverableVtxos : regular;\n\n const totalAmount = vtxosToRecover.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);\n\n return {\n vtxosToRecover,\n includesSubdust: shouldIncludeSubdust,\n totalAmount,\n };\n}\n\n/**\n * Check if a virtual output is expiring soon based on threshold\n *\n * @param vtxo - The virtual output to check\n * @param thresholdMs - Threshold in milliseconds from now\n * @returns true if virtual output expires within threshold, false otherwise\n */\nexport function isVtxoExpiringSoon(\n vtxo: ExtendedVirtualCoin,\n thresholdMs: number, // in milliseconds\n): boolean {\n const realThresholdMs = thresholdMs <= 100 ? DEFAULT_THRESHOLD_MS : thresholdMs;\n\n const { batchExpiry } = vtxo.virtualStatus;\n\n if (!batchExpiry) return false; // it doesn't expire\n\n // we use this as a workaround to avoid issue on regtest where expiry date is\n // expressed in blockheight instead of timestamp. If expiry, as Date, is before 2025,\n // then we admit it's too small to be a timestamp\n // TODO: API should return the expiry unit\n const expireAt = new Date(batchExpiry);\n if (expireAt.getFullYear() < 2025) return false;\n\n const now = Date.now();\n\n if (batchExpiry <= now) return false; // already expired\n\n return batchExpiry - now <= realThresholdMs;\n}\n\n/**\n * Filter virtual outputs that are expiring soon or are recoverable/subdust\n *\n * @param vtxos - Array of virtual outputs to check\n * @param thresholdMs - Threshold in milliseconds from now\n * @param dustAmount - Dust threshold amount in satoshis\n * @returns Array of virtual outputs expiring within threshold\n */\nexport function getExpiringAndRecoverableVtxos(\n vtxos: ExtendedVirtualCoin[],\n thresholdMs: number,\n dustAmount: bigint,\n): ExtendedVirtualCoin[] {\n return vtxos.filter(\n (vtxo) =>\n isVtxoExpiringSoon(vtxo, thresholdMs) ||\n isRecoverable(vtxo) ||\n (isSpendable(vtxo) && isExpired(vtxo)) ||\n isSubdust(vtxo, dustAmount),\n );\n}\n\n/**\n * VtxoManager is a unified class for managing virtual output lifecycle operations including\n * recovery of swept/expired virtual outputs and renewal to prevent expiration.\n *\n * Key Features:\n * - **Recovery**: Reclaim swept or expired virtual outputs back to the wallet\n * - **Renewal**: Refresh virtual output expiration time before they expire\n * - **Smart subdust handling**: Automatically includes subdust virtual outputs when economically viable\n * - **Expiry monitoring**: Check for virtual outputs that are expiring soon\n *\n * Virtual outputs become recoverable when:\n * - The Arkade server sweeps them (virtualStatus.state === \"swept\") and they remain spendable\n * - They are preconfirmed subdust (to consolidate small amounts without locking liquidity on settled virtual outputs)\n *\n * @example\n * ```typescript\n * const wallet = await Wallet.create({\n * identity,\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: {\n * // Seconds before virtual output expiry to trigger renewal\n * vtxoThreshold: 259_200, // 3 days\n * // Whether to sweep expired boarding inputs back to a fresh boarding address\n * boardingUtxoSweep: true,\n * // Polling interval in milliseconds for checking boarding inputs\n * pollIntervalMs: 60_000 // 1 minute\n * },\n * });\n * const manager = await wallet.getVtxoManager();\n *\n * // Check recoverable balance\n * const balance = await manager.getRecoverableBalance();\n * if (balance.recoverable > 0n) {\n * console.log(`Can recover ${balance.recoverable} sats`);\n * const txid = await manager.recoverVtxos();\n * }\n *\n * // Check for expiring virtual outputs\n * const expiring = await manager.getExpiringVtxos();\n * if (expiring.length > 0) {\n * console.log(`${expiring.length} virtual outputs expiring soon`);\n * const txid = await manager.renewVtxos();\n * }\n * ```\n */\nexport interface IVtxoManager {\n recoverVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string>;\n\n getRecoverableBalance(): Promise<{\n recoverable: bigint;\n subdust: bigint;\n includesSubdust: boolean;\n vtxoCount: number;\n }>;\n\n getExpiringVtxos(thresholdMs?: number): Promise<ExtendedVirtualCoin[]>;\n\n renewVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string>;\n\n getExpiredBoardingUtxos(): Promise<ExtendedCoin[]>;\n\n sweepExpiredBoardingUtxos(): Promise<string>;\n\n dispose(): Promise<void>;\n}\n\nexport class VtxoManager implements AsyncDisposable, IVtxoManager {\n readonly settlementConfig: SettlementConfig | false;\n private contractEventsSubscription?: () => void;\n private readonly contractEventsSubscriptionReady: Promise<(() => void) | undefined>;\n private disposePromise?: Promise<void>;\n private pollTimeoutId?: ReturnType<typeof setTimeout>;\n private knownBoardingUtxos = new Set<string>();\n private sweptBoardingUtxos = new Set<string>();\n private pollInProgress = false;\n private pollDone?: { promise: Promise<void>; resolve: () => void };\n private disposed = false;\n private consecutivePollFailures = 0;\n private startupPollTimeoutId?: ReturnType<typeof setTimeout>;\n private static readonly MAX_BACKOFF_MS = 5 * 60 * 1000; // 5 minutes\n\n // Guards against renewal feedback loop: when renewVtxos() settles, the\n // server emits new VTXOs → vtxo_received → renewVtxos() again → infinite loop.\n private renewalInProgress = false;\n private lastRenewalTimestamp = 0;\n private static readonly RENEWAL_COOLDOWN_MS = 30_000; // 30 seconds\n\n // Guards against a retry treadmill on the periodic-settle path: a failing\n // settle would otherwise re-submit identical intents on every 60s poll,\n // producing per-minute DeleteIntent RPCs forever. Mirrors the renewal\n // cooldown but with exponential backoff on consecutive failures, so a\n // persistently broken input eventually drops to the backoff cap instead\n // of hammering the server. Shared across boarding + expiring-VTXO work\n // because they now ride on the same settle intent.\n private lastPeriodicSettleTimestamp = 0;\n private consecutivePeriodicSettleFailures = 0;\n private static readonly PERIODIC_SETTLE_COOLDOWN_MS = 30_000;\n private static readonly PERIODIC_SETTLE_MAX_BACKOFF_MS = 5 * 60 * 1000;\n\n // Throttle for the VTXO_ALREADY_SPENT -> refreshVtxos() reconciliation.\n // The server's authoritative view says our local cache is stale, so we\n // trigger a full refresh to advance the global sync cursor. Rate-limit\n // to guard against a buggy indexer cycling us into a refresh storm.\n private lastVtxoSpentRefreshTimestamp = 0;\n private vtxoSpentRefreshPromise?: Promise<void>;\n private static readonly VTXO_SPENT_REFRESH_COOLDOWN_MS = 30_000;\n\n constructor(\n readonly wallet: IWallet,\n /** @deprecated Use settlementConfig instead */\n readonly renewalConfig?: RenewalConfig,\n settlementConfig?: SettlementConfig | false,\n ) {\n // Normalize: prefer settlementConfig, fall back to renewalConfig, default to enabled\n if (settlementConfig !== undefined) {\n this.settlementConfig = settlementConfig;\n } else if (renewalConfig && renewalConfig.enabled) {\n this.settlementConfig = {\n vtxoThreshold: renewalConfig.thresholdMs\n ? renewalConfig.thresholdMs / 1000\n : undefined,\n };\n } else if (renewalConfig) {\n // renewalConfig provided but not enabled → disabled\n this.settlementConfig = false;\n } else {\n // No config at all → enabled by default\n this.settlementConfig = { ...DEFAULT_SETTLEMENT_CONFIG };\n }\n\n this.contractEventsSubscriptionReady = this.initializeSubscription().then(\n (subscription) => {\n this.contractEventsSubscription = subscription;\n return subscription;\n },\n );\n }\n\n // ========== Recovery Methods ==========\n\n /**\n * Recover swept/expired virtual outputs by settling them back to the wallet's Arkade address.\n *\n * This method:\n * 1. Fetches all virtual outputs (including recoverable ones)\n * 2. Filters for swept but still spendable virtual outputs and preconfirmed subdust\n * 3. Includes subdust virtual outputs if the total value >= dust threshold\n * 4. Settles everything back to the wallet's Arkade address\n *\n * Note: Settled virtual outputs with long expiry are NOT recovered to avoid locking liquidity unnecessarily.\n * Only preconfirmed subdust is recovered to consolidate small amounts.\n *\n * @param eventCallback - Optional callback to receive settlement events\n * @returns Settlement transaction ID\n * @throws Error if no recoverable virtual outputs found\n *\n * @example\n * ```typescript\n * const manager = await wallet.getVtxoManager();\n *\n * // Simple recovery\n * const txid = await manager.recoverVtxos();\n *\n * // With event callback\n * const txid = await manager.recoverVtxos((event) => {\n * console.log('Settlement event:', event.type);\n * });\n * ```\n */\n async recoverVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string> {\n // Get all virtual outputs including recoverable ones\n const allVtxos = await this.wallet.getVtxos({\n withRecoverable: true,\n withUnrolled: false,\n });\n\n // Get dust amount from wallet\n const dustAmount = getDustAmount(this.wallet);\n\n // Filter recoverable virtual outputs and handle subdust logic\n const { vtxosToRecover, totalAmount } = getRecoverableWithSubdust(allVtxos, dustAmount);\n\n if (vtxosToRecover.length === 0) {\n throw new Error(\"No recoverable VTXOs found\");\n }\n\n const arkAddress = await this.wallet.getAddress();\n\n // Settle all recoverable virtual outputs back to the wallet\n return this.wallet.settle(\n {\n inputs: vtxosToRecover,\n outputs: [\n {\n address: arkAddress,\n amount: totalAmount,\n },\n ],\n },\n eventCallback,\n );\n }\n\n /**\n * Get information about recoverable balance without executing recovery.\n *\n * Useful for displaying to users before they decide to recover funds.\n *\n * @returns Object containing recoverable amounts and subdust information\n *\n * @example\n * ```typescript\n * const manager = await wallet.getVtxoManager();\n * const balance = await manager.getRecoverableBalance();\n *\n * if (balance.recoverable > 0n) {\n * console.log(`You can recover ${balance.recoverable} sats`);\n * if (balance.includesSubdust) {\n * console.log(`This includes ${balance.subdust} sats from subdust virtual outputs`);\n * }\n * }\n * ```\n */\n async getRecoverableBalance(): Promise<{\n recoverable: bigint;\n subdust: bigint;\n includesSubdust: boolean;\n vtxoCount: number;\n }> {\n const allVtxos = await this.wallet.getVtxos({\n withRecoverable: true,\n withUnrolled: false,\n });\n\n const dustAmount = getDustAmount(this.wallet);\n\n const { vtxosToRecover, includesSubdust, totalAmount } = getRecoverableWithSubdust(\n allVtxos,\n dustAmount,\n );\n\n // Calculate subdust amount separately for reporting\n const subdustAmount = vtxosToRecover\n .filter((v) => BigInt(v.value) < dustAmount)\n .reduce((sum, v) => sum + BigInt(v.value), 0n);\n\n return {\n recoverable: totalAmount,\n subdust: subdustAmount,\n includesSubdust,\n vtxoCount: vtxosToRecover.length,\n };\n }\n\n // ========== Renewal Methods ==========\n\n /**\n * Get virtual outputs that are expiring soon based on renewal configuration\n *\n * @param thresholdMs - Optional override for threshold in milliseconds\n * @returns Array of expiring virtual outputs, empty array if renewal is disabled or no virtual outputs expiring\n *\n * @example\n * ```typescript\n * const wallet = await Wallet.create({\n * identity,\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: {\n * vtxoThreshold: 86_400 // 24 hours\n * },\n * });\n * const manager = await wallet.getVtxoManager();\n * const expiringVtxos = await manager.getExpiringVtxos();\n * if (expiringVtxos.length > 0) {\n * console.log(`${expiringVtxos.length} virtual outputs expiring soon`);\n * }\n * ```\n */\n async getExpiringVtxos(thresholdMs?: number): Promise<ExtendedVirtualCoin[]> {\n // If settlementConfig is explicitly false and no override provided, renewal is disabled\n if (this.settlementConfig === false && thresholdMs === undefined) {\n return [];\n }\n\n const vtxos = await this.wallet.getVtxos({ withRecoverable: true });\n\n // Resolve threshold: method param > settlementConfig (seconds→ms) > renewalConfig > default\n let threshold: number;\n if (thresholdMs !== undefined) {\n threshold = thresholdMs;\n } else if (\n this.settlementConfig !== false &&\n this.settlementConfig &&\n this.settlementConfig.vtxoThreshold !== undefined\n ) {\n threshold = this.settlementConfig.vtxoThreshold * 1000;\n } else {\n threshold = this.renewalConfig?.thresholdMs ?? DEFAULT_RENEWAL_CONFIG.thresholdMs;\n }\n\n return getExpiringAndRecoverableVtxos(vtxos, threshold, getDustAmount(this.wallet));\n }\n\n /**\n * Renew expiring virtual outputs by settling them back to the wallet's address\n *\n * This method collects all expiring spendable virtual outputs (including recoverable ones) and settles\n * them back to the wallet, effectively refreshing their expiration time. This is the\n * primary way to prevent virtual outputs from expiring.\n *\n * @param eventCallback - Optional callback for settlement events\n * @returns Settlement transaction ID\n * @throws Error if no virtual outputs available to renew\n * @throws Error if total amount is below dust threshold\n *\n * @example\n * ```typescript\n * const manager = await wallet.getVtxoManager();\n *\n * // Simple renewal\n * const txid = await manager.renewVtxos();\n *\n * // With event callback\n * const txid = await manager.renewVtxos((event) => {\n * console.log('Settlement event:', event.type);\n * });\n * ```\n */\n async renewVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string> {\n if (this.renewalInProgress) {\n throw new Error(\"Renewal already in progress\");\n }\n\n this.renewalInProgress = true;\n\n try {\n // Get all virtual outputs (including recoverable ones)\n // Use default threshold to bypass settlementConfig gate (manual API should always work)\n const threshold =\n this.settlementConfig !== false &&\n this.settlementConfig?.vtxoThreshold !== undefined\n ? this.settlementConfig.vtxoThreshold * 1000\n : DEFAULT_RENEWAL_CONFIG.thresholdMs;\n let vtxos = await this.getExpiringVtxos(threshold);\n\n if (vtxos.length === 0) {\n throw new Error(\"No VTXOs available to renew\");\n }\n\n // Pre-flight: validate the chosen inputs against the indexer's\n // authoritative state before submitting. The cursor-derived\n // delta sync filters by `created_at`, so a VTXO created\n // before the cursor and spent recently can sit in the local\n // cache forever; settling against it yields a guaranteed\n // VTXO_ALREADY_SPENT 400. Refreshing the candidates here\n // catches that BEFORE the network round-trip.\n vtxos = await this.revalidateBeforeSettle(vtxos, threshold);\n if (vtxos.length === 0) {\n throw new Error(\"No VTXOs available to renew\");\n }\n\n const totalAmount = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);\n\n // Get dust amount from wallet\n const dustAmount = getDustAmount(this.wallet);\n\n // Check if total amount is above dust threshold\n if (BigInt(totalAmount) < dustAmount) {\n throw new Error(\n `Total amount ${totalAmount} is below dust threshold ${dustAmount}`,\n );\n }\n\n const arkAddress = await this.wallet.getAddress();\n\n const txid = await this.wallet.settle(\n {\n inputs: vtxos,\n outputs: [\n {\n address: arkAddress,\n amount: BigInt(totalAmount),\n },\n ],\n },\n eventCallback,\n );\n return txid;\n } finally {\n // Update cooldown on EVERY attempt (success or failure) so transient\n // settle failures (stream close, connector mismatch, duplicated input)\n // don't allow the next vtxo_received event to re-enter renewal\n // immediately. Without this, a failed settle leaves lastRenewalTimestamp\n // at its previous value and the cooldown check becomes a no-op.\n this.lastRenewalTimestamp = Date.now();\n this.renewalInProgress = false;\n }\n }\n\n // ========== Boarding Input Sweep Methods ==========\n\n /**\n * Get boarding inputs whose timelock has expired.\n *\n * These inputs can no longer be onboarded cooperatively via `settle()` and\n * must be swept back to a fresh boarding address using the unilateral exit path.\n *\n * @returns Array of expired boarding inputs\n *\n * @example\n * ```typescript\n * const manager = await wallet.getVtxoManager();\n * const expired = await manager.getExpiredBoardingUtxos();\n * if (expired.length > 0) {\n * console.log(`${expired.length} expired boarding inputs to sweep`);\n * }\n * ```\n */\n async getExpiredBoardingUtxos(prefetchedUtxos?: ExtendedCoin[]): Promise<ExtendedCoin[]> {\n const boardingUtxos = prefetchedUtxos ?? (await this.wallet.getBoardingUtxos());\n const boardingTimelock = this.getBoardingTimelock();\n\n // For block-based timelocks, fetch the chain tip height\n let chainTipHeight: number | undefined;\n if (boardingTimelock.type === \"blocks\") {\n const tip = await this.getOnchainProvider().getChainTip();\n chainTipHeight = tip.height;\n }\n\n return boardingUtxos.filter((utxo) =>\n hasBoardingTxExpired(utxo, boardingTimelock, chainTipHeight),\n );\n }\n\n /**\n * Sweep expired boarding inputs back to a fresh boarding address via\n * the unilateral exit path (onchain self-spend).\n *\n * This builds a raw onchain transaction that:\n * - Uses all expired boarding inputs as inputs (spent via the CSV exit script path)\n * - Has a single output to the wallet's boarding address (restarts the timelock)\n * - Batches multiple expired boarding inputs into one transaction\n * - Skips the sweep if the output after fees would be below dust\n *\n * No Arkade server involvement is needed — this is a pure onchain transaction.\n *\n * @returns The broadcast transaction ID\n * @throws Error if no expired boarding inputs are found\n * @throws Error if output after fees is below dust (not economical to sweep)\n * @throws Error if boarding input sweep is not enabled in settlementConfig\n *\n * @example\n * ```typescript\n * const wallet = await Wallet.create({\n * identity,\n * arkServerUrl: 'https://arkade.computer',\n * settlementConfig: {\n * boardingUtxoSweep: true,\n * },\n * });\n * const manager = await wallet.getVtxoManager();\n *\n * try {\n * const txid = await manager.sweepExpiredBoardingUtxos();\n * console.log('Swept expired boarding inputs:', txid);\n * } catch (e) {\n * console.log('No sweep needed or not economical');\n * }\n * ```\n */\n async sweepExpiredBoardingUtxos(prefetchedUtxos?: ExtendedCoin[]): Promise<string> {\n const sweepEnabled =\n this.settlementConfig !== false &&\n (this.settlementConfig?.boardingUtxoSweep ??\n DEFAULT_SETTLEMENT_CONFIG.boardingUtxoSweep);\n if (!sweepEnabled) {\n throw new Error(\"Boarding UTXO sweep is not enabled in settlementConfig\");\n }\n\n const allExpired = await this.getExpiredBoardingUtxos(prefetchedUtxos);\n // Filter out inputs already swept (tx broadcast but not yet confirmed).\n const expiredUtxos = allExpired.filter(\n (u) => !this.sweptBoardingUtxos.has(`${u.txid}:${u.vout}`),\n );\n if (expiredUtxos.length === 0) {\n throw new Error(\"No expired boarding UTXOs to sweep\");\n }\n\n const boardingAddress = await this.wallet.getBoardingAddress();\n\n // Get fee rate from onchain provider\n const feeRate = (await this.getOnchainProvider().getFeeRate()) ?? 1;\n\n // Get the exit tap leaf script for signing\n const exitTapLeafScript = this.getBoardingExitLeaf();\n\n // Estimate transaction size for fee calculation\n const sequence = getSequence(exitTapLeafScript);\n\n // TapLeafScript: [{version, internalKey, merklePath}, scriptWithVersion]\n const leafScript = exitTapLeafScript[1];\n const leafScriptSize = leafScript.length - 1; // minus version byte\n const controlBlockSize = exitTapLeafScript[0].merklePath.length * 32;\n // Exit path witness: 1 Schnorr signature (64 bytes)\n const leafWitnessSize = 64;\n\n const estimator = TxWeightEstimator.create();\n for (const _ of expiredUtxos) {\n estimator.addTapscriptInput(leafWitnessSize, leafScriptSize, controlBlockSize);\n }\n estimator.addOutputAddress(boardingAddress, this.getNetwork());\n\n const fee = Math.ceil(Number(estimator.vsize().value) * feeRate);\n const totalValue = expiredUtxos.reduce((sum, utxo) => sum + BigInt(utxo.value), 0n);\n const outputAmount = totalValue - BigInt(fee);\n\n // Dust check: skip if output after fees is below dust\n const dustAmount = getDustAmount(this.wallet);\n if (outputAmount < dustAmount) {\n throw new Error(\n `Sweep not economical: output ${outputAmount} sats after ${fee} sats fee is below dust (${dustAmount} sats)`,\n );\n }\n\n // Build the raw transaction\n const tx = new Transaction();\n\n for (const utxo of expiredUtxos) {\n tx.addInput({\n txid: utxo.txid,\n index: utxo.vout,\n witnessUtxo: {\n script: this.getBoardingOutputScript(),\n amount: BigInt(utxo.value),\n },\n tapLeafScript: [exitTapLeafScript],\n sequence,\n });\n }\n\n tx.addOutputAddress(boardingAddress, outputAmount, this.getNetwork());\n\n // Sign and finalize\n const signedTx = await this.getIdentity().sign(tx);\n signedTx.finalize();\n\n // Broadcast\n const txid = await this.getOnchainProvider().broadcastTransaction(signedTx.hex);\n\n // Mark boarding inputs as swept to prevent duplicate broadcasts on next poll\n for (const u of expiredUtxos) {\n this.sweptBoardingUtxos.add(`${u.txid}:${u.vout}`);\n }\n\n // Mark the sweep output as \"known\" so the next poll doesn't try to\n // auto-settle it back into Arkade (it lands at the same boarding address).\n this.knownBoardingUtxos.add(`${txid}:0`);\n\n return txid;\n }\n\n // ========== Private Helpers ==========\n\n /** Asserts sweep capability and returns the typed wallet. */\n private getSweepWallet(): IWallet & SweepCapableWallet {\n assertSweepCapable(this.wallet);\n return this.wallet;\n }\n\n /** Decodes the boarding tapscript exit path to extract the CSV timelock. */\n private getBoardingTimelock() {\n const wallet = this.getSweepWallet();\n const exitScript = CSVMultisigTapscript.decode(\n hex.decode(wallet.boardingTapscript.exitScript),\n );\n return exitScript.params.timelock;\n }\n\n /** Returns the TapLeafScript for the boarding tapscript's exit (CSV) path. */\n private getBoardingExitLeaf() {\n return this.getSweepWallet().boardingTapscript.exit();\n }\n\n /** Returns the pkScript (output script) of the boarding tapscript. */\n private getBoardingOutputScript() {\n return this.getSweepWallet().boardingTapscript.pkScript;\n }\n\n /** Returns the onchain provider for fee estimation and broadcasting. */\n private getOnchainProvider() {\n return this.getSweepWallet().onchainProvider;\n }\n\n /** Returns the Ark provider for intent fee and server info lookups. */\n private getArkProvider() {\n return this.getSweepWallet().arkProvider;\n }\n\n /** Returns the Bitcoin network configuration from the wallet. */\n private getNetwork() {\n return this.getSweepWallet().network;\n }\n\n /** Returns the wallet's identity for transaction signing. */\n private getIdentity() {\n return this.wallet.identity;\n }\n\n private async initializeSubscription(): Promise<(() => void) | undefined> {\n if (this.settlementConfig === false) {\n return undefined;\n }\n\n // Start polling for boarding inputs independently of contract manager\n // SSE setup. Use a short delay to let the wallet finish construction.\n this.startupPollTimeoutId = setTimeout(() => {\n if (this.disposed) return;\n this.startBoardingUtxoPoll();\n }, 1000);\n\n try {\n const [delegatorManager, contractManager, destination] = await Promise.all([\n this.wallet.getDelegatorManager(),\n this.wallet.getContractManager(),\n this.wallet.getAddress(),\n ]);\n\n const stopWatching = contractManager.onContractEvent((event) => {\n if (event.type !== \"vtxo_received\") {\n return;\n }\n\n const msSinceLastRenewal = Date.now() - this.lastRenewalTimestamp;\n const shouldRenew =\n !this.renewalInProgress &&\n msSinceLastRenewal >= VtxoManager.RENEWAL_COOLDOWN_MS;\n\n if (shouldRenew) {\n this.renewVtxos().catch((e) => {\n if (e instanceof Error) {\n if (e.message.includes(\"No VTXOs available to renew\")) {\n // Not an error, just no virtual outputs eligible for renewal.\n return;\n }\n if (e.message.includes(\"is below dust threshold\")) {\n // Not an error, just below dust threshold.\n // As more virtual outputs are received, the threshold will be raised.\n return;\n }\n if (\n e.message.includes(\"VTXO_ALREADY_REGISTERED\") ||\n e.message.includes(\"duplicated input\")\n ) {\n // Virtual output is already being used in a concurrent\n // user-initiated operation. Skip silently — the\n // wallet's tx lock serializes these, but the\n // renewal will retry on the next cycle.\n return;\n }\n if (e.message.includes(\"VTXO_ALREADY_SPENT\")) {\n // Our local VTXO cache is stale vs. the\n // server's authoritative view. Trigger a\n // throttled, targeted refresh on the\n // offending outpoint (if the server told\n // us which one), then skip — the next\n // cycle will see fresh data.\n void this.maybeRefreshAfterVtxoSpent(this.extractSpentOutpoint(e));\n return;\n }\n }\n console.error(\"Error renewing VTXOs:\", e);\n });\n }\n\n if (delegatorManager) {\n delegatorManager.delegate(event.vtxos, destination).catch((e) => {\n console.error(\"Error delegating VTXOs:\", e);\n });\n }\n });\n\n return stopWatching;\n } catch (e) {\n console.error(\"Error renewing VTXOs from VtxoManager\", e);\n return undefined;\n }\n }\n\n /**\n * VTXO_ALREADY_SPENT means the server's authoritative view of VTXO state\n * is ahead of ours — cross-instance race, pre-lock snapshot drift, or an\n * SSE gap left stale data in the local cache. Silent-swallowing\n * guarantees the same error on the next cycle because nothing\n * reconciles the cache.\n *\n * The cursor-derived delta sync filters by `created_at`, so a VTXO that\n * was created before the cursor but spent recently can never be\n * reconciled by `refreshVtxos()`. Use `refreshOutpoints` for surgical\n * recovery: query the indexer for the specific stale outpoint and\n * upsert its authoritative state into the wallet repository.\n *\n * Throttled because the same VTXO can fire repeatedly before the\n * upsert observably propagates through the renewal selector.\n */\n private maybeRefreshAfterVtxoSpent(spentOutpoint?: Outpoint): Promise<void> {\n if (this.vtxoSpentRefreshPromise) {\n return this.vtxoSpentRefreshPromise;\n }\n\n const now = Date.now();\n if (now - this.lastVtxoSpentRefreshTimestamp < VtxoManager.VTXO_SPENT_REFRESH_COOLDOWN_MS) {\n return Promise.resolve();\n }\n this.lastVtxoSpentRefreshTimestamp = now;\n this.vtxoSpentRefreshPromise = (async () => {\n try {\n const contractManager = await this.wallet.getContractManager();\n if (spentOutpoint) {\n await contractManager.refreshOutpoints([spentOutpoint]);\n } else {\n // No outpoint metadata — fall back to the broader refresh.\n await contractManager.refreshVtxos();\n }\n } catch (e) {\n console.error(\"Error refreshing VTXOs after VTXO_ALREADY_SPENT:\", e);\n } finally {\n this.vtxoSpentRefreshPromise = undefined;\n }\n })();\n\n return this.vtxoSpentRefreshPromise;\n }\n\n /**\n * Extract the offending VTXO outpoint from a `VTXO_ALREADY_SPENT` error,\n * if the server attached one in `metadata.vtxo_outpoint`. Returns\n * `undefined` when the error isn't a parsed ArkError, isn't this code,\n * or doesn't carry the metadata.\n */\n private extractSpentOutpoint(error: unknown): Outpoint | undefined {\n const ark = maybeArkError(error);\n if (!ark || ark.name !== \"VTXO_ALREADY_SPENT\") return undefined;\n const raw = ark.metadata?.vtxo_outpoint;\n if (typeof raw !== \"string\") return undefined;\n const [txid, voutStr] = raw.split(\":\");\n if (!txid || !voutStr) return undefined;\n const vout = Number(voutStr);\n if (!Number.isInteger(vout) || vout < 0) return undefined;\n return { txid, vout };\n }\n\n /**\n * Reconcile the chosen VTXOs with the indexer's authoritative state\n * before submitting a settle intent. Pulls the canonical record for\n * each candidate outpoint via {@link IContractManager.refreshOutpoints}\n * (which upserts the result into the wallet repository), then\n * re-selects through the standard expiring-vtxo filter so anything\n * the refresh flagged as spent is dropped.\n *\n * Best-effort: a failed refresh just falls back to the original\n * candidates and lets the post-submit `VTXO_ALREADY_SPENT` recovery\n * handle whatever slipped through.\n */\n private async revalidateBeforeSettle(\n candidates: ExtendedVirtualCoin[],\n thresholdMs?: number,\n ): Promise<ExtendedVirtualCoin[]> {\n if (candidates.length === 0) return candidates;\n try {\n const cm = await this.wallet.getContractManager();\n await cm.refreshOutpoints(candidates.map((v) => ({ txid: v.txid, vout: v.vout })));\n } catch (e) {\n console.error(\"Error pre-validating VTXOs before settle:\", e);\n return candidates;\n }\n // Re-select from the now-fresh local cache. Anything previously\n // selected but spent gets filtered out by the standard\n // `isSpendable`/`isSpent` checks inside getVtxos / getExpiringVtxos.\n try {\n const refreshed = await this.getExpiringVtxos(thresholdMs);\n const candidateKeys = new Set(candidates.map((v) => `${v.txid}:${v.vout}`));\n // Restrict to vtxos that were also in the original candidate set\n // — `getExpiringVtxos` may surface NEW vtxos and we don't want\n // pre-flight to silently expand the input set.\n return refreshed.filter((v) => candidateKeys.has(`${v.txid}:${v.vout}`));\n } catch (e) {\n console.error(\"Error re-selecting VTXOs after pre-validate:\", e);\n return candidates;\n }\n }\n\n /** Computes the next poll delay, applying exponential backoff on failures. */\n private getNextPollDelay(): number {\n if (this.settlementConfig === false) return 0;\n const baseMs =\n this.settlementConfig.pollIntervalMs ?? DEFAULT_SETTLEMENT_CONFIG.pollIntervalMs;\n if (this.consecutivePollFailures === 0) return baseMs;\n const backoff = Math.min(\n baseMs * Math.pow(2, this.consecutivePollFailures),\n VtxoManager.MAX_BACKOFF_MS,\n );\n return backoff;\n }\n\n /**\n * Starts a polling loop that:\n * 1. Auto-settles new boarding inputs into Arkade\n * 2. Sweeps expired boarding inputs (when boardingUtxoSweep is enabled)\n *\n * Uses setTimeout chaining (not setInterval) so a slow/blocked poll\n * cannot stack up and the next delay can incorporate backoff.\n */\n private startBoardingUtxoPoll(): void {\n if (this.settlementConfig === false) return;\n\n // Run once immediately, then schedule next\n this.pollBoardingUtxos();\n }\n\n private schedulePoll(): void {\n if (this.disposed || this.settlementConfig === false) return;\n const delay = this.getNextPollDelay();\n this.pollTimeoutId = setTimeout(() => this.pollBoardingUtxos(), delay);\n }\n\n private async pollBoardingUtxos(): Promise<void> {\n // Guard: wallet must support boarding input + sweep operations\n if (!isSweepCapable(this.wallet)) return;\n // Skip if disposed or a previous poll is still running\n if (this.disposed) return;\n if (this.pollInProgress) return;\n this.pollInProgress = true;\n\n // Create a promise that dispose() can await\n let resolve: () => void;\n const promise = new Promise<void>((r) => (resolve = r));\n this.pollDone = { promise, resolve: resolve! };\n\n let hadError = false;\n\n try {\n // Cross-instance guard: in browser / service worker environments,\n // serialize the poll body across tabs and SW contexts so only one\n // of them registers intents per interval. Without this, every tab\n // submits a parallel RegisterIntent for the same boarding input\n // and N-1 of them collide on the server's duplicated-input check,\n // each producing a DeleteIntent RPC. No-op outside the browser.\n await runWithCrossInstanceLock(BOARDING_POLL_LOCK_NAME, async () => {\n // Fetch boarding inputs once for the entire poll cycle so that\n // settle and sweep don't each hit the network independently.\n const boardingUtxos = await this.wallet.getBoardingUtxos();\n\n // Settle new (unexpired) boarding inputs + any near-expiry\n // VTXOs in a single intent, then sweep expired boarding\n // inputs. Sequential to avoid racing for the same inputs.\n try {\n await this.runPeriodicSettle(boardingUtxos);\n } catch (e) {\n hadError = true;\n console.error(\"Error during periodic settle:\", e);\n }\n\n const sweepEnabled =\n this.settlementConfig !== false &&\n (this.settlementConfig?.boardingUtxoSweep ??\n DEFAULT_SETTLEMENT_CONFIG.boardingUtxoSweep);\n if (sweepEnabled) {\n try {\n await this.sweepExpiredBoardingUtxos(boardingUtxos);\n } catch (e) {\n if (\n !(e instanceof Error) ||\n !e.message.includes(\"No expired boarding UTXOs\")\n ) {\n hadError = true;\n console.error(\"Error auto-sweeping boarding UTXOs:\", e);\n }\n }\n }\n });\n } catch (e) {\n hadError = true;\n console.error(\"Error fetching boarding UTXOs:\", e);\n } finally {\n if (hadError) {\n this.consecutivePollFailures++;\n } else {\n this.consecutivePollFailures = 0;\n }\n this.pollInProgress = false;\n this.pollDone.resolve();\n this.pollDone = undefined;\n this.schedulePoll();\n }\n }\n\n /**\n * Auto-settle new (unexpired) boarding inputs AND near-expiry VTXOs into\n * Arkade in a single intent. Skips boarding UTXOs that are already expired\n * (those are handled by sweep) and those already in-flight (tracked in\n * knownBoardingUtxos). If the event-driven renewal path is currently\n * running, VTXOs are omitted from this cycle to avoid double-spending.\n *\n * Failure bookkeeping: after every settle *attempt*, lastPeriodicSettleTimestamp\n * is armed and consecutive failures are counted so the next attempt is\n * blocked by an exponentially growing cooldown (capped). This stops a\n * persistently failing input from producing identical RegisterIntent +\n * DeleteIntent retries on every 60s poll.\n */\n private async runPeriodicSettle(boardingUtxos: ExtendedCoin[]): Promise<void> {\n // Exclude expired boarding inputs — those should be swept, not settled.\n // If we can't determine expired status, bail out entirely to avoid\n // accidentally settling expired inputs (which would conflict with sweep).\n let expiredSet: Set<string>;\n try {\n const boardingTimelock = this.getBoardingTimelock();\n let chainTipHeight: number | undefined;\n if (boardingTimelock.type === \"blocks\") {\n const tip = await this.getOnchainProvider().getChainTip();\n chainTipHeight = tip.height;\n }\n const expired = boardingUtxos.filter((utxo) =>\n hasBoardingTxExpired(utxo, boardingTimelock, chainTipHeight),\n );\n expiredSet = new Set(expired.map((u) => `${u.txid}:${u.vout}`));\n } catch (e) {\n throw e instanceof Error ? e : new Error(String(e));\n }\n\n const unsettledBoarding = boardingUtxos.filter(\n (u) =>\n u.status.confirmed &&\n !this.knownBoardingUtxos.has(`${u.txid}:${u.vout}`) &&\n !expiredSet.has(`${u.txid}:${u.vout}`),\n );\n\n // Collect near-expiry VTXOs unless the event-driven path is mid-renewal.\n // Skipping when renewalInProgress avoids double-submitting the same VTXOs.\n let expiringVtxos: ExtendedVirtualCoin[] = [];\n if (!this.renewalInProgress) {\n try {\n expiringVtxos = await this.getExpiringVtxos();\n // Pre-flight validation: see comment in `renewVtxos`. The\n // local cache may carry vtxos that the indexer already\n // marks spent because the cursor-derived delta sync only\n // catches `created_at`-recent updates, not status changes\n // for older VTXOs.\n expiringVtxos = await this.revalidateBeforeSettle(expiringVtxos);\n } catch (e) {\n // Non-fatal: fall back to boarding-only settle.\n console.error(\"Error fetching expiring VTXOs:\", e);\n }\n }\n\n if (unsettledBoarding.length === 0 && expiringVtxos.length === 0) {\n return;\n }\n\n // Respect the cooldown armed by the previous attempt. Cooldown grows\n // exponentially with consecutive failures and is capped by\n // PERIODIC_SETTLE_MAX_BACKOFF_MS.\n const cooldownMs = Math.min(\n VtxoManager.PERIODIC_SETTLE_COOLDOWN_MS *\n Math.pow(2, this.consecutivePeriodicSettleFailures),\n VtxoManager.PERIODIC_SETTLE_MAX_BACKOFF_MS,\n );\n if (Date.now() - this.lastPeriodicSettleTimestamp < cooldownMs) {\n return;\n }\n\n const dustAmount = getDustAmount(this.wallet);\n\n // Fetch server intent-fee config so each input/output can be priced.\n // Without this, settle sends `outputAmount = sum(inputs)` and the\n // server rejects with INTENT_INSUFFICIENT_FEE whenever the operator\n // charges non-zero intent fees.\n const { fees } = await this.getArkProvider().getInfo();\n const estimator = new Estimator(fees.intentFee);\n\n let totalAmount = 0n;\n\n const filteredBoarding: ExtendedCoin[] = [];\n for (const u of unsettledBoarding) {\n const inputFee = estimator.evalOnchainInput({\n amount: BigInt(u.value),\n });\n if (inputFee.value >= BigInt(u.value)) {\n // Fee exceeds input value — including it would drain the output.\n continue;\n }\n filteredBoarding.push(u);\n totalAmount += BigInt(u.value) - BigInt(inputFee.satoshis);\n }\n\n const filteredVtxos: ExtendedVirtualCoin[] = [];\n for (const v of expiringVtxos) {\n const inputFee = estimator.evalOffchainInput({\n amount: BigInt(v.value),\n type: v.virtualStatus.state === \"swept\" ? \"recoverable\" : \"vtxo\",\n weight: 0,\n birth: v.createdAt,\n expiry: v.virtualStatus.batchExpiry\n ? new Date(v.virtualStatus.batchExpiry)\n : undefined,\n });\n if (inputFee.satoshis >= v.value) {\n continue;\n }\n filteredVtxos.push(v);\n totalAmount += BigInt(v.value) - BigInt(inputFee.satoshis);\n }\n\n if (filteredBoarding.length === 0 && filteredVtxos.length === 0) {\n return;\n }\n\n const arkAddress = await this.wallet.getAddress();\n\n const outputFee = estimator.evalOffchainOutput({\n amount: totalAmount,\n script: hex.encode(ArkAddress.decode(arkAddress).pkScript),\n });\n totalAmount -= BigInt(outputFee.satoshis);\n\n if (totalAmount < dustAmount) return;\n\n const includesVtxos = filteredVtxos.length > 0;\n\n // Block the event-driven renewal path while this settle is in flight\n // when VTXOs are part of the intent. Mirrors renewVtxos()'s guard so\n // the two paths can't race on the same VTXO inputs.\n if (includesVtxos) {\n this.renewalInProgress = true;\n }\n\n let success = false;\n let staleCacheSkip = false;\n try {\n try {\n await this.wallet.settle({\n inputs: [...filteredBoarding, ...filteredVtxos],\n outputs: [{ address: arkAddress, amount: totalAmount }],\n });\n\n // Mark boarding inputs as known only after successful settle.\n for (const u of filteredBoarding) {\n this.knownBoardingUtxos.add(`${u.txid}:${u.vout}`);\n }\n success = true;\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"VTXO_ALREADY_SPENT\")) {\n // Local VTXO cache is stale vs. the server's\n // authoritative view — not a transient failure.\n // Trigger a throttled, targeted refresh on the\n // offending outpoint and skip this cycle without\n // bumping the failure counter, so the next poll\n // can retry once the cache reconciles.\n staleCacheSkip = true;\n void this.maybeRefreshAfterVtxoSpent(this.extractSpentOutpoint(e));\n } else {\n throw e;\n }\n }\n } finally {\n this.lastPeriodicSettleTimestamp = Date.now();\n if (includesVtxos) {\n // Match event-path semantics: bump the renewal cooldown\n // whether we succeeded or failed so a failed periodic settle\n // doesn't let the next vtxo_received event re-enter renewal\n // immediately.\n this.lastRenewalTimestamp = Date.now();\n this.renewalInProgress = false;\n }\n if (success) {\n this.consecutivePeriodicSettleFailures = 0;\n } else if (!staleCacheSkip) {\n // Don't bump on stale-cache skip: it's not a transient\n // failure, and the next cycle should try immediately\n // after the refresh lands.\n this.consecutivePeriodicSettleFailures++;\n }\n }\n }\n\n async dispose(): Promise<void> {\n this.disposePromise ??= (async () => {\n this.disposed = true;\n if (this.startupPollTimeoutId) {\n clearTimeout(this.startupPollTimeoutId);\n this.startupPollTimeoutId = undefined;\n }\n if (this.pollTimeoutId) {\n clearTimeout(this.pollTimeoutId);\n this.pollTimeoutId = undefined;\n }\n // Wait for any in-flight poll to finish (with timeout to avoid hanging)\n if (this.pollDone) {\n let timer: ReturnType<typeof setTimeout>;\n const timeout = new Promise<void>((r) => (timer = setTimeout(r, 30_000)));\n await Promise.race([this.pollDone.promise, timeout]);\n clearTimeout(timer!);\n }\n const subscription = await this.contractEventsSubscriptionReady;\n this.contractEventsSubscription = undefined;\n subscription?.();\n })();\n\n return this.disposePromise;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n}\n","import { base58, hex } from \"@scure/base\";\nimport { Bytes, sha256 } from \"@scure/btc-signer/utils.js\";\nimport { Script } from \"@scure/btc-signer\";\nimport { TapLeafScript, VtxoScript } from \"../script/base\";\nimport { ExtendedCoin, Status } from \"../wallet\";\n\n/**\n * ArkNotes are special virtual outputs in the Arkade protocol that\n * can be created and spent without requiring any transactions.\n * The server mints them, and they are encoded as base58 strings\n * with a human-readable prefix, a preimage and a value.\n *\n * @see VtxoScript\n *\n * @example\n * ```typescript\n * // Create an ArkNote\n * const note = new ArkNote(preimage, 50000);\n *\n * // Encode to string\n * const noteString = note.toString();\n *\n * // Decode from string\n * const decodedNote = ArkNote.fromString(noteString);\n * ```\n */\nexport class ArkNote implements ExtendedCoin {\n static readonly DefaultHRP = \"arknote\";\n static readonly PreimageLength = 32; // 32 bytes for the preimage\n static readonly ValueLength = 4; // 4 bytes for the value\n static readonly Length = ArkNote.PreimageLength + ArkNote.ValueLength;\n static readonly FakeOutpointIndex = 0;\n\n readonly vtxoScript: VtxoScript;\n\n /** Hashlock script backing the note. */\n readonly txid: string;\n readonly vout = 0;\n readonly forfeitTapLeafScript: TapLeafScript;\n readonly intentTapLeafScript: TapLeafScript;\n readonly tapTree: Bytes;\n readonly status: Status;\n readonly extraWitness?: Bytes[] | undefined;\n\n /**\n * Create an ArkNote from a preimage and value.\n *\n * @param preimage - 32-byte preimage revealed to spend the note\n * @param value - Note value in satoshis\n * @param HRP - Optional human-readable prefix for string encoding\n */\n constructor(\n public preimage: Uint8Array,\n public value: number,\n public HRP = ArkNote.DefaultHRP,\n ) {\n const preimageHash = sha256(this.preimage);\n this.vtxoScript = new VtxoScript([noteTapscript(preimageHash)]);\n\n const leaf = this.vtxoScript.leaves[0];\n\n this.txid = hex.encode(new Uint8Array(preimageHash).reverse());\n this.tapTree = this.vtxoScript.encode();\n this.forfeitTapLeafScript = leaf;\n this.intentTapLeafScript = leaf;\n this.value = value;\n this.status = { confirmed: true };\n this.extraWitness = [this.preimage];\n }\n\n /**\n * Encode the note as raw bytes.\n *\n * @returns Serialized note bytes\n * @see decode\n */\n encode(): Uint8Array {\n const result = new Uint8Array(ArkNote.Length);\n result.set(this.preimage, 0);\n writeUInt32BE(result, this.value, this.preimage.length);\n return result;\n }\n\n /**\n * Decode a note from raw bytes.\n *\n * @param data - Serialized note bytes\n * @param hrp - Human-readable prefix expected for future string encoding\n * @returns Decoded ArkNote\n * @throws Error if the payload length is invalid\n * @see encode\n */\n static decode(data: Uint8Array, hrp = ArkNote.DefaultHRP): ArkNote {\n if (data.length !== ArkNote.Length) {\n throw new Error(\n `invalid data length: expected ${ArkNote.Length} bytes, got ${data.length}`,\n );\n }\n\n const preimage = data.subarray(0, ArkNote.PreimageLength);\n const value = readUInt32BE(data, ArkNote.PreimageLength);\n\n return new ArkNote(preimage, value, hrp);\n }\n\n /**\n * Decode a note from its base58 string form.\n *\n * @param noteStr - Base58-encoded note string\n * @param hrp - Human-readable prefix expected on the note string\n * @returns Decoded ArkNote\n * @throws Error if the prefix or base58 payload is invalid\n * @see toString\n */\n static fromString(noteStr: string, hrp = ArkNote.DefaultHRP): ArkNote {\n noteStr = noteStr.trim();\n if (!noteStr.startsWith(hrp)) {\n throw new Error(\n `invalid human-readable part: expected ${hrp} prefix (note '${noteStr}')`,\n );\n }\n\n const encoded = noteStr.slice(hrp.length);\n\n const decoded = base58.decode(encoded);\n if (decoded.length === 0) {\n throw new Error(\"failed to decode base58 string\");\n }\n\n return ArkNote.decode(decoded, hrp);\n }\n\n /**\n * Encode the note to its human-readable base58 string form.\n *\n * @returns Base58-encoded note string\n * @see fromString\n */\n toString(): string {\n return this.HRP + base58.encode(this.encode());\n }\n}\n\nfunction writeUInt32BE(array: Uint8Array, value: number, offset: number): void {\n const view = new DataView(array.buffer, array.byteOffset + offset, 4);\n view.setUint32(0, value, false);\n}\n\nfunction readUInt32BE(array: Uint8Array, offset: number): number {\n const view = new DataView(array.buffer, array.byteOffset + offset, 4);\n return view.getUint32(0, false);\n}\n\nfunction noteTapscript(preimageHash: Uint8Array): Bytes {\n return Script.encode([\"SHA256\", preimageHash, \"EQUAL\"]);\n}\n","import { Recipient } from \".\";\nimport {\n ArkAddress,\n type Coin,\n type ExtendedCoin,\n type ExtendedVirtualCoin,\n type VirtualCoin,\n} from \"..\";\nimport type { Contract } from \"../contracts/types\";\nimport { contractHandlers } from \"../contracts/handlers\";\nimport { DefaultVtxo } from \"../script/default\";\nimport { DelegateVtxo } from \"../script/delegate\";\nimport { ReadonlyWallet } from \"./wallet\";\nimport { hex } from \"@scure/base\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\n\nexport const DUST_AMOUNT = 546; // sats\n\nexport function extendCoin(\n wallet: { boardingTapscript: ReadonlyWallet[\"boardingTapscript\"] },\n utxo: Coin,\n): ExtendedCoin {\n return {\n ...utxo,\n forfeitTapLeafScript: wallet.boardingTapscript.forfeit(),\n intentTapLeafScript: wallet.boardingTapscript.forfeit(),\n tapTree: wallet.boardingTapscript.encode(),\n };\n}\n\nfunction extendVtxoFromContract(vtxo: VirtualCoin, contract: Contract): ExtendedVirtualCoin {\n const handler = contractHandlers.get(contract.type);\n if (!handler) {\n throw new Error(`No handler for contract type '${contract.type}'`);\n }\n const script = handler.createScript(contract.params) as\n | DefaultVtxo.Script\n | DelegateVtxo.Script;\n return {\n ...vtxo,\n forfeitTapLeafScript: script.forfeit(),\n intentTapLeafScript: script.forfeit(),\n tapTree: script.encode(),\n };\n}\n\n/**\n * Extend a VirtualCoin with the tap scripts of whichever contract locks it.\n *\n * The second argument accepts either form, so each callsite passes what it\n * already has:\n * - a single `Contract` (when the caller already knows the owning contract,\n * e.g. the contract manager iterating its own `scriptToContract` map), or\n * - a `ReadonlyMap<script, Contract>` (when the caller resolves by\n * `vtxo.script`, populated by the indexer).\n *\n * Throws when no contract can be resolved — there is intentionally no\n * default-tapscript fallback. When the wallet owns multiple contracts\n * (default + delegate, several active vHTLCs, etc.) a default-tapscript path\n * silently stamps every VTXO with the same forfeit/intent data, overwriting\n * the correct data for any VTXO locked to a non-default contract. Callers\n * must feed a Contract or a populated script→Contract map; otherwise the\n * caller (typically `ContractManager.annotateVtxos`) should fetch the owning\n * contract first.\n */\nexport function extendVirtualCoinForContract(\n vtxo: VirtualCoin,\n contractOrMap?: Contract | ReadonlyMap<string, Contract>,\n): ExtendedVirtualCoin {\n const contract = resolveContract(vtxo, contractOrMap);\n if (!contract) {\n throw new Error(\n \"extendVirtualCoinForContract: no contract matched vtxo.script — callers must resolve the owning contract before annotating\",\n );\n }\n return extendVtxoFromContract(vtxo, contract);\n}\n\nfunction isContractMap(\n value: Contract | ReadonlyMap<string, Contract>,\n): value is ReadonlyMap<string, Contract> {\n // A `Contract` is a plain object with a string `type`. `ReadonlyMap` is\n // an interface so `instanceof Map` is not enough to narrow it — but a\n // contract has no `get` method, so duck-typing on that is unambiguous.\n return typeof (value as { get?: unknown }).get === \"function\";\n}\n\nfunction resolveContract(\n vtxo: VirtualCoin,\n contractOrMap?: Contract | ReadonlyMap<string, Contract>,\n): Contract | undefined {\n if (!contractOrMap) return undefined;\n if (isContractMap(contractOrMap)) {\n return contractOrMap.get(vtxo.script);\n }\n return contractOrMap;\n}\n\nexport function getRandomId(): string {\n const randomValue = crypto.getRandomValues(new Uint8Array(16));\n return hex.encode(randomValue);\n}\n\nexport function isValidArkAddress(address: string): boolean {\n try {\n ArkAddress.decode(address);\n return true;\n } catch (e) {\n return false;\n }\n}\n\ntype ValidatedRecipient = Required<Recipient> & { script: Bytes };\n\nexport function validateRecipients(\n recipients: Recipient[],\n dustAmount: number,\n): ValidatedRecipient[] {\n const validatedRecipients: ValidatedRecipient[] = [];\n\n for (const recipient of recipients) {\n let address: ArkAddress;\n try {\n address = ArkAddress.decode(recipient.address);\n } catch (e) {\n throw new Error(`Invalid Arkade address: ${recipient.address}`);\n }\n\n const amount = recipient.amount || dustAmount;\n if (amount <= 0) {\n throw new Error(\"Amount must be positive\");\n }\n\n validatedRecipients.push({\n address: recipient.address,\n assets: recipient.assets ?? [],\n amount,\n script: amount < dustAmount ? address.subdustPkScript : address.pkScript,\n });\n }\n\n return validatedRecipients;\n}\n","import { Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { base64 } from \"@scure/base\";\nimport { hex } from \"@scure/base\";\n\n/**\n * TxTreeNode is a node of the tree.\n * It contains the transaction id, the transaction and the children.\n * any TxTree can be serialized as a list of TxTreeNode.\n */\nexport type TxTreeNode = {\n txid: string;\n // base64 encoded root transaction\n tx: string;\n // map, output index -> child txid\n children: Record<number, string>;\n};\n\ntype DecodedNode = {\n tx: Transaction;\n children: Record<number, string>;\n};\n\n/**\n * TxTree is a graph of bitcoin transactions.\n * It is used to represent batch tree created during settlement session\n */\nexport class TxTree {\n constructor(\n readonly root: Transaction,\n readonly children: Map<number, TxTree> = new Map(),\n ) {}\n\n static create(chunks: TxTreeNode[]): TxTree {\n if (chunks.length === 0) {\n throw new Error(\"empty chunks\");\n }\n\n // Create a map to store all chunks by their txid for easy lookup\n const chunksByTxid = new Map<string, DecodedNode>();\n\n for (const chunk of chunks) {\n const decodedChunk = decodeNode(chunk);\n const txid = decodedChunk.tx.id;\n chunksByTxid.set(txid, decodedChunk);\n }\n\n // Find the root chunks (the ones that aren't referenced as a child)\n const rootTxids: string[] = [];\n for (const [txid] of chunksByTxid) {\n let isChild = false;\n for (const [otherTxid, otherChunk] of chunksByTxid) {\n if (otherTxid === txid) {\n // skip self\n continue;\n }\n\n // check if the current chunk is a child of the other chunk\n isChild = hasChild(otherChunk, txid);\n if (isChild) {\n break;\n }\n }\n\n // if the chunk is not a child of any other chunk, it is a root\n if (!isChild) {\n rootTxids.push(txid);\n continue;\n }\n }\n\n if (rootTxids.length === 0) {\n throw new Error(\"no root chunk found\");\n }\n\n if (rootTxids.length > 1) {\n throw new Error(`multiple root chunks found: ${rootTxids.join(\", \")}`);\n }\n\n const graph = buildGraph(rootTxids[0], chunksByTxid);\n if (!graph) {\n throw new Error(`chunk not found for root txid: ${rootTxids[0]}`);\n }\n\n // verify that the number of chunks is equal to the number node in the graph\n if (graph.nbOfNodes() !== chunks.length) {\n throw new Error(\n `number of chunks (${chunks.length}) is not equal to the number of nodes in the graph (${graph.nbOfNodes()})`,\n );\n }\n\n return graph;\n }\n\n nbOfNodes(): number {\n let count = 1; // count this node\n for (const child of this.children.values()) {\n count += child.nbOfNodes();\n }\n return count;\n }\n\n validate(): void {\n if (!this.root) {\n throw new Error(\"unexpected nil root\");\n }\n\n const nbOfOutputs = this.root.outputsLength;\n const nbOfInputs = this.root.inputsLength;\n\n if (nbOfInputs !== 1) {\n throw new Error(`unexpected number of inputs: ${nbOfInputs}, expected 1`);\n }\n\n // the children map can't be bigger than the number of outputs (excluding the P2A)\n // a graph can be \"partial\" and specify only some of the outputs as children,\n // that's why we allow len(g.Children) to be less than nbOfOutputs-1\n if (this.children.size > nbOfOutputs - 1) {\n throw new Error(\n `unexpected number of children: ${this.children.size}, expected maximum ${nbOfOutputs - 1}`,\n );\n }\n\n // validate each child\n for (const [outputIndex, child] of this.children) {\n if (outputIndex >= nbOfOutputs) {\n throw new Error(\n `output index ${outputIndex} is out of bounds (nb of outputs: ${nbOfOutputs})`,\n );\n }\n\n child.validate();\n\n const childInput = child.root.getInput(0);\n const parentTxid = this.root.id;\n\n // verify the input of the child is the output of the parent\n if (\n !childInput.txid ||\n hex.encode(childInput.txid) !== parentTxid ||\n childInput.index !== outputIndex\n ) {\n throw new Error(`input of child ${outputIndex} is not the output of the parent`);\n }\n\n // verify the sum of the child's outputs is equal to the output of the parent\n let childOutputsSum = 0n;\n for (let i = 0; i < child.root.outputsLength; i++) {\n const output = child.root.getOutput(i);\n if (output?.amount) {\n childOutputsSum += output.amount;\n }\n }\n\n const parentOutput = this.root.getOutput(outputIndex);\n if (!parentOutput?.amount) {\n throw new Error(`parent output ${outputIndex} has no amount`);\n }\n\n if (childOutputsSum !== parentOutput.amount) {\n throw new Error(\n `sum of child's outputs is not equal to the output of the parent: ${childOutputsSum} != ${parentOutput.amount}`,\n );\n }\n }\n }\n\n leaves(): Transaction[] {\n if (this.children.size === 0) {\n return [this.root];\n }\n\n const leaves: Transaction[] = [];\n for (const child of this.children.values()) {\n leaves.push(...child.leaves());\n }\n return leaves;\n }\n\n get txid(): string {\n return this.root.id;\n }\n\n find(txid: string): TxTree | null {\n if (txid === this.txid) {\n return this;\n }\n\n for (const child of this.children.values()) {\n const found = child.find(txid);\n if (found) {\n return found;\n }\n }\n\n return null;\n }\n\n update(txid: string, fn: (tx: Transaction) => void): void {\n if (txid === this.txid) {\n fn(this.root);\n return;\n }\n\n for (const child of this.children.values()) {\n try {\n child.update(txid, fn);\n return;\n } catch (error) {\n // Continue searching in other children if not found\n continue;\n }\n }\n\n throw new Error(`tx not found: ${txid}`);\n }\n\n *iterator(): Generator<TxTree, void, unknown> {\n for (const child of this.children.values()) {\n yield* child.iterator();\n }\n yield this;\n }\n}\n\n// Helper function to check if a chunk has a specific child\nfunction hasChild(chunk: DecodedNode, childTxid: string): boolean {\n return Object.values(chunk.children).includes(childTxid);\n}\n\n// buildGraph recursively builds the TxGraph starting from the given txid\nfunction buildGraph(rootTxid: string, chunksByTxid: Map<string, DecodedNode>): TxTree | null {\n const chunk = chunksByTxid.get(rootTxid);\n if (!chunk) {\n return null;\n }\n\n const rootTx = chunk.tx;\n const children = new Map<number, TxTree>();\n\n // Recursively build children graphs\n for (const [outputIndexStr, childTxid] of Object.entries(chunk.children)) {\n const outputIndex = parseInt(outputIndexStr);\n const childGraph = buildGraph(childTxid, chunksByTxid);\n if (childGraph) {\n children.set(outputIndex, childGraph);\n }\n }\n\n return new TxTree(rootTx, children);\n}\n\nfunction decodeNode(chunk: TxTreeNode): DecodedNode {\n const tx = Transaction.fromPSBT(base64.decode(chunk.tx));\n return { tx, children: chunk.children };\n}\n","import type {\n BatchStartedEvent,\n BatchFinalizedEvent,\n BatchFailedEvent,\n TreeTxEvent,\n TreeSignatureEvent,\n TreeSigningStartedEvent,\n TreeNoncesEvent,\n BatchFinalizationEvent,\n SettlementEvent,\n} from \"../providers/ark\";\nimport { SettlementEventType } from \"../providers/ark\";\nimport { TxTree, type TxTreeNode } from \"../tree/txTree\";\nimport { hex } from \"@scure/base\";\n\n/**\n * Batch namespace provides utilities for joining and processing batch session.\n * The batch settlement process involves multiple events, this namespace provides abstractions and types to handle them.\n * @see https://docs.arkadeos.com/learn/pillars/batch-swaps\n * @example\n * ```typescript\n * // use wallet handler or create a custom one\n * const handler = wallet.createBatchHandler(intentId, inputs, expectedRecipients, musig2session);\n *\n * const abortController = new AbortController();\n * // Get event stream from the Arkade provider\n * const eventStream = arkProvider.getEventStream(\n * abortController.signal,\n * ['your-topic-1', 'your-topic-2']\n * );\n *\n * // Join the batch and process events\n * try {\n * const commitmentTxid = await Batch.join(eventStream, handler);\n * console.log('Batch completed with commitment:', commitmentTxid);\n * } catch (error) {\n * console.error('Batch processing failed:', error);\n * } finally {\n * abortController.abort();\n * }\n * ```\n */\nexport namespace Batch {\n // Handler interface defines how to react to batch events\n export interface Handler {\n /**\n * Called on BatchStarted event.\n * @returns { skip: boolean } indicating whether the batch should be skipped or not.\n */\n onBatchStarted(event: BatchStartedEvent): Promise<{ skip: boolean }>;\n /**\n * Called when tree signing starts.\n * @param event The tree signing started event.\n * @param vtxoTree The unsigned virtual output tree, reconstructed from the TreeTxEvent events.\n * @returns Promise resolving to a boolean indicating whether to continue processing.\n */\n onTreeSigningStarted(\n event: TreeSigningStartedEvent,\n vtxoTree: TxTree,\n ): Promise<{ skip: boolean }>;\n /**\n * Called when tree nonces are received.\n * @param event The tree nonces event.\n * @returns Promise resolving to a boolean indicating whether signing is complete.\n */\n onTreeNonces(event: TreeNoncesEvent): Promise<{ fullySigned: boolean }>;\n /**\n * Called during batch finalization.\n * @param event The batch finalization event.\n * @param vtxoTree The signed virtual output tree, reconstructed from the TreeTxEvent events.\n * @param connectorTree The connector transaction tree, reconstructed from the TreeTxEvent events.\n */\n onBatchFinalization(\n event: BatchFinalizationEvent,\n vtxoTree?: TxTree,\n connectorTree?: TxTree,\n ): Promise<void>;\n\n /**\n * Called when batch finalization completes successfully.\n *\n * @param event - Batch finalized event\n */\n onBatchFinalized?(event: BatchFinalizedEvent): Promise<void>;\n\n /**\n * Called when batch processing fails.\n *\n * @param event - Batch failed event\n */\n onBatchFailed?(event: BatchFailedEvent): Promise<void>;\n\n /**\n * Called for each virtual output tree transaction chunk received during batch processing.\n *\n * @param event - Tree transaction event\n */\n onTreeTxEvent?(event: TreeTxEvent): Promise<void>;\n\n /**\n * Called for each tree signature event received during batch processing.\n *\n * @param event - Tree signature event\n */\n onTreeSignatureEvent?(event: TreeSignatureEvent): Promise<void>;\n }\n\n /**\n * Options for the join function.\n *\n * @property abortController - Abort controller used to cancel batch processing.\n * @property skipVtxoTreeSigning - Ignore events related to the virtual output tree musig2 signing session.\n * @property eventCallback - Callback invoked for each settlement event received while joining the batch.\n */\n export type JoinOptions = Partial<{\n abortController: AbortController;\n skipVtxoTreeSigning: boolean;\n eventCallback: (event: SettlementEvent) => Promise<void>;\n }>;\n\n // State machine steps for batch session\n enum Step {\n Start = \"start\",\n BatchStarted = \"batch_started\",\n TreeSigningStarted = \"tree_signing_started\",\n TreeNoncesAggregated = \"tree_nonces_aggregated\",\n BatchFinalization = \"batch_finalization\",\n }\n\n /**\n * Start the state machine that will process the batch events and join a batch.\n * @param eventIterator - The events stream to process.\n * @param handler - How to react to events.\n * @param options - Options.\n */\n export async function join(\n eventIterator: AsyncIterableIterator<SettlementEvent>,\n handler: Handler,\n options: JoinOptions = {},\n ): Promise<string> {\n const { abortController, skipVtxoTreeSigning = false, eventCallback } = options;\n\n let step = Step.Start;\n\n // keep track of tree transactions as they arrive\n const flatVtxoTree: TxTreeNode[] = [];\n const flatConnectorTree: TxTreeNode[] = [];\n // once everything is collected, the TxTree objects are created\n let vtxoTree: TxTree | undefined = undefined;\n let connectorTree: TxTree | undefined = undefined;\n\n for await (const event of eventIterator) {\n if (abortController?.signal.aborted) {\n throw new Error(\"canceled\");\n }\n\n if (eventCallback) {\n // don't wait for the callback to complete and ignore errors\n eventCallback(event).catch(() => {});\n }\n\n switch (event.type) {\n case SettlementEventType.BatchStarted: {\n const e = event as BatchStartedEvent;\n const { skip } = await handler.onBatchStarted(e);\n\n if (!skip) {\n step = Step.BatchStarted;\n\n if (skipVtxoTreeSigning) {\n // skip TxTree events and musig2 signatures and nonces\n step = Step.TreeNoncesAggregated;\n }\n }\n continue;\n }\n\n case SettlementEventType.BatchFinalized: {\n if (step !== Step.BatchFinalization) {\n continue;\n }\n\n if (handler.onBatchFinalized) {\n await handler.onBatchFinalized(event);\n }\n return event.commitmentTxid;\n }\n\n case SettlementEventType.BatchFailed: {\n if (handler.onBatchFailed) {\n await handler.onBatchFailed(event);\n continue;\n }\n\n throw new Error(event.reason);\n }\n\n case SettlementEventType.TreeTx: {\n if (step !== Step.BatchStarted && step !== Step.TreeNoncesAggregated) {\n continue;\n }\n\n // batchIndex 0 = virtual output tree, batchIndex 1 = connector tree\n if (event.batchIndex === 0) {\n flatVtxoTree.push(event.chunk);\n } else {\n flatConnectorTree.push(event.chunk);\n }\n\n if (handler.onTreeTxEvent) {\n await handler.onTreeTxEvent(event);\n }\n continue;\n }\n\n case SettlementEventType.TreeSignature: {\n if (step !== Step.TreeNoncesAggregated) {\n continue;\n }\n\n if (!vtxoTree) {\n throw new Error(\"vtxo tree not initialized\");\n }\n\n // push signature to the virtual output tree\n const tapKeySig = hex.decode(event.signature);\n vtxoTree.update(event.txid, (tx) => {\n tx.updateInput(0, {\n tapKeySig,\n });\n });\n\n if (handler.onTreeSignatureEvent) {\n await handler.onTreeSignatureEvent(event);\n }\n continue;\n }\n\n case SettlementEventType.TreeSigningStarted: {\n if (step !== Step.BatchStarted) {\n continue;\n }\n\n // create virtual output tree from collected chunks\n vtxoTree = TxTree.create(flatVtxoTree);\n\n const { skip } = await handler.onTreeSigningStarted(event, vtxoTree);\n\n if (!skip) {\n step = Step.TreeSigningStarted;\n }\n continue;\n }\n\n case SettlementEventType.TreeNonces: {\n if (step !== Step.TreeSigningStarted) {\n continue;\n }\n\n const { fullySigned } = await handler.onTreeNonces(event);\n if (fullySigned) {\n step = Step.TreeNoncesAggregated;\n }\n continue;\n }\n\n case SettlementEventType.BatchFinalization: {\n if (step !== Step.TreeNoncesAggregated) {\n continue;\n }\n\n // Build virtual output tree if it hasn't been built yet\n if (!vtxoTree && flatVtxoTree.length > 0) {\n vtxoTree = TxTree.create(flatVtxoTree);\n }\n\n if (!vtxoTree && !skipVtxoTreeSigning) {\n throw new Error(\"vtxo tree not initialized\");\n }\n\n // Build connector tree if we have chunks\n if (flatConnectorTree.length > 0) {\n connectorTree = TxTree.create(flatConnectorTree);\n }\n\n await handler.onBatchFinalization(event, vtxoTree, connectorTree);\n\n step = Step.BatchFinalization;\n continue;\n }\n\n default:\n // unknown event type, continue\n continue;\n }\n }\n\n // iterator closed without finalization, something went wrong\n throw new Error(\"event stream closed\");\n }\n}\n","import { ArkTransaction, Asset, TxKey, TxType, VirtualCoin } from \"../wallet\";\n\ntype ExtendedArkTransaction = ArkTransaction & {\n tag: \"offchain\" | \"boarding\" | \"exit\" | \"batch\";\n};\nconst txKey: TxKey = {\n commitmentTxid: \"\",\n boardingTxid: \"\",\n arkTxid: \"\",\n};\n\nfunction collectAssets(vtxos: VirtualCoin[]): Asset[] | undefined {\n const map = new Map<string, bigint>();\n for (const vtxo of vtxos) {\n if (vtxo.assets) {\n for (const a of vtxo.assets) {\n map.set(a.assetId, (map.get(a.assetId) ?? 0n) + a.amount);\n }\n }\n }\n if (map.size === 0) return undefined;\n return Array.from(map, ([assetId, amount]) => ({ assetId, amount }));\n}\n\nfunction subtractAssets(spent: VirtualCoin[], change: VirtualCoin[]): Asset[] | undefined {\n const map = new Map<string, bigint>();\n for (const vtxo of change) {\n if (vtxo.assets) {\n for (const a of vtxo.assets) {\n map.set(a.assetId, (map.get(a.assetId) ?? 0n) + a.amount);\n }\n }\n }\n for (const vtxo of spent) {\n if (vtxo.assets) {\n for (const a of vtxo.assets) {\n const current = map.get(a.assetId) ?? 0n;\n const remaining = current - a.amount;\n if (remaining !== 0n) {\n map.set(a.assetId, remaining);\n } else {\n map.delete(a.assetId);\n }\n }\n }\n }\n if (map.size === 0) return undefined;\n return Array.from(map, ([assetId, amount]) => ({ assetId, amount }));\n}\n\n/**\n * Builds the transaction history by analyzing virtual outputs, boarding transactions, and ignored commitments.\n * History is sorted from newest to oldest and is composed only of SENT and RECEIVED transactions.\n *\n * @param {VirtualCoin[]} vtxos - An array of virtual outputs representing the user's transactions and balances.\n * @param {ArkTransaction[]} allBoardingTxs - An array of boarding transactions to include in the history.\n * @param {Set<string>} commitmentsToIgnore - A set of commitment IDs that should be excluded from processing.\n * @return {ExtendedArkTransaction[]} A sorted array of extended Arkade transactions, representing the transaction history.\n */\nexport async function buildTransactionHistory(\n vtxos: VirtualCoin[],\n allBoardingTxs: ArkTransaction[],\n commitmentsToIgnore: Set<string>,\n getTxCreatedAt?: (txid: string) => Promise<number | undefined>,\n): Promise<ExtendedArkTransaction[]> {\n const fromOldestVtxo = [...vtxos].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n\n const sent: ExtendedArkTransaction[] = [];\n let received: ExtendedArkTransaction[] = [];\n\n for (const vtxo of fromOldestVtxo) {\n if (vtxo.status.isLeaf) {\n // If this virtual output is a leaf and it's not the settlement of a boarding or there's no virtual output refreshed by it,\n // it's translated into a received batch transaction\n if (\n !commitmentsToIgnore.has(vtxo.virtualStatus.commitmentTxIds![0]) &&\n fromOldestVtxo.filter((v) => v.settledBy === vtxo.virtualStatus.commitmentTxIds![0])\n .length === 0\n ) {\n const assets = collectAssets([vtxo]);\n received.push({\n key: {\n ...txKey,\n commitmentTxid: vtxo.virtualStatus.commitmentTxIds![0],\n },\n tag: \"batch\",\n type: TxType.TxReceived,\n amount: vtxo.value,\n settled: vtxo.status.isLeaf || vtxo.isSpent!,\n createdAt: vtxo.createdAt.getTime(),\n ...(assets && { assets }),\n });\n }\n } else if (fromOldestVtxo.filter((v) => v.arkTxId === vtxo.txid).length === 0) {\n // If this virtual output is preconfirmed and does not spend any other virtual outputs,\n // it's translated into a received offchain transaction\n const assets = collectAssets([vtxo]);\n received.push({\n key: { ...txKey, arkTxid: vtxo.txid! },\n tag: \"offchain\",\n type: TxType.TxReceived,\n amount: vtxo.value,\n settled: vtxo.status.isLeaf || vtxo.isSpent!,\n createdAt: vtxo.createdAt.getTime(),\n ...(assets && { assets }),\n });\n }\n\n // If the virtual output is spent, it's translated into a sent transaction unless:\n // - it's been refreshed (we don't want to add any record in this case)\n // - a sent transaction has been already added to avoid duplicates (can happen if many virtual outputs have been spent in the same tx or forfeited in the same batch)\n if (vtxo.isSpent) {\n // If the virtual output is spent offchain, it's translated into an offchain sent tx\n if (vtxo.arkTxId && !sent.some((s) => s.key.arkTxid === vtxo.arkTxId)) {\n const changes = fromOldestVtxo.filter((_) => _.txid === vtxo.arkTxId);\n\n // We want to find all the other virtual outputs spent by the same transaction to\n // calculate the full amount of the change.\n const allSpent = fromOldestVtxo.filter((v) => v.arkTxId === vtxo.arkTxId);\n const spentAmount = allSpent.reduce((acc, v) => acc + v.value, 0);\n\n let txAmount = 0;\n let txTime = 0;\n if (changes.length > 0) {\n const changeAmount = changes.reduce((acc, v) => acc + v.value, 0);\n txAmount = spentAmount - changeAmount;\n txTime = changes[0].createdAt.getTime();\n } else {\n txAmount = spentAmount;\n // TODO: fetch the virtual output with /v1/indexer/vtxos?outpoints=<vtxo.arkTxid:0> to know when the tx was made\n txTime = getTxCreatedAt\n ? ((await getTxCreatedAt(vtxo.arkTxId!)) ?? vtxo.createdAt.getTime() + 1)\n : vtxo.createdAt.getTime() + 1;\n }\n\n const assets = subtractAssets(allSpent, changes);\n sent.push({\n key: { ...txKey, arkTxid: vtxo.arkTxId },\n tag: \"offchain\",\n type: TxType.TxSent,\n amount: txAmount,\n settled: true,\n createdAt: txTime,\n ...(assets && { assets }),\n });\n }\n\n // If the virtual output is forfeited in a batch and the total sum of forfeited virtual outputs is bigger than the sum of new virtual outputs,\n // it's translated into an exit sent tx\n if (\n vtxo.settledBy &&\n !commitmentsToIgnore.has(vtxo.settledBy) &&\n !sent.some((s) => s.key.commitmentTxid === vtxo.settledBy)\n ) {\n const changes = fromOldestVtxo.filter(\n (v) =>\n v.status.isLeaf &&\n v.virtualStatus.commitmentTxIds?.every((_) => vtxo.settledBy === _),\n );\n\n const forfeitVtxos = fromOldestVtxo.filter((v) => v.settledBy === vtxo.settledBy);\n const forfeitAmount = forfeitVtxos.reduce((acc, v) => acc + v.value, 0);\n\n if (changes.length > 0) {\n const settledAmount = changes.reduce((acc, v) => acc + v.value, 0);\n\n // forfeitAmount > settledAmount --> collaborative exit with offchain change\n // TODO: make this support fees!\n if (forfeitAmount > settledAmount) {\n const assets = subtractAssets(forfeitVtxos, changes);\n sent.push({\n key: { ...txKey, commitmentTxid: vtxo.settledBy },\n tag: \"exit\",\n type: TxType.TxSent,\n amount: forfeitAmount - settledAmount,\n settled: true,\n createdAt: changes[0].createdAt.getTime(),\n ...(assets && { assets }),\n });\n }\n } else {\n // forfeitAmount > 0 && settledAmount == 0 --> collaborative exit without any offchain change\n const assets = subtractAssets(forfeitVtxos, []);\n sent.push({\n key: { ...txKey, commitmentTxid: vtxo.settledBy },\n tag: \"exit\",\n type: TxType.TxSent,\n amount: forfeitAmount,\n settled: true,\n // TODO: fetch commitment tx with /v1/indexer/commitmentTx/<commitmentTxid> to know when the tx was made\n createdAt: vtxo.createdAt.getTime() + 1,\n ...(assets && { assets }),\n });\n }\n }\n }\n }\n\n // Boardings are always inbound amounts, and we only hide the ones to ignore.\n const boardingTx = allBoardingTxs.map((tx) => ({ ...tx, tag: \"boarding\" }));\n\n const sorted = [...boardingTx, ...sent, ...received].sort((a, b) => b.createdAt - a.createdAt);\n\n return sorted as ExtendedArkTransaction[];\n}\n","import {\n AssetDetails,\n AssetMetadata,\n BurnParams,\n IAssetManager,\n IReadonlyAssetManager,\n IssuanceParams,\n IssuanceResult,\n ReissuanceParams,\n} from \".\";\nimport {\n AssetGroup,\n AssetId,\n AssetInput,\n AssetOutput,\n AssetRef,\n Metadata,\n Packet,\n} from \"../extension/asset\";\nimport { IndexerProvider } from \"../providers/indexer\";\nimport { ArkAddress } from \"../script/address\";\nimport { selectedCoinsToAssetInputs, selectCoinsWithAsset } from \"./asset\";\nimport { Extension } from \"../extension\";\nimport { selectVirtualCoins, Wallet } from \"./wallet\";\n\nexport class ReadonlyAssetManager implements IReadonlyAssetManager {\n constructor(readonly indexer: IndexerProvider) {}\n\n async getAssetDetails(assetId: string): Promise<AssetDetails> {\n // TODO: rely on db, and fallback to indexer if not found\n return this.indexer.getAssetDetails(assetId);\n }\n}\n\nexport class AssetManager extends ReadonlyAssetManager implements IAssetManager {\n constructor(readonly wallet: Wallet) {\n super(wallet.indexerProvider);\n }\n\n /**\n * Issue a new asset.\n * @param params - Parameters for asset issuance\n * @param params.amount - Amount of asset units to issue\n * @param params.controlAssetId - Optional control asset ID (for reissuable assets)\n * @param params.metadata - Optional metadata to attach to the asset\n * @returns Promise resolving to the Arkade transaction ID and asset ID\n *\n * @example\n * ```typescript\n * // Issue a simple non-reissuable asset\n * const result = await wallet.assetManager.issue({ amount: 1000 });\n * console.log('Asset ID:', result.assetId);\n *\n * // Issue a reissuable asset with an existing control asset\n * const result = await wallet.assetManager.issue({\n * amount: 1000,\n * controlAssetId: 'existingControlAssetId'\n * });\n * console.log('Asset ID:', result.assetId);\n * ```\n */\n async issue(params: IssuanceParams): Promise<IssuanceResult> {\n if (params.amount <= 0n) {\n throw new Error(`Issue amount must be greater than 0, got ${params.amount}`);\n }\n\n const metadata = castMetadata(params.metadata);\n\n const virtualCoins = await this.wallet.getVtxos({\n withRecoverable: false,\n });\n\n const controlAssetRef = params.controlAssetId\n ? AssetRef.fromId(AssetId.fromString(params.controlAssetId))\n : null;\n\n const coinSelection = selectVirtualCoins(virtualCoins, Number(this.wallet.dustAmount));\n let totalBtcSelected = 0n;\n\n // keep track of asset changes\n const assetChanges = new Map<string, bigint>();\n\n for (const coin of coinSelection.inputs) {\n totalBtcSelected += BigInt(coin.value);\n if (!coin.assets) continue;\n for (const { assetId, amount } of coin.assets) {\n const existing = assetChanges.get(assetId) ?? 0n;\n assetChanges.set(assetId, existing + amount);\n }\n }\n\n const groups: AssetGroup[] = [];\n\n // issued asset group\n const issuedAssetOutput = AssetOutput.create(0, params.amount);\n const issuedAssetGroup = AssetGroup.create(\n null,\n controlAssetRef,\n [],\n [issuedAssetOutput],\n metadata,\n );\n groups.push(issuedAssetGroup);\n\n // add asset groups for each asset change\n if (assetChanges.size > 0) {\n const assetInputs = selectedCoinsToAssetInputs(coinSelection.inputs);\n\n for (const [assetId, amount] of assetChanges) {\n const changeInputs: AssetInput[] = [];\n\n // collect all inputs for the asset change\n for (const [inputIndex, assets] of assetInputs) {\n for (const asset of assets) {\n if (asset.assetId !== assetId) continue;\n changeInputs.push(AssetInput.create(inputIndex, asset.amount));\n }\n }\n\n // add the change asset group\n groups.push(\n AssetGroup.create(\n AssetId.fromString(assetId),\n null,\n changeInputs,\n [AssetOutput.create(0, amount)],\n [],\n ),\n );\n }\n }\n\n // build transaction outputs\n const address = await this.wallet.getAddress();\n const outputAddress = ArkAddress.decode(address);\n const outputs = [\n {\n script: outputAddress.pkScript,\n amount: BigInt(totalBtcSelected),\n },\n Extension.create([Packet.create(groups)]).txOut(),\n ];\n\n const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(\n coinSelection.inputs,\n outputs,\n );\n return {\n arkTxId: arkTxid,\n assetId: AssetId.create(arkTxid, 0).toString(),\n };\n }\n\n /**\n * Reissue more units of an existing asset.\n * Requires ownership of the control asset.\n *\n * @param params - Parameters for asset reissuance\n * @param params.assetId - The asset ID to reissue (control asset ID is resolved via getAssetDetails)\n * @param params.amount - Amount of additional units to issue\n * @returns Promise resolving to the Arkade transaction ID\n *\n * @example\n * ```typescript\n * const txid = await wallet.assetManager.reissue({\n * assetId: 'def456...',\n * amount: 500\n * });\n * ```\n */\n async reissue(params: ReissuanceParams): Promise<string> {\n if (params.amount <= 0n) {\n throw new Error(`Reissuance amount must be greater than 0, got ${params.amount}`);\n }\n\n const { controlAssetId } = await this.getAssetDetails(params.assetId);\n if (!controlAssetId) {\n throw new Error(`Asset ${params.assetId} is not reissuable`);\n }\n\n const virtualCoins = await this.wallet.getVtxos({\n withRecoverable: false,\n });\n\n const assetChanges = new Map<string, bigint>();\n\n // select control asset inputs\n const { selected: controlCoins } = selectCoinsWithAsset(virtualCoins, controlAssetId, 1n);\n\n let selectedCoins = [...controlCoins];\n let assetToReissueAmount = 0n;\n\n // all control inputs assets go to asset changes, including the control asset itself\n for (const coin of controlCoins) {\n if (!coin.assets) continue;\n for (const { assetId, amount } of coin.assets) {\n if (assetId === params.assetId) {\n assetToReissueAmount += amount;\n continue;\n }\n const existing = assetChanges.get(assetId) ?? 0n;\n assetChanges.set(assetId, existing + amount);\n }\n }\n\n // select at least dust amount\n const minBtcNeeded = Number(this.wallet.dustAmount);\n let totalBtcSelected = selectedCoins.reduce((sum, c) => sum + c.value, 0);\n\n if (totalBtcSelected < minBtcNeeded) {\n const remainingCoins = virtualCoins.filter(\n (c) => !selectedCoins.find((sc) => sc.txid === c.txid && sc.vout === c.vout),\n );\n const additional = selectVirtualCoins(remainingCoins, minBtcNeeded - totalBtcSelected);\n for (const coin of additional.inputs) {\n // additional inputs assets go to asset changes\n if (!coin.assets) continue;\n for (const { assetId, amount } of coin.assets) {\n if (assetId === params.assetId) {\n assetToReissueAmount += amount;\n continue;\n }\n const existing = assetChanges.get(assetId) ?? 0n;\n assetChanges.set(assetId, existing + amount);\n }\n }\n selectedCoins = [...selectedCoins, ...additional.inputs];\n totalBtcSelected += additional.inputs.reduce((sum, c) => sum + c.value, 0);\n }\n\n const assetInputs = selectedCoinsToAssetInputs(selectedCoins);\n\n // collect all inputs for the asset to reissue\n const reissueInputs: AssetInput[] = [];\n for (const [inputIndex, assets] of assetInputs) {\n for (const asset of assets) {\n if (asset.assetId !== params.assetId) continue;\n reissueInputs.push(AssetInput.create(inputIndex, asset.amount));\n }\n }\n\n // the total output amount of the asset to reissue = new + (optional) selected amount\n const totalAssetAmount = assetToReissueAmount + params.amount;\n const reissueAssetIdObj = AssetId.fromString(params.assetId);\n\n // create the reissuance asset group\n const reissueAssetGroup = AssetGroup.create(\n reissueAssetIdObj,\n null,\n reissueInputs,\n [AssetOutput.create(0, totalAssetAmount)],\n [],\n );\n\n const groups = [reissueAssetGroup];\n\n // for each asset change, create a new asset group\n for (const [assetId, amount] of assetChanges) {\n const changeInputs: AssetInput[] = [];\n for (const [inputIndex, assets] of assetInputs) {\n for (const asset of assets) {\n if (asset.assetId !== assetId) continue;\n changeInputs.push(AssetInput.create(inputIndex, asset.amount));\n }\n }\n groups.push(\n AssetGroup.create(\n AssetId.fromString(assetId),\n null,\n changeInputs,\n [AssetOutput.create(0, amount)],\n [],\n ),\n );\n }\n\n // build transaction outputs\n const address = await this.wallet.getAddress();\n const outputAddress = ArkAddress.decode(address);\n const outputs = [\n {\n script: outputAddress.pkScript,\n amount: BigInt(totalBtcSelected),\n },\n Extension.create([Packet.create(groups)]).txOut(),\n ];\n\n const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(selectedCoins, outputs);\n return arkTxid;\n }\n\n /**\n * Burn assets.\n * @param params - Parameters for burning\n * @param params.assetId - The asset ID to burn\n * @param params.amount - Amount of units to burn\n * @returns Promise resolving to the Arkade transaction ID\n *\n * @example\n * ```typescript\n * const txid = await wallet.assetManager.burn({\n * assetId: 'abc123...',\n * amount: 100\n * });\n * ```\n */\n async burn(params: BurnParams): Promise<string> {\n if (params.amount <= 0n) {\n throw new Error(`Burn amount must be greater than 0, got ${params.amount}`);\n }\n\n const virtualCoins = await this.wallet.getVtxos({\n withRecoverable: false,\n });\n\n const assetChanges = new Map<string, bigint>();\n\n // select virtual outputs with the asset to burn\n const { selected: assetCoins } = selectCoinsWithAsset(\n virtualCoins,\n params.assetId,\n params.amount,\n );\n\n const selectedCoins = [...assetCoins];\n let totalBtcSelected = 0;\n\n // add the selected coins to asset changes, including the asset to burn\n for (const coin of assetCoins) {\n totalBtcSelected += coin.value;\n if (!coin.assets) continue;\n for (const { assetId, amount } of coin.assets) {\n const existing = assetChanges.get(assetId) ?? 0n;\n assetChanges.set(assetId, existing + amount);\n }\n }\n // subtract the amount to burn from the asset change\n assetChanges.set(params.assetId, (assetChanges.get(params.assetId) ?? 0n) - params.amount);\n\n const minBtcNeeded = Number(this.wallet.dustAmount);\n\n // we need to ensure at least dust amount is selected\n // if not, select additional coins\n if (totalBtcSelected < minBtcNeeded) {\n const remainingCoins = virtualCoins.filter(\n (c) => !selectedCoins.find((sc) => sc.txid === c.txid && sc.vout === c.vout),\n );\n const additional = selectVirtualCoins(remainingCoins, minBtcNeeded - totalBtcSelected);\n\n // additional inputs assets go to asset changes\n for (const coin of additional.inputs) {\n totalBtcSelected += coin.value;\n if (!coin.assets) continue;\n for (const { assetId, amount } of coin.assets) {\n const existing = assetChanges.get(assetId) ?? 0n;\n assetChanges.set(assetId, existing + amount);\n }\n }\n\n selectedCoins.push(...additional.inputs);\n }\n\n const groups: AssetGroup[] = [];\n const assetInputs = selectedCoinsToAssetInputs(selectedCoins);\n\n // for each asset, create a new asset group\n for (const [assetId, amount] of assetChanges) {\n const changeInputs: AssetInput[] = [];\n for (const [inputIndex, assets] of assetInputs) {\n for (const asset of assets) {\n if (asset.assetId !== assetId) continue;\n changeInputs.push(AssetInput.create(inputIndex, asset.amount));\n }\n }\n groups.push(\n AssetGroup.create(\n AssetId.fromString(assetId),\n null,\n changeInputs,\n amount > 0n ? [AssetOutput.create(0, amount)] : [],\n [],\n ),\n );\n }\n\n // build transaction outputs\n const address = await this.wallet.getAddress();\n const outputAddress = ArkAddress.decode(address);\n const outputs = [\n {\n script: outputAddress.pkScript,\n amount: BigInt(totalBtcSelected),\n },\n Extension.create([Packet.create(groups)]).txOut(),\n ];\n\n const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(selectedCoins, outputs);\n return arkTxid;\n }\n}\n\nfunction castMetadata(metadata?: AssetMetadata): Metadata[] {\n if (!metadata) {\n return [];\n }\n\n const md: Metadata[] = [];\n const textEncoder = new TextEncoder();\n for (const [key, value] of Object.entries(metadata)) {\n // convert value to bytes\n let valueBytes: Uint8Array;\n if (typeof value === \"string\") {\n valueBytes = textEncoder.encode(value);\n } else if (typeof value === \"number\") {\n valueBytes = textEncoder.encode(String(value));\n } else if (value instanceof Uint8Array) {\n valueBytes = value;\n } else if (value instanceof ArrayBuffer) {\n valueBytes = new Uint8Array(value);\n } else {\n throw new Error(\"Invalid metadata value type\");\n }\n\n md.push(Metadata.create(textEncoder.encode(key), valueBytes));\n }\n return md;\n}\n","import { TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport {\n ArkAddress,\n ArkInfo,\n ArkProvider,\n Asset,\n decodeTapscript,\n DelegateInfo,\n Estimator,\n ExtendedCoin,\n ExtendedVirtualCoin,\n Identity,\n Intent,\n isRecoverable,\n MultisigTapscript,\n Outpoint,\n Recipient,\n SignedIntent,\n TapLeafScript,\n Transaction,\n VirtualCoin,\n VtxoScript,\n} from \"..\";\nimport { ContractVtxo } from \"../contracts/types\";\nimport { DelegatorProvider } from \"../providers/delegator\";\nimport { base64, hex } from \"@scure/base\";\nimport { scriptFromTapLeafScript } from \"../script/base\";\nimport { buildForfeitTxWithOutput } from \"../forfeit\";\nimport { Address, OutScript, SigHash } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { equalBytes } from \"@scure/btc-signer/utils.js\";\nimport { getNetwork, NetworkName } from \"../networks\";\nimport { createAssetPacket } from \"./asset\";\nimport { Extension } from \"../extension\";\n\nexport interface IDelegatorManager {\n /**\n * Delegate virtual outputs to the remote delegation service.\n *\n * Vtxos that are not locked to a delegate-type contract (no tap leaf\n * matches the delegator's pubkey) are filtered out silently, since they\n * cannot be co-signed by the delegator.\n *\n * @param vtxos - Virtual outputs to delegate\n * @param destination - Arkade address that should receive renewed funds\n * @param delegateAt - Optional timestamp to force a specific delegation time\n * @returns Successfully delegated and failed outpoint groups\n */\n delegate(\n vtxos: ContractVtxo[],\n destination: string,\n delegateAt?: Date,\n ): Promise<{\n delegated: Outpoint[];\n failed: { outpoints: Outpoint[]; error: unknown }[];\n }>;\n\n /** Fetch delegate metadata such as pubkey, fee, and delegate address. */\n getDelegateInfo(): Promise<DelegateInfo>;\n}\n\nexport class DelegatorManagerImpl implements IDelegatorManager {\n /** Create a delegator manager from the configured provider, Arkade info source, and wallet identity. */\n constructor(\n readonly delegatorProvider: DelegatorProvider,\n readonly arkInfoProvider: Pick<ArkProvider, \"getInfo\">,\n readonly identity: Identity,\n ) {}\n\n async getDelegateInfo(): Promise<DelegateInfo> {\n return this.delegatorProvider.getDelegateInfo();\n }\n\n async delegate(\n vtxos: ContractVtxo[],\n destination: string,\n delegateAt?: Date,\n ): Promise<{\n delegated: Outpoint[];\n failed: { outpoints: Outpoint[]; error: unknown }[];\n }> {\n if (vtxos.length === 0) {\n return { delegated: [], failed: [] };\n }\n\n const destinationScript = ArkAddress.decode(destination).pkScript;\n\n // fetch server and delegator info once, shared across all groups\n const arkInfo = await this.arkInfoProvider.getInfo();\n const delegateInfo = await this.delegatorProvider.getDelegateInfo();\n\n // keep only vtxos that can be signed by the delegate. The guard\n // narrows ContractVtxo (with optional taproot fields) to the\n // ExtendedVirtualCoin shape required by makeDelegateForfeitTx.\n const eligible = vtxos.filter(\n (v): v is ContractVtxo & ExtendedVirtualCoin =>\n isAnnotated(v) && findDelegateTapLeaf(v, delegateInfo.pubkey) !== undefined,\n );\n if (eligible.length === 0) {\n return { delegated: [], failed: [] };\n }\n\n // if explicit delegateAt is provided, delegate all virtual outputs at once without sorting\n if (delegateAt) {\n try {\n await delegate(\n this.identity,\n this.delegatorProvider,\n arkInfo,\n delegateInfo,\n eligible,\n destinationScript,\n delegateAt,\n );\n } catch (error) {\n return {\n delegated: [],\n failed: [{ outpoints: eligible, error }],\n };\n }\n return { delegated: eligible, failed: [] };\n }\n\n // if no explicit delegateAt is provided, sort virtual outputs by expiry and delegate in groups of the same expiry day\n const groupByExpiry: Map<number, ExtendedVirtualCoin[]> = new Map();\n let recoverableVtxos: ExtendedVirtualCoin[] = [];\n\n for (const vtxo of eligible) {\n if (isRecoverable(vtxo)) {\n recoverableVtxos.push(vtxo);\n continue;\n }\n\n const expiry = vtxo.virtualStatus.batchExpiry;\n if (!expiry) continue;\n\n const dayKey = getDayTimestamp(expiry);\n groupByExpiry.set(dayKey, [...(groupByExpiry.get(dayKey) ?? []), vtxo]);\n }\n\n // if no groups, it means we only need to delegate the recoverable virtual outputs\n if (groupByExpiry.size === 0) {\n try {\n await delegate(\n this.identity,\n this.delegatorProvider,\n arkInfo,\n delegateInfo,\n recoverableVtxos,\n destinationScript,\n delegateAt,\n );\n } catch (error) {\n return {\n delegated: [],\n failed: [{ outpoints: recoverableVtxos, error }],\n };\n }\n return { delegated: recoverableVtxos, failed: [] };\n }\n\n // search for the earliest group, include recoverable virtual outputs into it\n const earliestGroup = Math.min(...groupByExpiry.keys());\n\n groupByExpiry.set(earliestGroup, [\n ...(groupByExpiry.get(earliestGroup) ?? []),\n ...recoverableVtxos,\n ]);\n\n const groupsList = Array.from(groupByExpiry.entries());\n\n const result = await Promise.allSettled(\n groupsList.map(async ([, vtxosGroup]) =>\n delegate(\n this.identity,\n this.delegatorProvider,\n arkInfo,\n delegateInfo,\n vtxosGroup,\n destinationScript,\n ),\n ),\n );\n\n const delegated: Outpoint[] = [];\n const failed: { outpoints: Outpoint[]; error: unknown }[] = [];\n\n for (const [index, resultItem] of result.entries()) {\n const vtxos = groupsList[index][1];\n if (resultItem.status === \"rejected\") {\n failed.push({ outpoints: vtxos, error: resultItem.reason });\n continue;\n }\n\n delegated.push(...vtxos);\n }\n\n return { delegated, failed };\n }\n}\n\n/**\n * Delegates virtual outputs to a delegation service, allowing them to manage their renewal\n * on behalf of the wallet owner.\n * @param vtxos - Array of extended virtual outputs to delegate. Must not be empty.\n * @param delegateAt - Optional Date specifying when the delegation\n * should occur. If not provided, defaults to 12 hours before the earliest\n * expiry time of the provided vtxos.\n */\nasync function delegate(\n identity: Identity,\n delegatorProvider: DelegatorProvider,\n arkInfo: ArkInfo,\n delegateInfo: DelegateInfo,\n vtxos: ExtendedVirtualCoin[],\n destinationScript: Bytes,\n delegateAt?: Date,\n): Promise<void> {\n if (vtxos.length === 0) {\n throw new Error(\"unable to delegate: no vtxos provided\");\n }\n\n if (!delegatorProvider) {\n throw new Error(\"unable to delegate: delegator provider not configured\");\n }\n\n if (!delegateAt) {\n const expiryTimestamp = vtxos\n .filter((coin) => !isRecoverable(coin) && coin.virtualStatus.batchExpiry)\n .reduce(\n (min, coin) => Math.min(min, coin.virtualStatus.batchExpiry!),\n Number.MAX_SAFE_INTEGER,\n );\n if (!expiryTimestamp || expiryTimestamp === Number.MAX_SAFE_INTEGER) {\n // if no expiry (recoverable virtual outputs), delegate 1 minute from now\n delegateAt = new Date(Date.now() + 1 * 60 * 1000);\n } else {\n const remainingTimeMs = expiryTimestamp - Date.now();\n if (remainingTimeMs <= 0) {\n delegateAt = new Date(Date.now() + 1 * 60 * 1000);\n } else {\n // delegate 10% before the expiry\n delegateAt = new Date(expiryTimestamp - remainingTimeMs * 0.1);\n }\n }\n }\n const { fees, dust, forfeitAddress, network } = arkInfo;\n\n const delegateAtSeconds = delegateAt.getTime() / 1000;\n const estimator = new Estimator({\n ...fees.intentFee,\n // replace now() function with the delegateAt timestamp\n offchainInput: fees.intentFee.offchainInput?.replace(\n \"now()\",\n `double(${delegateAtSeconds})`,\n ),\n offchainOutput: fees.intentFee.offchainOutput?.replace(\n \"now()\",\n `double(${delegateAtSeconds})`,\n ),\n });\n\n let amount = 0n;\n for (const coin of vtxos) {\n const inputFee = estimator.evalOffchainInput({\n amount: BigInt(coin.value),\n type: \"vtxo\",\n weight: 0,\n birth: coin.createdAt,\n expiry: coin.virtualStatus.batchExpiry\n ? new Date(coin.virtualStatus.batchExpiry)\n : undefined,\n });\n if (inputFee.value >= coin.value) {\n continue;\n }\n amount += BigInt(coin.value) - BigInt(inputFee.value);\n }\n const { delegatorAddress, pubkey, fee } = delegateInfo;\n\n const outputs = [];\n const delegatorFee = BigInt(Number(fee));\n\n if (delegatorFee > 0n) {\n outputs.push({\n script: ArkAddress.decode(delegatorAddress).pkScript,\n amount: delegatorFee,\n });\n }\n\n const outputFee = outputs.reduce((fee, output) => {\n if (!output.amount || !output.script) return fee;\n return (\n fee +\n estimator.evalOffchainOutput({\n amount: output.amount,\n script: hex.encode(output.script),\n }).satoshis\n );\n }, 0);\n\n if (amount - BigInt(outputFee) <= dust) {\n throw new Error(\"Amount is below dust limit, cannot delegate\");\n }\n amount -= BigInt(outputFee);\n\n amount -= delegatorFee;\n if (amount <= dust) {\n throw new Error(\"Amount is below dust limit, cannot delegate\");\n }\n\n outputs.push({\n script: destinationScript,\n amount: amount,\n });\n\n const registerIntent = await makeSignedDelegateIntent(\n identity,\n vtxos,\n outputs,\n [],\n [pubkey],\n delegateAtSeconds,\n destinationScript,\n );\n\n const forfeitOutputScript = OutScript.encode(\n Address(getNetwork(network as NetworkName)).decode(forfeitAddress),\n );\n\n const forfeits = await Promise.all(\n vtxos\n .filter((v) => !isRecoverable(v))\n .map(async (coin) => {\n const forfeit = await makeDelegateForfeitTx(\n coin,\n dust,\n pubkey,\n forfeitOutputScript,\n identity,\n );\n return base64.encode(forfeit.toPSBT());\n }),\n );\n\n await delegatorProvider.delegate(registerIntent, forfeits);\n}\n\nasync function makeDelegateForfeitTx(\n input: ExtendedVirtualCoin,\n connectorAmount: bigint,\n delegatePubkey: string,\n forfeitOutputScript: Bytes,\n identity: Identity,\n): Promise<Transaction> {\n const delegateTapLeaf = findDelegateTapLeaf(input, delegatePubkey);\n if (!delegateTapLeaf) {\n throw new Error(`delegate tap leaf not found for input: ${input.txid}:${input.vout}`);\n }\n\n const tx = buildForfeitTxWithOutput(\n [\n {\n txid: input.txid,\n index: input.vout,\n witnessUtxo: {\n amount: BigInt(input.value),\n script: VtxoScript.decode(input.tapTree).pkScript,\n },\n sighashType: SigHash.ALL_ANYONECANPAY,\n tapLeafScript: [delegateTapLeaf],\n },\n ],\n {\n script: forfeitOutputScript,\n amount: BigInt(input.value) + connectorAmount,\n },\n );\n\n return identity.sign(tx);\n}\n\nasync function makeSignedDelegateIntent(\n identity: Identity,\n coins: ExtendedCoin[],\n outputs: TransactionOutput[],\n onchainOutputsIndexes: number[],\n cosignerPubKeys: string[],\n validAt: number,\n destinationScript: Bytes,\n): Promise<SignedIntent<Intent.RegisterMessage>> {\n // if some of the inputs hold assets, build the asset packet and append as output\n // in the intent proof tx, there is a \"fake\" input at index 0\n // so the real coin indices are offset by +1\n const assetInputs = new Map<number, Asset[]>();\n for (let i = 0; i < coins.length; i++) {\n if (\"assets\" in coins[i]) {\n const assets = (coins[i] as unknown as VirtualCoin).assets;\n if (assets && assets.length > 0) {\n assetInputs.set(i + 1, assets);\n }\n }\n }\n\n let outputAssets: Asset[] | undefined;\n\n const assetOutputIndex = findDestinationOutputIndex(outputs, destinationScript);\n\n if (assetInputs.size > 0) {\n if (assetOutputIndex === -1) {\n throw new Error(\"Cannot assign assets: no output matches the destination address\");\n }\n // collect all input assets and assign them to the first offchain output\n const allAssets = new Map<string, bigint>();\n for (const [, assets] of assetInputs) {\n for (const asset of assets) {\n const existing = allAssets.get(asset.assetId) ?? 0n;\n allAssets.set(asset.assetId, existing + asset.amount);\n }\n }\n\n outputAssets = [];\n for (const [assetId, amount] of allAssets) {\n outputAssets.push({ assetId, amount });\n }\n }\n\n const recipients: Recipient[] = outputs.map((output, i) => ({\n address: \"\", // not needed for asset packet creation\n amount: Number(output.amount),\n assets: i === assetOutputIndex ? outputAssets : undefined,\n }));\n\n if (outputAssets && outputAssets.length > 0) {\n const assetPacket = createAssetPacket(assetInputs, recipients);\n outputs.push(Extension.create([assetPacket]).txOut());\n }\n\n const message: Intent.RegisterMessage = {\n type: \"register\",\n onchain_output_indexes: onchainOutputsIndexes,\n valid_at: Math.floor(validAt),\n expire_at: 0,\n cosigners_public_keys: cosignerPubKeys,\n };\n\n const proof = Intent.create(message, coins, outputs);\n const signedProof = await identity.sign(proof);\n\n return {\n proof: base64.encode(signedProof.toPSBT()),\n message,\n };\n}\n\n/**\n * Finds the index of the output whose script matches the destination script.\n * Returns -1 if no match is found.\n */\nexport function findDestinationOutputIndex(\n outputs: TransactionOutput[],\n destinationScript: Bytes,\n): number {\n return outputs.findIndex((o) => o.script && equalBytes(o.script, destinationScript));\n}\n\nfunction getDayTimestamp(timestamp: number): number {\n const date = new Date(timestamp);\n date.setUTCHours(0, 0, 0, 0);\n return date.getTime();\n}\n\nfunction findDelegateTapLeaf(\n vtxo: { tapTree?: Bytes },\n delegatePubkey: string,\n): TapLeafScript | undefined {\n if (!vtxo.tapTree) return undefined;\n const pk = delegatePubkey.length === 66 ? delegatePubkey.slice(2) : delegatePubkey;\n const vtxoScript = VtxoScript.decode(vtxo.tapTree);\n return vtxoScript.leaves.find((tapLeaf) => {\n const arkTapscript = decodeTapscript(scriptFromTapLeafScript(tapLeaf));\n if (!MultisigTapscript.is(arkTapscript)) return false;\n return arkTapscript.params.pubkeys.map(hex.encode).includes(pk);\n });\n}\n\nfunction isAnnotated(v: ContractVtxo): v is ContractVtxo & ExtendedVirtualCoin {\n return (\n v.tapTree !== undefined &&\n v.forfeitTapLeafScript !== undefined &&\n v.intentTapLeafScript !== undefined\n );\n}\n","import type { ExtendedVirtualCoin, VirtualCoin } from \"../wallet\";\nimport type { WalletRepository } from \"../repositories/walletRepository\";\nimport type { Contract } from \"./types\";\n\n/**\n * Tier 1 helpers that enforce VTXO ownership at call sites that already know\n * the intended contract script. Address-keyed repositories may still hand back\n * legacy duplicate rows under the wrong bucket; these helpers gate reads and\n * writes so a wrong-script row never wins.\n *\n * `script` is the authoritative ownership key. Equality is strict: a missing\n * or empty `vtxo.script` never matches.\n */\n\nexport function vtxoOutpoint(vtxo: Pick<VirtualCoin, \"txid\" | \"vout\">): string {\n return `${vtxo.txid}:${vtxo.vout}`;\n}\n\nexport function isVtxoForScript(vtxo: Pick<VirtualCoin, \"script\">, script: string): boolean {\n return !!vtxo.script && vtxo.script === script;\n}\n\nexport function filterVtxosForScript<T extends Pick<VirtualCoin, \"script\">>(\n vtxos: T[],\n script: string,\n): T[] {\n return vtxos.filter((v) => isVtxoForScript(v, script));\n}\n\n/**\n * Background/indexer sync flavour: drop wrong-script rows and log enough\n * context to identify each rejection. Returns only matching rows so the\n * caller can keep going.\n */\nexport function warnAndFilterVtxosForScript<\n T extends Pick<VirtualCoin, \"txid\" | \"vout\" | \"script\">,\n>(vtxos: T[], script: string, context: string): T[] {\n const matches: T[] = [];\n const rejected: string[] = [];\n for (const v of vtxos) {\n if (isVtxoForScript(v, script)) {\n matches.push(v);\n } else {\n rejected.push(`${vtxoOutpoint(v)}(script=${v.script ?? \"\"})`);\n }\n }\n if (rejected.length > 0) {\n console.warn(\n `${context}: dropped ${rejected.length} wrong-script VTXO(s) for script ${script}: ${rejected.join(\", \")}`,\n );\n }\n return matches;\n}\n\n/**\n * User-initiated transaction/signing flavour: throw before persisting or\n * signing inconsistent ownership state. Silently skipping here would hide a\n * serious bug in the wallet's spend path.\n */\nexport function validateVtxosForScript(\n vtxos: Array<Pick<VirtualCoin, \"txid\" | \"vout\" | \"script\">>,\n script: string,\n context: string,\n): void {\n const mismatches = vtxos.filter((v) => !isVtxoForScript(v, script));\n if (mismatches.length === 0) return;\n const detail = mismatches.map((v) => `${vtxoOutpoint(v)}(script=${v.script ?? \"\"})`).join(\", \");\n throw new Error(\n `${context}: refusing to persist ${mismatches.length} VTXO(s) whose script does not match ${script}: ${detail}`,\n );\n}\n\n/**\n * Tier 2 dispatch helpers: route to script-scoped repository methods when\n * available, falling back to Tier 1 address-based filtering otherwise.\n */\nexport async function getVtxosForContract(\n repo: WalletRepository,\n contract: Pick<Contract, \"script\" | \"address\">,\n): Promise<ExtendedVirtualCoin[]> {\n return repo.getVtxosForScript\n ? repo.getVtxosForScript(contract.script)\n : filterVtxosForScript(await repo.getVtxos(contract.address), contract.script);\n}\n\nexport async function saveVtxosForContract(\n repo: WalletRepository,\n contract: Pick<Contract, \"script\" | \"address\">,\n vtxos: ExtendedVirtualCoin[],\n): Promise<void> {\n if (repo.saveVtxosForScript) {\n return repo.saveVtxosForScript(\n { script: contract.script, address: contract.address },\n vtxos,\n );\n }\n validateVtxosForScript(vtxos, contract.script, \"saveVtxosForContract\");\n return repo.saveVtxos(contract.address, vtxos);\n}\n","import { ArkTransaction, ExtendedCoin, ExtendedVirtualCoin } from \"../../wallet\";\nimport { WalletRepository, WalletState, VtxoRepositoryKey } from \"../walletRepository\";\nimport { isVtxoForScript } from \"../../contracts/vtxoOwnership\";\n\n/**\n * In-memory implementation of WalletRepository.\n * Data is ephemeral and scoped to the instance.\n */\nexport class InMemoryWalletRepository implements WalletRepository {\n readonly version = 1 as const;\n private readonly vtxosByAddress = new Map<string, ExtendedVirtualCoin[]>();\n private readonly utxosByAddress = new Map<string, ExtendedCoin[]>();\n private readonly txsByAddress = new Map<string, ArkTransaction[]>();\n\n private walletState: WalletState | null = null;\n\n async getVtxos(address: string): Promise<ExtendedVirtualCoin[]> {\n return this.vtxosByAddress.get(address) ?? [];\n }\n\n async saveVtxos(address: string, vtxos: ExtendedVirtualCoin[]): Promise<void> {\n const existing = this.vtxosByAddress.get(address) ?? [];\n const next = mergeByKey(existing, vtxos, (item) => `${item.txid}:${item.vout}`);\n this.vtxosByAddress.set(address, next);\n }\n\n async deleteVtxos(address: string): Promise<void> {\n this.vtxosByAddress.delete(address);\n }\n\n async getVtxosForScript(script: string): Promise<ExtendedVirtualCoin[]> {\n const allMatches: ExtendedVirtualCoin[] = [];\n for (const bucket of this.vtxosByAddress.values()) {\n for (const vtxo of bucket) {\n if (isVtxoForScript(vtxo, script)) {\n allMatches.push(vtxo);\n }\n }\n }\n // Dedup by outpoint (last-write-wins across address buckets)\n return mergeByKey([], allMatches, (item) => `${item.txid}:${item.vout}`);\n }\n\n async saveVtxosForScript(key: VtxoRepositoryKey, vtxos: ExtendedVirtualCoin[]): Promise<void> {\n if (!key.address) {\n throw new Error(\"InMemoryWalletRepository requires an address\");\n }\n for (const vtxo of vtxos) {\n if (!isVtxoForScript(vtxo, key.script)) {\n throw new Error(\n `VTXO ${vtxo.txid}:${vtxo.vout} script mismatch: expected ${key.script}, got ${vtxo.script}`,\n );\n }\n }\n return this.saveVtxos(key.address, vtxos);\n }\n\n async deleteVtxosForScript(script: string): Promise<void> {\n for (const [address, bucket] of this.vtxosByAddress.entries()) {\n const next = bucket.filter((v) => !isVtxoForScript(v, script));\n if (next.length === 0) {\n this.vtxosByAddress.delete(address);\n } else {\n this.vtxosByAddress.set(address, next);\n }\n }\n }\n\n async getUtxos(address: string): Promise<ExtendedCoin[]> {\n return this.utxosByAddress.get(address) ?? [];\n }\n\n async saveUtxos(address: string, utxos: ExtendedCoin[]): Promise<void> {\n const existing = this.utxosByAddress.get(address) ?? [];\n const next = mergeByKey(existing, utxos, (item) => `${item.txid}:${item.vout}`);\n this.utxosByAddress.set(address, next);\n }\n\n async deleteUtxos(address: string): Promise<void> {\n this.utxosByAddress.delete(address);\n }\n\n async getTransactionHistory(address: string): Promise<ArkTransaction[]> {\n return this.txsByAddress.get(address) ?? [];\n }\n\n async saveTransactions(address: string, txs: ArkTransaction[]): Promise<void> {\n const existing = this.txsByAddress.get(address) ?? [];\n const next = mergeByKey(existing, txs, serializeTxKey);\n this.txsByAddress.set(address, next);\n }\n\n async deleteTransactions(address: string): Promise<void> {\n this.txsByAddress.delete(address);\n }\n\n async getWalletState(): Promise<WalletState | null> {\n return this.walletState;\n }\n\n async saveWalletState(state: WalletState): Promise<void> {\n this.walletState = state;\n }\n\n async clear(): Promise<void> {\n this.vtxosByAddress.clear();\n this.utxosByAddress.clear();\n this.txsByAddress.clear();\n this.walletState = null;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n // nothing to dispose, data is ephemeral and scoped to the instance\n return;\n }\n}\n\nfunction serializeTxKey(tx: ArkTransaction): string {\n const key = tx.key;\n return `${key.boardingTxid}:${key.commitmentTxid}:${key.arkTxid}`;\n}\n\nfunction mergeByKey<T>(existing: T[], incoming: T[], toKey: (item: T) => string): T[] {\n const next = new Map<string, T>();\n existing.forEach((item) => {\n next.set(toKey(item), item);\n });\n incoming.forEach((item) => {\n next.set(toKey(item), item);\n });\n return Array.from(next.values());\n}\n","import { ContractFilter, ContractRepository } from \"../contractRepository\";\nimport { Contract } from \"../../contracts\";\n\n/**\n * In-memory implementation of ContractRepository.\n * Data is ephemeral and scoped to the instance.\n */\nexport class InMemoryContractRepository implements ContractRepository {\n readonly version = 1 as const;\n private readonly contractData = new Map<string, unknown>();\n private readonly collections = new Map<string, unknown[]>();\n private readonly contractsByScript = new Map<string, Contract>();\n\n async clear(): Promise<void> {\n this.contractData.clear();\n this.collections.clear();\n this.contractsByScript.clear();\n }\n\n // Contract entity management methods\n\n async getContracts(filter?: ContractFilter): Promise<Contract[]> {\n const contracts = this.contractsByScript.values();\n\n if (!filter) {\n return [...contracts];\n }\n\n const matches = <T>(value: T, criterion?: T | T[]) => {\n if (criterion === undefined) {\n return true;\n }\n return Array.isArray(criterion) ? criterion.includes(value) : value === criterion;\n };\n\n const results: Contract[] = [];\n for (const contract of contracts) {\n if (\n matches(contract.script, filter.script) &&\n matches(contract.state, filter.state) &&\n matches(contract.type, filter.type)\n ) {\n results.push(contract);\n }\n }\n return results;\n }\n\n async saveContract(contract: Contract): Promise<void> {\n this.contractsByScript.set(contract.script, contract);\n }\n\n async deleteContract(script: string): Promise<void> {\n this.contractsByScript.delete(script);\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n // nothing to dispose, data is ephemeral and scoped to the instance\n return;\n }\n}\n","import { hex } from \"@scure/base\";\nimport { ArkAddress } from \"../index\";\n\n/**\n * Compute the hex-encoded `scriptPubKey` locking a VTXO from its owning Ark\n * address. Used by repository-layer migrations to backfill `script` on legacy\n * rows that pre-date the column (the indexer now guarantees the field, so new\n * rows never go through this path). The `script` field is required by the\n * domain type, so backfill must produce the same value the indexer would\n * have returned — which is the hex of the address's `pkScript`.\n */\nexport function scriptFromArkAddress(address: string): string {\n return hex.encode(ArkAddress.decode(address).pkScript);\n}\n","import { scriptFromArkAddress } from \"../scriptFromAddress\";\n\n// Store names introduced in V2, they are all new to the migration\nexport const STORE_VTXOS = \"vtxos\";\nexport const STORE_UTXOS = \"utxos\";\nexport const STORE_TRANSACTIONS = \"transactions\";\nexport const STORE_WALLET_STATE = \"walletState\";\nexport const STORE_CONTRACTS = \"contracts\";\n\n// @deprecated use only for migrations, this is created in V1\nexport const LEGACY_STORE_CONTRACT_COLLECTIONS = \"contractsCollections\";\n\n// Version history:\n// v1 — initial wallet repo schema, `contractsCollections` store.\n// v2 — new `vtxos/utxos/transactions/walletState/contracts` stores.\n// v3 — add `script` index on the vtxos store and backfill missing\n// `vtxo.script` from `vtxo.address` so the field is always present\n// at read time. Matches the `script` indexing already in place for\n// Realm (`realm/schemas.ts`) and SQLite (`sqlite/walletRepository.ts`).\nexport const DB_VERSION = 3;\n\nexport function initDatabase(\n db: IDBDatabase,\n oldVersion: number,\n transaction: IDBTransaction | null,\n): void {\n // Create wallet stores\n if (!db.objectStoreNames.contains(STORE_VTXOS)) {\n const vtxosStore = db.createObjectStore(STORE_VTXOS, {\n keyPath: [\"address\", \"txid\", \"vout\"],\n });\n\n if (!vtxosStore.indexNames.contains(\"address\")) {\n vtxosStore.createIndex(\"address\", \"address\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"txid\")) {\n vtxosStore.createIndex(\"txid\", \"txid\", { unique: false });\n }\n if (!vtxosStore.indexNames.contains(\"value\")) {\n vtxosStore.createIndex(\"value\", \"value\", { unique: false });\n }\n if (!vtxosStore.indexNames.contains(\"status\")) {\n vtxosStore.createIndex(\"status\", \"status\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"virtualStatus\")) {\n vtxosStore.createIndex(\"virtualStatus\", \"virtualStatus\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"createdAt\")) {\n vtxosStore.createIndex(\"createdAt\", \"createdAt\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"isSpent\")) {\n vtxosStore.createIndex(\"isSpent\", \"isSpent\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"isUnrolled\")) {\n vtxosStore.createIndex(\"isUnrolled\", \"isUnrolled\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"spentBy\")) {\n vtxosStore.createIndex(\"spentBy\", \"spentBy\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"settledBy\")) {\n vtxosStore.createIndex(\"settledBy\", \"settledBy\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"arkTxId\")) {\n vtxosStore.createIndex(\"arkTxId\", \"arkTxId\", {\n unique: false,\n });\n }\n if (!vtxosStore.indexNames.contains(\"script\")) {\n vtxosStore.createIndex(\"script\", \"script\", {\n unique: false,\n });\n }\n }\n\n if (!db.objectStoreNames.contains(STORE_UTXOS)) {\n const utxosStore = db.createObjectStore(STORE_UTXOS, {\n keyPath: [\"address\", \"txid\", \"vout\"],\n });\n\n if (!utxosStore.indexNames.contains(\"address\")) {\n utxosStore.createIndex(\"address\", \"address\", {\n unique: false,\n });\n }\n if (!utxosStore.indexNames.contains(\"txid\")) {\n utxosStore.createIndex(\"txid\", \"txid\", { unique: false });\n }\n if (!utxosStore.indexNames.contains(\"value\")) {\n utxosStore.createIndex(\"value\", \"value\", { unique: false });\n }\n if (!utxosStore.indexNames.contains(\"status\")) {\n utxosStore.createIndex(\"status\", \"status\", {\n unique: false,\n });\n }\n }\n\n if (!db.objectStoreNames.contains(STORE_TRANSACTIONS)) {\n const transactionsStore = db.createObjectStore(STORE_TRANSACTIONS, {\n keyPath: [\"address\", \"keyBoardingTxid\", \"keyCommitmentTxid\", \"keyArkTxid\"],\n });\n\n if (!transactionsStore.indexNames.contains(\"address\")) {\n transactionsStore.createIndex(\"address\", \"address\", {\n unique: false,\n });\n }\n if (!transactionsStore.indexNames.contains(\"type\")) {\n transactionsStore.createIndex(\"type\", \"type\", {\n unique: false,\n });\n }\n if (!transactionsStore.indexNames.contains(\"amount\")) {\n transactionsStore.createIndex(\"amount\", \"amount\", {\n unique: false,\n });\n }\n if (!transactionsStore.indexNames.contains(\"settled\")) {\n transactionsStore.createIndex(\"settled\", \"settled\", {\n unique: false,\n });\n }\n if (!transactionsStore.indexNames.contains(\"createdAt\")) {\n transactionsStore.createIndex(\"createdAt\", \"createdAt\", {\n unique: false,\n });\n }\n if (!transactionsStore.indexNames.contains(\"arkTxid\")) {\n transactionsStore.createIndex(\"arkTxid\", \"key.arkTxid\", {\n unique: false,\n });\n }\n }\n\n if (!db.objectStoreNames.contains(STORE_WALLET_STATE)) {\n db.createObjectStore(STORE_WALLET_STATE, {\n keyPath: \"key\",\n });\n }\n\n // Create contract stores\n if (!db.objectStoreNames.contains(STORE_CONTRACTS)) {\n const contractsStore = db.createObjectStore(STORE_CONTRACTS, {\n keyPath: \"script\",\n });\n\n if (!contractsStore.indexNames.contains(\"type\")) {\n contractsStore.createIndex(\"type\", \"type\", {\n unique: false,\n });\n }\n if (!contractsStore.indexNames.contains(\"state\")) {\n contractsStore.createIndex(\"state\", \"state\", {\n unique: false,\n });\n }\n }\n\n if (!db.objectStoreNames.contains(LEGACY_STORE_CONTRACT_COLLECTIONS)) {\n db.createObjectStore(LEGACY_STORE_CONTRACT_COLLECTIONS, {\n keyPath: \"key\",\n });\n }\n\n // v2 → v3: add the `script` index on the existing vtxos store and\n // backfill missing `script` on legacy VTXO rows. The upgrade transaction\n // is null only on a brand-new database (oldVersion === 0), where no\n // legacy rows exist. `createIndex` scans existing records; rows still\n // missing `script` are skipped and get indexed automatically when the\n // backfill's `cursor.update()` adds the field.\n if (oldVersion >= 1 && oldVersion < 3 && transaction) {\n const vtxosStore = transaction.objectStore(STORE_VTXOS);\n if (!vtxosStore.indexNames.contains(\"script\")) {\n vtxosStore.createIndex(\"script\", \"script\", { unique: false });\n }\n backfillVtxoScripts(transaction);\n }\n}\n\n// Exported for unit tests — the `onupgradeneeded` transaction can't be\n// forged in-process, so tests exercise the cursor logic with a regular\n// readwrite transaction on a live DB.\nexport function backfillVtxoScripts(transaction: IDBTransaction): void {\n const store = transaction.objectStore(STORE_VTXOS);\n const cursorRequest = store.openCursor();\n cursorRequest.onsuccess = () => {\n const cursor = cursorRequest.result;\n if (!cursor) return;\n const value = cursor.value as { script?: string; address: string };\n if (!value.script) {\n value.script = scriptFromArkAddress(value.address);\n cursor.update(value);\n }\n cursor.continue();\n };\n}\n","import { hex } from \"@scure/base\";\nimport { TaprootControlBlock } from \"@scure/btc-signer\";\nimport { TapLeafScript } from \"../script/base\";\nimport { ArkTransaction, Asset, ExtendedCoin, ExtendedVirtualCoin } from \"../wallet\";\n\nexport type SerializedTapLeaf = { cb: string; s: string };\nexport type SerializedVtxo = ReturnType<typeof serializeVtxo>;\nexport type SerializedUtxo = ReturnType<typeof serializeUtxo>;\nexport type SerializedTransaction = ReturnType<typeof serializeTransaction>;\n\n// `Asset.amount` is a `bigint`, which `JSON.stringify` cannot serialize\n// (`TypeError: Do not know how to serialize a BigInt`). Persist it as a\n// decimal string so SQLite/Realm/legacy localStorage paths round-trip\n// correctly across process restarts.\nexport type SerializedAsset = { assetId: string; amount: string };\n\nexport const serializeTapLeaf = ([cb, s]: TapLeafScript): SerializedTapLeaf => ({\n cb: hex.encode(TaprootControlBlock.encode(cb)),\n s: hex.encode(s),\n});\n\nexport const serializeAsset = (a: Asset): SerializedAsset => ({\n assetId: a.assetId,\n amount: a.amount.toString(),\n});\n\n// Accept legacy persisted shapes where `amount` is a `number` — pre-bigint\n// data already on disk must keep round-tripping.\nexport const deserializeAsset = (a: {\n assetId: string;\n amount: string | number | bigint;\n}): Asset => {\n if (typeof a.amount === \"number\" && !Number.isSafeInteger(a.amount)) {\n throw new Error(\n `Unsafe legacy asset amount for ${a.assetId}; re-sync from the original source`,\n );\n }\n return {\n assetId: a.assetId,\n amount: typeof a.amount === \"bigint\" ? a.amount : BigInt(a.amount),\n };\n};\n\nexport const serializeAssets = (assets: Asset[] | undefined): SerializedAsset[] | undefined =>\n assets?.map(serializeAsset);\n\nexport const deserializeAssets = (\n assets: Array<{ assetId: string; amount: string | number | bigint }> | undefined,\n): Asset[] | undefined => assets?.map(deserializeAsset);\n\nexport const serializeVtxo = (v: ExtendedVirtualCoin) => ({\n ...v,\n tapTree: hex.encode(v.tapTree),\n forfeitTapLeafScript: serializeTapLeaf(v.forfeitTapLeafScript),\n intentTapLeafScript: serializeTapLeaf(v.intentTapLeafScript),\n extraWitness: v.extraWitness?.map(hex.encode),\n assets: serializeAssets(v.assets),\n});\n\nexport const serializeUtxo = (u: ExtendedCoin) => ({\n ...u,\n tapTree: hex.encode(u.tapTree),\n forfeitTapLeafScript: serializeTapLeaf(u.forfeitTapLeafScript),\n intentTapLeafScript: serializeTapLeaf(u.intentTapLeafScript),\n extraWitness: u.extraWitness?.map(hex.encode),\n});\n\nexport const serializeTransaction = (t: ArkTransaction) => ({\n ...t,\n assets: serializeAssets(t.assets),\n});\n\nexport const deserializeTapLeaf = (t: SerializedTapLeaf): TapLeafScript => {\n const cb = TaprootControlBlock.decode(hex.decode(t.cb));\n const s = hex.decode(t.s);\n return [cb, s];\n};\n\nexport const deserializeVtxo = (o: SerializedVtxo): ExtendedVirtualCoin => ({\n ...o,\n createdAt: new Date(o.createdAt),\n tapTree: hex.decode(o.tapTree),\n forfeitTapLeafScript: deserializeTapLeaf(o.forfeitTapLeafScript),\n intentTapLeafScript: deserializeTapLeaf(o.intentTapLeafScript),\n extraWitness: o.extraWitness?.map(hex.decode),\n assets: deserializeAssets(o.assets),\n});\n\nexport const deserializeUtxo = (o: SerializedUtxo): ExtendedCoin => ({\n ...o,\n tapTree: hex.decode(o.tapTree),\n forfeitTapLeafScript: deserializeTapLeaf(o.forfeitTapLeafScript),\n intentTapLeafScript: deserializeTapLeaf(o.intentTapLeafScript),\n extraWitness: o.extraWitness?.map(hex.decode),\n});\n\nexport const deserializeTransaction = (o: SerializedTransaction): ArkTransaction => ({\n ...o,\n assets: deserializeAssets(o.assets),\n});\n","export function getGlobalObject(): {\n globalObject: typeof globalThis;\n} {\n if (typeof globalThis !== \"undefined\") {\n if (typeof globalThis.self === \"object\" && globalThis.self !== null) {\n return { globalObject: globalThis.self };\n }\n if (typeof globalThis.window === \"object\" && globalThis.window !== null) {\n return { globalObject: globalThis.window };\n }\n return { globalObject: globalThis };\n }\n throw new Error(\"Global object not found\");\n}\n\ntype DBCacheEntry = {\n version: number;\n promise: Promise<IDBDatabase>;\n};\n\n// database instance cache, avoiding multiple open requests\nconst dbCache = new Map<string, DBCacheEntry>();\n// track reference counts for each database to avoid closing it prematurely\nconst refCounts = new Map<string, number>();\n\n/**\n * Opens an IndexedDB database and increments the reference count.\n * Handles global object detection and callbacks.\n *\n * @param dbName The name of the database to open.\n * @param dbVersion The database version to open.\n * @param initDatabase A function that migrates the database schema, called\n * on `onupgradeneeded` only. Receives the database, the previous version\n * (0 for fresh installs), and the upgrade transaction — the transaction is\n * required for data migrations (cursor/update on existing stores).\n *\n * @returns A promise that resolves to the database instance.\n */\nexport async function openDatabase(\n dbName: string,\n dbVersion: number,\n initDatabase: (db: IDBDatabase, oldVersion: number, transaction: IDBTransaction | null) => void,\n): Promise<IDBDatabase> {\n const { globalObject } = getGlobalObject();\n if (!globalObject.indexedDB) {\n throw new Error(\"IndexedDB is not available in this environment\");\n }\n\n // Return cached promise if available (handles concurrent calls)\n const cached = dbCache.get(dbName);\n if (cached) {\n if (cached.version !== dbVersion) {\n throw new Error(\n `Database \"${dbName}\" already opened with version ${cached.version}; requested ${dbVersion}`,\n );\n }\n refCounts.set(dbName, (refCounts.get(dbName) ?? 0) + 1);\n return cached.promise;\n }\n\n const dbPromise = new Promise<IDBDatabase>((resolve, reject) => {\n const request = globalObject.indexedDB.open(dbName, dbVersion);\n\n request.onerror = () => {\n dbCache.delete(dbName); // Clean up on failure\n refCounts.delete(dbName);\n reject(request.error);\n };\n request.onsuccess = () => {\n resolve(request.result);\n };\n request.onupgradeneeded = (event) => {\n const db = request.result;\n initDatabase(db, event.oldVersion, request.transaction);\n };\n request.onblocked = () => {\n console.warn(\"Database upgrade blocked - close other tabs/connections\");\n };\n });\n\n // Cache immediately before awaiting\n dbCache.set(dbName, { version: dbVersion, promise: dbPromise });\n refCounts.set(dbName, 1);\n\n return dbPromise;\n}\n\n/**\n * Decrements the reference count and closes the database when no references remain.\n *\n * @param dbName The name of the database to close.\n *\n * @returns True if the database was closed, false otherwise.\n */\nexport async function closeDatabase(dbName: string): Promise<boolean> {\n const cachedEntry = dbCache.get(dbName);\n if (!cachedEntry) return false;\n\n const count = (refCounts.get(dbName) ?? 1) - 1;\n if (count > 0) {\n refCounts.set(dbName, count);\n return false;\n }\n\n // Last reference — actually close\n refCounts.delete(dbName);\n dbCache.delete(dbName);\n\n try {\n const db = await cachedEntry.promise;\n db.close();\n } catch {\n // DB failed to open, nothing to close\n }\n return true;\n}\n","export const DEFAULT_DB_NAME = \"arkade-service-worker\";\nexport const DEFAULT_SERVICE_WORKER_ACTIVATION_TIMEOUT_MS = 10_000;\n\ntype SetupServiceWorkerOptions = {\n path: string;\n activationTimeoutMs?: number;\n};\n\nfunction normalizeOptions(\n pathOrOptions: string | SetupServiceWorkerOptions,\n): Required<SetupServiceWorkerOptions> {\n if (typeof pathOrOptions === \"string\") {\n return {\n path: pathOrOptions,\n activationTimeoutMs: DEFAULT_SERVICE_WORKER_ACTIVATION_TIMEOUT_MS,\n };\n }\n\n return {\n path: pathOrOptions.path,\n activationTimeoutMs:\n pathOrOptions.activationTimeoutMs ?? DEFAULT_SERVICE_WORKER_ACTIVATION_TIMEOUT_MS,\n };\n}\n\nfunction waitForServiceWorkerReady(timeoutMs: number) {\n return new Promise<ServiceWorkerRegistration>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(`Service worker activation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n navigator.serviceWorker.ready\n .then((registration) => {\n clearTimeout(timeoutId);\n resolve(registration);\n })\n .catch((error) => {\n clearTimeout(timeoutId);\n reject(error);\n });\n });\n}\n\n/**\n * setupServiceWorker sets up the service worker.\n * @param pathOrOptions - the path to the service worker script or setup options\n * @throws if service workers are not supported or activation fails\n * @example\n * ```typescript\n * const worker = await setupServiceWorker(\"/service-worker.js\");\n * ```\n */\nexport async function setupServiceWorker(\n pathOrOptions: string | SetupServiceWorkerOptions,\n): Promise<ServiceWorker> {\n // check if service workers are supported\n if (!(\"serviceWorker\" in navigator)) {\n throw new Error(\"Service workers are not supported in this browser\");\n }\n\n const { path, activationTimeoutMs } = normalizeOptions(pathOrOptions);\n\n // register service worker\n const registration = await navigator.serviceWorker.register(path);\n\n // force update to ensure the service worker is active\n await registration.update();\n\n const serviceWorker = registration.active || registration.waiting || registration.installing;\n if (!serviceWorker) {\n throw new Error(\"Failed to get service worker instance\");\n }\n\n if (serviceWorker.state === \"activated\") {\n return serviceWorker;\n }\n\n const readyRegistration = await waitForServiceWorkerReady(activationTimeoutMs);\n\n if (!readyRegistration.active) {\n throw new Error(\"Service worker registration is ready but has no active worker\");\n }\n\n return readyRegistration.active;\n}\n","import { DB_VERSION, STORE_CONTRACTS } from \"./db\";\nimport { Contract } from \"../../contracts\";\nimport { ContractFilter, ContractRepository } from \"../contractRepository\";\nimport { closeDatabase, openDatabase } from \"./manager\";\nimport { initDatabase } from \"./schema\";\nimport { DEFAULT_DB_NAME } from \"../../worker/browser/utils\";\n\n/**\n * IndexedDB-based implementation of ContractRepository.\n *\n * Data is stored as JSON strings in key/value stores.\n */\nexport class IndexedDBContractRepository implements ContractRepository {\n readonly version = 1 as const;\n private db: IDBDatabase | null = null;\n\n constructor(private readonly dbName: string = DEFAULT_DB_NAME) {}\n\n async clear(): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_CONTRACTS], \"readwrite\");\n const contractDataStore = transaction.objectStore(STORE_CONTRACTS);\n const contractsStore = transaction.objectStore(STORE_CONTRACTS);\n\n const contractDataRequest = contractDataStore.clear();\n const contractsRequest = contractsStore.clear();\n\n let completed = 0;\n const checkComplete = () => {\n completed++;\n if (completed === 2) {\n resolve();\n }\n };\n\n contractDataRequest.onsuccess = checkComplete;\n contractsRequest.onsuccess = checkComplete;\n\n contractDataRequest.onerror = () => reject(contractDataRequest.error);\n contractsRequest.onerror = () => reject(contractsRequest.error);\n });\n } catch (error) {\n console.error(\"Failed to clear contract data:\", error);\n throw error;\n }\n }\n\n async getContracts(filter?: ContractFilter): Promise<Contract[]> {\n try {\n const db = await this.getDB();\n const store = db\n .transaction([STORE_CONTRACTS], \"readonly\")\n .objectStore(STORE_CONTRACTS);\n\n if (!filter || Object.keys(filter).length === 0) {\n return new Promise((resolve, reject) => {\n const request = store.getAll();\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve(request.result ?? []);\n });\n }\n\n const normalizedFilter = normalizeFilter(filter);\n\n // first by script, primary key\n if (normalizedFilter.has(\"script\")) {\n const scripts = normalizedFilter.get(\"script\")!;\n const contracts = await Promise.all(\n scripts.map(\n (script) =>\n new Promise<Contract | undefined>((resolve, reject) => {\n const req = store.get(script);\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve(req.result);\n }),\n ),\n );\n return this.applyContractFilter(contracts, normalizedFilter);\n }\n\n // by state, still an index\n if (normalizedFilter.has(\"state\")) {\n const contracts = await this.getContractsByIndexValues(\n store,\n \"state\",\n normalizedFilter.get(\"state\")!,\n );\n return this.applyContractFilter(contracts, normalizedFilter);\n }\n\n // by type, still an index\n if (normalizedFilter.has(\"type\")) {\n const contracts = await this.getContractsByIndexValues(\n store,\n \"type\",\n normalizedFilter.get(\"type\")!,\n );\n return this.applyContractFilter(contracts, normalizedFilter);\n }\n\n // any other filtering happens in-memory\n const allContracts = await new Promise<Contract[]>((resolve, reject) => {\n const request = store.getAll();\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve(request.result ?? []);\n });\n return this.applyContractFilter(allContracts, normalizedFilter);\n } catch (error) {\n console.error(\"Failed to get contracts:\", error);\n return [];\n }\n }\n\n async saveContract(contract: Contract): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_CONTRACTS], \"readwrite\");\n const store = transaction.objectStore(STORE_CONTRACTS);\n const request = store.put(contract);\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve();\n });\n } catch (error) {\n console.error(\"Failed to save contract:\", error);\n throw error;\n }\n }\n\n async deleteContract(script: string): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_CONTRACTS], \"readwrite\");\n const store = transaction.objectStore(STORE_CONTRACTS);\n const getRequest = store.get(script);\n\n getRequest.onerror = () => reject(getRequest.error);\n getRequest.onsuccess = () => {\n const request = store.delete(script);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve();\n };\n });\n } catch (error) {\n console.error(`Failed to delete contract ${script}:`, error);\n throw error;\n }\n }\n\n private getContractsByIndexValues(\n store: IDBObjectStore,\n indexName: string,\n values: string[],\n ): Promise<Contract[]> {\n if (values.length === 0) return Promise.resolve([]);\n const index = store.index(indexName);\n const requests = values.map(\n (value) =>\n new Promise<Contract[]>((resolve, reject) => {\n const request = index.getAll(value);\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve(request.result ?? []);\n }),\n );\n return Promise.all(requests).then((results) => results.flatMap((result) => result));\n }\n\n private applyContractFilter(\n // can filter directly the result of a query\n contracts: (Contract | undefined)[],\n filter: ReturnType<typeof normalizeFilter>,\n ): Contract[] {\n return contracts.filter((contract) => {\n if (contract === undefined) return false;\n if (filter.has(\"script\") && !filter.get(\"script\")?.includes(contract.script))\n return false;\n if (filter.has(\"state\") && !filter.get(\"state\")?.includes(contract.state)) return false;\n if (filter.has(\"type\") && !filter.get(\"type\")?.includes(contract.type)) return false;\n return true;\n }) as Contract[];\n }\n\n private async getDB(): Promise<IDBDatabase> {\n if (this.db) return this.db;\n this.db = await openDatabase(this.dbName, DB_VERSION, initDatabase);\n return this.db;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (!this.db) return;\n await closeDatabase(this.dbName);\n this.db = null;\n }\n}\n\nconst FILTER_FIELDS = [\"script\", \"state\", \"type\"] as (keyof ContractFilter)[];\n\n// Transform all filter fields into an array of values\nfunction normalizeFilter(filter: ContractFilter) {\n const res = new Map<keyof ContractFilter, string[]>();\n FILTER_FIELDS.forEach((current) => {\n if (!filter?.[current]) return;\n if (Array.isArray(filter[current])) {\n res.set(current, filter[current]);\n } else {\n res.set(current, [filter[current]]);\n }\n });\n return res;\n}\n","import { ExtendedCoin, ExtendedVirtualCoin, ArkTransaction } from \"../../wallet\";\nimport { WalletRepository, WalletState, VtxoRepositoryKey } from \"../walletRepository\";\nimport {\n STORE_VTXOS,\n STORE_UTXOS,\n STORE_TRANSACTIONS,\n STORE_WALLET_STATE,\n serializeVtxo,\n serializeUtxo,\n deserializeVtxo,\n deserializeUtxo,\n SerializedVtxo,\n DB_VERSION,\n} from \"./db\";\nimport { closeDatabase, openDatabase } from \"./manager\";\nimport { initDatabase } from \"./schema\";\nimport { scriptFromArkAddress } from \"../scriptFromAddress\";\nimport { DEFAULT_DB_NAME } from \"../../worker/browser/utils\";\nimport { isVtxoForScript } from \"../../contracts/vtxoOwnership\";\n\n/**\n * IndexedDB-based implementation of WalletRepository.\n */\nexport class IndexedDBWalletRepository implements WalletRepository {\n readonly version = 1 as const;\n private db: IDBDatabase | null = null;\n\n constructor(private readonly dbName: string = DEFAULT_DB_NAME) {}\n\n async clear(): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction(\n [STORE_VTXOS, STORE_UTXOS, STORE_TRANSACTIONS, STORE_WALLET_STATE],\n \"readwrite\",\n );\n const vtxosStore = transaction.objectStore(STORE_VTXOS);\n const utxosStore = transaction.objectStore(STORE_UTXOS);\n const transactionsStore = transaction.objectStore(STORE_TRANSACTIONS);\n const walletStateStore = transaction.objectStore(STORE_WALLET_STATE);\n\n const requests = [\n vtxosStore.clear(),\n utxosStore.clear(),\n transactionsStore.clear(),\n walletStateStore.clear(),\n ];\n\n let completed = 0;\n const checkComplete = () => {\n completed++;\n if (completed === requests.length) {\n resolve();\n }\n };\n\n requests.forEach((request) => {\n request.onsuccess = checkComplete;\n request.onerror = () => reject(request.error);\n });\n });\n } catch (error) {\n console.error(\"Failed to clear wallet data:\", error);\n throw error;\n }\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (!this.db) return;\n await closeDatabase(this.dbName);\n this.db = null;\n }\n\n async getVtxos(address: string): Promise<ExtendedVirtualCoin[]> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_VTXOS], \"readonly\");\n const store = transaction.objectStore(STORE_VTXOS);\n const index = store.index(\"address\");\n const request: IDBRequest<(SerializedVtxo & { address: string })[]> =\n index.getAll(address);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const results = request.result || [];\n // Wrap `.map` in try/catch so a bad row (e.g. a legacy\n // VTXO whose address can't be decoded during backfill)\n // rejects the promise instead of silently throwing\n // inside the IDB event handler, which would otherwise\n // hang the caller.\n try {\n resolve(results.map(deserializeVtxoWithBackfill));\n } catch (err) {\n reject(err);\n }\n };\n });\n } catch (error) {\n console.error(`Failed to get VTXOs for address ${address}:`, error);\n return [];\n }\n }\n\n async saveVtxos(address: string, vtxos: ExtendedVirtualCoin[]): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_VTXOS], \"readwrite\");\n const store = transaction.objectStore(STORE_VTXOS);\n\n const promises = vtxos.map((vtxo) => {\n return new Promise<void>((resolveItem, rejectItem) => {\n const serialized: SerializedVtxo = serializeVtxo(vtxo);\n const item = {\n address,\n ...serialized,\n };\n const request = store.put(item);\n\n request.onerror = () => rejectItem(request.error);\n request.onsuccess = () => resolveItem();\n });\n });\n\n Promise.all(promises)\n .then(() => resolve())\n .catch(reject);\n\n transaction.onerror = () => reject(transaction.error);\n });\n } catch (error) {\n console.error(`Failed to save VTXOs for address ${address}:`, error);\n throw error;\n }\n }\n\n async deleteVtxos(address: string): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_VTXOS], \"readwrite\");\n const store = transaction.objectStore(STORE_VTXOS);\n const index = store.index(\"address\");\n const request = index.openCursor(IDBKeyRange.only(address));\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor) {\n cursor.delete();\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n } catch (error) {\n console.error(`Failed to clear VTXOs for address ${address}:`, error);\n throw error;\n }\n }\n\n async getVtxosForScript(script: string): Promise<ExtendedVirtualCoin[]> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_VTXOS], \"readonly\");\n const store = transaction.objectStore(STORE_VTXOS);\n const index = store.index(\"script\");\n const request: IDBRequest<(SerializedVtxo & { address: string })[]> =\n index.getAll(script);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const results = request.result || [];\n try {\n // Defensive filter: only rows whose script matches.\n const matching = results.filter((r) => r.script === script);\n\n // Dedup same outpoint rows across address buckets.\n // Work on raw rows so the address field is available\n // for the canonicality tiebreaker.\n const byOutpoint = new Map<string, SerializedVtxo & { address: string }>();\n for (const row of matching) {\n const outpoint = `${row.txid}:${row.vout}`;\n const existing = byOutpoint.get(outpoint);\n if (!existing) {\n byOutpoint.set(outpoint, row);\n continue;\n }\n if (shouldReplaceVtxo(existing, row)) {\n byOutpoint.set(outpoint, row);\n }\n }\n resolve(Array.from(byOutpoint.values()).map(deserializeVtxoWithBackfill));\n } catch (err) {\n reject(err);\n }\n };\n });\n } catch (error) {\n console.error(`Failed to get VTXOs for script ${script}:`, error);\n throw error;\n }\n }\n\n async saveVtxosForScript(key: VtxoRepositoryKey, vtxos: ExtendedVirtualCoin[]): Promise<void> {\n if (!key.address) {\n throw new Error(\"IndexedDBWalletRepository requires an address\");\n }\n for (const vtxo of vtxos) {\n if (!isVtxoForScript(vtxo, key.script)) {\n throw new Error(\n `VTXO ${vtxo.txid}:${vtxo.vout} script mismatch: expected ${key.script}, got ${vtxo.script}`,\n );\n }\n }\n return this.saveVtxos(key.address, vtxos);\n }\n\n async deleteVtxosForScript(script: string): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_VTXOS], \"readwrite\");\n const store = transaction.objectStore(STORE_VTXOS);\n const index = store.index(\"script\");\n const request = index.openCursor(IDBKeyRange.only(script));\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor) {\n cursor.delete();\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n } catch (error) {\n console.error(`Failed to clear VTXOs for script ${script}:`, error);\n throw error;\n }\n }\n\n async getUtxos(address: string): Promise<ExtendedCoin[]> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_UTXOS], \"readonly\");\n const store = transaction.objectStore(STORE_UTXOS);\n const index = store.index(\"address\");\n const request = index.getAll(address);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const results = request.result || [];\n const utxos = results.map(deserializeUtxo);\n resolve(utxos);\n };\n });\n } catch (error) {\n console.error(`Failed to get UTXOs for address ${address}:`, error);\n return [];\n }\n }\n\n async saveUtxos(address: string, utxos: ExtendedCoin[]): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_UTXOS], \"readwrite\");\n const store = transaction.objectStore(STORE_UTXOS);\n\n const promises = utxos.map((utxo) => {\n return new Promise<void>((resolveItem, rejectItem) => {\n const serialized = serializeUtxo(utxo);\n const item = {\n address,\n ...serialized,\n };\n const request = store.put(item);\n\n request.onerror = () => rejectItem(request.error);\n request.onsuccess = () => resolveItem();\n });\n });\n\n Promise.all(promises)\n .then(() => resolve())\n .catch(reject);\n\n transaction.onerror = () => reject(transaction.error);\n });\n } catch (error) {\n console.error(`Failed to save UTXOs for address ${address}:`, error);\n throw error;\n }\n }\n\n async deleteUtxos(address: string): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_UTXOS], \"readwrite\");\n const store = transaction.objectStore(STORE_UTXOS);\n const index = store.index(\"address\");\n const request = index.openCursor(IDBKeyRange.only(address));\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor) {\n cursor.delete();\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n } catch (error) {\n console.error(`Failed to clear UTXOs for address ${address}:`, error);\n throw error;\n }\n }\n\n async getTransactionHistory(address: string): Promise<ArkTransaction[]> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_TRANSACTIONS], \"readonly\");\n const store = transaction.objectStore(STORE_TRANSACTIONS);\n const index = store.index(\"address\");\n const request = index.getAll(address);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const results = request.result || [];\n resolve(results.sort((a, b) => a.createdAt - b.createdAt));\n };\n });\n } catch (error) {\n console.error(`Failed to get transaction history for address ${address}:`, error);\n return [];\n }\n }\n\n async saveTransactions(address: string, txs: ArkTransaction[]): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_TRANSACTIONS], \"readwrite\");\n const store = transaction.objectStore(STORE_TRANSACTIONS);\n\n // Queue all put operations\n txs.forEach((tx) => {\n const item = {\n address,\n ...tx,\n keyBoardingTxid: tx.key.boardingTxid,\n keyCommitmentTxid: tx.key.commitmentTxid,\n keyArkTxid: tx.key.arkTxid,\n };\n store.put(item);\n });\n\n // Handle transaction completion\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error);\n transaction.onabort = () => reject(new Error(\"Transaction aborted\"));\n });\n } catch (error) {\n console.error(`Failed to save transactions for address ${address}:`, error);\n throw error;\n }\n }\n\n async deleteTransactions(address: string): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_TRANSACTIONS], \"readwrite\");\n const store = transaction.objectStore(STORE_TRANSACTIONS);\n const index = store.index(\"address\");\n const request = index.openCursor(IDBKeyRange.only(address));\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor) {\n cursor.delete();\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n } catch (error) {\n console.error(`Failed to clear transactions for address ${address}:`, error);\n throw error;\n }\n }\n\n async getWalletState(): Promise<WalletState | null> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_WALLET_STATE], \"readonly\");\n const store = transaction.objectStore(STORE_WALLET_STATE);\n const request = store.get(\"state\");\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const result = request.result;\n if (result && result.data) {\n resolve(result.data);\n } else {\n resolve(null);\n }\n };\n });\n } catch (error) {\n console.error(\"Failed to get wallet state:\", error);\n return null;\n }\n }\n\n async saveWalletState(state: WalletState): Promise<void> {\n try {\n const db = await this.getDB();\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([STORE_WALLET_STATE], \"readwrite\");\n const store = transaction.objectStore(STORE_WALLET_STATE);\n const item = {\n key: \"state\",\n data: state,\n };\n const request = store.put(item);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve();\n });\n } catch (error) {\n console.error(\"Failed to save wallet state:\", error);\n throw error;\n }\n }\n\n private async getDB(): Promise<IDBDatabase> {\n if (this.db) return this.db;\n this.db = await openDatabase(this.dbName, DB_VERSION, initDatabase);\n return this.db;\n }\n}\n\n// Post-migration every row has `script`, but the backfill is idempotent: if a\n// legacy row is ever read before the upgrade-path completes, derive `script`\n// from `address` the same way the indexer would have populated it.\nfunction deserializeVtxoWithBackfill(o: SerializedVtxo & { address: string }): ExtendedVirtualCoin {\n if (!o.script) {\n o = { ...o, script: scriptFromArkAddress(o.address) };\n }\n return deserializeVtxo(o);\n}\n\ntype RawVtxoRow = SerializedVtxo & { address: string };\n\nfunction isCanonicalRow(row: RawVtxoRow): boolean {\n try {\n return scriptFromArkAddress(row.address) === row.script;\n } catch {\n return false;\n }\n}\n\nfunction shouldReplaceVtxo(existing: RawVtxoRow, incoming: RawVtxoRow): boolean {\n const existingCanonical = isCanonicalRow(existing);\n const incomingCanonical = isCanonicalRow(incoming);\n\n if (incomingCanonical && !existingCanonical) return true;\n if (existingCanonical && !incomingCanonical) return false;\n\n // Tie on canonicality, check lifecycle completeness\n const existingWeight = getLifecycleWeight(existing);\n const incomingWeight = getLifecycleWeight(incoming);\n\n if (incomingWeight > existingWeight) return true;\n if (existingWeight > incomingWeight) return false;\n\n // Tie on weight, stable sort by address\n return incoming.address < existing.address;\n}\n\nfunction getLifecycleWeight(v: RawVtxoRow): number {\n let weight = 0;\n if (v.isSpent !== undefined) weight += 1;\n if (v.spentBy) weight += 2;\n if (v.settledBy) weight += 2;\n if (v.arkTxId) weight += 2;\n return weight;\n}\n","import { hex } from \"@scure/base\";\nimport { TaprootControlBlock } from \"@scure/btc-signer\";\nimport { WalletRepository, WalletState } from \"../walletRepository\";\nimport { StorageAdapter } from \"../../storage\";\nimport { ArkTransaction, ExtendedCoin, ExtendedVirtualCoin } from \"../../wallet\";\nimport { TapLeafScript } from \"../../script/base\";\nimport {\n serializeAssets,\n deserializeAssets,\n serializeTransaction,\n deserializeTransaction,\n} from \"../serialization\";\n\nconst getVtxosStorageKey = (address: string) => `vtxos:${address}`;\nconst getUtxosStorageKey = (address: string) => `utxos:${address}`;\nconst getTransactionsStorageKey = (address: string) => `tx:${address}`;\nconst walletStateStorageKey = \"wallet:state\";\n\n// Utility functions for (de)serializing complex structures\nconst serializeVtxo = (v: ExtendedVirtualCoin) => ({\n ...v,\n tapTree: hex.encode(v.tapTree),\n forfeitTapLeafScript: serializeTapLeaf(v.forfeitTapLeafScript),\n intentTapLeafScript: serializeTapLeaf(v.intentTapLeafScript),\n extraWitness: v.extraWitness?.map(hex.encode),\n assets: serializeAssets(v.assets),\n});\n\nconst serializeUtxo = (u: ExtendedCoin) => ({\n ...u,\n tapTree: hex.encode(u.tapTree),\n forfeitTapLeafScript: serializeTapLeaf(u.forfeitTapLeafScript),\n intentTapLeafScript: serializeTapLeaf(u.intentTapLeafScript),\n extraWitness: u.extraWitness?.map(hex.encode),\n});\n\nconst deserializeVtxo = (o: any): ExtendedVirtualCoin => ({\n ...o,\n createdAt: new Date(o.createdAt),\n tapTree: hex.decode(o.tapTree),\n forfeitTapLeafScript: deserializeTapLeaf(o.forfeitTapLeafScript),\n intentTapLeafScript: deserializeTapLeaf(o.intentTapLeafScript),\n extraWitness: o.extraWitness?.map(hex.decode),\n assets: deserializeAssets(o.assets),\n});\n\nconst deserializeUtxo = (o: any): ExtendedCoin => ({\n ...o,\n tapTree: hex.decode(o.tapTree),\n forfeitTapLeafScript: deserializeTapLeaf(o.forfeitTapLeafScript),\n intentTapLeafScript: deserializeTapLeaf(o.intentTapLeafScript),\n extraWitness: o.extraWitness?.map(hex.decode),\n});\n\nconst serializeTapLeaf = ([cb, s]: TapLeafScript) => ({\n cb: hex.encode(TaprootControlBlock.encode(cb)),\n s: hex.encode(s),\n});\n\nconst deserializeTapLeaf = (t: { cb: string; s: string }): TapLeafScript => {\n const cb = TaprootControlBlock.decode(hex.decode(t.cb));\n const s = hex.decode(t.s);\n return [cb, s];\n};\n\n/**\n * @deprecated This is only to be used in migration from storage V1\n */\nexport class WalletRepositoryImpl implements WalletRepository {\n readonly version = 1 as const;\n private storage: StorageAdapter;\n\n constructor(storage: StorageAdapter) {\n this.storage = storage;\n }\n\n async getVtxos(address: string): Promise<ExtendedVirtualCoin[]> {\n const stored = await this.storage.getItem(getVtxosStorageKey(address));\n if (!stored) return [];\n\n try {\n const parsed = JSON.parse(stored) as ExtendedVirtualCoin[];\n return parsed.map(deserializeVtxo);\n } catch (error) {\n console.error(`Failed to parse VTXOs for address ${address}:`, error);\n return [];\n }\n }\n\n async saveVtxos(address: string, vtxos: ExtendedVirtualCoin[]): Promise<void> {\n const storedVtxos = await this.getVtxos(address);\n for (const vtxo of vtxos) {\n const existing = storedVtxos.findIndex(\n (v) => v.txid === vtxo.txid && v.vout === vtxo.vout,\n );\n if (existing !== -1) {\n storedVtxos[existing] = vtxo;\n } else {\n storedVtxos.push(vtxo);\n }\n }\n await this.storage.setItem(\n getVtxosStorageKey(address),\n JSON.stringify(storedVtxos.map(serializeVtxo)),\n );\n }\n\n async clearVtxos(address: string): Promise<void> {\n return this.deleteVtxos(address);\n }\n\n async deleteVtxos(address: string): Promise<void> {\n await this.storage.removeItem(getVtxosStorageKey(address));\n }\n\n async getUtxos(address: string): Promise<ExtendedCoin[]> {\n const stored = await this.storage.getItem(getUtxosStorageKey(address));\n if (!stored) return [];\n\n try {\n const parsed = JSON.parse(stored) as ExtendedCoin[];\n return parsed.map(deserializeUtxo);\n } catch (error) {\n console.error(`Failed to parse UTXOs for address ${address}:`, error);\n return [];\n }\n }\n\n async saveUtxos(address: string, utxos: ExtendedCoin[]): Promise<void> {\n const storedUtxos = await this.getUtxos(address);\n utxos.forEach((utxo) => {\n const existing = storedUtxos.findIndex(\n (u) => u.txid === utxo.txid && u.vout === utxo.vout,\n );\n if (existing !== -1) {\n storedUtxos[existing] = utxo;\n } else {\n storedUtxos.push(utxo);\n }\n });\n await this.storage.setItem(\n getUtxosStorageKey(address),\n JSON.stringify(storedUtxos.map(serializeUtxo)),\n );\n }\n\n async clearUtxos(address: string): Promise<void> {\n return this.deleteVtxos(address);\n }\n\n async deleteUtxos(address: string): Promise<void> {\n await this.storage.removeItem(getUtxosStorageKey(address));\n }\n\n async getTransactionHistory(address: string): Promise<ArkTransaction[]> {\n const storageKey = getTransactionsStorageKey(address);\n\n const stored = await this.storage.getItem(storageKey);\n if (!stored) return [];\n\n try {\n const parsed = JSON.parse(stored) as Array<ReturnType<typeof serializeTransaction>>;\n return parsed.map(deserializeTransaction);\n } catch (error) {\n console.error(`Failed to parse transactions for address ${address}:`, error);\n return [];\n }\n }\n\n async saveTransactions(address: string, txs: ArkTransaction[]): Promise<void> {\n const storedTransactions = await this.getTransactionHistory(address);\n for (const tx of txs) {\n const existing = storedTransactions.findIndex(\n (t) =>\n t.key.boardingTxid === tx.key.boardingTxid &&\n t.key.commitmentTxid === tx.key.commitmentTxid &&\n t.key.arkTxid === tx.key.arkTxid,\n );\n if (existing !== -1) {\n storedTransactions[existing] = tx;\n } else {\n storedTransactions.push(tx);\n }\n }\n await this.storage.setItem(\n getTransactionsStorageKey(address),\n JSON.stringify(storedTransactions.map(serializeTransaction)),\n );\n }\n\n async clearTransactions(address: string): Promise<void> {\n return this.deleteTransactions(address);\n }\n\n async deleteTransactions(address: string): Promise<void> {\n await this.storage.removeItem(getTransactionsStorageKey(address));\n }\n\n async getWalletState(): Promise<WalletState | null> {\n const stored = await this.storage.getItem(walletStateStorageKey);\n if (!stored) return null;\n\n try {\n const state = JSON.parse(stored) as WalletState;\n return state;\n } catch (error) {\n console.error(\"Failed to parse wallet state:\", error);\n return null;\n }\n }\n\n async saveWalletState(state: WalletState): Promise<void> {\n await this.storage.setItem(walletStateStorageKey, JSON.stringify(state));\n }\n\n // New method added in V2, not implemented for legacy\n async clear(): Promise<void> {\n throw new Error(\"Method not implemented.\");\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n // deprecated StorageAdapter doesn't have a `close()` method\n return;\n }\n}\n","import { StorageAdapter } from \"../../storage\";\nimport { WalletRepository } from \"../walletRepository\";\nimport { WalletRepositoryImpl } from \"./walletRepositoryImpl\";\n\nexport const MIGRATION_KEY = (repoType: \"wallet\" | \"contract\") =>\n `migration-from-storage-adapter-${repoType}`;\n\nexport type MigrationStatus = \"pending\" | \"in-progress\" | \"done\" | \"not-needed\";\n\nexport async function getMigrationStatus(\n repoType: \"wallet\" | \"contract\",\n storageAdapter: StorageAdapter,\n): Promise<MigrationStatus> {\n try {\n const migration = await storageAdapter.getItem(MIGRATION_KEY(repoType));\n if (migration === \"done\") return \"done\";\n if (migration === \"in-progress\") return \"in-progress\";\n return \"pending\";\n } catch (e) {\n if (e instanceof DOMException && e.name === \"NotFoundError\") return \"not-needed\";\n throw e;\n }\n}\n\nexport async function requiresMigration(\n repoType: \"wallet\" | \"contract\",\n storageAdapter: StorageAdapter,\n): Promise<boolean> {\n const status = await getMigrationStatus(repoType, storageAdapter);\n return status === \"pending\" || status === \"in-progress\";\n}\n\nexport async function rollbackMigration(\n repoType: \"wallet\" | \"contract\",\n storageAdapter: StorageAdapter,\n): Promise<void> {\n await storageAdapter.removeItem(MIGRATION_KEY(repoType));\n}\n\n/**\n * Migrate wallet data from the legacy storage adapter to the new one.\n * It accepts both onchain and offchain addresses, make sure to pass both.\n *\n * @param storageAdapter\n * @param fresh\n * @param addresses\n */\nexport async function migrateWalletRepository(\n storageAdapter: StorageAdapter,\n fresh: WalletRepository,\n addresses: { onchain: string[]; offchain: string[] },\n): Promise<void> {\n const migrate = await requiresMigration(\"wallet\", storageAdapter);\n if (!migrate) return;\n\n await storageAdapter.setItem(MIGRATION_KEY(\"wallet\"), \"in-progress\");\n\n const old = new WalletRepositoryImpl(storageAdapter);\n\n const walletData = await old.getWalletState();\n\n const onchainAddrData = await Promise.all(\n addresses.onchain.map(async (address) => {\n const utxos = await old.getUtxos(address);\n return { address, utxos };\n }),\n );\n const offchainAddrData = await Promise.all(\n addresses.offchain.map(async (address) => {\n const vtxos = await old.getVtxos(address);\n const txs = await old.getTransactionHistory(address);\n return { address, vtxos, txs };\n }),\n );\n\n await Promise.all([\n walletData && fresh.saveWalletState(walletData),\n ...offchainAddrData.map((addressData) =>\n Promise.all([\n fresh.saveVtxos(addressData.address, addressData.vtxos),\n fresh.saveTransactions(addressData.address, addressData.txs),\n ]),\n ),\n ...onchainAddrData.map((addressData) =>\n fresh.saveUtxos(addressData.address, addressData.utxos),\n ),\n ]);\n\n await storageAdapter.setItem(MIGRATION_KEY(\"wallet\"), \"done\");\n}\n","import { StorageAdapter } from \"../../storage\";\nimport { ContractFilter, ContractRepository } from \"../contractRepository\";\nimport { Contract } from \"../../contracts/types\";\n\nexport const getContractStorageKey = (id: string, key: string) => `contract:${id}:${key}`;\nexport const getCollectionStorageKey = (type: string) => `collection:${type}`;\n\n/**\n * @deprecated This is only to be used in migration from storage V1\n */\nexport class ContractRepositoryImpl implements ContractRepository {\n readonly version = 1 as const;\n private storage: StorageAdapter;\n\n constructor(storage: StorageAdapter) {\n this.storage = storage;\n }\n\n async getContractData<T>(contractId: string, key: string): Promise<T | null> {\n const stored = await this.storage.getItem(getContractStorageKey(contractId, key));\n if (!stored) return null;\n\n try {\n const data = JSON.parse(stored) as T;\n return data;\n } catch (error) {\n console.error(`Failed to parse contract data for ${contractId}:${key}:`, error);\n return null;\n }\n }\n\n async setContractData<T>(contractId: string, key: string, data: T): Promise<void> {\n try {\n await this.storage.setItem(\n getContractStorageKey(contractId, key),\n JSON.stringify(data),\n );\n } catch (error) {\n console.error(`Failed to persist contract data for ${contractId}:${key}:`, error);\n throw error; // Rethrow to notify caller of failure\n }\n }\n\n async deleteContractData(contractId: string, key: string): Promise<void> {\n try {\n await this.storage.removeItem(getContractStorageKey(contractId, key));\n } catch (error) {\n console.error(`Failed to remove contract data for ${contractId}:${key}:`, error);\n throw error; // Rethrow to notify caller of failure\n }\n }\n\n async getContractCollection<T>(contractType: string): Promise<ReadonlyArray<T>> {\n const stored = await this.storage.getItem(getCollectionStorageKey(contractType));\n if (!stored) return [];\n\n try {\n const collection = JSON.parse(stored) as T[];\n return collection;\n } catch (error) {\n console.error(`Failed to parse contract collection ${contractType}:`, error);\n return [];\n }\n }\n\n async saveToContractCollection<T, K extends keyof T>(\n contractType: string,\n item: T,\n idField: K,\n ): Promise<void> {\n const collection = await this.getContractCollection<T>(contractType);\n\n // Validate that the item has the required id field\n const itemId = item[idField];\n if (itemId === undefined || itemId === null) {\n throw new Error(`Item is missing required field '${String(idField)}'`);\n }\n\n // Find existing item index without mutating the original collection\n const existingIndex = collection.findIndex((i) => i[idField] === itemId);\n\n // Build new collection without mutating the cached one\n let newCollection: T[];\n if (existingIndex !== -1) {\n // Replace existing item\n newCollection = [\n ...collection.slice(0, existingIndex),\n item,\n ...collection.slice(existingIndex + 1),\n ];\n } else {\n // Add new item\n newCollection = [...collection, item];\n }\n\n try {\n await this.storage.setItem(\n getCollectionStorageKey(contractType),\n JSON.stringify(newCollection),\n );\n } catch (error) {\n console.error(`Failed to persist contract collection ${contractType}:`, error);\n throw error; // Rethrow to notify caller of failure\n }\n }\n\n async removeFromContractCollection<T, K extends keyof T>(\n contractType: string,\n id: T[K],\n idField: K,\n ): Promise<void> {\n // Validate input parameters\n if (id === undefined || id === null) {\n throw new Error(`Invalid id provided for removal: ${String(id)}`);\n }\n\n const collection = await this.getContractCollection<T>(contractType);\n\n // Build new collection without the specified item\n const filtered = collection.filter((item) => item[idField] !== id);\n\n try {\n await this.storage.setItem(\n getCollectionStorageKey(contractType),\n JSON.stringify(filtered),\n );\n } catch (error) {\n console.error(\n `Failed to persist contract collection removal for ${contractType}:`,\n error,\n );\n throw error; // Rethrow to notify caller of failure\n }\n }\n\n // The following methods are implemented for compatibility with the new ContractRepository interface\n // but aren't used.\n async getContracts(_?: ContractFilter): Promise<Contract[]> {\n throw new TypeError(\n \"Method not implemented, this is a legacy class and should only be used for migrating data.\",\n );\n }\n\n async saveContract(_: Contract): Promise<void> {\n throw new TypeError(\n \"Method not implemented, this is a legacy class and should only be used for migrating data.\",\n );\n }\n\n async deleteContract(_: string): Promise<void> {\n throw new TypeError(\n \"Method not implemented, this is a legacy class and should only be used for migrating data.\",\n );\n }\n\n // used only for tests\n async clear(): Promise<void> {\n await this.storage.clear();\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n // deprecated StorageAdapter doesn't have a `close()` method\n return;\n }\n}\n","import { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { EncodedVtxoScript, TapLeafScript, VtxoScript } from \"../script/base\";\nimport { ExtendedVirtualCoin, VirtualCoin, TapLeaves } from \"../wallet\";\nimport { ContractFilter } from \"../repositories\";\nimport type { RelativeTimelock } from \"../script/tapscript\";\nimport type { IndexerProvider } from \"../providers/indexer\";\nimport type { OnchainProvider } from \"../providers/onchain\";\n\n/**\n * Contract state indicating whether it should be actively monitored.\n */\nexport type ContractState = \"active\" | \"inactive\";\n\n/**\n * Represents a contract that can receive and manage virtual outputs.\n *\n * A contract is defined by its type and parameters, which together\n * determine the VtxoScript (spending paths). The wallet's default\n * receiving address is itself a contract of type \"default\".\n *\n * External services (Boltz swaps, atomic swaps, etc.) create additional\n * contracts with their own types and parameters.\n *\n * @example\n * ```typescript\n * const vhtlcContract: Contract = {\n * type: \"vhtlc\",\n * params: {\n * sender: \"ab12...\",\n * receiver: \"cd34...\",\n * server: \"ef56...\",\n * hash: \"1234...\",\n * refundLocktime: \"800000\",\n * // ... timelocks\n * },\n * script: \"5120...\",\n * address: \"ark1q...\",\n * state: \"active\",\n * createdAt: 1704067200000,\n * };\n * ```\n */\nexport interface Contract {\n /** Human-readable label for display purposes. */\n label?: string;\n\n /**\n * Contract type identifier.\n * Built-in types: \"default\", \"vhtlc\"\n * Custom types can be registered via ContractHandler.\n */\n type: string;\n\n /**\n * Type-specific parameters for constructing the VtxoScript.\n * All values are serialized as strings (hex for bytes, string for bigint).\n * The ContractHandler for this type knows how to interpret these.\n */\n params: Record<string, string>;\n\n /** The pkScript hex, used as the unique identifier and primary key for contracts. */\n script: string;\n\n /** Address derived from the contract script. */\n address: string;\n\n /** Current state of the contract. */\n state: ContractState;\n\n /** Unix timestamp in milliseconds when this contract was created. */\n createdAt: number;\n\n /**\n * Optional metadata for external integrations.\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * A virtual output that has been associated with a specific contract.\n */\nexport type ContractVtxo = VirtualCoin &\n Partial<TapLeaves & EncodedVtxoScript> & {\n extraWitness?: Bytes[];\n contractScript: string;\n };\n\n/**\n * A {@link ContractVtxo} with all taproot annotation fields required.\n *\n * Mirrors the {@link ExtendedVirtualCoin} / {@link VirtualCoin} split:\n * - {@link ContractVtxo} carries `TapLeaves` and `EncodedVtxoScript` as\n * `Partial<>` because VTXOs fetched raw from the indexer do not yet have\n * taproot data.\n * - `ExtendedContractVtxo` narrows those fields to required, guaranteeing\n * that `annotateVtxos` has run and the taproot leaves are present.\n *\n * Use this type (instead of {@link ContractVtxo}) wherever the compiler\n * should enforce that annotation has happened — e.g. `saveVtxos` and\n * forfeit transaction construction.\n */\nexport type ExtendedContractVtxo = ExtendedVirtualCoin & {\n contractScript: string;\n};\n\n/**\n * Result of path selection, including the tapleaf to use and any extra witness data.\n */\nexport interface PathSelection {\n /** Tapleaf script to use for spending. */\n leaf: TapLeafScript;\n\n /** Additional witness elements, for example a preimage for HTLC-like paths. */\n extraWitness?: Bytes[];\n\n /**\n * nSequence for the spending input, BIP-68 encoded when the leaf\n * uses CSV. Decode with `sequenceToTimelock`; do NOT use as an\n * absolute `Transaction.lockTime`.\n */\n sequence?: number;\n}\n\n/**\n * Context for path selection decisions.\n */\nexport interface PathContext {\n /** Whether collaborative spending is available through server cooperation. */\n collaborative: boolean;\n\n /** Current time in milliseconds. */\n currentTime: number;\n\n /** Current block height, when known. */\n blockHeight?: number;\n\n /**\n * Wallet's descriptor for signing.\n * Format: tr(pubkey) for static keys, tr([fingerprint/path']xpub/0/{index}) for HD.\n * Used by handlers to determine wallet's role in multi-party contracts.\n */\n walletDescriptor?: string;\n\n /**\n * Wallet's public key (x-only, 32 bytes hex).\n * @deprecated Use walletDescriptor instead.\n */\n walletPubKey?: string;\n\n /**\n * Explicit role override for multi-party contracts such as VHTLC.\n * If not provided, the handler may derive the role by matching\n * {@link walletDescriptor} (preferred) — or {@link walletPubKey} as a\n * fallback — against the contract's sender/receiver params.\n */\n role?: string;\n\n /** The specific virtual output being evaluated. */\n vtxo?: VirtualCoin;\n}\n\n/**\n * Handler for a specific contract type.\n *\n * Each contract type (`default`, `vhtlc`, etc.) has a handler that knows how to:\n * 1. Create the VtxoScript from parameters\n * 2. Serialize/deserialize parameters for storage\n * 3. Select the appropriate spending path based on context\n *\n * @example\n * ```typescript\n * const vhtlcHandler: ContractHandler = {\n * type: \"vhtlc\",\n * createScript(params) {\n * return new VHTLC.Script(this.deserializeParams(params));\n * },\n * selectPath(script, contract, context) {\n * const vhtlc = script as VHTLC.Script;\n * const preimage = contract.data?.preimage;\n * if (context.collaborative && preimage) {\n * return { leaf: vhtlc.claim(), extraWitness: [hex.decode(preimage)] };\n * }\n * // ... other paths\n * },\n * // ...\n * };\n * ```\n */\nexport interface ContractHandler<P = Record<string, unknown>, S extends VtxoScript = VtxoScript> {\n /** Contract type managed by this handler. */\n readonly type: string;\n\n /**\n * Create the VtxoScript from serialized parameters.\n *\n * @param params - Serialized contract parameters\n * @returns Contract script instance\n */\n createScript(params: Record<string, string>): S;\n\n /**\n * Serialize typed parameters to string key-value pairs.\n *\n * @param params - Typed contract parameters\n * @returns Serialized key-value representation\n */\n serializeParams(params: P): Record<string, string>;\n\n /**\n * Deserialize string key-value pairs to typed parameters.\n */\n deserializeParams(params: Record<string, string>): P;\n\n /**\n * Select the preferred spending path based on contract state and context.\n * Returns the best available path (e.g., collaborative over unilateral).\n *\n * @returns PathSelection if a viable path exists, null otherwise\n */\n selectPath(script: S, contract: Contract, context: PathContext): PathSelection | null;\n\n /**\n * Get all possible spending paths for the current context.\n * Returns empty array if no paths are available.\n *\n * Useful for showing users which spending options exist regardless of\n * current spendability.\n */\n getAllSpendingPaths(script: S, contract: Contract, context: PathContext): PathSelection[];\n\n /**\n * Get all currently spendable paths.\n * Returns empty array if no paths are available.\n */\n getSpendablePaths(script: S, contract: Contract, context: PathContext): PathSelection[];\n}\n\n/**\n * What a {@link Discoverable.discoverAt} call returns — exactly the\n * shape `ContractManager.createContract` accepts (script-keyed,\n * idempotent on re-register).\n */\nexport interface DiscoveredContract {\n type: string;\n params: Record<string, string>;\n script: string;\n address: string;\n metadata?: Record<string, unknown>;\n label?: string;\n}\n\n/**\n * Read-only context the scanner injects into every `discoverAt` call.\n * The boltz/swap handler does NOT receive its Boltz client here — it\n * closes over its own client at registration time.\n */\nexport interface DiscoveryDeps {\n indexerProvider: IndexerProvider;\n onchainProvider: OnchainProvider;\n network: { hrp: string };\n serverPubKey: Uint8Array;\n /** Relative timelocks the wallet treats as its baseline matrix. */\n csvTimelocks: RelativeTimelock[];\n /** Present only for delegate wallets. */\n delegatePubKey?: Uint8Array;\n}\n\n/**\n * Optional capability a {@link ContractHandler} implements to participate\n * in `wallet.restore()`'s gap-limit scan. The scanner owns the index\n * loop and the gap counter; the handler answers \"do I own a contract\n * anchored to the pubkey/descriptor at this index?\" — checked against\n * the indexer / explorer / (for swaps) the handler's own source. The\n * handler MAY batch/cache internally across calls.\n */\nexport interface Discoverable {\n discoverAt(\n index: number,\n descriptor: string,\n deps: DiscoveryDeps,\n ): Promise<DiscoveredContract[]>;\n}\n\n/** Duck-typed guard (mirrors `hasReceiveRotatorFactory`). */\nexport function isDiscoverable(\n handler: ContractHandler<unknown> | undefined,\n): handler is ContractHandler<unknown> & Discoverable {\n return !!handler && typeof (handler as Partial<Discoverable>).discoverAt === \"function\";\n}\n\n/**\n * Event emitted when contract-related changes occur.\n */\nexport type ContractEvent =\n | {\n type: \"vtxo_received\";\n contractScript: string;\n vtxos: ContractVtxo[];\n contract: Contract;\n timestamp: number;\n }\n | {\n type: \"vtxo_spent\";\n contractScript: string;\n vtxos: ContractVtxo[];\n contract: Contract;\n timestamp: number;\n }\n | { type: \"connection_reset\"; timestamp: number };\n\n/**\n * Callback for contract events.\n */\nexport type ContractEventCallback = (event: ContractEvent) => void;\n\n/**\n * Options for retrieving contracts from the Contract Manager.\n * Currently an alias of the repository's filter type but can be extended in the future.\n */\nexport type GetContractsFilter = ContractFilter;\n\n/**\n * Contract with its virtual outputs included.\n */\nexport type ContractWithVtxos = {\n contract: Contract;\n vtxos: ExtendedContractVtxo[];\n};\n\n/**\n * Summary of a contract's balance.\n */\nexport interface ContractBalance {\n /** Total balance (settled + pending) in satoshis */\n total: number;\n\n /** Spendable balance in satoshis */\n spendable: number;\n\n /** Number of virtual outputs in this contract */\n vtxoCount: number;\n}\n","import { IndexerProvider, SubscriptionResponse } from \"../providers/indexer\";\nimport { VirtualCoin } from \"../wallet\";\nimport { extendVirtualCoinForContract } from \"../wallet/utils\";\nimport { WalletRepository } from \"../repositories/walletRepository\";\nimport { Contract, ContractVtxo, ContractEventCallback, ContractEvent } from \"./types\";\nimport { isEventSourceError } from \"../providers/utils\";\nimport { filterVtxosForScript, getVtxosForContract } from \"./vtxoOwnership\";\n\n/**\n * Configuration for the ContractWatcher.\n *\n * @see ContractWatcher\n *\n * @example\n * ```typescript\n * const watcher = new ContractWatcher({\n * indexerProvider,\n * walletRepository,\n * })\n * ```\n */\nexport interface ContractWatcherConfig {\n /** Indexer provider used for subscriptions and queries. */\n indexerProvider: IndexerProvider;\n\n /** Wallet repository used to store virtual output state between watcher updates. */\n walletRepository: WalletRepository;\n\n /**\n * Interval for failsafe polling (ms).\n * Polls even when subscription is active to catch missed events.\n *\n * @defaultValue `60_000` (1 minute)\n */\n failsafePollIntervalMs?: number;\n\n /**\n * Initial reconnection delay (ms).\n * Uses exponential backoff on repeated failures.\n *\n * @defaultValue `1_000` (1 second)\n */\n reconnectDelayMs?: number;\n\n /**\n * Maximum reconnection delay (ms).\n *\n * @defaultValue `30_000` (30 seconds)\n */\n maxReconnectDelayMs?: number;\n\n /**\n * Maximum reconnection attempts before giving up.\n * Set to 0 for unlimited attempts.\n *\n * @defaultValue `0` (unlimited)\n */\n maxReconnectAttempts?: number;\n}\n\n/**\n * Internal state for tracking contracts.\n */\ninterface ContractState {\n contract: Contract;\n\n /** Last known virtual outputs keyed by `txid:vout`. */\n lastKnownVtxos: Map<string, VirtualCoin>;\n}\n\n/**\n * Connection state for the watcher.\n */\ntype ConnectionState = \"disconnected\" | \"connecting\" | \"connected\" | \"reconnecting\";\n\n/**\n * Watches multiple contracts for virtual output state changes with resilient connection handling.\n *\n * Features:\n * - Automatic reconnection with exponential backoff\n * - Failsafe polling to catch missed events\n * - Polls immediately after (re)connection to sync state\n * - Graceful handling of subscription failures\n *\n * @example\n * ```typescript\n * const watcher = new ContractWatcher({\n * indexerProvider: wallet.indexerProvider,\n * });\n *\n * // Add the wallet's default contract\n * await watcher.addContract(defaultContract);\n *\n * // Add additional contracts (swaps, etc.)\n * await watcher.addContract(swapContract);\n *\n * // Start watching for events\n * const stop = await watcher.startWatching((event) => {\n * console.log(`${event.type} on contract ${event.contractScript}`);\n * });\n *\n * // Later: stop watching\n * stop();\n * ```\n */\nexport class ContractWatcher {\n private config: Required<Omit<ContractWatcherConfig, \"walletRepository\">> &\n Pick<ContractWatcherConfig, \"walletRepository\">;\n private contracts: Map<string, ContractState> = new Map();\n private subscriptionId?: string;\n private abortController?: AbortController;\n private isWatching = false;\n private eventCallback?: ContractEventCallback;\n private connectionState: ConnectionState = \"disconnected\";\n private reconnectAttempts = 0;\n private reconnectTimeoutId?: ReturnType<typeof setTimeout>;\n private failsafePollIntervalId?: ReturnType<typeof setInterval>;\n\n /**\n * Create a contract watcher with the given providers and polling settings.\n *\n * @param config - Contract watcher configuration\n * @see ContractWatcherConfig\n */\n constructor(config: ContractWatcherConfig) {\n this.config = {\n failsafePollIntervalMs: 60_000, // 1 minute\n reconnectDelayMs: 1000, // 1 second\n maxReconnectDelayMs: 30_000, // 30 seconds\n maxReconnectAttempts: 0, // unlimited\n ...config,\n };\n }\n\n /**\n * Add a contract to be watched.\n *\n * Active contracts are immediately subscribed.\n *\n * All contracts are polled to discover any existing virtual outputs\n * (which may cause them to be watched even if inactive).\n */\n async addContract(contract: Contract): Promise<void> {\n const state: ContractState = {\n contract,\n lastKnownVtxos: new Map(),\n };\n\n this.contracts.set(contract.script, state);\n\n // Seed the baseline from the repository BEFORE any poll or event\n // emits. Without this, the first poll after (re)start treats every\n // persisted vtxo as \"new\" and emits `vtxo_received` for each —\n // which downstream triggers a redundant per-vtxo sync on every\n // app launch and can confuse consumers that react to the event.\n await this.seedLastKnownVtxos(state);\n\n // If we're already watching, poll to discover virtual outputs and update subscription\n if (this.isWatching) {\n // Poll first to discover virtual outputs (may affect whether we watch this contract).\n await this.pollContracts([contract.script]);\n // Update subscription based on active state and virtual outputs.\n await this.tryUpdateSubscription();\n }\n }\n\n /**\n * Pre-populate `lastKnownVtxos` from the wallet repository.\n *\n * Runs on add (and can be re-run after reconnect) so polling always\n * compares the indexer's view against what is already persisted,\n * emitting only genuine deltas.\n */\n private async seedLastKnownVtxos(state: ContractState): Promise<void> {\n try {\n // Apply the same script gate used by getContractVtxos so a legacy\n // wrong-script row in the address bucket can't seed the baseline\n // and then look \"spent\" on the first poll.\n const cached = await getVtxosForContract(this.config.walletRepository, state.contract);\n for (const vtxo of cached) {\n if (vtxo.isSpent) continue;\n const key = `${vtxo.txid}:${vtxo.vout}`;\n state.lastKnownVtxos.set(key, vtxo);\n }\n } catch (error) {\n // Don't throw — the watcher can still recover via poll and\n // subscription events. A failed seed just means the first poll\n // may emit some redundant `vtxo_received` events for already\n // known vtxos.\n console.error(\n `ContractWatcher: failed to seed lastKnownVtxos for ${state.contract.script}`,\n error,\n );\n }\n }\n\n /**\n * Update an existing contract.\n */\n async updateContract(contract: Contract): Promise<void> {\n const existing = this.contracts.get(contract.script);\n if (!existing) {\n throw new Error(`Contract ${contract.script} not found`);\n }\n\n existing.contract = contract;\n\n if (this.isWatching) {\n await this.tryUpdateSubscription();\n }\n }\n\n /**\n * Remove a contract from watching.\n */\n async removeContract(contractScript: string): Promise<void> {\n const state = this.contracts.get(contractScript);\n if (state) {\n this.contracts.delete(contractScript);\n\n if (this.isWatching) {\n await this.tryUpdateSubscription();\n }\n }\n }\n\n /**\n * Get all in-memory contracts.\n */\n getAllContracts(): Contract[] {\n return Array.from(this.contracts.values()).map((s) => s.contract);\n }\n\n /**\n * Contracts the watcher is actually tracking:\n * - all active contracts, plus\n * - inactive contracts that still hold known virtual outputs\n * (the subscription keeps watching them so `vtxo_spent` events for\n * those unspent outputs are still observed).\n *\n * This is the single source of truth for \"contracts whose VTXO state\n * we still care about\" — callers and the subscription itself fan out\n * over the same set so nothing is reconciled that isn't also watched.\n */\n getWatchedContracts(): Contract[] {\n return Array.from(this.contracts.values())\n .filter((s) => s.contract.state === \"active\" || s.lastKnownVtxos.size > 0)\n .map((s) => s.contract);\n }\n\n /**\n * Get virtual outputs for contracts, grouped by contract script.\n * @see WalletRepository for `repo`\n */\n private async getContractVtxos(options: {\n includeSpent?: boolean;\n contractScripts?: string[];\n }): Promise<Map<string, ContractVtxo[]>> {\n const { contractScripts, includeSpent } = options;\n const repo = this.config.walletRepository;\n\n const contractsToQuery = Array.from(this.contracts.values());\n\n const asyncResults = contractsToQuery\n .filter((_) => {\n if (contractScripts && !contractScripts.includes(_.contract.script)) return false;\n return true;\n })\n .map(async (state): Promise<[[string, ContractVtxo[]]] | []> => {\n // Use contract address as cache key. Legacy address buckets\n // can contain rows from other contracts; gate by script before\n // converting so a wrong-script row never reaches the watcher.\n const cached = await getVtxosForContract(repo, state.contract);\n if (cached.length > 0) {\n // Convert to ContractVtxo with contractScript\n const contractVtxos: ContractVtxo[] = cached.map((v) => ({\n ...v,\n contractScript: state.contract.script,\n }));\n const filtered = includeSpent\n ? contractVtxos\n : contractVtxos.filter((v) => !v.isSpent);\n return [[state.contract.script, filtered]];\n }\n return [];\n });\n\n const results = await Promise.all(asyncResults);\n return new Map(results.flat(1));\n }\n\n /**\n * Start watching for virtual output events across all active contracts.\n */\n async startWatching(callback: ContractEventCallback): Promise<() => void> {\n if (this.isWatching) {\n throw new Error(\"Already watching\");\n }\n\n this.eventCallback = callback;\n this.isWatching = true;\n this.abortController = new AbortController();\n this.reconnectAttempts = 0;\n\n // Start connection\n await this.connect();\n\n // Start failsafe polling\n this.startFailsafePolling();\n\n return () => this.stopWatching();\n }\n\n /**\n * Stop watching for events.\n */\n async stopWatching(): Promise<void> {\n this.isWatching = false;\n this.connectionState = \"disconnected\";\n this.abortController?.abort();\n\n // Clear timers\n if (this.reconnectTimeoutId) {\n clearTimeout(this.reconnectTimeoutId);\n this.reconnectTimeoutId = undefined;\n }\n if (this.failsafePollIntervalId) {\n clearInterval(this.failsafePollIntervalId);\n this.failsafePollIntervalId = undefined;\n }\n\n // Unsubscribe\n if (this.subscriptionId) {\n try {\n await this.config.indexerProvider.unsubscribeForScripts(this.subscriptionId);\n } catch {\n // Ignore unsubscribe errors\n }\n this.subscriptionId = undefined;\n }\n\n this.eventCallback = undefined;\n }\n\n /**\n * Check if currently watching.\n */\n isCurrentlyWatching(): boolean {\n return this.isWatching;\n }\n\n /**\n * Get current connection state.\n */\n getConnectionState(): ConnectionState {\n return this.connectionState;\n }\n\n /**\n * Force a poll of all active contracts.\n * Useful for manual refresh or after app resume.\n */\n async forcePoll(): Promise<void> {\n if (!this.isWatching) return;\n await this.pollAllContracts();\n }\n\n /**\n * Connect to the subscription.\n *\n * @param skipUpdate - Skip the leading `updateSubscription` call when\n * the caller has already established `subscriptionId`.\n */\n private async connect(skipUpdate = false): Promise<void> {\n if (!this.isWatching) return;\n\n this.connectionState = \"connecting\";\n\n try {\n if (!skipUpdate) {\n await this.updateSubscription();\n }\n\n // Poll immediately after connection to sync state\n await this.pollAllContracts();\n\n this.connectionState = \"connected\";\n this.reconnectAttempts = 0;\n\n // Start listening\n this.listenLoop().catch((e) => {\n // This is handled asynchronously otherwise `connect()` would hang\n // indefinitely and block the caller.\n // Error management must be implemented to ensure the connection\n // is restored and events are fired.\n if (isEventSourceError(e)) {\n console.debug(\"ContractWatcher subscription disconnected; reconnecting\");\n } else {\n console.error(e);\n }\n this.connectionState = \"disconnected\";\n this.eventCallback?.({\n type: \"connection_reset\",\n timestamp: Date.now(),\n });\n this.scheduleReconnect();\n });\n } catch (error) {\n console.error(\"ContractWatcher connection failed:\", error);\n this.connectionState = \"disconnected\";\n this.eventCallback?.({\n type: \"connection_reset\",\n timestamp: Date.now(),\n });\n this.scheduleReconnect();\n }\n }\n\n /**\n * Schedule a reconnection attempt.\n */\n private scheduleReconnect(): void {\n if (!this.isWatching) return;\n\n // Check max attempts\n if (\n this.config.maxReconnectAttempts > 0 &&\n this.reconnectAttempts >= this.config.maxReconnectAttempts\n ) {\n console.error(\n `ContractWatcher: Max reconnection attempts (${this.config.maxReconnectAttempts}) reached`,\n );\n return;\n }\n\n this.connectionState = \"reconnecting\";\n this.reconnectAttempts++;\n\n // Calculate delay with exponential backoff\n const delay = Math.min(\n this.config.reconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),\n this.config.maxReconnectDelayMs,\n );\n\n this.reconnectTimeoutId = setTimeout(() => {\n this.reconnectTimeoutId = undefined;\n this.connect();\n }, delay);\n }\n\n /**\n * Start the failsafe polling interval.\n */\n private startFailsafePolling(): void {\n if (this.failsafePollIntervalId) {\n clearInterval(this.failsafePollIntervalId);\n }\n\n this.failsafePollIntervalId = setInterval(() => {\n if (this.isWatching) {\n this.pollAllContracts().catch((error) => {\n console.error(\"ContractWatcher failsafe poll failed:\", error);\n });\n }\n }, this.config.failsafePollIntervalMs);\n }\n\n private async pollAllContracts(): Promise<void> {\n const scripts = this.getWatchedContracts().map((c) => c.script);\n if (scripts.length === 0) return;\n await this.pollContracts(scripts);\n }\n\n /**\n * Poll specific contracts and emit events for changes.\n */\n private async pollContracts(contractScripts: string[]): Promise<void> {\n if (!this.eventCallback) return;\n\n const now = Date.now();\n\n try {\n // Load all the virtual outputs for these contracts, from DB\n const vtxosMap = await this.getContractVtxos({\n contractScripts,\n includeSpent: false, // only spendable ones!\n });\n\n for (const contractScript of contractScripts) {\n const state = this.contracts.get(contractScript);\n if (!state) continue;\n\n const currentVtxos = vtxosMap.get(contractScript) || [];\n const currentKeys = new Set(currentVtxos.map((v) => `${v.txid}:${v.vout}`));\n\n // Find new virtual outputs and add them to the contract's state\n const newVtxos: VirtualCoin[] = [];\n for (const vtxo of currentVtxos) {\n const key = `${vtxo.txid}:${vtxo.vout}`;\n if (!state.lastKnownVtxos.has(key)) {\n newVtxos.push(vtxo);\n state.lastKnownVtxos.set(key, vtxo);\n }\n }\n\n // Find spent virtual outputs and remove them from the contract's state\n const spentVtxos: VirtualCoin[] = [];\n for (const [key, vtxo] of state.lastKnownVtxos) {\n if (!currentKeys.has(key)) {\n spentVtxos.push(vtxo);\n state.lastKnownVtxos.delete(key);\n }\n }\n\n // Emit events\n if (newVtxos.length > 0) {\n this.emitVtxoEvent(contractScript, newVtxos, \"vtxo_received\", now);\n }\n\n if (spentVtxos.length > 0) {\n // Note: We can't distinguish spent vs swept from polling alone\n // The subscription provides more accurate event types\n this.emitVtxoEvent(contractScript, spentVtxos, \"vtxo_spent\", now);\n }\n }\n } catch (error) {\n console.error(\"ContractWatcher poll failed:\", error);\n // Don't throw - polling failures shouldn't crash the watcher\n }\n }\n\n private async tryUpdateSubscription() {\n const hadSubscription = this.subscriptionId !== undefined;\n try {\n await this.updateSubscription();\n } catch (error) {\n // nothing, the connection will be retried later\n return;\n }\n\n // Cold start: `startWatching` may have run with zero scripts,\n // leaving `listenLoop` parked behind the reconnect timer. Kick\n // `connect` now so streaming resumes without waiting on the\n // backoff. `skipUpdate` avoids re-issuing `subscribeForScripts`.\n const justGotSubscription = !hadSubscription && this.subscriptionId !== undefined;\n const listenerParked =\n this.connectionState === \"disconnected\" || this.connectionState === \"reconnecting\";\n if (this.isWatching && justGotSubscription && listenerParked) {\n if (this.reconnectTimeoutId) {\n clearTimeout(this.reconnectTimeoutId);\n this.reconnectTimeoutId = undefined;\n }\n this.reconnectAttempts = 0;\n this.connect(true).catch((error) => {\n console.warn(\"ContractWatcher cold-start connect failed:\", error);\n });\n }\n }\n\n /**\n * Update the subscription with scripts that should be watched.\n *\n * Watches both active contracts and contracts with virtual outputs.\n */\n private async updateSubscription(): Promise<void> {\n const scriptsToWatch = this.getWatchedContracts().map((c) => c.script);\n\n if (scriptsToWatch.length === 0) {\n if (this.subscriptionId) {\n try {\n await this.config.indexerProvider.unsubscribeForScripts(this.subscriptionId);\n } catch {\n // Ignore\n }\n this.subscriptionId = undefined;\n }\n return;\n }\n\n try {\n this.subscriptionId = await this.config.indexerProvider.subscribeForScripts(\n scriptsToWatch,\n this.subscriptionId,\n );\n } catch (error) {\n // If we sent a stale subscription ID that the server no longer\n // recognises, clear it and retry to create a fresh subscription.\n // The server currently returns HTTP 500 with a JSON body whose\n // message field looks like \"subscription <uuid> not found\".\n // All other errors (network failures, parse errors, etc.) are rethrown.\n const isStale =\n error instanceof Error && /subscription\\s+\\S+\\s+not\\s+found/i.test(error.message);\n if (this.subscriptionId && isStale) {\n this.subscriptionId = undefined;\n this.subscriptionId =\n await this.config.indexerProvider.subscribeForScripts(scriptsToWatch);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Main listening loop for subscription events.\n */\n private async listenLoop(): Promise<void> {\n if (!this.subscriptionId || !this.abortController || !this.isWatching) {\n if (this.isWatching) {\n this.connectionState = \"disconnected\";\n this.scheduleReconnect();\n }\n return;\n }\n\n const subscription = this.config.indexerProvider.getSubscription(\n this.subscriptionId,\n this.abortController.signal,\n );\n\n for await (const update of subscription) {\n if (!this.isWatching) break;\n this.handleSubscriptionUpdate(update);\n }\n\n // Stream ended normally - reconnect if still watching\n if (this.isWatching) {\n this.connectionState = \"disconnected\";\n this.scheduleReconnect();\n }\n }\n\n /**\n * Handle a subscription update.\n */\n private handleSubscriptionUpdate(update: SubscriptionResponse): void {\n if (!this.eventCallback) return;\n\n const timestamp = Date.now();\n\n if (update.newVtxos?.length) {\n this.processSubscriptionVtxos(update.newVtxos, \"vtxo_received\", timestamp);\n }\n\n if (update.spentVtxos?.length) {\n this.processSubscriptionVtxos(update.spentVtxos, \"vtxo_spent\", timestamp);\n }\n }\n\n /**\n * Process virtual outputs from subscription and route each VTXO to the\n * single contract that actually locks it via `vtxo.script`. If the script\n * doesn't match any watched contract, skip the VTXO rather than fan it\n * out to every matching contract — fan-out produced phantom state in\n * non-owning contracts that then never reconciled.\n */\n private processSubscriptionVtxos(\n vtxos: VirtualCoin[],\n eventType: ContractEvent[\"type\"],\n timestamp: number,\n ): void {\n const byContract = new Map<string, VirtualCoin[]>();\n let unknownScript = 0;\n for (const vtxo of vtxos) {\n if (!this.contracts.has(vtxo.script)) {\n unknownScript++;\n continue;\n }\n let bucket = byContract.get(vtxo.script);\n if (!bucket) {\n bucket = [];\n byContract.set(vtxo.script, bucket);\n }\n bucket.push(vtxo);\n }\n\n if (unknownScript > 0) {\n // The failsafe poll is the backstop for these; log at debug so we\n // can correlate \"VTXO state drift\" reports with subscription\n // drops rather than chase phantom bugs.\n console.debug(\n `ContractWatcher.processSubscriptionVtxos[${eventType}]: dropped ${unknownScript} unknown-script VTXOs (${vtxos.length} total)`,\n );\n }\n\n for (const [contractScript, bucketVtxos] of byContract) {\n const state = this.contracts.get(contractScript);\n if (state) {\n for (const vtxo of bucketVtxos) {\n const key = `${vtxo.txid}:${vtxo.vout}`;\n if (eventType === \"vtxo_received\") {\n state.lastKnownVtxos.set(key, vtxo);\n } else if (eventType === \"vtxo_spent\") {\n state.lastKnownVtxos.delete(key);\n }\n }\n }\n this.emitVtxoEvent(contractScript, bucketVtxos, eventType, timestamp);\n }\n }\n\n /**\n * Emit a virtual output event for a contract.\n */\n private emitVtxoEvent(\n contractScript: string,\n vtxos: VirtualCoin[],\n eventType: ContractEvent[\"type\"],\n timestamp: number,\n ): void {\n if (!this.eventCallback) return;\n const state = this.contracts.get(contractScript);\n if (!state) return;\n\n const extended: ContractVtxo[] = [];\n for (const v of vtxos) {\n try {\n const extendedVtxo = extendVirtualCoinForContract(v, state.contract);\n extended.push({ ...extendedVtxo, contractScript });\n } catch (err) {\n console.warn(`failed to extend vtxo ${v.txid}:${v.vout}`, err);\n extended.push({ ...v, contractScript });\n }\n }\n\n switch (eventType) {\n case \"vtxo_received\":\n this.eventCallback({\n type: \"vtxo_received\",\n vtxos: extended,\n contractScript,\n contract: state.contract,\n timestamp,\n });\n return;\n case \"vtxo_spent\":\n this.eventCallback({\n type: \"vtxo_spent\",\n vtxos: extended,\n contractScript,\n contract: state.contract,\n timestamp,\n });\n return;\n default:\n return;\n }\n }\n}\n","import { WalletRepository, WalletState } from \"../repositories/walletRepository\";\n\n/** Lag behind real-time to avoid racing with indexer writes. */\nexport const SAFETY_LAG_MS = 30_000;\n\n/** Overlap window so boundary virtual outputs are never missed. */\nexport const OVERLAP_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Per-repository mutex that serializes wallet-state mutations so that\n * concurrent read-modify-write cycles never silently overwrite\n * each other's changes.\n */\nconst walletStateLocks = new WeakMap<WalletRepository, Promise<void>>();\n\n/**\n * Atomically read, mutate, and persist wallet state.\n * All callers that modify wallet state should go through this helper\n * to avoid lost-update races between interleaved async operations.\n */\nexport async function updateWalletState(\n repo: WalletRepository,\n updater: (state: WalletState) => WalletState,\n): Promise<void> {\n const prev = walletStateLocks.get(repo) ?? Promise.resolve();\n const op = prev.then(async () => {\n const state = (await repo.getWalletState()) ?? {};\n await repo.saveWalletState(updater(state));\n });\n // Store a version that never rejects so the chain doesn't break.\n walletStateLocks.set(\n repo,\n op.catch(() => {}),\n );\n return op;\n}\n\n/**\n * Settings key that gates interpretation of the `lastSyncTime` field.\n *\n * The `lastSyncTime` column existed pre-PR with a different semantic\n * (wall-clock at sync completion, written by the buggy sync loop this\n * PR fixes). On upgrade we cannot trust any pre-existing value, so the\n * cursor is only honoured after the first successful post-upgrade\n * advance writes this marker into the `settings` JSON blob. Reusing\n * `settings` avoids any schema migration.\n */\nconst CURSOR_MIGRATED_KEY = \"vtxoCursorMigrated\";\n\nfunction hasMigrationMarker(state: WalletState | null | undefined): boolean {\n return state?.settings?.[CURSOR_MIGRATED_KEY] === true;\n}\n\n/**\n * Read the global high-water mark for VTXO indexer syncs.\n *\n * Returns `0` when:\n * - the wallet has never been synced (bootstrap case), or\n * - the stored `lastSyncTime` was written by pre-PR code and is not\n * safe to reuse under the new semantics (see {@link CURSOR_MIGRATED_KEY}).\n */\nexport async function getSyncCursor(repo: WalletRepository): Promise<number> {\n const state = await repo.getWalletState();\n if (!hasMigrationMarker(state)) return 0;\n return state?.lastSyncTime ?? 0;\n}\n\n/**\n * Advance the global cursor after a successful full-scope delta sync.\n *\n * Clamped with `Math.max` against the current value so concurrent syncs\n * that finish out of order can't rewind the cursor: `lastUpdatedAt` is\n * captured before each sync enters the `updateWalletState` mutex, and\n * the later-started sync would otherwise overwrite the earlier-captured\n * one with a smaller value. The legacy value is discarded on the first\n * advance if the migration marker is absent so pre-PR data doesn't\n * survive the upgrade.\n */\nexport async function advanceSyncCursor(\n repo: WalletRepository,\n lastUpdatedAt: number,\n): Promise<void> {\n await updateWalletState(repo, (state) => {\n const current = hasMigrationMarker(state) ? (state.lastSyncTime ?? 0) : 0;\n return {\n ...state,\n lastSyncTime: Math.max(current, lastUpdatedAt),\n settings: {\n ...(state.settings ?? {}),\n [CURSOR_MIGRATED_KEY]: true,\n },\n };\n });\n}\n\n/**\n * Remove the sync cursor, forcing a full re-bootstrap on next sync.\n *\n * Also clears the migration marker so any stored `lastSyncTime` is\n * treated as untrusted on the next read.\n */\nexport async function clearSyncCursor(repo: WalletRepository): Promise<void> {\n await updateWalletState(repo, (state) => {\n const { [CURSOR_MIGRATED_KEY]: _, ...restSettings } = state.settings ?? {};\n return {\n ...state,\n lastSyncTime: undefined,\n settings: restSettings,\n };\n });\n}\n\n/**\n * Compute the `after` lower-bound for a delta sync query.\n *\n * No upper bound (`before`) is applied to the query so that freshly\n * created virtual outputs are never excluded. The safety lag is applied only\n * when advancing the cursor (see @see cursorCutoff).\n */\nexport function computeSyncWindow(cursor: number): { after: number } {\n const after = Math.max(0, cursor - OVERLAP_MS);\n return { after };\n}\n\n/**\n * The safe high-water mark for cursor advancement.\n * Lags behind real-time by @see SAFETY_LAG_MS so that virtual outputs still\n * being indexed are re-queried on the next sync.\n *\n * When `requestStartedAt` is provided the cutoff is frozen to the\n * request start rather than wall-clock at commit time, preventing\n * long-running paginated fetches from advancing the cursor past the\n * data they actually observed.\n */\nexport function cursorCutoff(requestStartedAt?: number): number {\n return (requestStartedAt ?? Date.now()) - SAFETY_LAG_MS;\n}\n","import { hex } from \"@scure/base\";\nimport { IndexerProvider } from \"../providers/indexer\";\nimport { WalletRepository } from \"../repositories/walletRepository\";\nimport {\n Contract,\n ContractEvent,\n ContractEventCallback,\n ContractState,\n ContractVtxo,\n ContractWithVtxos,\n DiscoveredContract,\n DiscoveryDeps,\n GetContractsFilter,\n PathContext,\n PathSelection,\n ExtendedContractVtxo,\n isDiscoverable,\n} from \"./types\";\nimport { ContractWatcher, ContractWatcherConfig } from \"./contractWatcher\";\nimport { contractHandlers } from \"./handlers\";\nimport { ExtendedVirtualCoin, Outpoint, VirtualCoin } from \"../wallet\";\nimport { extendVirtualCoinForContract } from \"../wallet/utils\";\nimport { ContractFilter, ContractRepository } from \"../repositories\";\nimport {\n advanceSyncCursor,\n computeSyncWindow,\n cursorCutoff,\n getSyncCursor,\n} from \"../utils/syncCursors\";\nimport {\n filterVtxosForScript,\n getVtxosForContract,\n saveVtxosForContract,\n warnAndFilterVtxosForScript,\n} from \"./vtxoOwnership\";\n\nconst DEFAULT_PAGE_SIZE = 500;\n\n/**\n * Hard upper bound on the HD index range probed by {@link scanContracts}.\n * Safety valve: a buggy or malicious `Discoverable` handler that returns a\n * hit at every index would otherwise keep the gap window open forever and\n * hang the wallet. 10k is far past any plausible real-world receive\n * history; reaching it without the gap closing is treated as a structural\n * failure rather than a normal scan completion.\n */\nconst SCAN_MAX_INDEX = 10_000;\n\nexport type RefreshVtxosOptions = {\n scripts?: string[];\n after?: number;\n before?: number;\n /**\n * When true and `scripts` is not set, refresh every contract in\n * the repository — including those marked `inactive` and those\n * that have dropped out of the watcher's active set. Useful for\n * \"did anyone send funds to a stale rotated display address?\"\n * audits.\n *\n * Because this is a *superset* of the watcher's watched set, the\n * cursor invariant still holds and the cursor advances normally\n * (unless an explicit `after` / `before` window is also supplied).\n *\n * Ignored when `scripts` is set (the explicit list already\n * specifies what to refresh, regardless of contract state).\n *\n * @defaultValue `false`\n */\n includeInactive?: boolean;\n};\n\n/**\n * A single `Discoverable` handler's `discoverAt` rejection, captured during\n * a {@link IContractManager.scanContracts} run instead of aborting the loop.\n */\nexport interface HandlerError {\n handler: string;\n index: number;\n error: unknown;\n}\n\n/**\n * Outcome of a {@link IContractManager.scanContracts} run.\n *\n * `lastIndexUsed` is the highest HD index at which any handler discovered a\n * contract (`-1` if nothing was found). `handlerErrors` collects per-handler\n * `discoverAt` failures — non-empty means the gap window may have closed\n * early and the caller should surface this (the scan itself still resolved).\n */\nexport interface ScanResult {\n lastIndexUsed: number;\n handlerErrors: HandlerError[];\n}\n\n/**\n * Options for {@link IContractManager.scanContracts}.\n */\nexport interface ScanContractsOptions {\n /** Default 20. A non-positive / non-integer value throws. */\n gapLimit?: number;\n /** HD mode → unbounded gap loop guided by the gap counter; false → probe only index 0 (single static pass). */\n hd: boolean;\n /**\n * Materialize the descriptor at an HD index. Pure derivation; a throw\n * here is structural/fatal and propagates out of `scanContracts`.\n */\n materialize: (index: number) => string;\n /** Read-only context injected into every `discoverAt` call. */\n deps: DiscoveryDeps;\n}\n\nexport interface IContractManager extends Disposable {\n /**\n * Create and register a new contract.\n *\n * Implementations may validate that:\n * - A handler exists for `params.type`\n * - `params.script` matches the script derived from `params.params`\n *\n * The contract script is used as the unique identifier.\n */\n createContract(params: CreateContractParams): Promise<Contract>;\n\n /**\n * List contracts with optional filters.\n *\n * @example\n * ```typescript\n * const vhtlcs = await manager.getContracts({ type: \"vhtlc\" });\n * const active = await manager.getContracts({ state: \"active\" });\n * ```\n */\n getContracts(filter?: GetContractsFilter): Promise<Contract[]>;\n\n /**\n * List contracts and their current virtual outputs.\n *\n * If no filter is provided, returns all contracts with their virtual outputs.\n */\n getContractsWithVtxos(filter?: GetContractsFilter): Promise<ContractWithVtxos[]>;\n\n /**\n * Stamp raw virtual outputs with the correct per-contract tapscripts\n * (forfeit, intent, tap tree).\n *\n * Resolves each vtxo's `script` to its owning contract via the contract\n * repository and attaches the matching tapscripts. Throws when any vtxo\n * references a script with no registered contract — callers are expected\n * to register the contract before asking for annotation. This is the\n * single shared path that replaces scattered `extendVirtualCoin*` calls\n * in wallet/handler code, and keeps the wallet from silently stamping the\n * default tapscript onto a non-default vtxo.\n */\n annotateVtxos(vtxos: VirtualCoin[]): Promise<ExtendedVirtualCoin[]>;\n\n /**\n * Update mutable contract fields.\n *\n * `script` and `createdAt` are immutable.\n */\n updateContract(\n script: string,\n updates: Partial<Omit<Contract, \"script\" | \"createdAt\">>,\n ): Promise<Contract>;\n\n /**\n * Convenience helper to update only the contract state.\n */\n setContractState(script: string, state: ContractState): Promise<void>;\n\n /**\n * Delete a contract by script and stop watching it (if applicable).\n */\n deleteContract(script: string): Promise<void>;\n\n /**\n * Get all currently spendable paths for a contract.\n *\n * Returns an empty array if the contract or its handler cannot be found.\n */\n getSpendablePaths(options: GetSpendablePathsOptions): Promise<PathSelection[]>;\n\n /**\n * Get all possible spending paths for a contract.\n *\n * Returns an empty array if the contract or its handler cannot be found.\n */\n getAllSpendingPaths(options: GetAllSpendingPathsOptions): Promise<PathSelection[]>;\n\n /**\n * Subscribe to contract events.\n *\n * @returns Unsubscribe function\n */\n onContractEvent(callback: ContractEventCallback): () => void;\n\n /**\n * Force a virtual output refresh from the indexer.\n *\n * Without options, refreshes all contracts from scratch.\n * With options, narrows the refresh to specific scripts and/or a time window.\n */\n refreshVtxos(opts?: RefreshVtxosOptions): Promise<void>;\n\n /**\n * Reconcile specific outpoints with the indexer's authoritative state and\n * upsert the result into the wallet repository.\n *\n * The cursor-derived delta sync filters by `created_at`, so a VTXO that\n * was created before the cursor but spent recently won't surface in a\n * standard `refreshVtxos()` call. This method is the surgical recovery\n * path for that case: when something hands us a stale outpoint (e.g. the\n * server returns `VTXO_ALREADY_SPENT` with a `vtxo_outpoint` in its\n * error metadata), call this to pull the latest state and unblock the\n * caller — no full re-scan, no cursor change.\n *\n * Outpoints not owned by any tracked contract are silently dropped.\n */\n refreshOutpoints(outpoints: Outpoint[]): Promise<void>;\n\n /**\n * Explicit, gap-limit contract discovery used by `wallet.restore()`.\n *\n * Walks HD indices from 0, asking every registered `Discoverable`\n * handler whether it owns a contract anchored at that index, and\n * registers each find via the idempotent {@link createContract}. A hit\n * at index `i` (by any handler, including an injected swap handler)\n * resets the gap counter, so swap discovery keeps the HD window open.\n *\n * Error contract (safety-critical — see spec §4):\n * - A handler's `discoverAt` rejecting is **collected** into\n * `handlerErrors` and the loop **continues**; it never aborts the\n * scan or throws.\n * - A fatal operational error — `materialize()` throwing, or\n * `createContract` rejecting — **propagates** out of `scanContracts`\n * (it invalidates the gap-window signal, so a silent truncation\n * would risk hiding user funds).\n *\n * @param opts See {@link ScanContractsOptions}.\n * @returns `{ lastIndexUsed, handlerErrors }` — the caller surfaces\n * `handlerErrors` *after* the inline VTXO pull.\n */\n scanContracts(opts: ScanContractsOptions): Promise<ScanResult>;\n\n /**\n * Whether the underlying watcher is currently active.\n */\n isWatching(): Promise<boolean>;\n\n /**\n * Release resources (stop watching, clear listeners).\n */\n dispose(): void;\n}\n\n/**\n * Options for getting spendable paths.\n */\nexport type GetSpendablePathsOptions = {\n /** The contract script */\n contractScript: string;\n /** The specific virtual output being evaluated */\n vtxo: VirtualCoin;\n /** Whether collaborative spending is available (default: true) */\n collaborative?: boolean;\n /** Wallet's public key (hex) to determine role */\n walletPubKey?: string;\n};\n\n/**\n * Options for getting all possible spending paths.\n */\nexport type GetAllSpendingPathsOptions = {\n /** The contract script */\n contractScript: string;\n /** Whether collaborative spending is available (default: true) */\n collaborative?: boolean;\n /** Wallet's public key (hex) to determine role */\n walletPubKey?: string;\n};\n\n/**\n * Configuration for the ContractManager.\n */\nexport interface ContractManagerConfig {\n /** The indexer provider */\n indexerProvider: IndexerProvider;\n\n /** The contract repository for persistence */\n contractRepository: ContractRepository;\n\n /** The wallet repository for virtual output storage (single source of truth) */\n walletRepository: WalletRepository;\n\n /** Watcher configuration */\n watcherConfig?: Partial<ContractWatcherConfig>;\n}\n\n/**\n * Parameters for creating a new contract.\n */\nexport type CreateContractParams = Omit<Contract, \"createdAt\" | \"state\"> & {\n /** Initial state (defaults to \"active\") */\n state?: ContractState;\n};\n\n/**\n * Central manager for contract lifecycle and operations.\n *\n * Responsibilities:\n * - Create and persist contracts\n * - Query stored contracts (optionally with their virtual outputs)\n * - Provide spendable path selection for a contract\n * - Emit contract-related events (virtual output received/spent, connection reset)\n *\n * Notes:\n * - Implementations typically start watching automatically during initialization\n * (so `onContractEvent()` is just for subscribing).\n *\n * @example\n * ```typescript\n * const manager = await ContractManager.create({\n * indexerProvider: wallet.indexerProvider,\n * contractRepository: wallet.contractRepository,\n * });\n *\n * // Create a new VHTLC contract\n * const contract = await manager.createContract({\n * label: \"Lightning Receive\",\n * type: \"vhtlc\",\n * params: { sender: \"ark1q...\", receiver: \"ark1q...\", ... },\n * script: \"5120...\",\n * address: \"ark1q...\",\n * });\n *\n * // Start watching for events\n * const unsubscribe = manager.onContractEvent((event) => {\n * console.log(`${event.type} on ${event.contractScript}`);\n * });\n *\n * // Query contracts together with their current virtual outputs\n * const contractsWithVtxos = await manager.getContractsWithVtxos();\n *\n * // Get balance across all contracts\n * const balances = contractsWithVtxos.flatMap(({vtxos}) => vtxos).reduce((acc, vtxo) => acc + vtxo.value, 0)\n *\n * // Later: unsubscribe from events\n * unsubscribe();\n *\n * // Clean up\n * manager.dispose();\n * ```\n */\nexport class ContractManager implements IContractManager {\n private config: ContractManagerConfig;\n private watcher: ContractWatcher;\n private initialized = false;\n private eventCallbacks: Set<ContractEventCallback> = new Set();\n private stopWatcherFn?: () => void;\n\n private constructor(config: ContractManagerConfig) {\n this.config = config;\n\n // Create watcher with wallet repository for virtual output caching\n this.watcher = new ContractWatcher({\n indexerProvider: config.indexerProvider,\n walletRepository: config.walletRepository,\n ...config.watcherConfig,\n });\n }\n\n /**\n * Static factory method for creating a new ContractManager.\n * Initialize the manager by loading persisted contracts and starting to watch.\n *\n * After initialization, the manager automatically watches all active contracts\n * and contracts with virtual outputs. Use `onContractEvent()` to register event callbacks.\n *\n * @param config ContractManagerConfig\n */\n static async create(config: ContractManagerConfig): Promise<ContractManager> {\n const cm = new ContractManager(config);\n await cm.initialize();\n return cm;\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Register persisted contracts with the watcher BEFORE the first\n // sync. `addContract` seeds `lastKnownVtxos` from the repo without\n // starting to poll, so it's cheap, and it populates\n // `getWatchedContracts()` so the sync below can scope itself to the\n // real watched set instead of every contract ever persisted.\n const contracts = await this.config.contractRepository.getContracts();\n for (const contract of contracts) {\n await this.watcher.addContract(contract);\n }\n\n await this.reconcileWatched();\n\n this.initialized = true;\n\n // Start watching automatically\n this.stopWatcherFn = await this.watcher.startWatching((event) => {\n this.handleContractEvent(event).catch((error) => {\n console.error(\"Error handling contract event:\", error);\n });\n });\n }\n\n /**\n * Delta-sync the full watched set and reconcile the pending frontier.\n *\n * Shared recovery path used on initial boot and after a subscription\n * reconnect. `syncContracts({})` scopes to the current watched set\n * (see {@link ContractWatcher.getWatchedContracts}), uses the\n * cursor-derived delta window, and advances the cursor on success.\n * `reconcilePendingFrontier` catches not-yet-finalized virtual\n * outputs that could sit outside any delta window.\n */\n private async reconcileWatched(): Promise<void> {\n await this.syncContracts({});\n const watched = this.watcher.getWatchedContracts();\n if (watched.length > 0) {\n await this.reconcilePendingFrontier(watched);\n }\n }\n\n /**\n * Create and register a new contract.\n *\n * @param params - Contract parameters\n * @returns The created contract\n */\n async createContract(params: CreateContractParams): Promise<Contract> {\n const { contract, persisted } = await this.upsertContract(params);\n if (persisted) {\n // fetch all virtual outputs (including spent/swept) for this contract\n await this.fetchContractVxosFromIndexer([contract]);\n await this.watcher.addContract(contract);\n }\n return contract;\n }\n\n /**\n * Lightweight variant of {@link createContract} for batch discovery\n * paths (currently: {@link scanContracts}). Validates, dedupes, persists,\n * and registers the watcher — but skips the per-contract\n * `fetchContractVxosFromIndexer` round-trip. The caller is responsible\n * for hydrating VTXOs afterwards via a bulk `refreshVtxos(...)` so a\n * scan that finds N contracts costs one batched indexer call instead\n * of N + 1. Error semantics are identical to `createContract`:\n * validation / type-mismatch / persistence failures propagate.\n */\n private async persistAndWatchContract(params: CreateContractParams): Promise<Contract> {\n const { contract, persisted } = await this.upsertContract(params);\n if (persisted) {\n await this.watcher.addContract(contract);\n }\n return contract;\n }\n\n /**\n * Shared validate + check-existing + persist core for\n * {@link createContract} and {@link persistAndWatchContract}. Returns\n * the resolved contract and whether *this* call wrote it — callers\n * that need to attach hydration / watcher work do so only when\n * `persisted` is `true`.\n */\n private async upsertContract(\n params: CreateContractParams,\n ): Promise<{ contract: Contract; persisted: boolean }> {\n // Validate that a handler exists for this contract type\n const handler = contractHandlers.get(params.type);\n if (!handler) {\n throw new Error(`No handler registered for contract type '${params.type}'`);\n }\n\n // Validate params by attempting to create the script\n // This catches invalid/missing params early\n try {\n const script = handler.createScript(params.params);\n const derivedScript = hex.encode(script.pkScript);\n\n // Verify the derived script matches the provided script\n if (derivedScript !== params.script) {\n throw new Error(\n `Script mismatch: provided script does not match script derived from params. ` +\n `Expected ${derivedScript}, got ${params.script}`,\n );\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"mismatch\")) {\n throw error;\n }\n throw new Error(\n `Invalid params for contract type '${params.type}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n // Check if contract already exists and verify it's the same type to avoid silent mismatches\n const [existing] = await this.getContracts({ script: params.script });\n if (existing) {\n if (existing.type === params.type) return { contract: existing, persisted: false };\n throw new Error(\n `Contract with script ${params.script} already exists with with type ${existing.type}.`,\n );\n }\n\n const contract: Contract = {\n ...params,\n createdAt: Date.now(),\n state: params.state || \"active\",\n };\n\n await this.config.contractRepository.saveContract(contract);\n return { contract, persisted: true };\n }\n\n /**\n * Explicit, gap-limit contract discovery (see {@link IContractManager.scanContracts}).\n *\n * Each hit is routed through {@link persistAndWatchContract} — the same\n * dedupe + watcher-register path as {@link createContract} minus the\n * per-contract indexer round-trip. The caller (`Wallet.restore`) follows\n * up with a single bulk `refreshVtxos({ includeInactive: true })`, so a\n * scan that finds N contracts costs one batched indexer call instead of\n * N + 1.\n *\n * Safety-critical invariants (spec §2.C / §4):\n * - `opts.materialize(i)` throwing is structural/fatal: it is NOT\n * wrapped — it propagates and aborts the scan.\n * - A `discoverAt` rejection is collected into `handlerErrors` and the\n * loop continues (the gap counter still advances for that index if no\n * other handler hit it).\n * - `persistAndWatchContract` rejecting is operational/fatal and\n * propagates (only `discoverAt` is guarded).\n */\n async scanContracts(opts: ScanContractsOptions): Promise<ScanResult> {\n const gapLimit = opts.gapLimit ?? 20;\n if (!Number.isInteger(gapLimit) || gapLimit <= 0) {\n throw new Error(\n `scanContracts: gapLimit must be a positive integer (got ${String(opts.gapLimit)})`,\n );\n }\n const discoverables = contractHandlers\n .getRegisteredTypes()\n .map((t) => contractHandlers.get(t))\n .filter(isDiscoverable);\n\n const maxIdx = opts.hd ? SCAN_MAX_INDEX : 0;\n const handlerErrors: HandlerError[] = [];\n let lastIndexUsed = -1;\n let unused = 0;\n let i = 0;\n\n while (i <= maxIdx && unused < gapLimit) {\n // Materialization failure is fatal/structural — let it propagate.\n const descriptor = opts.materialize(i);\n let hitAtThisIndex = false;\n for (const h of discoverables) {\n let found: DiscoveredContract[];\n try {\n found = await h.discoverAt(i, descriptor, opts.deps);\n } catch (error) {\n handlerErrors.push({ handler: h.type, index: i, error });\n continue;\n }\n for (const c of found) {\n await this.persistAndWatchContract(c); // idempotent (script-keyed)\n hitAtThisIndex = true;\n }\n }\n if (hitAtThisIndex) {\n lastIndexUsed = i;\n unused = 0;\n } else {\n unused += 1;\n }\n i += 1;\n }\n\n // Hit the safety ceiling without the gap window closing — the\n // scan was truncated. Surface loudly (matching the materialize-\n // fatal contract) rather than silently returning a partial\n // result, since the caller cannot otherwise distinguish \"no\n // more funds past lastIndexUsed\" from \"we stopped scanning\".\n if (opts.hd && i > maxIdx && unused < gapLimit) {\n throw new Error(\n `scanContracts: reached SCAN_MAX_INDEX (${SCAN_MAX_INDEX}) without closing the ` +\n `${gapLimit}-index gap window; a Discoverable handler may be returning ` +\n `unconditional hits`,\n );\n }\n\n return { lastIndexUsed, handlerErrors };\n }\n\n /**\n * Get contracts with optional filters.\n *\n * @param filter - Optional filter criteria\n * @returns Filtered contracts TODO: filter spent/unspent\n *\n * @example\n * ```typescript\n * // Get all VHTLC contracts\n * const vhtlcs = await manager.getContracts({ type: 'vhtlc' });\n *\n * // Get all active contracts\n * const active = await manager.getContracts({ state: 'active' });\n * ```\n */\n async getContracts(filter?: GetContractsFilter): Promise<Contract[]> {\n const dbFilter = this.buildContractsDbFilter(filter ?? {});\n return await this.config.contractRepository.getContracts(dbFilter);\n }\n\n async getContractsWithVtxos(\n filter?: GetContractsFilter,\n pageSize?: number,\n ): Promise<ContractWithVtxos[]> {\n const contracts = await this.getContracts(filter);\n await this.syncContracts({ contracts, pageSize });\n const vtxos = await this.getVtxosForContracts(contracts);\n return contracts.map((contract) => ({\n contract,\n vtxos: vtxos.filter((vtxo) => vtxo.contractScript === contract.script),\n }));\n }\n\n async annotateVtxos(vtxos: VirtualCoin[]): Promise<ExtendedVirtualCoin[]> {\n if (vtxos.length === 0) return [];\n\n const scripts = Array.from(new Set(vtxos.map((v) => v.script)));\n\n const byScript = new Map<string, Contract>();\n const contracts = await this.config.contractRepository.getContracts({\n script: scripts,\n });\n for (const contract of contracts) {\n byScript.set(contract.script, contract);\n }\n\n return vtxos.map((vtxo) => extendVirtualCoinForContract(vtxo, byScript));\n }\n\n private buildContractsDbFilter(filter: GetContractsFilter): ContractFilter {\n return {\n script: filter.script,\n state: filter.state,\n type: filter.type,\n };\n }\n\n /**\n * Update a contract.\n * Nested fields like `params` and `metadata` are replaced with the provided values.\n * If you need to preserve existing fields, merge them manually.\n *\n * @param script - Contract script\n * @param updates - Fields to update\n */\n async updateContract(\n script: string,\n updates: Partial<Omit<Contract, \"script\" | \"createdAt\">>,\n ): Promise<Contract> {\n const contracts = await this.config.contractRepository.getContracts({\n script,\n });\n const existing = contracts[0];\n if (!existing) {\n throw new Error(`Contract ${script} not found`);\n }\n\n const updated: Contract = {\n ...existing,\n ...updates,\n };\n\n await this.config.contractRepository.saveContract(updated);\n await this.watcher.updateContract(updated);\n\n return updated;\n }\n\n /**\n * Update a contract's params.\n * This method preserves existing params by merging the provided values.\n *\n * @param script - Contract script\n * @param updates - The new values to merge with existing params\n */\n async updateContractParams(script: string, updates: Contract[\"params\"]): Promise<Contract> {\n const contracts = await this.config.contractRepository.getContracts({\n script,\n });\n const existing = contracts[0];\n if (!existing) {\n throw new Error(`Contract ${script} not found`);\n }\n\n const updated: Contract = {\n ...existing,\n params: { ...existing.params, ...updates },\n };\n\n await this.config.contractRepository.saveContract(updated);\n await this.watcher.updateContract(updated);\n\n return updated;\n }\n\n /**\n * Set a contract's state.\n */\n async setContractState(script: string, state: ContractState): Promise<void> {\n await this.updateContract(script, { state });\n }\n\n /**\n * Delete a contract.\n *\n * @param script - Contract script\n */\n async deleteContract(script: string): Promise<void> {\n await this.config.contractRepository.deleteContract(script);\n await this.watcher.removeContract(script);\n }\n\n /**\n * Get currently spendable paths for a contract.\n *\n * @param options - Options for getting spendable paths\n */\n async getSpendablePaths(options: GetSpendablePathsOptions): Promise<PathSelection[]> {\n const { contractScript, collaborative = true, walletPubKey, vtxo } = options;\n\n const [contract] = await this.getContracts({ script: contractScript });\n if (!contract) return [];\n\n const handler = contractHandlers.get(contract.type);\n if (!handler) return [];\n\n const script = handler.createScript(contract.params);\n const context: PathContext = {\n collaborative,\n currentTime: Date.now(),\n walletPubKey,\n vtxo,\n };\n\n return handler.getSpendablePaths(script, contract, context);\n }\n\n /**\n * Get every currently valid spending path for a contract.\n *\n * @param options - Options for getting spending paths\n */\n async getAllSpendingPaths(options: GetAllSpendingPathsOptions): Promise<PathSelection[]> {\n const { contractScript, collaborative = true, walletPubKey } = options;\n\n const [contract] = await this.getContracts({ script: contractScript });\n if (!contract) return [];\n\n const handler = contractHandlers.get(contract.type);\n if (!handler) return [];\n\n const script = handler.createScript(contract.params);\n const context: PathContext = {\n collaborative,\n currentTime: Date.now(),\n walletPubKey,\n };\n\n return handler.getAllSpendingPaths(script, contract, context);\n }\n\n /**\n * Register a callback for contract events.\n *\n * The manager automatically watches after `initialize()`. This method\n * allows registering callbacks to receive events.\n *\n * @param callback - Event callback\n * @returns Unsubscribe function to remove this callback\n *\n * @example\n * ```typescript\n * const unsubscribe = manager.onContractEvent((event) => {\n * console.log(`${event.type} on ${event.contractScript}`);\n * });\n *\n * // Later: stop receiving events\n * unsubscribe();\n * ```\n */\n onContractEvent(callback: ContractEventCallback): () => void {\n this.eventCallbacks.add(callback);\n return () => {\n this.eventCallbacks.delete(callback);\n };\n }\n\n /**\n * Force refresh virtual outputs from the indexer.\n *\n * Without options, re-fetches every contract in the watcher's\n * watched set and advances the global cursor.\n *\n * `scripts` narrows the refresh to a specific list (subset query —\n * cursor is not advanced because contracts outside the list may\n * have data we'd skip).\n *\n * `includeInactive: true` (and no `scripts`) widens the refresh to\n * every contract in the repository, including ones marked\n * `inactive` and ones that have dropped out of the watcher's\n * active set. This is a *superset* of the watched set, so the\n * cursor invariant still holds and the cursor advances normally.\n *\n * `after` / `before` apply a caller-supplied time window. The\n * cursor never advances on a windowed query because the window\n * may skip data outside its bounds.\n */\n async refreshVtxos(opts?: RefreshVtxosOptions): Promise<void> {\n const contracts = opts?.scripts\n ? await this.getContracts({ script: opts.scripts })\n : undefined;\n // Only forward an explicit window when the caller supplied one. An\n // empty `{ after: undefined, before: undefined }` would short-circuit\n // both the cursor-derived `?after=` query in `syncContracts` (because\n // `??` doesn't fire on a non-nullish object) AND the cursor-advance\n // gate (which requires `options.window === undefined`), turning every\n // `refreshVtxos()` call into an unbounded full re-scan whose cursor\n // never moves forward.\n const hasExplicitWindow = opts?.after !== undefined || opts?.before !== undefined;\n await this.syncContracts({\n contracts,\n // Scope-only widener; never set together with explicit\n // `contracts` because `scripts` already names the exact set.\n includeInactive: contracts ? false : opts?.includeInactive,\n window: hasExplicitWindow ? { after: opts?.after, before: opts?.before } : undefined,\n });\n }\n\n async refreshOutpoints(outpoints: Outpoint[]): Promise<void> {\n if (outpoints.length === 0) return;\n\n const { vtxos } = await this.config.indexerProvider.getVtxos({\n outpoints,\n });\n if (vtxos.length === 0) return;\n\n // Filter to outputs whose script we own. Map them to their owning\n // contract so we can write through to the right per-address entry\n // in the wallet repository.\n const scripts = Array.from(new Set(vtxos.map((v) => v.script)));\n const contracts = await this.config.contractRepository.getContracts({\n script: scripts,\n });\n const scriptToContract = new Map(contracts.map((c) => [c.script, c]));\n const owned = vtxos.filter((v) => scriptToContract.has(v.script));\n if (owned.length === 0) return;\n\n const annotated = await this.annotateVtxos(owned);\n const byAddress = new Map<string, ExtendedVirtualCoin[]>();\n for (const vtxo of annotated) {\n const contract = scriptToContract.get(vtxo.script);\n if (!contract) continue;\n const address = contract.address;\n const arr = byAddress.get(address) ?? [];\n arr.push(vtxo);\n byAddress.set(address, arr);\n }\n for (const [address, addressVtxos] of byAddress) {\n const contract = contracts.find((c) => c.address === address);\n if (contract) {\n await saveVtxosForContract(this.config.walletRepository, contract, addressVtxos);\n } else {\n await this.config.walletRepository.saveVtxos(address, addressVtxos);\n }\n }\n }\n\n /**\n * Check if currently watching.\n */\n async isWatching(): Promise<boolean> {\n return this.watcher.isCurrentlyWatching();\n }\n\n /**\n * Emit an event to all registered callbacks.\n */\n private emitEvent(event: ContractEvent): void {\n for (const callback of this.eventCallbacks) {\n try {\n callback(event);\n } catch (error) {\n console.error(\"Error in contract event callback:\", error);\n }\n }\n }\n\n /**\n * Handle events from the watcher.\n */\n private async handleContractEvent(event: ContractEvent) {\n switch (event.type) {\n // Delta-sync only the changed virtual outputs for this contract.\n case \"vtxo_received\":\n case \"vtxo_spent\":\n await this.syncContracts({ contracts: [event.contract] });\n break;\n case \"connection_reset\":\n // Same recovery path as boot: delta-sync the watched set\n // and reconcile the pending frontier. `advanceSyncCursor`\n // is monotonic so this never rewinds the cursor.\n await this.reconcileWatched();\n break;\n }\n\n // Forward to all callbacks\n this.emitEvent(event);\n }\n\n private async getVtxosForContracts(contracts: Contract[]): Promise<ExtendedContractVtxo[]> {\n const res = await Promise.all(\n contracts.map((contract) =>\n getVtxosForContract(this.config.walletRepository, contract).then((vtxos) =>\n vtxos.map(\n (vtxo): ExtendedContractVtxo => ({\n ...vtxo,\n contractScript: contract.script,\n }),\n ),\n ),\n ),\n );\n return res.flat();\n }\n\n /**\n * Sync virtual outputs for the given contracts against the indexer.\n *\n * When `options.contracts` is omitted the sync covers the full\n * watched set (active contracts plus any inactive contracts still\n * holding cached VTXOs) and the global cursor is advanced on\n * success. Passing an explicit subset leaves the cursor alone so a\n * narrow poll can't hide data that other contracts still need to\n * pick up.\n */\n private async syncContracts(options: {\n contracts?: Contract[];\n pageSize?: number;\n // Overrides the cursor-derived window.\n window?: { after?: number; before?: number };\n // When `contracts` is omitted: query every contract in the\n // repository (active + inactive) instead of just the watcher's\n // watched set. This is a superset of the watched set, so the\n // cursor invariant still holds and the cursor still advances.\n includeInactive?: boolean;\n }): Promise<Map<string, ExtendedContractVtxo[]>> {\n const cursor = await getSyncCursor(this.config.walletRepository);\n const window = options.window ?? computeSyncWindow(cursor);\n\n // Advance the global cursor only on cursor-derived delta syncs\n // whose contract scope covers at least the watcher's watched\n // set. Targeted subset queries (caller-supplied `contracts`) and\n // bounded-window queries must not move the cursor — they may\n // skip data outside their bounds. `includeInactive` (with no\n // `contracts`) widens the scope rather than narrowing it, so it\n // is cursor-safe. `<=` lets the bootstrap case (cursor=0,\n // window.after=0) write the migration marker on first boot.\n const mustUpdateCursor =\n options.contracts === undefined &&\n options.window === undefined &&\n (window.after ?? 0) <= cursor;\n\n const contracts =\n options.contracts ??\n (options.includeInactive\n ? await this.config.contractRepository.getContracts({})\n : this.watcher.getWatchedContracts());\n\n const requestStartedAt = Date.now();\n const result = await this.fetchContractVxosFromIndexer(contracts, options.pageSize, window);\n\n if (mustUpdateCursor) {\n const cutoff = cursorCutoff(requestStartedAt);\n await advanceSyncCursor(this.config.walletRepository, cutoff);\n }\n\n return result;\n }\n\n /**\n * Fetch all pending (unfinalized) virtual outputs and upsert them into the\n * repository. This catches virtual outputs whose state changed outside the delta\n * window (e.g. a spend that hasn't settled yet).\n */\n private async reconcilePendingFrontier(contracts: Contract[]): Promise<void> {\n const scripts = contracts.map((c) => c.script);\n const scriptToContract = new Map<string, Contract>(contracts.map((c) => [c.script, c]));\n\n const { vtxos } = await this.config.indexerProvider.getVtxos({\n scripts,\n pendingOnly: true,\n });\n\n // Share the annotation path with external callers so the two entry\n // points can't drift.\n const owned = vtxos.filter((v) => scriptToContract.has(v.script));\n const annotated = await this.annotateVtxos(owned);\n\n const byContract = new Map<string, ExtendedContractVtxo[]>();\n for (const vtxo of annotated) {\n const contract = scriptToContract.get(vtxo.script)!;\n let arr = byContract.get(contract.address);\n if (!arr) {\n arr = [];\n byContract.set(contract.address, arr);\n }\n arr.push({\n ...vtxo,\n contractScript: contract.script,\n });\n }\n\n for (const [addr, contractVtxos] of byContract) {\n // The bucket is keyed by contract address, so the script filter\n // here is the same as the contract's. Skip wrong-script rows\n // rather than crash the reconcile loop.\n const contract = contracts.find((c) => c.address === addr)!;\n const filtered = warnAndFilterVtxosForScript(\n contractVtxos,\n contract.script,\n \"ContractManager.reconcilePendingFrontier\",\n );\n if (filtered.length === 0) continue;\n await saveVtxosForContract(\n this.config.walletRepository,\n contract,\n filtered as ExtendedVirtualCoin[],\n );\n }\n }\n\n private async fetchContractVxosFromIndexer(\n contracts: Contract[],\n pageSize?: number,\n syncWindow?: { after?: number; before?: number },\n ): Promise<Map<string, ExtendedContractVtxo[]>> {\n const fetched = await this.fetchContractVtxosBulk(contracts, pageSize, syncWindow);\n const result = new Map<string, ExtendedContractVtxo[]>();\n for (const [contractScript, vtxos] of fetched) {\n result.set(contractScript, vtxos);\n const contract = contracts.find((c) => c.script === contractScript);\n if (contract) {\n const filtered = warnAndFilterVtxosForScript(\n vtxos,\n contract.script,\n \"ContractManager.fetchContractVxosFromIndexer\",\n );\n if (filtered.length === 0) continue;\n await saveVtxosForContract(\n this.config.walletRepository,\n contract,\n filtered as ExtendedVirtualCoin[],\n );\n }\n }\n return result;\n }\n\n private async fetchContractVtxosBulk(\n contracts: Contract[],\n pageSize: number = DEFAULT_PAGE_SIZE,\n syncWindow?: { after?: number; before?: number },\n ): Promise<Map<string, ExtendedContractVtxo[]>> {\n if (contracts.length === 0) {\n return new Map();\n }\n\n // Batch all scripts into a single indexer call per page to minimise\n // round-trips. Results are keyed by script so we can distribute them\n // back to the correct contract afterwards. Always fetches the full\n // history (spent/swept included) so the repo is the source of truth.\n const scriptToContract = new Map<string, Contract>(contracts.map((c) => [c.script, c]));\n const result = new Map<string, ExtendedContractVtxo[]>(\n contracts.map((c) => [c.script, []]),\n );\n\n const scripts = contracts.map((c) => c.script);\n const windowOpts = syncWindow\n ? {\n ...(syncWindow.after !== undefined && {\n after: syncWindow.after,\n }),\n ...(syncWindow.before !== undefined && {\n before: syncWindow.before,\n }),\n }\n : {};\n let pageIndex = 0;\n let hasMore = true;\n\n while (hasMore) {\n const { vtxos, page } = await this.config.indexerProvider.getVtxos({\n scripts,\n ...windowOpts,\n pageIndex,\n pageSize,\n });\n\n // Match virtual outputs back to their contract via the script field\n // populated by the indexer, then share the annotation path with\n // external callers via annotateVtxos so the two entry points can't\n // drift.\n const owned = vtxos.filter((v) => scriptToContract.has(v.script));\n const annotated = await this.annotateVtxos(owned);\n for (const vtxo of annotated) {\n result.get(vtxo.script)!.push({\n ...vtxo,\n contractScript: vtxo.script,\n });\n }\n\n hasMore = page ? vtxos.length === pageSize : false;\n pageIndex++;\n if (hasMore) await new Promise((r) => setTimeout(r, 500));\n }\n\n return result;\n }\n\n /**\n * Dispose of the ContractManager and release all resources.\n *\n * Stops the watcher, clears callbacks, and marks\n * the manager as uninitialized.\n *\n * Implements the disposable pattern for cleanup.\n */\n dispose(): void {\n // Stop watching\n this.stopWatcherFn?.();\n this.stopWatcherFn = undefined;\n\n // Clear callbacks\n this.eventCallbacks.clear();\n\n // Mark as uninitialized\n this.initialized = false;\n }\n\n /**\n * Symbol.dispose implementation for using with `using` keyword.\n * @example\n * ```typescript\n * {\n * using manager = await wallet.getContractManager();\n * // ... use manager\n * } // automatically disposed\n * ```\n */\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n","import { expand, networks } from \"@bitcoinerlab/descriptors-scure\";\nimport { isMainnetDescriptor } from \"../identity/descriptor\";\nimport { DescriptorProvider, DescriptorSigningRequest } from \"../identity/descriptorProvider\";\nimport { HDCapableIdentity } from \"../identity/hdCapableIdentity\";\nimport { WalletRepository, WalletState } from \"../repositories/walletRepository\";\nimport { Transaction } from \"../utils/transaction\";\nimport { updateWalletState } from \"../utils/syncCursors\";\nimport {\n ReceiveRotatorBoot,\n ReceiveRotatorBootOpts,\n ReceiveRotatorFactory,\n WalletReceiveRotator,\n} from \"./walletReceiveRotator\";\n\n/**\n * Persisted HD wallet state stored under {@link WalletState.settings}`.hd`.\n * @internal\n */\ninterface HDWalletSettings {\n /**\n * Account descriptor (ends in `/*)`). Used as a strong identity guard:\n * a repo populated by a different seed will have a different descriptor\n * and must not be reused.\n */\n descriptor: string;\n\n /**\n * The most recently allocated descriptor index. `undefined` means no\n * descriptor has ever been allocated; the next allocation will return\n * index 0.\n */\n lastIndexUsed?: number;\n}\n\n/** Settings key under {@link WalletState.settings} where HD state lives. */\nconst HD_SETTINGS_KEY = \"hd\";\n\n/**\n * HD-wallet {@link DescriptorProvider} that allocates a fresh signing\n * descriptor on every call. The provider holds no notion of \"current\" — it\n * is a pure rotating allocator. The question of \"which descriptor is the\n * wallet currently bound to?\" is answered by querying the contract\n * repository for active contracts, not by asking this provider.\n *\n * State is persisted under `WalletRepository.getWalletState().settings.hd` so\n * that no storage-schema migration is required when switching a wallet from\n * single-key to HD. The provider is backed by an {@link HDCapableIdentity},\n * which carries the wildcard account descriptor template (for derivation)\n * and the signing primitives.\n *\n * The read-modify-write of the persisted index runs inside the shared per-\n * repo `updateWalletState` mutex, so two `getNextSigningDescriptor` callers\n * — including those driving separate `HDDescriptorProvider` instances on\n * the same repo — can never observe the same index.\n *\n * @example\n * ```ts\n * const provider = await HDDescriptorProvider.create(identity, walletRepo);\n * const descriptor = await provider.getNextSigningDescriptor();\n * // descriptor: tr([fp/86'/0'/0']xpub/0/0)\n * const next = await provider.getNextSigningDescriptor();\n * // next: tr([fp/86'/0'/0']xpub/0/1)\n * ```\n */\nexport class HDDescriptorProvider implements DescriptorProvider, ReceiveRotatorFactory {\n private constructor(\n private readonly identity: HDCapableIdentity,\n private readonly walletRepository: WalletRepository,\n ) {}\n\n /**\n * Construct an HDDescriptorProvider. No I/O is performed here;\n * persisted state is read lazily on the first call to\n * `getNextSigningDescriptor`. A descriptor-mismatch error surfaces on\n * first use rather than at boot.\n */\n static async create(\n identity: HDCapableIdentity,\n walletRepository: WalletRepository,\n ): Promise<HDDescriptorProvider> {\n return new HDDescriptorProvider(identity, walletRepository);\n }\n\n /**\n * Allocate the next descriptor and return it. The first call on a fresh\n * wallet returns descriptor at index 0; subsequent calls return 1, 2, 3,\n * ... in order. Each call is atomic with respect to other rotations on\n * the same repo: two concurrent callers can never observe the same\n * index.\n */\n async getNextSigningDescriptor(): Promise<string> {\n return this.mutate((settings) => {\n const next = settings.lastIndexUsed === undefined ? 0 : settings.lastIndexUsed + 1;\n settings.lastIndexUsed = next;\n return this.materializeDescriptorAt(next);\n });\n }\n\n /**\n * Re-derive the descriptor at the most recently allocated index\n * WITHOUT advancing — i.e. read the same descriptor\n * `getNextSigningDescriptor` last returned. Returns `undefined`\n * when no descriptor has ever been allocated on this repo.\n *\n * Used by the boot path to keep the wallet's display address\n * stable across restarts: when no tagged display contract exists\n * (e.g. a fresh wallet that hasn't rotated yet, or a wallet whose\n * baseline-only repo carries no rotation history), the boot should\n * re-derive the existing index rather than burn a new one.\n */\n async getCurrentSigningDescriptor(): Promise<string | undefined> {\n const state = await this.walletRepository.getWalletState();\n const settings = this.parseSettings(state ?? ({} as WalletState));\n if (settings.lastIndexUsed === undefined) return undefined;\n return this.materializeDescriptorAt(settings.lastIndexUsed);\n }\n\n /**\n * Monotonically advance the allocation watermark so the next\n * `getNextSigningDescriptor()` skips indices discovered by a restore\n * scan. Never rewinds: a lower or equal `index` is a no-op.\n *\n * An invalid `index` (non-integer / negative) is ignored (no-op):\n * persisting it would corrupt `lastIndexUsed` and make the next\n * `parseSettings()` throw, mirroring the validation parseSettings\n * already enforces.\n */\n async advanceLastIndexUsed(index: number): Promise<void> {\n if (!Number.isInteger(index) || index < 0) return;\n await this.mutate((settings) => {\n if (settings.lastIndexUsed === undefined || index > settings.lastIndexUsed) {\n settings.lastIndexUsed = index;\n }\n });\n }\n\n /**\n * Returns true when the given descriptor is derivable from this wallet's\n * seed. Delegates to the underlying identity, which handles both HD and\n * simple `tr(pubkey)` descriptors.\n */\n isOurs(descriptor: string): boolean {\n return this.identity.isOurs(descriptor);\n }\n\n /**\n * Signs each request with the key derived from its descriptor. Delegates\n * to the identity's signing primitives — the identity, not the provider,\n * holds the seed.\n */\n async signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]> {\n return this.identity.signWithDescriptor(requests);\n }\n\n /** Signs a message using the key derived from `descriptor`. */\n async signMessageWithDescriptor(\n descriptor: string,\n message: Uint8Array,\n signatureType: \"schnorr\" | \"ecdsa\" = \"schnorr\",\n ): Promise<Uint8Array> {\n return this.identity.signMessageWithDescriptor(descriptor, message, signatureType);\n }\n\n /**\n * HD providers participate in receive rotation. The default\n * factory boot (contract-repo lookup → allocate fresh descriptor)\n * is exactly what we want, so this just delegates to\n * {@link WalletReceiveRotator.defaultBoot}.\n */\n async createReceiveRotator(\n opts: ReceiveRotatorBootOpts,\n ): Promise<ReceiveRotatorBoot | undefined> {\n return WalletReceiveRotator.defaultBoot(this, opts);\n }\n\n // ── internals ────────────────────────────────────────────────────\n\n /**\n * Substitute the wildcard in the identity's account-descriptor template\n * with a concrete index, going through the descriptors-scure parser\n * rather than ad-hoc string substitution. The parser's `expand({ index })`\n * call validates that the input is a ranged template AND produces a\n * canonical materialized key expression at the given index.\n *\n * This is a pure read: it does NOT advance the allocation watermark.\n * Used by restore's gap-scan to peek descriptors at arbitrary indices\n * without side-effects.\n */\n materializeDescriptorAt(index: number): string {\n const descriptor = this.identity.descriptor;\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n const expansion = expand({ descriptor, network, index });\n const keyInfo = expansion.expansionMap?.[\"@0\"];\n if (!keyInfo?.keyExpression) {\n throw new Error(\n `HDDescriptorProvider: cannot materialize descriptor at index ${index}`,\n );\n }\n return `tr(${keyInfo.keyExpression})`;\n }\n\n /**\n * Run the read-modify-write of HD settings inside the shared per-repo\n * wallet-state mutex. The closure receives a freshly-validated settings\n * snapshot, mutates it, and returns whatever value the caller wants to\n * surface; the mutated settings are then persisted as part of the same\n * atomic update.\n *\n * Doing the read inside the lock is what prevents two providers (or two\n * concurrent callers on the same provider) from racing on a stale index.\n */\n private async mutate<T>(fn: (settings: HDWalletSettings) => T): Promise<T> {\n let result!: T;\n await updateWalletState(this.walletRepository, (state) => {\n const settings = this.parseSettings(state);\n result = fn(settings);\n return {\n ...state,\n settings: {\n ...(state.settings ?? {}),\n [HD_SETTINGS_KEY]: settings,\n },\n };\n });\n return result;\n }\n\n /**\n * Validate the persisted HD settings (or initialize a fresh record when\n * absent) and return a clone safe for the caller to mutate.\n *\n * The cast to `HDWalletSettings` trusts storage; a corrupted or\n * partially-migrated repo could otherwise produce `NaN` descriptors.\n * Fail loud rather than silently derive garbage.\n */\n private parseSettings(state: WalletState): HDWalletSettings {\n const stored = state.settings?.[HD_SETTINGS_KEY] as HDWalletSettings | undefined;\n const expected = this.identity.descriptor;\n if (!stored) {\n return { descriptor: expected };\n }\n if (stored.descriptor !== expected) {\n throw new Error(\n `HD descriptor mismatch: stored \"${stored.descriptor}\", expected \"${expected}\". ` +\n `Refusing to reuse HD state from a different identity.`,\n );\n }\n if (\n stored.lastIndexUsed !== undefined &&\n (typeof stored.lastIndexUsed !== \"number\" ||\n !Number.isInteger(stored.lastIndexUsed) ||\n stored.lastIndexUsed < 0)\n ) {\n throw new Error(\n `Corrupt HD settings: lastIndexUsed is not a non-negative integer (got ${String(stored.lastIndexUsed)}).`,\n );\n }\n // Shallow clone so the closure may mutate without aliasing the repo's copy.\n return { ...stored };\n }\n}\n","import { equalBytes } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\n\nimport { deriveDescriptorLeafPubKey } from \"../identity/descriptor\";\nimport { DescriptorProvider } from \"../identity/descriptorProvider\";\nimport { isHDCapableIdentity } from \"../identity/hdCapableIdentity\";\nimport { ContractRepository } from \"../repositories/contractRepository\";\nimport { WalletRepository } from \"../repositories/walletRepository\";\nimport { IContractManager } from \"../contracts/contractManager\";\nimport { WALLET_RECEIVE_SOURCE } from \"../contracts/metadata\";\nimport { DefaultVtxo } from \"../script/default\";\nimport { DelegateVtxo } from \"../script/delegate\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport { HDDescriptorProvider } from \"./hdDescriptorProvider\";\nimport type { WalletConfig, WalletMode } from \".\";\n\n/**\n * Inputs the wallet hands to a {@link ReceiveRotatorFactory} when\n * asking it to construct the rotator at boot. The factory uses these\n * to look up the wallet's current display contract (or allocate a\n * fresh receive descriptor). Note: no `offchainTapscript` here — the\n * factory's job is allocation, not script construction. The wallet's\n * orchestrator (`WalletReceiveRotator.resolveBoot`) handles the\n * tapscript rebuild on top of the factory's result.\n */\nexport interface ReceiveRotatorBootOpts {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n serverPubKey: Uint8Array;\n /**\n * Expected contract family (\"default\" or \"delegate\"). When provided,\n * boot will only consider contracts of this type when looking up the\n * wallet's current display contract, preventing a default wallet from\n * accidentally picking up a delegate contract or vice versa.\n */\n expectedContractType?: \"default\" | \"delegate\";\n /**\n * Logger to receive rotation-failure + backoff diagnostics. Defaults\n * to `console` when omitted. Any object implementing\n * {@link Logger.error} works (winston, pino, Sentry breadcrumbs,\n * the runtime's own logger).\n */\n logger?: Logger;\n}\n\n/**\n * Output of {@link ReceiveRotatorFactory.createReceiveRotator}: the\n * constructed rotator paired with the receive pubkey it resolved at\n * boot (either the existing tagged display contract's pubkey, or a\n * freshly allocated one).\n */\nexport interface ReceiveRotatorBoot {\n rotator: WalletReceiveRotator;\n receivePubkey: Uint8Array;\n}\n\n/**\n * Result returned by {@link WalletReceiveRotator.resolveBoot} to the\n * wallet: the rotator plus the offchain tapscript the wallet should\n * actually use (rebuilt to the resolved boot pubkey when it differs\n * from the identity's static pubkey), plus the {@link DescriptorProvider}\n * the rotator was built around. The wallet retains the provider so\n * spending paths can route per-input signing through\n * {@link DescriptorProvider.signWithDescriptor} instead of the\n * identity's index-0 key.\n */\nexport interface ReceiveRotatorBootResult {\n rotator: WalletReceiveRotator;\n offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;\n provider: DescriptorProvider;\n}\n\n/**\n * Opt-in extension to {@link DescriptorProvider} for providers that\n * drive HD receive rotation. Implemented by {@link HDDescriptorProvider}\n * out of the box; custom providers (HSMs, external signers, …) can also\n * implement it when they want to participate.\n *\n * Kept out of the core `DescriptorProvider` interface so providers that\n * only do allocation + signing don't have to know about the wallet's\n * receive lifecycle. The wallet detects support via\n * {@link hasReceiveRotatorFactory} (a duck-typed `instanceof`-style\n * check) and falls back to {@link WalletReceiveRotator.defaultBoot}\n * when the provider doesn't implement the extension.\n */\nexport interface ReceiveRotatorFactory {\n createReceiveRotator(opts: ReceiveRotatorBootOpts): Promise<ReceiveRotatorBoot | undefined>;\n}\n\n/** Type guard: does this provider implement {@link ReceiveRotatorFactory}? */\nexport function hasReceiveRotatorFactory(\n provider: DescriptorProvider,\n): provider is DescriptorProvider & ReceiveRotatorFactory {\n return typeof (provider as Partial<ReceiveRotatorFactory>).createReceiveRotator === \"function\";\n}\n\n/**\n * Type guard: does this provider expose a `getCurrentSigningDescriptor`\n * peek method? HD-style providers do (`HDDescriptorProvider`); static\n * providers don't because the concept of a \"current index\" is\n * meaningless for them.\n */\ninterface PeekableDescriptorProvider {\n getCurrentSigningDescriptor(): Promise<string | undefined>;\n}\nfunction hasPeekableDescriptor(\n provider: DescriptorProvider,\n): provider is DescriptorProvider & PeekableDescriptorProvider {\n return (\n typeof (provider as Partial<PeekableDescriptorProvider>).getCurrentSigningDescriptor ===\n \"function\"\n );\n}\n\n// Re-exported from the contracts layer (src/contracts/metadata.ts) for\n// backward compatibility of any existing import paths that reference this\n// module. The source-of-truth declaration now lives in `contracts/metadata`\n// so contract handlers can import it without creating a contracts→wallet\n// dependency cycle.\nexport { WALLET_RECEIVE_SOURCE } from \"../contracts/metadata\";\n\n/**\n * Parse the trailing HD child index from a materialized signing\n * descriptor (`tr(...xpub.../0/<index>)`). Returns 0 when the\n * descriptor is absent or carries no parseable child index — restore\n * registers the index-0 baseline untagged, so a missing descriptor\n * legitimately maps to 0.\n */\nexport function signingDescriptorIndex(descriptor: unknown): number {\n if (typeof descriptor !== \"string\") return 0;\n // captures the trailing child index N from \"...xpub.../0/N)\"\n const m = descriptor.match(/\\/(\\d+)\\)\\s*$/);\n if (!m) return 0;\n const n = Number(m[1]);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n}\n\n/**\n * Thrown when a descriptor expected to be rangeable (have a wildcard\n * leaf) cannot produce a leaf pubkey. Surfaces from the rotator's\n * `defaultBoot` path so `resolveBoot` can distinguish a legitimate\n * incompatibility (silent fallback under `walletMode: 'auto'`) from\n * any other runtime failure.\n */\nexport class NonRangeableDescriptorError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"NonRangeableDescriptorError\";\n }\n}\n\n/**\n * Minimal logging surface the rotator needs. `console` satisfies it\n * out of the box; SDK consumers can pass a structured logger\n * (winston / pino / Sentry adapter) via {@link ReceiveRotatorBootOpts}\n * to capture rotation failures + backoff diagnostics through their\n * own pipeline.\n */\nexport interface Logger {\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Cap on the exponential backoff applied to repeated rotation\n * failures. After this delay, every fresh `vtxo_received` event\n * re-attempts a rotation at this rate until one succeeds (which\n * resets the counter) or the wallet is disposed.\n */\nexport const ROTATION_MAX_BACKOFF_MS = 60_000;\n\n/**\n * Narrow surface the rotator needs from the wallet at runtime: the\n * mutable display tapscript, the display contract's script hex, the\n * contract manager (for subscribing + registering rotated contracts),\n * and the display address (for the contract's `address` field).\n *\n * Kept as an interface so the rotator module avoids a circular\n * dependency on `wallet.ts`. `Wallet` implements this surface\n * structurally — no `implements` clause is required.\n */\nexport interface RotatableWallet {\n readonly defaultContractScript: string;\n readonly network: { hrp: string };\n readonly arkServerPublicKey: Uint8Array;\n readonly offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;\n /**\n * @internal Sole sanctioned write path for `offchainTapscript`\n * after construction. The rotator calls this once per rotation\n * after persisting the new display contract.\n */\n setOffchainTapscriptForRotation(tapscript: DefaultVtxo.Script | DelegateVtxo.Script): void;\n getContractManager(): Promise<IContractManager>;\n getAddress(): Promise<string>;\n}\n\n/**\n * Owns the wallet's HD receive-rotation lifecycle.\n *\n * The rotator is constructed only when the wallet's `walletMode`\n * resolves to a {@link DescriptorProvider}; static wallets and\n * non-HD-capable wallets under `'auto'` never see one.\n *\n * Lifecycle:\n * 1. `resolveBoot()` — pre-Wallet-construction. Resolves the provider\n * from `walletMode`, then either reuses the existing display\n * contract's pubkey (if any) or allocates the first descriptor.\n * Returns the rotator paired with the boot pubkey.\n * 2. `install(wallet)` — post-`getVtxoManager()`. Subscribes to\n * `vtxo_received` on the contract manager and routes matching events\n * through the rotation chain.\n * 3. `dispose()` — tears down the subscription and drains any in-flight\n * rotation so the contract manager can be disposed cleanly.\n *\n * This class follows the dotnet-sdk's split of responsibilities: the\n * provider is a pure rotating allocator; \"what address am I currently\n * bound to?\" is answered by querying the contract repository, not by\n * asking the provider.\n */\nexport class WalletReceiveRotator {\n private unsubscribe?: () => void;\n private chain: Promise<void> = Promise.resolve();\n\n /**\n * Script of the most-recent tagged display contract — populated\n * either from the boot-time repo lookup or from the previous\n * `rotate()` call within this session. The next `rotate()` marks\n * this contract `inactive` once the new tagged contract is in\n * place. `undefined` means the wallet's current display is the\n * untagged index-0 baseline (no rotation has happened yet on this\n * repo), and the baseline must NOT be deactivated.\n */\n private currentTaggedScript: string | undefined;\n\n /**\n * Consecutive rotation failures since the last successful rotate.\n * Drives an exponential backoff (capped at\n * {@link ROTATION_MAX_BACKOFF_MS}) so a broken provider can't make\n * the rotator hammer `getNextSigningDescriptor` + `createContract`\n * on every inbound VTXO. Reset to zero on a successful rotate.\n */\n private consecutiveFailures = 0;\n /**\n * Unix-ms timestamp before which incoming `vtxo_received` events\n * skip the rotation attempt entirely. Zero means \"no backoff\n * active\" — the next event can rotate immediately.\n */\n private nextRotationAllowedAt = 0;\n\n private readonly logger: Logger;\n\n private constructor(\n private readonly provider: DescriptorProvider,\n priorTaggedScript: string | undefined,\n logger?: Logger,\n ) {\n this.currentTaggedScript = priorTaggedScript;\n this.logger = logger ?? console;\n }\n\n /**\n * Phase 1 — pre-Wallet-construction. Resolves `walletMode` to a\n * {@link DescriptorProvider}, then asks that provider to construct\n * the rotator (delegated through\n * {@link DescriptorProvider.createReceiveRotator}, which falls back\n * to {@link defaultBoot} when the provider doesn't override it).\n *\n * Returns the rotator paired with the offchain tapscript the wallet\n * should actually install (rebuilt to the resolved receive pubkey\n * when it differs from the identity's static pubkey), or\n * `undefined` when the wallet should stay on the static path.\n *\n * Errors during pubkey resolution propagate when:\n * - `walletMode === 'hd'` (caller asked for HD; loud failure expected).\n * - `walletMode` is a {@link DescriptorProvider} (caller supplied an\n * explicit allocator; silently degrading would hide misconfig).\n *\n * Errors are silently swallowed (returning `undefined`) only under\n * `walletMode: 'auto'` with the built-in HD provider, to preserve\n * backwards compatibility with wallets whose identity descriptor\n * isn't actually rangeable.\n */\n static async resolveBoot(\n config: WalletConfig,\n setup: ReceiveRotatorBootOpts & {\n offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;\n },\n ): Promise<ReceiveRotatorBootResult | undefined> {\n const provider = await resolveDescriptorProvider(config, setup.walletRepository);\n if (!provider) return undefined;\n\n const allowSilentFallback = (config.walletMode ?? \"auto\") === \"auto\";\n const expectedContractType: \"default\" | \"delegate\" =\n setup.offchainTapscript instanceof DelegateVtxo.Script ? \"delegate\" : \"default\";\n const factoryOpts: ReceiveRotatorBootOpts = {\n walletRepository: setup.walletRepository,\n contractRepository: setup.contractRepository,\n serverPubKey: setup.serverPubKey,\n expectedContractType,\n };\n\n let boot: ReceiveRotatorBoot | undefined;\n try {\n boot = hasReceiveRotatorFactory(provider)\n ? await provider.createReceiveRotator(factoryOpts)\n : await WalletReceiveRotator.defaultBoot(provider, factoryOpts);\n } catch (e) {\n // Only swallow non-rangeable-descriptor errors, and only\n // under `walletMode: 'auto'`. Explicit HD/`DescriptorProvider`\n // callers always see the failure.\n if (allowSilentFallback && e instanceof NonRangeableDescriptorError) {\n return undefined;\n }\n throw e;\n }\n if (!boot) return undefined;\n\n // Rebuild the offchain tapscript with the resolved receive\n // pubkey. Skipping the rebuild when pubkeys already match keeps\n // the tapscript instance stable for static / first-boot paths\n // (no allocation churn, no observable change for callers\n // that retain the reference across `Wallet.create`).\n const offchainTapscript = equalBytes(\n boot.receivePubkey,\n setup.offchainTapscript.options.pubKey,\n )\n ? setup.offchainTapscript\n : rebuildTapscript(setup.offchainTapscript, boot.receivePubkey);\n\n return { rotator: boot.rotator, offchainTapscript, provider };\n }\n\n /**\n * Default factory-shaped boot any\n * {@link ReceiveRotatorFactory.createReceiveRotator} implementation\n * can delegate to. Pulls the wallet's current display contract from\n * the contract repository (or allocates a fresh receive descriptor\n * via the provider when no tagged display contract exists), and\n * returns the rotator paired with the resolved receive pubkey.\n *\n * Used internally by `resolveBoot` when the provider doesn't\n * implement {@link ReceiveRotatorFactory}. Exported so providers\n * that *do* override can still invoke the default work for the\n * parts of the boot path they don't want to customise. Tapscript\n * construction is intentionally NOT in here — that's the\n * orchestrator's job.\n */\n static async defaultBoot(\n provider: DescriptorProvider,\n opts: ReceiveRotatorBootOpts,\n ): Promise<ReceiveRotatorBoot> {\n const existing = await pickActiveReceive(\n opts.contractRepository,\n opts.serverPubKey,\n opts.expectedContractType,\n );\n if (existing) {\n return {\n rotator: new WalletReceiveRotator(provider, existing.script, opts.logger),\n receivePubkey: existing.pubKey,\n };\n }\n\n // No tagged display contract on this repo. Avoid burning a\n // fresh HD index per restart: re-derive the descriptor at the\n // most recently allocated index when the provider supports it\n // (HD-style allocators do; static / one-shot providers don't\n // and fall through to a regular allocation, which is a no-op\n // for them anyway).\n let descriptor: string | undefined;\n if (hasPeekableDescriptor(provider)) {\n descriptor = await provider.getCurrentSigningDescriptor();\n }\n descriptor ??= await provider.getNextSigningDescriptor();\n\n return {\n rotator: new WalletReceiveRotator(provider, undefined, opts.logger),\n receivePubkey: deriveLeafPubkey(descriptor),\n };\n }\n\n /**\n * Phase 2 — post-`getVtxoManager()`. Subscribe to `vtxo_received`\n * and trigger a rotation whenever the currently-active display\n * contract receives funds. Old display contracts remain `active`\n * in the repo so earlier shared addresses keep crediting this\n * wallet.\n */\n async install(wallet: RotatableWallet): Promise<void> {\n const manager = await wallet.getContractManager();\n this.unsubscribe = manager.onContractEvent((event) => {\n if (event.type !== \"vtxo_received\") return;\n if (event.contractScript !== wallet.defaultContractScript) return;\n // Serialise rotations: each `vtxo_received` event is its\n // own rotation trigger (BIP-44-style: one receive ⇒ one\n // fresh address), so two rapid events on the same script\n // are *expected* to burn two consecutive HD indices. The\n // chain here only prevents the rotate → rebuild →\n // createContract sequences from interleaving; it does not\n // — and intentionally does not — dedupe events on the same\n // script. `runRotateWithBackoff` owns the failure handling\n // — it logs, increments the consecutive-failure counter,\n // and gates future attempts behind exponential backoff so\n // a broken provider can't make the rotator hammer\n // `createContract` on every event.\n this.chain = this.chain\n .catch(() => undefined)\n .then(() => this.runRotateWithBackoff(wallet));\n });\n }\n\n /**\n * Run a single rotation attempt, applying exponential backoff on\n * failure. Public-shaped behavior:\n * - During a backoff window: log + skip (no `rotate()` call).\n * - On success: reset failure count and backoff.\n * - On failure: increment counter, schedule next attempt at\n * `min(2^consecutiveFailures * 1s, ROTATION_MAX_BACKOFF_MS)`.\n *\n * Errors are deliberately swallowed (logged, not rethrown) so the\n * surrounding `chain` Promise never settles to rejected — the next\n * `vtxo_received` event must still get a chance to run.\n */\n private async runRotateWithBackoff(wallet: RotatableWallet): Promise<void> {\n const now = Date.now();\n if (now < this.nextRotationAllowedAt) {\n this.logger.error(\"WalletReceiveRotator: skipping rotation (in backoff)\", {\n consecutiveFailures: this.consecutiveFailures,\n retryInMs: this.nextRotationAllowedAt - now,\n });\n return;\n }\n try {\n await this.rotate(wallet);\n this.consecutiveFailures = 0;\n this.nextRotationAllowedAt = 0;\n } catch (err) {\n this.consecutiveFailures += 1;\n // 2^1=2s, 2^2=4s, … capped at ROTATION_MAX_BACKOFF_MS (60s).\n // `Math.min` on the exponent prevents `2 ** 1024` overflow\n // for pathologically long failure streaks.\n const exponent = Math.min(this.consecutiveFailures, 16);\n const backoffMs = Math.min(2 ** exponent * 1_000, ROTATION_MAX_BACKOFF_MS);\n this.nextRotationAllowedAt = Date.now() + backoffMs;\n this.logger.error(\"WalletReceiveRotator: rotation failed\", err, {\n consecutiveFailures: this.consecutiveFailures,\n nextAttemptInMs: backoffMs,\n });\n }\n }\n\n /**\n * Wait for any in-flight rotation to complete. Useful in tests\n * that need to observe the post-rotation state after dispatching\n * a `vtxo_received` event synchronously; production code rarely\n * needs to call this directly.\n */\n async drain(): Promise<void> {\n await this.chain.catch(() => undefined);\n }\n\n /**\n * Tear down the subscription first so no late `vtxo_received` event\n * can queue work on a disposing wallet, then drain any in-flight\n * rotation so its `createContract` finishes before the contract\n * manager itself disposes.\n */\n async dispose(): Promise<void> {\n if (this.unsubscribe) {\n try {\n this.unsubscribe();\n } catch {\n // best-effort teardown\n } finally {\n this.unsubscribe = undefined;\n }\n }\n await this.chain.catch(() => undefined);\n }\n\n /**\n * Allocate the next descriptor, swap it into the wallet's active\n * offchain tapscript, register the new tagged contract, and retire\n * the previous tagged contract (if any) by setting its state to\n * `inactive`. The contract watcher keeps watching inactive\n * contracts until their VTXOs are spent, so funds in flight at the\n * old display address are not lost — only the address stops being\n * advertised.\n *\n * Contract type matches the wallet's tapscript shape: a default\n * wallet rotates to a new `default` contract, a delegate wallet to\n * a new `delegate` contract.\n *\n * The first rotation on a fresh wallet does NOT deactivate\n * anything: `currentTaggedScript` is `undefined` because the wallet\n * was displaying the untagged index-0 baseline, which must stay\n * active forever.\n */\n private async rotate(wallet: RotatableWallet): Promise<void> {\n // Build the new tapscript + derived strings entirely locally,\n // so the wallet's visible state (`offchainTapscript`,\n // `defaultContractScript`, `getAddress()`) doesn't change\n // until the contract registration has succeeded. If\n // `createContract` throws partway, the wallet is still\n // displaying the OLD (registered) address — no\n // unwatched-display-window.\n const descriptor = await this.provider.getNextSigningDescriptor();\n const pubKey = deriveLeafPubkey(descriptor);\n const newTapscript = rebuildTapscript(wallet.offchainTapscript, pubKey);\n const newScript = hex.encode(newTapscript.pkScript);\n const newAddress = newTapscript\n .address(wallet.network.hrp, wallet.arkServerPublicKey)\n .encode();\n\n const manager = await wallet.getContractManager();\n const csvTimelock = newTapscript.options.csvTimelock ?? DefaultVtxo.Script.DEFAULT_TIMELOCK;\n const csvTimelockStr = timelockToSequence(csvTimelock).toString();\n const serverPubKeyHex = hex.encode(newTapscript.options.serverPubKey);\n\n const baseParams = {\n script: newScript,\n address: newAddress,\n state: \"active\" as const,\n // Persist the materialized signing descriptor alongside the\n // source tag. The wallet's spending paths read this at sign\n // time to route inputs locked by a rotated pubkey through\n // `DescriptorProvider.signWithDescriptor` instead of the\n // identity's index-0 key. Without it, post-rotation sends\n // produce unsigned PSBTs that the server rejects with\n // `INVALID_PSBT_INPUT (5): missing tapscript spend sig`.\n metadata: {\n source: WALLET_RECEIVE_SOURCE,\n signingDescriptor: descriptor,\n },\n };\n\n if (newTapscript instanceof DelegateVtxo.Script) {\n await manager.createContract({\n ...baseParams,\n type: \"delegate\",\n params: {\n pubKey: hex.encode(pubKey),\n serverPubKey: serverPubKeyHex,\n delegatePubKey: hex.encode(newTapscript.options.delegatePubKey),\n csvTimelock: csvTimelockStr,\n },\n });\n } else {\n await manager.createContract({\n ...baseParams,\n type: \"default\",\n params: {\n pubKey: hex.encode(pubKey),\n serverPubKey: serverPubKeyHex,\n csvTimelock: csvTimelockStr,\n },\n });\n }\n\n // Persistence succeeded — commit the new tapscript to the\n // wallet's visible state. From this point onward\n // `wallet.defaultContractScript` and `getAddress()` reflect\n // the rotated identity. `setOffchainTapscriptForRotation` is\n // the only write path; the field is read-only otherwise.\n wallet.setOffchainTapscriptForRotation(newTapscript);\n\n // Retire the previous tagged contract (if any). The order\n // matters: deactivate FIRST, then update `currentTaggedScript`,\n // so that if `setContractState` throws the next rotation will\n // retry deactivating the same orphaned contract instead of\n // racing forward and orphaning the new one.\n const previousTagged = this.currentTaggedScript;\n if (previousTagged !== undefined && previousTagged !== newScript) {\n await manager.setContractState(previousTagged, \"inactive\");\n }\n this.currentTaggedScript = newScript;\n }\n}\n\n/**\n * Wrapper around {@link deriveDescriptorLeafPubKey} that re-throws as a\n * typed {@link NonRangeableDescriptorError} so callers (most importantly\n * `resolveBoot`'s silent-fallback path) can branch on the typed error\n * class instead of grepping `err.message`.\n */\nfunction deriveLeafPubkey(descriptor: string): Uint8Array {\n try {\n return deriveDescriptorLeafPubKey(descriptor);\n } catch (e) {\n throw new NonRangeableDescriptorError(\n \"Cannot derive leaf pubkey: descriptor is not a materialized, parsable tr(...) shape.\",\n { cause: e },\n );\n }\n}\n\n/**\n * Rebuild the given offchain tapscript with a different owner pubkey,\n * preserving its {@link DelegateVtxo.Script} vs {@link DefaultVtxo.Script}\n * shape and all other options.\n *\n * Exported because the wallet's boot path also needs to rebuild the\n * initial tapscript when the resolved boot pubkey differs from the\n * identity's default pubkey.\n */\nexport function rebuildTapscript(\n current: DefaultVtxo.Script | DelegateVtxo.Script,\n pubKey: Uint8Array,\n): DefaultVtxo.Script | DelegateVtxo.Script {\n if (current instanceof DelegateVtxo.Script) {\n return new DelegateVtxo.Script({ ...current.options, pubKey });\n }\n return new DefaultVtxo.Script({ ...current.options, pubKey });\n}\n\n/**\n * Look up the most-recently-created active tagged display contract that\n * this wallet itself generated. Returns the contract's pubkey + script,\n * or `undefined` when no such contract exists — the caller should treat\n * that as \"fresh wallet (or static-only history) on this repo\" and\n * allocate a new descriptor.\n *\n * Filters by `serverPubKey` so a contract repo seeded against a different\n * server doesn't accidentally resurrect an unrelated pubkey, and by the\n * `metadata.source` sentinel so untagged baseline contracts (and\n * contracts created by other code paths — legacy timelock registrations,\n * external integrations) are not mistaken for the wallet's display\n * address.\n *\n * When `expectedType` is provided, only contracts of that type are considered,\n * preventing a \"default\" wallet from accidentally picking up a \"delegate\" contract\n * or vice versa.\n */\nasync function pickActiveReceive(\n contractRepository: ContractRepository,\n serverPubKey: Uint8Array,\n expectedType?: \"default\" | \"delegate\",\n): Promise<{ pubKey: Uint8Array; script: string } | undefined> {\n // Both `default` and `delegate` contract types can be the wallet's\n // display address (delegate wallets use the delegate variant). The\n // `metadata.source` tag is the discriminator that says \"this is the\n // one I generated for myself.\"\n const candidates = await contractRepository.getContracts({\n type: expectedType ? [expectedType] : [\"default\", \"delegate\"],\n state: \"active\",\n });\n const serverPubKeyHex = hex.encode(serverPubKey);\n const matching = candidates\n .filter(\n (c) =>\n c.params.serverPubKey === serverPubKeyHex &&\n c.metadata?.source === WALLET_RECEIVE_SOURCE,\n )\n .sort((a, b) => {\n if (b.createdAt !== a.createdAt) return b.createdAt - a.createdAt;\n return (\n signingDescriptorIndex(b.metadata?.signingDescriptor) -\n signingDescriptorIndex(a.metadata?.signingDescriptor)\n );\n });\n const newest = matching[0];\n if (!newest?.params.pubKey) return undefined;\n try {\n return {\n pubKey: hex.decode(newest.params.pubKey),\n script: newest.script,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve the polymorphic `walletMode` config field into a concrete\n * {@link DescriptorProvider} (or `undefined` for the static path).\n *\n * - `'auto'` *(default)*: **short-term**, behaves like `'static'` — no\n * HD rotation. See the `TODO` below for the criteria to flip this\n * back to the identity-probing behaviour.\n * - `'static'`: returns `undefined`.\n * - A {@link DescriptorProvider} instance: returns it as-is.\n * - `'hd'`: builds the built-in HD provider from the identity. Throws\n * if the identity isn't HD-capable or the descriptor isn't rangeable —\n * no silent fallback.\n */\nasync function resolveDescriptorProvider(\n config: WalletConfig,\n walletRepository: WalletRepository,\n): Promise<DescriptorProvider | undefined> {\n const mode: WalletMode = config.walletMode ?? \"auto\";\n\n // TODO(hd-maturation): TEMPORARY — collapse `'auto'` into `'static'`\n // until the HD receive-rotation pipeline has soaked in the field.\n // Flip `'auto'` back to its identity-probing behaviour once:\n // 1. At least one consumer (btcpay-arkade, arkade-os/wallet,\n // Fulmine) has been running with `walletMode: 'hd'` against\n // mainnet for ≥ 1 month with no rotation-induced fund-loss\n // or address-drift reports.\n // 2. The test `default ('auto') currently behaves like 'static'`\n // in `test/walletHdRotation.test.ts` is flipped in the same\n // commit (it's the explicit gate — flipping the default\n // MUST flip the test).\n // 3. The `WalletMode` docstring in `src/wallet/index.ts` is\n // updated to drop the \"behaves like 'static' for now\" notice.\n if (mode === \"static\" || mode === \"auto\") return undefined;\n\n if (typeof mode !== \"string\") {\n // Caller supplied a DescriptorProvider directly.\n return mode;\n }\n\n // mode === 'hd'\n if (!isHDCapableIdentity(config.identity)) {\n throw new Error(\n \"walletMode 'hd' requires an HD-capable identity \" +\n \"(SeedIdentity / MnemonicIdentity with a rangeable BIP-32 \" +\n \"descriptor) or an explicit DescriptorProvider.\",\n );\n }\n try {\n return await HDDescriptorProvider.create(config.identity, walletRepository);\n } catch (e) {\n throw new Error(\n \"walletMode 'hd' failed to initialize: \" + (e instanceof Error ? e.message : String(e)),\n { cause: e },\n );\n }\n}\n","/**\n * Thrown when a rotated contract (default or delegate) is missing the\n * metadata.signingDescriptor required to route it to a descriptor-aware\n * signer.\n */\nexport class MissingSigningDescriptorError extends Error {\n readonly name = \"MissingSigningDescriptorError\";\n\n constructor(\n readonly contractScript: string,\n readonly contractType: \"default\" | \"delegate\",\n ) {\n super(\n `Cannot sign input for ${contractType} contract ${contractScript}: ` +\n `metadata.signingDescriptor is missing. This wallet was rotated ` +\n `on an earlier build that did not persist signing descriptors. ` +\n `Manually set metadata.signingDescriptor on the contract record, ` +\n `or restore from a pre-rotation snapshot.`,\n );\n }\n}\n\n/**\n * Thrown when an input needs descriptor-aware signing but no\n * DescriptorProvider was wired into the wallet.\n */\nexport class DescriptorSigningProviderMissingError extends Error {\n readonly name = \"DescriptorSigningProviderMissingError\";\n\n constructor() {\n super(\"Descriptor signing requested but no DescriptorProvider was wired into this wallet\");\n }\n}\n","import { hex } from \"@scure/base\";\nimport { Transaction } from \"@scure/btc-signer\";\nimport { Identity } from \"../identity\";\nimport { ContractRepository } from \"../repositories/contractRepository\";\nimport { DescriptorProvider } from \"../identity/descriptorProvider\";\nimport {\n DescriptorSigningProviderMissingError,\n MissingSigningDescriptorError,\n} from \"./signingErrors\";\n\nexport interface InputSigningJob {\n /** Index in the source transaction. */\n index: number;\n /**\n * Script used to identify the owning contract. For normal inputs this\n * is the input's witnessUtxo script. For arkTx inputs this is the\n * source VTXO script, because the witnessUtxo carries the checkpoint\n * script instead.\n */\n lookupScript: Uint8Array;\n}\n\nexport interface InputSignerRouterDeps {\n identity: Identity;\n contractRepository: ContractRepository;\n descriptorProvider?: DescriptorProvider;\n boardingPkScript: Uint8Array;\n}\n\nconst DESCRIPTOR_CAPABLE_CONTRACT_TYPES = new Set([\"default\", \"delegate\"]);\n\n/**\n * Routes PSBT inputs to the correct signer based on the owning contract.\n * Inputs whose script matches a `default`/`delegate` contract with a\n * non-baseline owner are sent to {@link DescriptorProvider}; everything\n * else (baseline-owned contracts, non-default/non-delegate contracts,\n * and the boarding script) is sent to {@link Identity}. Inputs with no\n * matching contract and no boarding match are silently skipped, matching\n * how the wallet historically handled cosigner/connector inputs.\n */\nexport class InputSignerRouter {\n constructor(private readonly deps: InputSignerRouterDeps) {}\n\n async sign(tx: Transaction, jobs: InputSigningJob[]): Promise<Transaction> {\n if (jobs.length === 0) return tx;\n\n const distinctScripts = Array.from(new Set(jobs.map((j) => hex.encode(j.lookupScript))));\n const contracts = await this.deps.contractRepository.getContracts({\n script: distinctScripts,\n });\n // Repo may yield duplicates if seeded oddly; keep the first one\n // for each script to match the wallet's historical behaviour.\n const scriptToContract = new Map<string, (typeof contracts)[number]>();\n for (const contract of contracts) {\n if (!scriptToContract.has(contract.script)) {\n scriptToContract.set(contract.script, contract);\n }\n }\n\n const baselinePubKeyHex = hex.encode(await this.deps.identity.xOnlyPublicKey());\n const boardingScriptHex = hex.encode(this.deps.boardingPkScript);\n\n const identityIndexes: number[] = [];\n const descriptorGroups = new Map<string, number[]>();\n\n for (const job of jobs) {\n const scriptHex = hex.encode(job.lookupScript);\n const contract = scriptToContract.get(scriptHex);\n\n if (!contract) {\n if (scriptHex === boardingScriptHex) {\n identityIndexes.push(job.index);\n }\n continue;\n }\n\n if (!DESCRIPTOR_CAPABLE_CONTRACT_TYPES.has(contract.type)) {\n identityIndexes.push(job.index);\n continue;\n }\n\n // `baselinePubKeyHex` is freshly produced by `hex.encode`,\n // so it is already lowercase. `contract.params.pubKey` is\n // persisted data: a migration or custom repository adapter\n // could legitimately store it uppercase, so canonicalize\n // before comparing to match the legacy router behaviour.\n const ownerPubKeyHex = contract.params.pubKey?.toLowerCase();\n if (ownerPubKeyHex && ownerPubKeyHex === baselinePubKeyHex) {\n identityIndexes.push(job.index);\n continue;\n }\n\n const descriptor = contract.metadata?.signingDescriptor;\n if (typeof descriptor !== \"string\" || descriptor.length === 0) {\n throw new MissingSigningDescriptorError(\n contract.script,\n contract.type as \"default\" | \"delegate\",\n );\n }\n\n const bucket = descriptorGroups.get(descriptor);\n if (bucket) {\n bucket.push(job.index);\n } else {\n descriptorGroups.set(descriptor, [job.index]);\n }\n }\n\n let signed = tx;\n if (identityIndexes.length > 0) {\n signed = await this.deps.identity.sign(signed, identityIndexes);\n }\n\n if (descriptorGroups.size > 0) {\n if (!this.deps.descriptorProvider) {\n throw new DescriptorSigningProviderMissingError();\n }\n\n const sortedDescriptors = Array.from(descriptorGroups.keys()).sort();\n for (const descriptor of sortedDescriptors) {\n const indexes = descriptorGroups.get(descriptor)!;\n const [next] = await this.deps.descriptorProvider.signWithDescriptor([\n {\n tx: signed,\n descriptor,\n inputIndexes: indexes,\n },\n ]);\n signed = next;\n }\n }\n\n return signed;\n }\n}\n","import { base64, hex } from \"@scure/base\";\nimport { tapLeafHash } from \"@scure/btc-signer/payment.js\";\nimport { Address, OutScript, SigHash, Transaction } from \"@scure/btc-signer\";\nimport { TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport { Bytes, equalBytes, sha256 } from \"@scure/btc-signer/utils.js\";\nimport { ArkAddress } from \"../script/address\";\nimport { DefaultVtxo } from \"../script/default\";\nimport { getNetwork, Network, NetworkName } from \"../networks\";\nimport { ESPLORA_URL, EsploraProvider, OnchainProvider } from \"../providers/onchain\";\nimport {\n ArkProvider,\n BatchFinalizationEvent,\n BatchStartedEvent,\n RestArkProvider,\n SettlementEvent,\n SignedIntent,\n TreeNoncesEvent,\n TreeSigningStartedEvent,\n} from \"../providers/ark\";\nimport { SignerSession } from \"../tree/signingSession\";\nimport { buildForfeitTx } from \"../forfeit\";\nimport { validateConnectorsTxGraph, validateVtxoTxGraph } from \"../tree/validation\";\nimport { validateBatchRecipients } from \"./validation\";\nimport { Identity, ReadonlyIdentity } from \"../identity\";\nimport {\n ArkTransaction,\n Asset,\n Coin,\n DEFAULT_ARKADE_SERVER_URL,\n ExtendedCoin,\n ExtendedVirtualCoin,\n GetVtxosFilter,\n IAssetManager,\n IReadonlyAssetManager,\n IReadonlyWallet,\n isExpired,\n isRecoverable,\n isSpendable,\n isSubdust,\n IWallet,\n ReadonlyWalletConfig,\n Recipient,\n SendBitcoinParams,\n SettleParams,\n TxType,\n VirtualCoin,\n WalletBalance,\n WalletConfig,\n} from \".\";\nimport { createAssetPacket, selectCoinsWithAsset, selectedCoinsToAssetInputs } from \"./asset\";\nimport { VtxoScript } from \"../script/base\";\nimport { CSVMultisigTapscript, RelativeTimelock } from \"../script/tapscript\";\nimport { buildOffchainTx, hasBoardingTxExpired, isValidArkAddress } from \"../utils/arkTransaction\";\nimport {\n DEFAULT_RENEWAL_CONFIG,\n DEFAULT_SETTLEMENT_CONFIG,\n SettlementConfig,\n VtxoManager,\n} from \"./vtxo-manager\";\nimport { ArkNote } from \"../arknote\";\nimport { Intent } from \"../intent\";\nimport { IndexerProvider, RestIndexerProvider } from \"../providers/indexer\";\nimport { TxTree } from \"../tree/txTree\";\nimport { WalletRepository } from \"../repositories/walletRepository\";\nimport { ContractRepository } from \"../repositories/contractRepository\";\nimport { extendCoin, validateRecipients } from \"./utils\";\nimport { ArkError } from \"../providers/errors\";\nimport { Batch } from \"./batch\";\nimport { Estimator } from \"../arkfee\";\nimport { DelegatorProvider } from \"../providers/delegator\";\nimport { buildTransactionHistory } from \"../utils/transactionHistory\";\nimport { AssetManager, ReadonlyAssetManager } from \"./asset-manager\";\nimport { Extension } from \"../extension\";\nimport { DelegateVtxo } from \"../script/delegate\";\nimport { DelegatorManagerImpl, findDestinationOutputIndex, IDelegatorManager } from \"./delegator\";\nimport { IndexedDBContractRepository, IndexedDBWalletRepository } from \"../repositories\";\nimport { ContractManager } from \"../contracts/contractManager\";\nimport { contractHandlers } from \"../contracts/handlers\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport { clearSyncCursor, updateWalletState } from \"../utils/syncCursors\";\nimport { validateVtxosForScript, saveVtxosForContract } from \"../contracts/vtxoOwnership\";\nimport { WalletReceiveRotator } from \"./walletReceiveRotator\";\nimport { HDDescriptorProvider } from \"./hdDescriptorProvider\";\nimport { DescriptorProvider } from \"../identity/descriptorProvider\";\nimport { DiscoveryDeps } from \"../contracts/types\";\nimport { InputSignerRouter, InputSigningJob } from \"./inputSignerRouter\";\nimport {\n DescriptorSigningProviderMissingError,\n MissingSigningDescriptorError,\n} from \"./signingErrors\";\n\nexport const getArkadeServerUrl = ({ arkServerUrl }: { arkServerUrl?: string }) =>\n arkServerUrl || DEFAULT_ARKADE_SERVER_URL;\n\n// Build per-input jobs for an intent proof. Index 0 of the proof is a\n// synthetic BIP-322 toSpend reference whose witnessUtxo.script mirrors\n// coin[0]'s pkScript, so we map it to the same source contract as\n// coin[0]; coins 0..N-1 then map to proof inputs 1..N.\nfunction intentProofJobs(coins: ReadonlyArray<{ tapTree: Bytes }>): InputSigningJob[] {\n if (coins.length === 0) return [];\n const coinJobs = coins.map((coin, i) => ({\n index: i + 1,\n lookupScript: VtxoScript.decode(coin.tapTree).pkScript,\n }));\n return [{ index: 0, lookupScript: coinJobs[0].lookupScript }, ...coinJobs];\n}\n\n// Built-in ArkProvider implementations (Rest/Expo) expose `serverUrl`,\n// but the interface itself does not declare a URL accessor — so this is a\n// structural read that returns undefined for custom implementations.\nfunction extractArkProviderUrl(provider: ArkProvider): string | undefined {\n const serverUrl = (provider as { serverUrl?: unknown }).serverUrl;\n return typeof serverUrl === \"string\" && serverUrl.length > 0 ? serverUrl : undefined;\n}\n\n// Historical unilateral exit delay for mainnet (~7 days in seconds).\n// Kept so existing wallets can still discover and spend VTXOs sent to the\n// legacy address after arkd starts advertising a different delay.\nconst MAINNET_UNILATERAL_EXIT_DELAY = 605184n;\n\nfunction delayToTimelock(delay: bigint): RelativeTimelock {\n return {\n value: delay,\n type: delay < 512n ? \"blocks\" : \"seconds\",\n };\n}\n\nfunction dedupeTimelocks(timelocks: RelativeTimelock[]): RelativeTimelock[] {\n const seen = new Set<string>();\n const deduped: RelativeTimelock[] = [];\n\n for (const timelock of timelocks) {\n const sequence = timelockToSequence(timelock).toString();\n if (seen.has(sequence)) continue;\n seen.add(sequence);\n deduped.push(timelock);\n }\n\n return deduped;\n}\n\nexport type IncomingFunds =\n | {\n type: \"utxo\";\n coins: Coin[];\n }\n | {\n type: \"vtxo\";\n newVtxos: ExtendedVirtualCoin[];\n spentVtxos: ExtendedVirtualCoin[];\n };\n\n/**\n * Type guard interface for identities that support conversion to readonly.\n */\ninterface HasToReadonly {\n toReadonly(): Promise<ReadonlyIdentity>;\n}\n\n/**\n * Type guard function to check if an identity has a toReadonly method.\n */\nfunction hasToReadonly(identity: unknown): identity is HasToReadonly {\n return (\n typeof identity === \"object\" &&\n identity !== null &&\n \"toReadonly\" in identity &&\n typeof (identity as any).toReadonly === \"function\"\n );\n}\n\nexport { DescriptorSigningProviderMissingError, MissingSigningDescriptorError };\n\nexport class ReadonlyWallet implements IReadonlyWallet {\n private _contractManager?: ContractManager;\n private _contractManagerInitializing?: Promise<ContractManager>;\n protected readonly watcherConfig?: ReadonlyWalletConfig[\"watcherConfig\"];\n private readonly _assetManager: IReadonlyAssetManager;\n private _syncVtxosInflight?: Promise<void>;\n readonly walletContractTimelocks: RelativeTimelock[];\n // Outpoints (\"txid:vout\") committed to an in-flight settle/send. Filtered\n // from getVtxos() so concurrent callers (UI, VtxoManager auto-renewal,\n // another send/settle racing the _txLock) can't reselect coins that are\n // already on their way out. The set is in-memory only: a process crash\n // clears it, and a stale entry only hides a VTXO (never spends one).\n protected _pendingSpendOutpoints = new Set<string>();\n\n get assetManager(): IReadonlyAssetManager {\n return this._assetManager;\n }\n\n /**\n * Backing field for the active receive tapscript. Read via the\n * public `offchainTapscript` getter; written only by\n * {@link Wallet.setOffchainTapscriptForRotation}, which\n * {@link WalletReceiveRotator.rotate} is the sole intended caller of.\n */\n protected _offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;\n\n protected constructor(\n readonly identity: ReadonlyIdentity,\n readonly network: Network,\n readonly onchainProvider: OnchainProvider,\n readonly indexerProvider: IndexerProvider,\n readonly arkServerPublicKey: Bytes,\n offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script,\n readonly boardingTapscript: DefaultVtxo.Script,\n readonly dustAmount: bigint,\n public readonly walletRepository: WalletRepository,\n public readonly contractRepository: ContractRepository,\n readonly delegatorProvider?: DelegatorProvider,\n watcherConfig?: ReadonlyWalletConfig[\"watcherConfig\"],\n walletContractTimelocks?: RelativeTimelock[],\n ) {\n // Guard: detect identity/server network mismatch for descriptor-based identities.\n // This duplicates the check in setupWalletConfig() so that subclasses\n // bypassing the factory still get the safety net.\n if (\"descriptor\" in identity) {\n const descriptor = identity.descriptor as string;\n const identityIsMainnet = !descriptor.includes(\"tpub\");\n const serverIsMainnet = network.bech32 === \"bc\";\n if (identityIsMainnet !== serverIsMainnet) {\n throw new Error(\n `Network mismatch: identity uses ${identityIsMainnet ? \"mainnet\" : \"testnet\"} derivation ` +\n `but wallet network is ${serverIsMainnet ? \"mainnet\" : \"testnet\"}. ` +\n `Create identity with { isMainnet: ${serverIsMainnet} } to match.`,\n );\n }\n }\n this._offchainTapscript = offchainTapscript;\n this.watcherConfig = watcherConfig;\n this._assetManager = new ReadonlyAssetManager(this.indexerProvider);\n // Defensive for direct-construction callers; setupWalletConfig already\n // passes a deduped list through the public create() factories.\n this.walletContractTimelocks =\n walletContractTimelocks && walletContractTimelocks.length > 0\n ? dedupeTimelocks(walletContractTimelocks)\n : [\n this.offchainTapscript.options.csvTimelock ??\n DefaultVtxo.Script.DEFAULT_TIMELOCK,\n ];\n }\n\n /**\n * Currently-active receive tapscript. Read-only from the outside;\n * mutated only via {@link Wallet.setOffchainTapscriptForRotation}\n * by {@link WalletReceiveRotator.rotate}.\n */\n get offchainTapscript(): DefaultVtxo.Script | DelegateVtxo.Script {\n return this._offchainTapscript;\n }\n\n /**\n * Protected helper to set up shared wallet configuration.\n * Extracts common logic used by both ReadonlyWallet.create() and Wallet.create().\n */\n protected static async setupWalletConfig(config: ReadonlyWalletConfig, pubKey: Uint8Array) {\n const arkadeServerUrl = getArkadeServerUrl(config);\n\n // Use provided arkProvider instance or create a new one from arkServerUrl\n const arkProvider = config.arkProvider ?? new RestArkProvider(arkadeServerUrl);\n\n // Resolve the indexer provider. If a full instance is supplied, use it\n // directly. Otherwise pick a URL with priority:\n // 1. explicit config.indexerUrl\n // 2. URL derived from the injected arkProvider (so a custom\n // arkProvider does not silently pair with the public default)\n // 3. arkadeServerUrl (only when no custom arkProvider was injected)\n let indexerProvider = config.indexerProvider;\n if (!indexerProvider) {\n let indexerUrl = config.indexerUrl;\n if (!indexerUrl) {\n if (config.arkProvider) {\n const derived = extractArkProviderUrl(config.arkProvider);\n if (!derived) {\n throw new Error(\n \"indexerUrl is required when arkProvider is provided without a discoverable serverUrl\",\n );\n }\n indexerUrl = derived;\n } else {\n indexerUrl = arkadeServerUrl;\n }\n }\n indexerProvider = new RestIndexerProvider(indexerUrl);\n }\n\n const info = await arkProvider.getInfo();\n\n const network = getNetwork(info.network as NetworkName);\n\n // Guard: detect identity/server network mismatch for seed-based identities.\n // A mainnet descriptor (xpub, coin type 0) connected to a testnet server\n // (or vice versa) means wrong derivation path → wrong keys → potential fund loss.\n if (\"descriptor\" in config.identity) {\n const descriptor = config.identity.descriptor as string;\n const identityIsMainnet = !descriptor.includes(\"tpub\");\n const serverIsMainnet = info.network === \"bitcoin\";\n if (identityIsMainnet && !serverIsMainnet) {\n throw new Error(\n `Network mismatch: identity uses mainnet derivation (coin type 0) ` +\n `but the Arkade server is on ${info.network}. ` +\n `Create identity with { isMainnet: false } to use testnet derivation.`,\n );\n }\n if (!identityIsMainnet && serverIsMainnet) {\n throw new Error(\n `Network mismatch: identity uses testnet derivation (coin type 1) ` +\n `but the Arkade server is on mainnet. ` +\n `Create identity with { isMainnet: true } or omit isMainnet (defaults to mainnet).`,\n );\n }\n }\n\n // Extract esploraUrl from provider if not explicitly provided\n const esploraUrl = config.esploraUrl || ESPLORA_URL[info.network as NetworkName];\n\n // Use provided onchainProvider instance or create a new one\n const onchainProvider = config.onchainProvider || new EsploraProvider(esploraUrl);\n\n // validate unilateral exit timelock passed in config if any\n if (config.exitTimelock) {\n const { value, type } = config.exitTimelock;\n if ((value < 512n && type !== \"blocks\") || (value >= 512n && type !== \"seconds\")) {\n throw new Error(\"invalid exitTimelock\");\n }\n }\n\n const arkdExitTimelock = delayToTimelock(info.unilateralExitDelay);\n\n // create unilateral exit timelock\n const exitTimelock: RelativeTimelock = config.exitTimelock ?? arkdExitTimelock;\n\n const walletContractTimelocks = config.exitTimelock\n ? [exitTimelock]\n : dedupeTimelocks([\n arkdExitTimelock,\n ...(info.network === \"bitcoin\"\n ? [delayToTimelock(MAINNET_UNILATERAL_EXIT_DELAY)]\n : []),\n ]);\n\n // validate boarding timelock passed in config if any\n if (config.boardingTimelock) {\n const { value, type } = config.boardingTimelock;\n if ((value < 512n && type !== \"blocks\") || (value >= 512n && type !== \"seconds\")) {\n throw new Error(\"invalid boardingTimelock\");\n }\n }\n\n // create boarding timelock\n const boardingTimelock: RelativeTimelock = config.boardingTimelock ?? {\n value: info.boardingExitDelay,\n type: info.boardingExitDelay < 512n ? \"blocks\" : \"seconds\",\n };\n\n // Generate tapscripts for offchain and boarding address\n const serverPubKey = hex.decode(info.signerPubkey).slice(1);\n\n const delegatePubKey = config.delegatorProvider\n ? await config.delegatorProvider\n .getDelegateInfo()\n .then((info) => hex.decode(info.pubkey).slice(1))\n : undefined;\n\n const offchainOptions = {\n pubKey,\n serverPubKey,\n csvTimelock: exitTimelock,\n };\n const offchainTapscript = !delegatePubKey\n ? new DefaultVtxo.Script(offchainOptions)\n : new DelegateVtxo.Script({ ...offchainOptions, delegatePubKey });\n const boardingTapscript = new DefaultVtxo.Script({\n ...offchainOptions,\n csvTimelock: boardingTimelock,\n });\n\n const walletRepository =\n config.storage?.walletRepository ?? new IndexedDBWalletRepository();\n\n const contractRepository =\n config.storage?.contractRepository ?? new IndexedDBContractRepository();\n\n return {\n arkProvider,\n indexerProvider,\n onchainProvider,\n network,\n networkName: info.network as NetworkName,\n serverPubKey,\n offchainTapscript,\n boardingTapscript,\n dustAmount: info.dust,\n walletRepository,\n contractRepository,\n info,\n delegatorProvider: config.delegatorProvider,\n walletContractTimelocks,\n };\n }\n\n /**\n * Create a readonly wallet for querying balances, addresses, and history.\n *\n * @param config - Readonly wallet configuration\n * @returns A readonly wallet instance\n */\n static async create(config: ReadonlyWalletConfig): Promise<ReadonlyWallet> {\n const pubkey = await config.identity.xOnlyPublicKey();\n if (!pubkey) {\n throw new Error(\"Invalid configured public key\");\n }\n\n const setup = await ReadonlyWallet.setupWalletConfig(config, pubkey);\n\n return new ReadonlyWallet(\n config.identity,\n setup.network,\n setup.onchainProvider,\n setup.indexerProvider,\n setup.serverPubKey,\n setup.offchainTapscript,\n setup.boardingTapscript,\n setup.dustAmount,\n setup.walletRepository,\n setup.contractRepository,\n setup.delegatorProvider,\n config.watcherConfig,\n setup.walletContractTimelocks,\n );\n }\n\n get arkAddress(): ArkAddress {\n return this.offchainTapscript.address(this.network.hrp, this.arkServerPublicKey);\n }\n\n /**\n * Get the pkScript hex for the wallet's primary offchain address.\n * For the full wallet-owned script set registered in ContractManager, use getWalletScripts().\n */\n get defaultContractScript(): string {\n return hex.encode(this.offchainTapscript.pkScript);\n }\n\n /** Returns the wallet's Arkade address. */\n async getAddress(): Promise<string> {\n return this.arkAddress.encode();\n }\n\n /** Returns the onchain boarding address used to move funds into Arkade. */\n async getBoardingAddress(): Promise<string> {\n return this.boardingTapscript.onchainAddress(this.network);\n }\n\n /**\n * Return the wallet's combined onchain and offchain balances.\n */\n async getBalance(): Promise<WalletBalance> {\n const [boardingUtxos, vtxos] = await Promise.all([\n this.getBoardingUtxos(),\n this.getVtxos(),\n ]);\n\n // boarding\n let confirmed = 0;\n let unconfirmed = 0;\n for (const utxo of boardingUtxos) {\n if (utxo.status.confirmed) {\n confirmed += utxo.value;\n } else {\n unconfirmed += utxo.value;\n }\n }\n\n // offchain\n let settled = 0;\n let preconfirmed = 0;\n let recoverable = 0;\n settled = vtxos\n .filter((coin) => coin.virtualStatus.state === \"settled\")\n .reduce((sum, coin) => sum + coin.value, 0);\n preconfirmed = vtxos\n .filter((coin) => coin.virtualStatus.state === \"preconfirmed\")\n .reduce((sum, coin) => sum + coin.value, 0);\n recoverable = vtxos\n .filter((coin) => isSpendable(coin) && coin.virtualStatus.state === \"swept\")\n .reduce((sum, coin) => sum + coin.value, 0);\n\n const totalBoarding = confirmed + unconfirmed;\n const totalOffchain = settled + preconfirmed + recoverable;\n\n // aggregate asset balances from spendable virtual outputs\n const assetBalances = new Map<string, bigint>();\n for (const vtxo of vtxos) {\n if (!isSpendable(vtxo)) continue;\n if (vtxo.assets) {\n for (const a of vtxo.assets) {\n const current = assetBalances.get(a.assetId) ?? 0n;\n assetBalances.set(a.assetId, current + a.amount);\n }\n }\n }\n const assets = Array.from(assetBalances.entries()).map(([assetId, amount]) => ({\n assetId,\n amount,\n }));\n\n return {\n boarding: {\n confirmed,\n unconfirmed,\n total: totalBoarding,\n },\n settled,\n preconfirmed,\n available: settled + preconfirmed,\n recoverable,\n total: totalBoarding + totalOffchain,\n assets,\n };\n }\n\n /**\n * Return virtual outputs tracked by the wallet.\n *\n * @param filter - Optional flags controlling whether recoverable or unrolled VTXOs are included\n */\n async getVtxos(filter?: GetVtxosFilter): Promise<ExtendedVirtualCoin[]> {\n const f = filter ?? { withRecoverable: true, withUnrolled: false };\n const contractManager = await this.getContractManager();\n const vtxos = await contractManager.getContractsWithVtxos();\n\n return vtxos\n .flatMap((_) => _.vtxos)\n .filter((vtxo) => {\n if (this._pendingSpendOutpoints.has(`${vtxo.txid}:${vtxo.vout}`)) {\n return false;\n }\n if (isSpendable(vtxo)) {\n if (!f.withRecoverable && (isRecoverable(vtxo) || isExpired(vtxo))) {\n return false;\n }\n return true;\n }\n return !!(f.withUnrolled && vtxo.isUnrolled);\n });\n }\n\n /**\n * Return wallet transaction history derived from Arkade state and boarding transactions.\n */\n async getTransactionHistory(): Promise<ArkTransaction[]> {\n const contractManager = await this.getContractManager();\n const response = await contractManager.getContractsWithVtxos();\n const allVtxos = response.flatMap((_) => _.vtxos);\n\n const { boardingTxs, commitmentsToIgnore } = await this.getBoardingTxs();\n\n const getTxCreatedAt = (txid: string) =>\n this.indexerProvider\n .getVtxos({ outpoints: [{ txid, vout: 0 }] })\n .then((res) => res.vtxos[0]?.createdAt.getTime());\n\n return buildTransactionHistory(allVtxos, boardingTxs, commitmentsToIgnore, getTxCreatedAt);\n }\n\n /**\n * Clear the global VTXO sync cursor, forcing a full re-bootstrap on next sync.\n * Useful for recovery after indexer reprocessing or debugging.\n */\n async clearSyncCursor(): Promise<void> {\n await clearSyncCursor(this.walletRepository);\n }\n /**\n * Build a transaction history view for the wallet's boarding address.\n */\n async getBoardingTxs(): Promise<{\n boardingTxs: ArkTransaction[];\n commitmentsToIgnore: Set<string>;\n }> {\n const utxos: VirtualCoin[] = [];\n const commitmentsToIgnore = new Set<string>();\n const boardingAddress = await this.getBoardingAddress();\n const txs = await this.onchainProvider.getTransactions(boardingAddress);\n\n const outspendCache = new Map<\n string,\n Awaited<ReturnType<typeof this.onchainProvider.getTxOutspends>>\n >();\n\n for (const tx of txs) {\n for (let i = 0; i < tx.vout.length; i++) {\n const vout = tx.vout[i];\n if (vout.scriptpubkey_address === boardingAddress) {\n let spentStatuses = outspendCache.get(tx.txid);\n if (!spentStatuses) {\n spentStatuses = await this.onchainProvider.getTxOutspends(tx.txid);\n outspendCache.set(tx.txid, spentStatuses);\n }\n const spentStatus = spentStatuses[i];\n\n if (spentStatus?.spent) {\n commitmentsToIgnore.add(spentStatus.txid);\n }\n\n utxos.push({\n txid: tx.txid,\n vout: i,\n value: Number(vout.value),\n status: {\n confirmed: tx.status.confirmed,\n block_time: tx.status.block_time,\n },\n isUnrolled: true,\n virtualStatus: {\n state: spentStatus?.spent ? \"spent\" : \"settled\",\n commitmentTxIds: spentStatus?.spent ? [spentStatus.txid] : undefined,\n },\n createdAt: tx.status.confirmed\n ? new Date(tx.status.block_time * 1000)\n : new Date(0),\n script: hex.encode(this.boardingTapscript.pkScript),\n });\n }\n }\n }\n\n const unconfirmedTxs: ArkTransaction[] = [];\n const confirmedTxs: ArkTransaction[] = [];\n\n for (const utxo of utxos) {\n const tx: ArkTransaction = {\n key: {\n boardingTxid: utxo.txid,\n commitmentTxid: \"\",\n arkTxid: \"\",\n },\n amount: utxo.value,\n type: TxType.TxReceived,\n settled: utxo.virtualStatus.state === \"spent\",\n createdAt: utxo.status.block_time\n ? new Date(utxo.status.block_time * 1000).getTime()\n : 0,\n };\n\n if (!utxo.status.block_time) {\n unconfirmedTxs.push(tx);\n } else {\n confirmedTxs.push(tx);\n }\n }\n\n return {\n boardingTxs: [...unconfirmedTxs, ...confirmedTxs],\n commitmentsToIgnore,\n };\n }\n\n /**\n * Fetch and cache onchain inputs (UTXOs) received at the boarding address.\n */\n async getBoardingUtxos(): Promise<ExtendedCoin[]> {\n const boardingAddress = await this.getBoardingAddress();\n const boardingUtxos = await this.onchainProvider.getCoins(boardingAddress);\n\n const utxos = boardingUtxos.map((utxo) => {\n return extendCoin(this, utxo);\n });\n\n // Save boarding inputs using unified repository\n await this.walletRepository.saveUtxos(boardingAddress, utxos);\n\n return utxos;\n }\n\n /**\n * Subscribe to onchain and offchain notifications for newly received funds.\n *\n * @param eventCallback - Callback invoked when matching funds are detected\n * @returns A function that stops the subscriptions\n */\n async notifyIncomingFunds(eventCallback: (coins: IncomingFunds) => void): Promise<() => void> {\n const arkAddress = await this.getAddress();\n const boardingAddress = await this.getBoardingAddress();\n\n let onchainStopFunc: () => void;\n let indexerStopFunc: () => void;\n\n if (this.onchainProvider && boardingAddress) {\n const findVoutOnTx = (tx: any) => {\n return tx.vout.findIndex((v: any) => v.scriptpubkey_address === boardingAddress);\n };\n onchainStopFunc = await this.onchainProvider.watchAddresses(\n [boardingAddress],\n (txs) => {\n // find all onchain outputs belonging to our boarding address\n const coins: Coin[] = txs\n // filter txs where address is in output\n .filter((tx) => findVoutOnTx(tx) !== -1)\n // return boarding input as Coin\n .map((tx) => {\n const { txid, status } = tx;\n const vout = findVoutOnTx(tx);\n const value = Number(tx.vout[vout].value);\n return { txid, vout, value, status };\n });\n\n // and notify via callback\n eventCallback({\n type: \"utxo\",\n coins,\n });\n },\n );\n }\n\n if (this.indexerProvider && arkAddress) {\n // Share the ContractWatcher's single subscription instead of\n // opening a second SSE stream.\n const cm = await this.getContractManager();\n\n // Serialize annotation+notification: parallel `annotateVtxos`\n // awaits could resolve out of order and deliver eventCallback\n // calls in the wrong sequence (e.g. `vtxo_spent` before its\n // matching `vtxo_received`).\n let annotationQueue: Promise<void> = Promise.resolve();\n\n indexerStopFunc = cm.onContractEvent((event) => {\n if (event.type !== \"vtxo_received\" && event.type !== \"vtxo_spent\") {\n return;\n }\n if (event.contract.type !== \"default\" && event.contract.type !== \"delegate\") {\n return;\n }\n\n // `event.vtxos` carries placeholder tapscript fields from\n // the watcher; `annotateVtxos` fills them in.\n annotationQueue = annotationQueue.then(async () => {\n try {\n const annotated = await cm.annotateVtxos(event.vtxos);\n eventCallback({\n type: \"vtxo\",\n newVtxos: event.type === \"vtxo_received\" ? annotated : [],\n spentVtxos: event.type === \"vtxo_spent\" ? annotated : [],\n });\n } catch (error) {\n console.warn(\n \"Dropping subscription update after annotation failed; next sync will reconcile:\",\n error,\n );\n }\n });\n });\n }\n\n const stopFunc = () => {\n onchainStopFunc?.();\n indexerStopFunc?.();\n };\n\n return stopFunc;\n }\n\n /** Fetch Arkade transaction ids that are still pending final settlement. */\n async fetchPendingTxs(): Promise<string[]> {\n // get non-swept virtual outputs, rely on the indexer only in case DB doesn't have the right state\n const scripts = await this.getWalletScripts();\n let { vtxos } = await this.indexerProvider.getVtxos({\n scripts,\n });\n return vtxos\n .filter(\n (vtxo) =>\n vtxo.virtualStatus.state !== \"swept\" &&\n vtxo.virtualStatus.state !== \"settled\" &&\n vtxo.arkTxId !== undefined,\n )\n .map((_) => _.arkTxId!);\n }\n\n // ========================================================================\n // Multi-script support (default + delegate addresses)\n // ========================================================================\n\n /**\n * Get all pkScript hex strings for the wallet's own addresses\n * (both delegate and non-delegate, current and historical).\n */\n async getWalletScripts(): Promise<string[]> {\n const manager = await this.getContractManager();\n const contracts = await manager.getContracts({\n type: [\"default\", \"delegate\"],\n });\n return contracts.map((c) => c.script);\n }\n\n /**\n * Build a map of scriptHex → VtxoScript for all wallet contracts,\n * so virtual outputs can be extended with the correct tapscript per contract.\n */\n async getScriptMap(): Promise<Map<string, DefaultVtxo.Script | DelegateVtxo.Script>> {\n const map = new Map<string, DefaultVtxo.Script | DelegateVtxo.Script>();\n\n const manager = await this.getContractManager();\n const contracts = await manager.getContracts({\n type: [\"default\", \"delegate\"],\n });\n for (const contract of contracts) {\n if (map.has(contract.script)) continue;\n const handler = contractHandlers.get(contract.type);\n if (handler) {\n const script = handler.createScript(contract.params) as\n | DefaultVtxo.Script\n | DelegateVtxo.Script;\n map.set(contract.script, script);\n }\n }\n\n return map;\n }\n\n // ========================================================================\n // Contract Management\n // ========================================================================\n\n /**\n * Get the ContractManager for managing contracts including the wallet's default address.\n *\n * The ContractManager handles:\n * - The wallet's default receiving address (as a \"default\" contract)\n * - External contracts (Boltz swaps, HTLCs, etc.)\n * - Multi-contract watching with resilient connections\n *\n * @example\n * ```typescript\n * const manager = await wallet.getContractManager();\n *\n * // Create a contract for a Boltz swap\n * const contract = await manager.createContract({\n * label: \"Boltz Swap\",\n * type: \"vhtlc\",\n * params: { ... },\n * script: swapScript,\n * address: swapAddress,\n * });\n *\n * // Start watching for events (includes wallet's default address)\n * const stop = await manager.onContractEvent((event) => {\n * console.log(`${event.type} on ${event.contractScript}`);\n * });\n * ```\n */\n async getContractManager(): Promise<ContractManager> {\n // Return existing manager if already initialized\n if (this._contractManager) {\n return this._contractManager;\n }\n\n // If initialization is in progress, wait for it\n if (this._contractManagerInitializing) {\n return this._contractManagerInitializing;\n }\n\n // Start initialization and store the promise\n this._contractManagerInitializing = this.initializeContractManager();\n\n try {\n const manager = await this._contractManagerInitializing;\n this._contractManager = manager;\n return manager;\n } catch (error) {\n // Clear the initializing promise so subsequent calls can retry\n this._contractManagerInitializing = undefined;\n throw error;\n } finally {\n // Clear the initializing promise after completion\n this._contractManagerInitializing = undefined;\n }\n }\n\n private async initializeContractManager(): Promise<ContractManager> {\n const manager = await ContractManager.create({\n indexerProvider: this.indexerProvider,\n contractRepository: this.contractRepository,\n walletRepository: this.walletRepository,\n watcherConfig: this.watcherConfig,\n });\n\n // Register the wallet's baseline always-active contracts: every\n // `walletContractTimelocks` entry × {default, delegate-if-enabled}.\n // This matrix is bound to INDEX 0 — the identity's x-only pubkey\n // — by design: it's the permanent fallback set the wallet wants\n // active forever, independent of any HD rotation. Rotated\n // display contracts (registered separately by\n // {@link WalletReceiveRotator.rotate}) are intentionally\n // single-timelock-single-pubkey at the CURRENT arkd delay, and\n // get the `metadata.source = WALLET_RECEIVE_SOURCE` tag so the\n // next boot can find them. We deliberately do NOT re-register\n // the matrix at a rotated pubkey: doing so would dilute the\n // \"index-0 baseline\" guarantee and turn every rotation into a\n // multi-timelock matrix expansion on every boot.\n const baselinePubkey = await this.identity.xOnlyPublicKey();\n for (const csvTimelock of this.walletContractTimelocks) {\n const csvTimelockStr = timelockToSequence(csvTimelock).toString();\n const defaultScript = new DefaultVtxo.Script({\n pubKey: baselinePubkey,\n serverPubKey: this.offchainTapscript.options.serverPubKey,\n csvTimelock,\n });\n const defaultScriptHex = hex.encode(defaultScript.pkScript);\n\n await manager.createContract({\n type: \"default\",\n params: {\n pubKey: hex.encode(defaultScript.options.pubKey),\n serverPubKey: hex.encode(defaultScript.options.serverPubKey),\n csvTimelock: csvTimelockStr,\n },\n script: defaultScriptHex,\n address: defaultScript.address(this.network.hrp, this.arkServerPublicKey).encode(),\n state: \"active\",\n });\n\n if (this.offchainTapscript instanceof DelegateVtxo.Script) {\n const delegateScript = new DelegateVtxo.Script({\n pubKey: baselinePubkey,\n serverPubKey: this.offchainTapscript.options.serverPubKey,\n delegatePubKey: this.offchainTapscript.options.delegatePubKey,\n csvTimelock,\n });\n const delegateScriptHex = hex.encode(delegateScript.pkScript);\n\n await manager.createContract({\n type: \"delegate\",\n params: {\n pubKey: hex.encode(delegateScript.options.pubKey),\n serverPubKey: hex.encode(delegateScript.options.serverPubKey),\n delegatePubKey: hex.encode(delegateScript.options.delegatePubKey),\n csvTimelock: csvTimelockStr,\n },\n script: delegateScriptHex,\n address: delegateScript\n .address(this.network.hrp, this.arkServerPublicKey)\n .encode(),\n state: \"active\",\n });\n }\n }\n\n return manager;\n }\n\n /** Dispose wallet-owned managers and release background resources. */\n async dispose(): Promise<void> {\n const manager =\n this._contractManager ??\n (this._contractManagerInitializing\n ? await this._contractManagerInitializing.catch(() => undefined)\n : undefined);\n\n manager?.dispose();\n this._contractManager = undefined;\n this._contractManagerInitializing = undefined;\n }\n\n /** Async-dispose hook that forwards to `dispose()`. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n}\n\n/**\n * Main wallet implementation for Bitcoin transactions with Arkade protocol support.\n * The wallet does not store any data locally and relies on Arkade and onchain\n * providers to fetch onchain and virtual outputs.\n *\n * @example\n * ```typescript\n * // Create a wallet with URL configuration\n * const wallet = await Wallet.create({\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),\n * arkServerUrl: 'https://arkade.computer',\n * esploraUrl: 'https://mempool.space/api'\n * });\n *\n * // Or with custom provider instances (e.g., for Expo/React Native)\n * const wallet = await Wallet.create({\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),\n * arkProvider: new ExpoArkProvider('https://arkade.computer'),\n * indexerProvider: new ExpoIndexerProvider('https://arkade.computer'),\n * esploraUrl: 'https://mempool.space/api'\n * });\n *\n * // Get addresses\n * const arkAddress = await wallet.getAddress();\n * const boardingAddress = await wallet.getBoardingAddress();\n *\n * // Send bitcoin\n * const txid = await wallet.send({\n * address: 'ark1q...',\n * amount: 50000,\n * });\n * ```\n */\nexport class Wallet extends ReadonlyWallet implements IWallet {\n static MIN_FEE_RATE = 1; // sats/vbyte\n\n override readonly identity: Identity;\n private readonly _delegatorManager?: IDelegatorManager;\n private _vtxoManager?: VtxoManager;\n private _vtxoManagerInitializing?: Promise<VtxoManager>;\n\n private _walletAssetManager?: IAssetManager;\n\n /**\n * HD receive rotator. Owns the {@link DescriptorProvider}, the\n * `vtxo_received` subscription, and the rotate-and-register\n * lifecycle. Absent in `walletMode: 'static'` and for SingleKey\n * wallets under `'auto'`. Wired in via the constructor; the actual\n * subscription is installed lazily on first `getVtxoManager()` so\n * the contract manager is up first.\n */\n private _receiveRotator?: WalletReceiveRotator;\n private _receiveRotatorInstalled = false;\n\n /**\n * Descriptor-aware signer used by {@link _signerRouter} to sign\n * inputs locked by rotated pubkeys. Same instance the rotator owns;\n * stashed here so the spending paths don't have to reach inside the\n * rotator. Undefined for static / non-HD-capable wallets — those\n * paths only ever take the identity-sign branch.\n */\n private readonly _descriptorProvider?: DescriptorProvider;\n\n private readonly _signerRouter: InputSignerRouter;\n\n /**\n * @internal Sole write path for `offchainTapscript` after construction.\n * Called by {@link WalletReceiveRotator.rotate} once the rotated\n * display contract has been persisted. External code must treat\n * `offchainTapscript` as read-only.\n */\n setOffchainTapscriptForRotation(tapscript: DefaultVtxo.Script | DelegateVtxo.Script): void {\n this._offchainTapscript = tapscript;\n }\n\n /**\n * Async mutex that serializes all operations submitting VTXOs to the Arkade\n * server (`settle`, `send`, `sendBitcoin`). This prevents VtxoManager's\n * background renewal from racing with user-initiated transactions for the\n * same VTXO inputs.\n */\n private _txLock: Promise<void> = Promise.resolve();\n\n /**\n * In-flight guard for {@link restore}. A second `restore()` while one\n * is running returns the same promise so concurrent callers coalesce\n * into a single scan (spec §3.E). Cleared on settle so a later\n * explicit `restore()` re-runs.\n */\n private _restoreInFlight?: Promise<void>;\n\n private _addPendingSpends(inputs: readonly ExtendedCoin[]): void {\n for (const input of inputs) {\n if (\"virtualStatus\" in input) {\n this._pendingSpendOutpoints.add(`${input.txid}:${input.vout}`);\n }\n }\n }\n\n private _removePendingSpends(inputs: readonly ExtendedCoin[]): void {\n for (const input of inputs) {\n if (\"virtualStatus\" in input) {\n this._pendingSpendOutpoints.delete(`${input.txid}:${input.vout}`);\n }\n }\n }\n\n private _withTxLock<T>(fn: () => Promise<T>): Promise<T> {\n let release!: () => void;\n const lock = new Promise<void>((r) => (release = r));\n const prev = this._txLock;\n this._txLock = lock;\n return prev.then(async () => {\n try {\n return await fn();\n } finally {\n release();\n }\n });\n }\n\n /**\n * Explicitly recover this wallet's contracts and balance on a fresh\n * repo. HD wallets run a gap-limit scan across the index range;\n * static / non-HD wallets restore based on the single default\n * pubkey. Never throws because of identity/mode (a static identity\n * is a valid, narrower restore); throws on operational failure (so a\n * truncated restore is loud, not silent — the gap window may have\n * closed early). Idempotent and safe to call concurrently (calls\n * coalesce into one scan).\n *\n * Ordering is deliberate (spec §3.B / §4): scan → advance the HD\n * watermark → inline VTXO pull → only THEN surface aggregated\n * handler errors, so safely-discovered funds are always recovered\n * even when one discovery handler failed.\n *\n * @param opts.gapLimit - Consecutive-unused-index window. Default\n * 20. A non-positive / non-integer value is a programmer error and\n * throws synchronously (distinct from operational failure).\n *\n * @note Concurrent calls coalesce: if a restore is already in flight,\n * subsequent callers receive the same promise and their `gapLimit` is\n * ignored — the first caller's value governs the running scan.\n */\n async restore(opts?: { gapLimit?: number }): Promise<void> {\n // Coalesce concurrent calls FIRST: the documented contract says a\n // second caller's `gapLimit` is ignored while a restore is running,\n // so validating it ahead of the coalesce check would surface a\n // misleading \"invalid gapLimit\" error to a caller whose value was\n // never going to be used. Only the caller that actually starts the\n // run gets its gapLimit validated.\n if (this._restoreInFlight) return this._restoreInFlight;\n const gapLimit = opts?.gapLimit ?? 20;\n if (!Number.isInteger(gapLimit) || gapLimit <= 0) {\n throw new Error(\n `restore: gapLimit must be a positive integer (got ${String(opts?.gapLimit)})`,\n );\n }\n this._restoreInFlight = this._runRestore(gapLimit).finally(() => {\n this._restoreInFlight = undefined;\n });\n return this._restoreInFlight;\n }\n\n private async _runRestore(gapLimit: number): Promise<void> {\n const manager = await this.getContractManager();\n const provider = this._descriptorProvider;\n // Use `instanceof` rather than duck-typing the\n // materializeDescriptorAt / advanceLastIndexUsed surface: a\n // non-HD provider that happens to expose either method name\n // would otherwise be mis-classified as HD and TypeError mid-\n // scan. There is no production extension point for custom HD\n // providers today — if one is added, lift this into an\n // `isHDCapableDescriptorProvider` type guard alongside\n // `isHDCapableIdentity`.\n const hd = provider instanceof HDDescriptorProvider;\n\n const staticDescriptor = hd\n ? undefined\n : `tr(${hex.encode(await this.identity.xOnlyPublicKey())})`;\n const materialize = (index: number): string =>\n hd ? provider.materializeDescriptorAt(index) : staticDescriptor!;\n\n const delegatePubKey =\n this.offchainTapscript instanceof DelegateVtxo.Script\n ? this.offchainTapscript.options.delegatePubKey\n : undefined;\n\n const deps: DiscoveryDeps = {\n indexerProvider: this.indexerProvider,\n onchainProvider: this.onchainProvider,\n network: { hrp: this.network.hrp },\n serverPubKey: this.offchainTapscript.options.serverPubKey,\n csvTimelocks: this.walletContractTimelocks,\n delegatePubKey,\n };\n\n const result = await manager.scanContracts({\n gapLimit,\n hd,\n materialize,\n deps,\n });\n\n if (hd && result.lastIndexUsed >= 0) {\n await provider.advanceLastIndexUsed(result.lastIndexUsed);\n }\n\n // Inline pull BEFORE surfacing any handler errors so safely\n // discovered funds are always recovered (spec §3.B / §4).\n await manager.refreshVtxos({ includeInactive: true });\n\n if (result.handlerErrors.length > 0) {\n throw new AggregateError(\n result.handlerErrors.map((e) =>\n e.error instanceof Error ? e.error : new Error(String(e.error)),\n ),\n `restore: ${result.handlerErrors.length} discovery handler(s) failed; ` +\n `the gap window may have closed early — retry is safe (idempotent).`,\n );\n }\n }\n\n /** @deprecated Use settlementConfig instead */\n public readonly renewalConfig: Required<Omit<WalletConfig[\"renewalConfig\"], \"enabled\">> & {\n enabled: boolean;\n thresholdMs: number;\n };\n\n public readonly settlementConfig: SettlementConfig | false;\n\n protected constructor(\n identity: Identity,\n network: Network,\n onchainProvider: OnchainProvider,\n readonly arkProvider: ArkProvider,\n indexerProvider: IndexerProvider,\n arkServerPublicKey: Bytes,\n offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script,\n boardingTapscript: DefaultVtxo.Script,\n readonly serverUnrollScript: CSVMultisigTapscript.Type,\n readonly forfeitOutputScript: Bytes,\n readonly forfeitPubkey: Bytes,\n dustAmount: bigint,\n walletRepository: WalletRepository,\n contractRepository: ContractRepository,\n /** @deprecated Use settlementConfig */\n renewalConfig?: WalletConfig[\"renewalConfig\"],\n delegatorProvider?: DelegatorProvider,\n watcherConfig?: WalletConfig[\"watcherConfig\"],\n settlementConfig?: WalletConfig[\"settlementConfig\"],\n walletContractTimelocks?: RelativeTimelock[],\n receiveRotator?: WalletReceiveRotator,\n descriptorProvider?: DescriptorProvider,\n ) {\n super(\n identity,\n network,\n onchainProvider,\n indexerProvider,\n arkServerPublicKey,\n offchainTapscript,\n boardingTapscript,\n dustAmount,\n walletRepository,\n contractRepository,\n delegatorProvider,\n watcherConfig,\n walletContractTimelocks,\n );\n this.identity = identity;\n\n // Backwards-compatible: keep renewalConfig populated for any code reading it\n this.renewalConfig = {\n enabled: renewalConfig?.enabled ?? false,\n ...DEFAULT_RENEWAL_CONFIG,\n ...renewalConfig,\n };\n\n // Normalize: prefer settlementConfig, fall back to renewalConfig, default to enabled\n if (settlementConfig !== undefined) {\n this.settlementConfig = settlementConfig;\n } else if (renewalConfig && this.renewalConfig.enabled) {\n this.settlementConfig = {\n vtxoThreshold: renewalConfig.thresholdMs\n ? renewalConfig.thresholdMs / 1000\n : undefined,\n };\n } else if (renewalConfig) {\n // renewalConfig provided but not enabled → disabled\n this.settlementConfig = false;\n } else {\n // No config at all → enabled by default\n this.settlementConfig = { ...DEFAULT_SETTLEMENT_CONFIG };\n }\n this._delegatorManager = delegatorProvider\n ? new DelegatorManagerImpl(delegatorProvider, arkProvider, identity)\n : undefined;\n this._receiveRotator = receiveRotator;\n this._descriptorProvider = descriptorProvider;\n this._signerRouter = new InputSignerRouter({\n identity,\n contractRepository,\n descriptorProvider,\n boardingPkScript: boardingTapscript.pkScript,\n });\n }\n\n override get assetManager(): IAssetManager {\n this._walletAssetManager ??= new AssetManager(this);\n return this._walletAssetManager;\n }\n\n async getVtxoManager(): Promise<VtxoManager> {\n if (this._vtxoManager) {\n return this._vtxoManager;\n }\n\n if (this._vtxoManagerInitializing) {\n return this._vtxoManagerInitializing;\n }\n\n this._vtxoManagerInitializing = Promise.resolve(\n new VtxoManager(this, this.renewalConfig, this.settlementConfig),\n );\n\n try {\n const manager = await this._vtxoManagerInitializing;\n // First-time hookup of the HD rotator: subscribe to\n // `vtxo_received` AFTER the contract manager (which is\n // initialised inside the VtxoManager construction path) has\n // registered the wallet's baseline contracts. The flag\n // makes this idempotent across repeated `getVtxoManager`\n // calls — install runs at most once per wallet instance.\n // Cache the manager and flip the install flag only after\n // `install()` resolves; otherwise a failing install would\n // leave the manager cached and silently disable HD\n // rotation for the lifetime of this wallet.\n if (this._receiveRotator && !this._receiveRotatorInstalled) {\n try {\n await this._receiveRotator.install(this);\n } catch (installErr) {\n await manager.dispose();\n throw installErr;\n }\n this._receiveRotatorInstalled = true;\n }\n this._vtxoManager = manager;\n return manager;\n } finally {\n this._vtxoManagerInitializing = undefined;\n }\n }\n\n override async dispose(): Promise<void> {\n // Drain any in-flight restore before touching the contract/vtxo\n // managers — _runRestore calls manager.refreshVtxos() and\n // manager.scanContracts(), both of which would hit a torn-down\n // manager if we proceeded concurrently. _runRestore never calls\n // dispose(), so awaiting it here is deadlock-free.\n await this._restoreInFlight?.catch(() => undefined);\n\n // Tear down the rotation subscription + drain in-flight rotations\n // first so no late `vtxo_received` event can queue work on a\n // disposing wallet, and so any in-flight `createContract` call\n // finishes before we dispose the contract manager underneath it.\n // A rotator-disposal failure must not abort the rest of\n // teardown — the contract manager / super still need to run on\n // best-effort, so we capture and rethrow at the end.\n let rotatorError: unknown;\n try {\n await this._receiveRotator?.dispose();\n } catch (error) {\n rotatorError = error;\n }\n\n const manager =\n this._vtxoManager ??\n (this._vtxoManagerInitializing\n ? await this._vtxoManagerInitializing.catch(() => undefined)\n : undefined);\n try {\n if (manager) {\n await manager.dispose();\n }\n } catch {\n // best-effort teardown; ensure super.dispose() still runs\n } finally {\n this._vtxoManager = undefined;\n this._vtxoManagerInitializing = undefined;\n await super.dispose();\n }\n\n if (rotatorError) {\n throw rotatorError;\n }\n }\n\n /**\n * Create a full wallet and initialize its background managers.\n *\n * @param config - Wallet configuration\n * @returns A wallet ready to query balances and send transactions\n * @example\n * ```typescript\n * const wallet = await Wallet.create({\n * identity,\n * arkServerUrl: 'https://arkade.computer',\n * });\n * ```\n */\n static async create(config: WalletConfig): Promise<Wallet> {\n const pubkey = await config.identity.xOnlyPublicKey();\n if (!pubkey) {\n throw new Error(\"Invalid configured public key\");\n }\n\n const setup = await ReadonlyWallet.setupWalletConfig(config, pubkey);\n\n // Compute Wallet-specific forfeit and unroll scripts\n // the serverUnrollScript is the one used to create output scripts of the checkpoint transactions\n let serverUnrollScript: CSVMultisigTapscript.Type;\n try {\n const raw = hex.decode(setup.info.checkpointTapscript);\n serverUnrollScript = CSVMultisigTapscript.decode(raw);\n } catch (e) {\n throw new Error(\"Invalid checkpointTapscript from server\");\n }\n\n // parse the server forfeit address\n // server is expecting funds to be sent to this address\n const forfeitPubkey = hex.decode(setup.info.forfeitPubkey).slice(1);\n const forfeitAddress = Address(setup.network).decode(setup.info.forfeitAddress);\n const forfeitOutputScript = OutScript.encode(forfeitAddress);\n\n // HD wiring (boot path) — resolved via the descriptor provider.\n // The rotator (when present) is handed to the constructor as\n // the last positional arg and `getVtxoManager()` lazily\n // installs its `vtxo_received` subscription on first call,\n // after the contract manager has registered the wallet's\n // baseline contracts.\n const boot = await WalletReceiveRotator.resolveBoot(config, setup);\n\n const wallet = new Wallet(\n config.identity,\n setup.network,\n setup.onchainProvider,\n setup.arkProvider,\n setup.indexerProvider,\n setup.serverPubKey,\n boot?.offchainTapscript ?? setup.offchainTapscript,\n setup.boardingTapscript,\n serverUnrollScript,\n forfeitOutputScript,\n forfeitPubkey,\n setup.dustAmount,\n setup.walletRepository,\n setup.contractRepository,\n config.renewalConfig,\n config.delegatorProvider,\n config.watcherConfig,\n config.settlementConfig,\n setup.walletContractTimelocks,\n boot?.rotator,\n boot?.provider,\n );\n\n await wallet.getVtxoManager();\n return wallet;\n }\n\n /**\n * Convert this wallet to a readonly wallet.\n *\n * @returns A readonly wallet with the same configuration but readonly identity\n * @example\n * ```typescript\n * const wallet = await Wallet.create({ identity: MnemonicIdentity.fromMnemonic('abandon abandon...'), ... });\n * const readonlyWallet = await wallet.toReadonly();\n *\n * // Can query balance and addresses\n * const balance = await readonlyWallet.getBalance();\n * const address = await readonlyWallet.getAddress();\n *\n * // But cannot send transactions (type error)\n * // readonlyWallet.send(...); // TypeScript error\n * ```\n */\n async toReadonly(): Promise<ReadonlyWallet> {\n // Check if the identity has a toReadonly method using type guard\n const readonlyIdentity: ReadonlyIdentity = hasToReadonly(this.identity)\n ? await this.identity.toReadonly()\n : this.identity; // Identity extends ReadonlyIdentity, so this is safe\n\n return new ReadonlyWallet(\n readonlyIdentity,\n this.network,\n this.onchainProvider,\n this.indexerProvider,\n this.arkServerPublicKey,\n this.offchainTapscript,\n this.boardingTapscript,\n this.dustAmount,\n this.walletRepository,\n this.contractRepository,\n this.delegatorProvider,\n this.watcherConfig,\n this.walletContractTimelocks,\n );\n }\n\n /** Returns the delegator manager when delegation support is configured. */\n async getDelegatorManager(): Promise<IDelegatorManager | undefined> {\n return this._delegatorManager;\n }\n\n /**\n * Send bitcoin to an Arkade address.\n *\n * @deprecated Use `send`.\n * @param params - Send parameters\n */\n async sendBitcoin(params: SendBitcoinParams): Promise<string> {\n if (params.amount <= 0) {\n throw new Error(\"Amount must be positive\");\n }\n\n if (!isValidArkAddress(params.address)) {\n throw new Error(\"Invalid Arkade address \" + params.address);\n }\n\n if (params.selectedVtxos && params.selectedVtxos.length > 0) {\n return this._withTxLock(async () => {\n // Snapshot the active receive tapscript synchronously\n // before any `await` so the change output's pkScript and\n // the change-VTXO metadata written later by\n // `updateDbAfterOffchainTx` are bound to the same\n // tapscript even if `WalletReceiveRotator.rotate` fires\n // during the offchain round-trip.\n const offchainTapscript = this.offchainTapscript;\n const arkAddress = offchainTapscript.address(\n this.network.hrp,\n this.arkServerPublicKey,\n );\n\n const selectedVtxoSum = params\n .selectedVtxos!.map((v) => v.value)\n .reduce((a, b) => a + b, 0);\n if (selectedVtxoSum < params.amount) {\n throw new Error(\"Selected VTXOs do not cover specified amount\");\n }\n const changeAmount = selectedVtxoSum - params.amount;\n\n const selected = {\n inputs: params.selectedVtxos!,\n changeAmount: BigInt(changeAmount),\n };\n\n const outputAddress = ArkAddress.decode(params.address);\n const outputScript =\n BigInt(params.amount) < this.dustAmount\n ? outputAddress.subdustPkScript\n : outputAddress.pkScript;\n\n const outputs: TransactionOutput[] = [\n {\n script: outputScript,\n amount: BigInt(params.amount),\n },\n ];\n\n // add change output if needed\n if (selected.changeAmount > 0n) {\n const changeOutputScript =\n selected.changeAmount < this.dustAmount\n ? arkAddress.subdustPkScript\n : arkAddress.pkScript;\n\n outputs.push({\n script: changeOutputScript,\n amount: BigInt(selected.changeAmount),\n });\n }\n\n this._addPendingSpends(selected.inputs);\n try {\n const { arkTxid, signedCheckpointTxs } = await this.buildAndSubmitOffchainTx(\n selected.inputs,\n outputs,\n );\n\n await this.updateDbAfterOffchainTx(\n selected.inputs,\n arkTxid,\n signedCheckpointTxs,\n params.amount,\n selected.changeAmount,\n selected.changeAmount > 0n ? outputs.length - 1 : 0,\n offchainTapscript,\n );\n\n return arkTxid;\n } finally {\n this._removePendingSpends(selected.inputs);\n }\n });\n }\n\n return this.send({\n address: params.address,\n amount: params.amount,\n });\n }\n\n /**\n * Settle boarding inputs and/or virtual outputs into a finalized mainnet transaction.\n *\n * @param params - Optional settlement inputs and outputs. When omitted, the wallet settles all eligible funds.\n * @param eventCallback - Optional callback invoked for settlement stream events.\n * @returns The finalized Arkade transaction id\n */\n async settle(\n params?: SettleParams,\n eventCallback?: (event: SettlementEvent) => void,\n ): Promise<string> {\n return this._withTxLock(() => this._settleImpl(params, eventCallback));\n }\n\n private async _settleImpl(\n params?: SettleParams,\n eventCallback?: (event: SettlementEvent) => void,\n ): Promise<string> {\n if (params?.inputs) {\n for (const input of params.inputs) {\n // validate arknotes inputs\n if (typeof input === \"string\") {\n try {\n ArkNote.fromString(input);\n } catch (e) {\n throw new Error(`Invalid arknote \"${input}\"`);\n }\n }\n }\n }\n\n // if no params are provided, use all non-expired boarding inputs and offchain virtual outputs as inputs\n // and send all to the offchain address\n if (!params) {\n const { fees } = await this.arkProvider.getInfo();\n const estimator = new Estimator(fees.intentFee);\n\n let amount = 0;\n\n const exitScript = CSVMultisigTapscript.decode(\n hex.decode(this.boardingTapscript.exitScript),\n );\n\n const boardingTimelock = exitScript.params.timelock;\n\n // For block-based timelocks, fetch the chain tip height\n let chainTipHeight: number | undefined;\n if (boardingTimelock.type === \"blocks\") {\n const tip = await this.onchainProvider.getChainTip();\n chainTipHeight = tip.height;\n }\n\n const boardingUtxos = (await this.getBoardingUtxos()).filter(\n (utxo) =>\n utxo.status.confirmed &&\n !hasBoardingTxExpired(utxo, boardingTimelock, chainTipHeight),\n );\n\n const filteredBoardingUtxos = [];\n for (const utxo of boardingUtxos) {\n const inputFee = estimator.evalOnchainInput({\n amount: BigInt(utxo.value),\n });\n if (inputFee.value >= utxo.value) {\n // skip if fees are greater than the boarding input value\n continue;\n }\n\n filteredBoardingUtxos.push(utxo);\n amount += utxo.value - inputFee.satoshis;\n }\n\n const vtxos = await this.getVtxos({ withRecoverable: true });\n\n const filteredVtxos = [];\n for (const vtxo of vtxos) {\n const inputFee = estimator.evalOffchainInput({\n amount: BigInt(vtxo.value),\n type: vtxo.virtualStatus.state === \"swept\" ? \"recoverable\" : \"vtxo\",\n weight: 0,\n birth: vtxo.createdAt,\n expiry: vtxo.virtualStatus.batchExpiry\n ? new Date(vtxo.virtualStatus.batchExpiry)\n : undefined,\n });\n if (inputFee.satoshis >= vtxo.value) {\n // skip if fees are greater than the virtual output value\n continue;\n }\n\n filteredVtxos.push(vtxo);\n amount += vtxo.value - inputFee.satoshis;\n }\n\n const inputs = [...filteredBoardingUtxos, ...filteredVtxos];\n if (inputs.length === 0) {\n throw new Error(\"No inputs found\");\n }\n\n const output = {\n address: await this.getAddress(),\n amount: BigInt(amount),\n };\n\n const outputFee = estimator.evalOffchainOutput({\n amount: output.amount,\n script: hex.encode(ArkAddress.decode(output.address).pkScript),\n });\n\n output.amount -= BigInt(outputFee.satoshis);\n\n if (output.amount <= this.dustAmount) {\n throw new Error(\"Output amount is below dust limit\");\n }\n\n params = {\n inputs,\n outputs: [output],\n };\n }\n\n const onchainOutputIndexes: number[] = [];\n const outputs: TransactionOutput[] = [];\n let hasOffchainOutputs = false;\n\n for (const [index, output] of params.outputs.entries()) {\n let script: Bytes | undefined;\n try {\n // offchain\n const addr = ArkAddress.decode(output.address);\n script = addr.pkScript;\n hasOffchainOutputs = true;\n } catch {\n // onchain\n const addr = Address(this.network).decode(output.address);\n script = OutScript.encode(addr);\n onchainOutputIndexes.push(index);\n }\n\n outputs.push({\n amount: output.amount,\n script,\n });\n }\n\n // if some of the inputs hold assets, build the asset packet and append as output\n // in the intent proof tx, there is a \"fake\" input at index 0\n // so the real coin indices are offset by +1\n const assetInputs = new Map<number, Asset[]>();\n for (let i = 0; i < params.inputs.length; i++) {\n if (\"assets\" in params.inputs[i]) {\n const assets = (params.inputs[i] as unknown as VirtualCoin).assets;\n if (assets && assets.length > 0) {\n assetInputs.set(i + 1, assets);\n }\n }\n }\n\n let outputAssets: Asset[] | undefined;\n\n const destinationScript = ArkAddress.decode(await this.getAddress()).pkScript;\n const assetOutputIndex = findDestinationOutputIndex(outputs, destinationScript);\n\n if (assetInputs.size > 0) {\n if (assetOutputIndex === -1) {\n throw new Error(\"Cannot assign assets: no output matches the destination address\");\n }\n // collect all input assets and assign them to the destination output\n const allAssets = new Map<string, bigint>();\n for (const [, assets] of assetInputs) {\n for (const asset of assets) {\n const existing = allAssets.get(asset.assetId) ?? 0n;\n allAssets.set(asset.assetId, existing + asset.amount);\n }\n }\n\n outputAssets = [];\n for (const [assetId, amount] of allAssets) {\n outputAssets.push({ assetId, amount });\n }\n }\n\n const recipients: Recipient[] = params.outputs.map((output, i) => ({\n address: output.address,\n amount: Number(output.amount),\n assets: i === assetOutputIndex ? outputAssets : undefined,\n }));\n\n if (outputAssets && outputAssets.length > 0) {\n const assetPacket = createAssetPacket(assetInputs, recipients);\n outputs.push(Extension.create([assetPacket]).txOut());\n }\n\n // session holds the state of the musig2 signing process of the virtual output tree\n let session: SignerSession | undefined;\n const signingPublicKeys: string[] = [];\n if (hasOffchainOutputs) {\n session = this.identity.signerSession();\n signingPublicKeys.push(hex.encode(await session.getPublicKey()));\n }\n\n const [intent, deleteIntent] = await Promise.all([\n this.makeRegisterIntentSignature(\n params.inputs,\n outputs,\n onchainOutputIndexes,\n signingPublicKeys,\n ),\n this.makeDeleteIntentSignature(params.inputs),\n ]);\n\n const topics = [\n ...signingPublicKeys,\n ...params.inputs.map((input) => `${input.txid}:${input.vout}`),\n ];\n\n const abortController = new AbortController();\n let stream: AsyncIterableIterator<SettlementEvent> | undefined;\n\n // Optimistically hide these inputs from concurrent getVtxos() callers\n // while the settlement is in flight. Set before safeRegisterIntent so\n // there's no window between intent registration and coin-visibility.\n this._addPendingSpends(params.inputs);\n\n try {\n stream = this.arkProvider.getEventStream(abortController.signal, topics);\n\n // Prime the iterator so the provider opens the SSE subscription\n // before safeRegisterIntent can trigger server-side batch events.\n const firstNext = stream.next();\n // If settle exits before Batch.join consumes the primed result,\n // keep the orphaned promise from surfacing as an unhandled rejection.\n void firstNext.catch(() => {});\n const primedStream = (async function* () {\n const first = await firstNext;\n if (!first.done) {\n yield first.value;\n }\n yield* stream;\n })();\n\n const intentId = await this.safeRegisterIntent(intent, params.inputs);\n\n const handler = this.createBatchHandler(intentId, params.inputs, recipients, session);\n\n const commitmentTxid = await Batch.join(primedStream, handler, {\n abortController,\n skipVtxoTreeSigning: !hasOffchainOutputs,\n eventCallback: eventCallback\n ? (event) => Promise.resolve(eventCallback(event))\n : undefined,\n });\n\n await this.updateDbAfterSettle(params.inputs, commitmentTxid);\n\n return commitmentTxid;\n } catch (error) {\n // delete the intent to not be stuck in the queue. If deletion fails\n // the intent stays on the server and the next settle will hit\n // \"duplicated input\" in safeRegisterIntent — surface the failure\n // rather than silently swallowing it.\n const inputIds = params.inputs.map((i) => `${i.txid}:${i.vout}`).join(\",\");\n await this.arkProvider.deleteIntent(deleteIntent).catch((e) => {\n console.warn(\n `Failed to delete intent after settle failure for inputs [${inputIds}]; intent may linger on server and cause 'duplicated input' on next settle`,\n e,\n );\n });\n throw error;\n } finally {\n // Clear state first so a synchronous handler firing from abort()\n // never observes a stale pending-spend set.\n this._removePendingSpends(params.inputs);\n // close the stream — abort() fires the in-body handler if the\n // generator has started iterating; return() also releases the\n // eager resource if the body is still suspended or never ran\n // (e.g. safeRegisterIntent threw before Batch.join was called).\n abortController.abort();\n await stream?.return?.().catch(() => {});\n }\n }\n\n private async handleSettlementFinalizationEvent(\n event: BatchFinalizationEvent,\n inputs: SettleParams[\"inputs\"],\n forfeitOutputScript: Bytes,\n connectorsGraph?: TxTree,\n ) {\n // the signed forfeits transactions to submit\n const signedForfeits: string[] = [];\n\n const isVtxo = (input: ExtendedCoin): input is ExtendedVirtualCoin =>\n \"virtualStatus\" in input;\n\n let settlementPsbt = Transaction.fromPSBT(base64.decode(event.commitmentTx));\n let hasBoardingUtxos = false;\n\n let connectorIndex = 0;\n\n const connectorsLeaves = connectorsGraph?.leaves() || [];\n\n for (const input of inputs) {\n // boarding input, we need to sign the settlement tx\n if (!isVtxo(input)) {\n for (let i = 0; i < settlementPsbt.inputsLength; i++) {\n const settlementInput = settlementPsbt.getInput(i);\n\n if (!settlementInput.txid || settlementInput.index === undefined) {\n throw new Error(\n \"The server returned incomplete data. No settlement input found in the PSBT\",\n );\n }\n const inputTxId = hex.encode(settlementInput.txid);\n if (inputTxId !== input.txid) continue;\n if (settlementInput.index !== input.vout) continue;\n // input found in the settlement tx, sign it\n settlementPsbt.updateInput(i, {\n tapLeafScript: [input.forfeitTapLeafScript],\n });\n const script = settlementPsbt.getInput(i).witnessUtxo?.script;\n if (!script) {\n throw new Error(\n \"The server returned incomplete data. Settlement input is missing witnessUtxo.script\",\n );\n }\n settlementPsbt = await this._signerRouter.sign(settlementPsbt, [\n { index: i, lookupScript: script },\n ]);\n hasBoardingUtxos = true;\n break;\n }\n\n continue;\n }\n\n if (isRecoverable(input) || isSubdust(input, this.dustAmount)) {\n // recoverable or subdust coin, we don't need to create a forfeit tx\n continue;\n }\n\n if (connectorsLeaves.length === 0) {\n throw new Error(\"connectors not received\");\n }\n\n if (connectorIndex >= connectorsLeaves.length) {\n throw new Error(\"not enough connectors received\");\n }\n\n const connectorLeaf = connectorsLeaves[connectorIndex];\n const connectorTxId = connectorLeaf.id;\n const connectorOutput = connectorLeaf.getOutput(0);\n if (!connectorOutput) {\n throw new Error(\"connector output not found\");\n }\n\n const connectorAmount = connectorOutput.amount;\n const connectorPkScript = connectorOutput.script;\n\n if (!connectorAmount || !connectorPkScript) {\n throw new Error(\"invalid connector output\");\n }\n\n connectorIndex++;\n\n let forfeitTx = buildForfeitTx(\n [\n {\n txid: input.txid,\n index: input.vout,\n witnessUtxo: {\n amount: BigInt(input.value),\n script: VtxoScript.decode(input.tapTree).pkScript,\n },\n sighashType: SigHash.DEFAULT,\n tapLeafScript: [input.forfeitTapLeafScript],\n },\n {\n txid: connectorTxId,\n index: 0,\n witnessUtxo: {\n amount: connectorAmount,\n script: connectorPkScript,\n },\n },\n ],\n forfeitOutputScript,\n );\n\n // do not sign the connector input\n forfeitTx = await this._signerRouter.sign(forfeitTx, [\n {\n index: 0,\n lookupScript: VtxoScript.decode(input.tapTree).pkScript,\n },\n ]);\n\n signedForfeits.push(base64.encode(forfeitTx.toPSBT()));\n }\n\n if (signedForfeits.length > 0 || hasBoardingUtxos) {\n await this.arkProvider.submitSignedForfeitTxs(\n signedForfeits,\n hasBoardingUtxos ? base64.encode(settlementPsbt.toPSBT()) : undefined,\n );\n }\n }\n\n /**\n * Create a batch event handler for settlement flows.\n *\n * @param intentId - The intent ID.\n * @param inputs - Inputs used by the intent.\n * @param expectedRecipients - Expected recipients to validate in the virtual output tree.\n * @param session - Optional musig2 signing session. When omitted, signing steps are skipped.\n */\n createBatchHandler(\n intentId: string,\n inputs: ExtendedCoin[],\n expectedRecipients: Recipient[],\n session?: SignerSession,\n ): Batch.Handler {\n let sweepTapTreeRoot: Uint8Array | undefined;\n return {\n onBatchStarted: async (event: BatchStartedEvent): Promise<{ skip: boolean }> => {\n const utf8IntentId = new TextEncoder().encode(intentId);\n const intentIdHash = sha256(utf8IntentId);\n const intentIdHashStr = hex.encode(intentIdHash);\n\n let skip = true;\n\n // check if our intent ID hash matches any in the event\n for (const idHash of event.intentIdHashes) {\n if (idHash === intentIdHashStr) {\n if (!this.arkProvider) {\n throw new Error(\"Arkade provider not configured\");\n }\n await this.arkProvider.confirmRegistration(intentId);\n skip = false;\n }\n }\n\n if (skip) {\n return { skip };\n }\n\n const sweepTapscript = CSVMultisigTapscript.encode({\n timelock: {\n value: event.batchExpiry,\n type: event.batchExpiry >= 512n ? \"seconds\" : \"blocks\",\n },\n pubkeys: [this.forfeitPubkey],\n }).script;\n\n sweepTapTreeRoot = tapLeafHash(sweepTapscript);\n\n return { skip: false };\n },\n onTreeSigningStarted: async (\n event: TreeSigningStartedEvent,\n vtxoTree: TxTree,\n ): Promise<{ skip: boolean }> => {\n if (!session) {\n return { skip: true };\n }\n if (!sweepTapTreeRoot) {\n throw new Error(\"Sweep tap tree root not set\");\n }\n\n const xOnlyPublicKeys = event.cosignersPublicKeys.map((k) => k.slice(2));\n const signerPublicKey = await session.getPublicKey();\n const xonlySignerPublicKey = signerPublicKey.subarray(1);\n\n if (!xOnlyPublicKeys.includes(hex.encode(xonlySignerPublicKey))) {\n // not a cosigner, skip the signing\n return { skip: true };\n }\n\n // validate the unsigned virtual output tree\n const commitmentTx = Transaction.fromPSBT(\n base64.decode(event.unsignedCommitmentTx),\n );\n validateVtxoTxGraph(vtxoTree, commitmentTx, sweepTapTreeRoot);\n\n // validate that all expected receivers are in the virtual output tree with correct amounts and assets\n if (expectedRecipients && expectedRecipients.length > 0) {\n validateBatchRecipients(\n commitmentTx,\n vtxoTree.leaves(),\n expectedRecipients,\n this.network,\n );\n }\n\n const sharedOutput = commitmentTx.getOutput(0);\n if (!sharedOutput?.amount) {\n throw new Error(\"Shared output not found\");\n }\n\n await session.init(vtxoTree, sweepTapTreeRoot, sharedOutput.amount);\n\n const pubkey = hex.encode(await session.getPublicKey());\n const nonces = await session.getNonces();\n\n await this.arkProvider.submitTreeNonces(event.id, pubkey, nonces);\n\n return { skip: false };\n },\n onTreeNonces: async (event: TreeNoncesEvent): Promise<{ fullySigned: boolean }> => {\n if (!session) {\n return { fullySigned: true }; // Signing complete (no signing needed)\n }\n\n const { hasAllNonces } = await session.aggregatedNonces(event.txid, event.nonces);\n\n // wait to receive and aggregate all nonces before sending signatures\n if (!hasAllNonces) return { fullySigned: false };\n\n const signatures = await session.sign();\n const pubkey = hex.encode(await session.getPublicKey());\n\n await this.arkProvider.submitTreeSignatures(event.id, pubkey, signatures);\n return { fullySigned: true };\n },\n onBatchFinalization: async (\n event: BatchFinalizationEvent,\n _?: TxTree,\n connectorTree?: TxTree,\n ): Promise<void> => {\n if (!this.forfeitOutputScript) {\n throw new Error(\"Forfeit output script not set\");\n }\n\n if (connectorTree) {\n validateConnectorsTxGraph(event.commitmentTx, connectorTree);\n }\n\n await this.handleSettlementFinalizationEvent(\n event,\n inputs,\n this.forfeitOutputScript,\n connectorTree,\n );\n },\n };\n }\n\n /**\n * Build {@link InputSigningJob}s for a tx whose signable inputs can be\n * resolved from their own `witnessUtxo.script`. Inputs without a\n * `witnessUtxo` are silently omitted, mirroring the wallet's\n * historical silent-skip behaviour for cosigner/connector inputs.\n */\n private inputSigningJobsFromWitnessUtxos(\n tx: Transaction,\n indexes?: number[],\n ): InputSigningJob[] {\n const candidateIndexes = indexes ?? Array.from({ length: tx.inputsLength }, (_, i) => i);\n const jobs: InputSigningJob[] = [];\n for (const index of candidateIndexes) {\n const script = tx.getInput(index).witnessUtxo?.script;\n if (script) jobs.push({ index, lookupScript: script });\n }\n return jobs;\n }\n\n async safeRegisterIntent(\n intent: SignedIntent<Intent.RegisterMessage>,\n inputs: ExtendedCoin[],\n ): Promise<string> {\n try {\n return await this.arkProvider.registerIntent(intent);\n } catch (error) {\n // catch the \"already registered by another intent\" error\n if (\n error instanceof ArkError &&\n error.code === 0 &&\n error.message.includes(\"duplicated input\")\n ) {\n // Clear any queued intent spending these exact inputs. The\n // previous implementation signed a proof over getVtxos() only,\n // which misses boarding UTXOs — the most common trigger for\n // \"duplicated input\" on the auto-settle path. Signing the\n // caller's own inputs keeps the proof surgical and correct\n // regardless of whether the stuck input is a VTXO or boarding.\n const deleteIntent = await this.makeDeleteIntentSignature(inputs);\n await this.arkProvider.deleteIntent(deleteIntent);\n\n // try again\n return this.arkProvider.registerIntent(intent);\n }\n\n throw error;\n }\n }\n\n async makeRegisterIntentSignature(\n coins: ExtendedCoin[],\n outputs: TransactionOutput[],\n onchainOutputsIndexes: number[],\n cosignerPubKeys: string[],\n validAt?: number,\n ): Promise<SignedIntent<Intent.RegisterMessage>> {\n const message: Intent.RegisterMessage = {\n type: \"register\",\n onchain_output_indexes: onchainOutputsIndexes,\n valid_at: validAt ? Math.floor(validAt) : 0,\n expire_at: 0,\n cosigners_public_keys: cosignerPubKeys,\n };\n\n const proof = Intent.create(message, coins, outputs);\n const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));\n\n return {\n proof: base64.encode(signedProof.toPSBT()),\n message,\n };\n }\n\n async makeDeleteIntentSignature(\n coins: ExtendedCoin[],\n ): Promise<SignedIntent<Intent.DeleteMessage>> {\n const message: Intent.DeleteMessage = {\n type: \"delete\",\n expire_at: 0,\n };\n\n const proof = Intent.create(message, coins, []);\n const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));\n\n return {\n proof: base64.encode(signedProof.toPSBT()),\n message,\n };\n }\n\n async makeGetPendingTxIntentSignature(\n coins: ExtendedVirtualCoin[],\n ): Promise<SignedIntent<Intent.GetPendingTxMessage>> {\n const message: Intent.GetPendingTxMessage = {\n type: \"get-pending-tx\",\n expire_at: 0,\n };\n\n const proof = Intent.create(message, coins, []);\n const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));\n\n return {\n proof: base64.encode(signedProof.toPSBT()),\n message,\n };\n }\n\n /**\n * Finalizes pending transactions by retrieving them from the server and finalizing each one.\n * Skips the server check entirely when no send was interrupted (no pending tx flag set).\n * @param vtxos - Optional list of virtual outputs to use instead of retrieving them from the server\n * @returns Array of transaction IDs that were finalized\n */\n async finalizePendingTxs(\n vtxos?: ExtendedVirtualCoin[],\n ): Promise<{ finalized: string[]; pending: string[] }> {\n const hasPending = await this.hasPendingTxFlag();\n if (!hasPending) {\n return { finalized: [], pending: [] };\n }\n\n const MAX_INPUTS_PER_INTENT = 20;\n\n if (!vtxos || vtxos.length === 0) {\n // Batch all scripts into a single indexer call\n const scriptMap = await this.getScriptMap();\n const allExtended: ExtendedVirtualCoin[] = [];\n\n const allScripts = [...scriptMap.keys()];\n const { vtxos: fetchedVtxos } = await this.indexerProvider.getVtxos({\n scripts: allScripts,\n });\n\n for (const vtxo of fetchedVtxos) {\n const vtxoScript = scriptMap.get(vtxo.script);\n if (!vtxoScript) continue;\n\n if (\n vtxo.virtualStatus.state === \"swept\" ||\n vtxo.virtualStatus.state === \"settled\"\n ) {\n continue;\n }\n\n allExtended.push({\n ...vtxo,\n forfeitTapLeafScript: vtxoScript.forfeit(),\n intentTapLeafScript: vtxoScript.forfeit(),\n tapTree: vtxoScript.encode(),\n });\n }\n\n if (allExtended.length === 0) {\n return { finalized: [], pending: [] };\n }\n\n vtxos = allExtended;\n }\n const batches: ExtendedVirtualCoin[][] = [];\n for (let i = 0; i < vtxos.length; i += MAX_INPUTS_PER_INTENT) {\n batches.push(vtxos.slice(i, i + MAX_INPUTS_PER_INTENT));\n }\n\n // Track seen arkTxids so parallel batches don't finalize the same tx twice\n const seen = new Set<string>();\n\n const results = await Promise.all(\n batches.map(async (batch) => {\n const batchFinalized: string[] = [];\n const batchPending: string[] = [];\n\n const intent = await this.makeGetPendingTxIntentSignature(batch);\n const pendingTxs = await this.arkProvider.getPendingTxs(intent);\n\n for (const pendingTx of pendingTxs) {\n if (seen.has(pendingTx.arkTxid)) continue;\n seen.add(pendingTx.arkTxid);\n\n batchPending.push(pendingTx.arkTxid);\n try {\n const finalCheckpoints = await Promise.all(\n pendingTx.signedCheckpointTxs.map(async (c) => {\n const tx = Transaction.fromPSBT(base64.decode(c));\n const signedCheckpoint = await this._signerRouter.sign(\n tx,\n this.inputSigningJobsFromWitnessUtxos(tx),\n );\n return base64.encode(signedCheckpoint.toPSBT());\n }),\n );\n\n await this.arkProvider.finalizeTx(pendingTx.arkTxid, finalCheckpoints);\n batchFinalized.push(pendingTx.arkTxid);\n } catch (error) {\n console.error(\n `Failed to finalize transaction ${pendingTx.arkTxid}:`,\n error,\n );\n }\n }\n\n return {\n finalized: batchFinalized,\n pending: batchPending,\n };\n }),\n );\n\n const finalized: string[] = [];\n const pending: string[] = [];\n for (const result of results) {\n finalized.push(...result.finalized);\n pending.push(...result.pending);\n }\n\n // Only clear the flag if every discovered pending tx was finalized;\n // if any failed, keep it so recovery retries on next startup.\n if (finalized.length === pending.length) {\n await this.setPendingTxFlag(false);\n }\n\n return { finalized, pending };\n }\n\n private async hasPendingTxFlag(): Promise<boolean> {\n const state = await this.walletRepository.getWalletState();\n return state?.settings?.hasPendingTx === true;\n }\n\n private async setPendingTxFlag(value: boolean): Promise<void> {\n await updateWalletState(this.walletRepository, (state) => ({\n ...state,\n settings: { ...state.settings, hasPendingTx: value },\n }));\n }\n\n /**\n * Send BTC and/or assets to one or more recipients.\n *\n * @param args - Recipients with their addresses, BTC amounts, and assets\n * @returns Promise resolving to the Arkade transaction ID\n *\n * @example\n * ```typescript\n * const txid = await wallet.send({\n * address: 'ark1q...',\n * amount: 1000, // (optional, default to dust) btc amount to send to the output\n * assets: [{ assetId: 'abc123...', amount: 50n }] // (optional) list of assets to send\n * });\n * ```\n */\n async send(...args: [Recipient, ...Recipient[]]): Promise<string> {\n return this._withTxLock(() => this._sendImpl(...args));\n }\n\n private async _sendImpl(...args: [Recipient, ...Recipient[]]): Promise<string> {\n if (args.length === 0) {\n throw new Error(\"At least one receiver is required\");\n }\n\n // Snapshot the active receive tapscript synchronously before any\n // `await`. `WalletReceiveRotator.rotate` mutates\n // `this.offchainTapscript` without acquiring `_txLock`, so any\n // yield between here and `updateDbAfterOffchainTx` opens a window\n // where the change-output pkScript (built from `outputAddress`\n // below) and the change-VTXO metadata (built from the snapshot\n // inside `updateDbAfterOffchainTx`) could come from different\n // tapscripts. Threading the snapshot pins both reads.\n const offchainTapscript = this.offchainTapscript;\n const outputAddress = offchainTapscript.address(this.network.hrp, this.arkServerPublicKey);\n const address = outputAddress.encode();\n\n // validate recipients and populate undefined amount with dust amount\n const recipients = validateRecipients(args, Number(this.dustAmount));\n\n const virtualCoins = await this.getVtxos({\n withRecoverable: false,\n });\n\n // keep track of asset changes\n const assetChanges = new Map<string, bigint>();\n\n let selectedCoins: ExtendedVirtualCoin[] = [];\n let btcAmountToSelect = 0;\n\n for (const recipient of recipients) {\n btcAmountToSelect += Math.max(recipient.amount, Number(this.dustAmount));\n }\n\n // select assets\n for (const recipient of recipients) {\n if (!recipient.assets) {\n continue;\n }\n for (const receiverAsset of recipient.assets) {\n let amountToSelect = receiverAsset.amount;\n\n // check if existing change covers the needed amount\n const existingChange = assetChanges.get(receiverAsset.assetId) ?? 0n;\n if (existingChange >= amountToSelect) {\n assetChanges.set(receiverAsset.assetId, existingChange - amountToSelect);\n if (assetChanges.get(receiverAsset.assetId) === 0n) {\n assetChanges.delete(receiverAsset.assetId);\n }\n continue;\n }\n if (existingChange > 0n) {\n amountToSelect -= existingChange;\n assetChanges.delete(receiverAsset.assetId);\n }\n\n const availableCoins = virtualCoins.filter(\n (c) => !selectedCoins.find((sc) => sc.txid === c.txid && sc.vout === c.vout),\n );\n\n const { selected, totalAssetAmount } = selectCoinsWithAsset(\n availableCoins,\n receiverAsset.assetId,\n amountToSelect,\n );\n\n for (const coin of selected) {\n selectedCoins.push(coin);\n // asset coins contain btc, subtract from total amount to select\n btcAmountToSelect -= coin.value;\n // coin may contain other assets, add them to asset changes\n if (coin.assets) {\n for (const a of coin.assets) {\n if (a.assetId === receiverAsset.assetId) {\n continue;\n }\n const existing = assetChanges.get(a.assetId) ?? 0n;\n assetChanges.set(a.assetId, existing + a.amount);\n }\n }\n }\n\n const assetChangeAmount = totalAssetAmount - amountToSelect;\n if (assetChangeAmount > 0n) {\n const existing = assetChanges.get(receiverAsset.assetId) ?? 0n;\n assetChanges.set(receiverAsset.assetId, existing + assetChangeAmount);\n }\n }\n }\n\n // select remaining btc\n if (btcAmountToSelect > 0) {\n const availableCoins = virtualCoins.filter(\n (c) => !selectedCoins.find((sc) => sc.txid === c.txid && sc.vout === c.vout),\n );\n const { inputs: btcCoins } = selectVirtualCoins(availableCoins, btcAmountToSelect);\n\n // some coins may contain assets, add them to asset changes\n for (const coin of btcCoins) {\n if (coin.assets) {\n for (const asset of coin.assets) {\n const existing = assetChanges.get(asset.assetId) ?? 0n;\n assetChanges.set(asset.assetId, existing + asset.amount);\n }\n }\n }\n\n selectedCoins = [...selectedCoins, ...btcCoins];\n }\n\n let totalBtcSelected = selectedCoins.reduce((sum, c) => sum + c.value, 0);\n\n // build tx outputs\n const outputs = recipients.map((recipient) => ({\n script: recipient.script,\n amount: BigInt(recipient.amount),\n }));\n\n const totalBtcOutput = outputs.reduce((sum, o) => sum + Number(o.amount), 0);\n let changeAmount = totalBtcSelected - totalBtcOutput;\n\n // enforce minimum change amount when there are asset changes\n if (assetChanges.size > 0 && changeAmount < Number(this.dustAmount)) {\n const availableCoins = virtualCoins.filter(\n (c) => !selectedCoins.find((sc) => sc.txid === c.txid && sc.vout === c.vout),\n );\n const { inputs: extraCoins } = selectVirtualCoins(\n availableCoins,\n Number(this.dustAmount) - changeAmount,\n );\n\n for (const coin of extraCoins) {\n if (coin.assets) {\n for (const asset of coin.assets) {\n const existing = assetChanges.get(asset.assetId) ?? 0n;\n assetChanges.set(asset.assetId, existing + asset.amount);\n }\n }\n }\n\n selectedCoins = [...selectedCoins, ...extraCoins];\n totalBtcSelected += extraCoins.reduce((sum, c) => sum + c.value, 0);\n changeAmount = totalBtcSelected - totalBtcOutput;\n }\n\n // build change receiver with BTC change and all asset changes\n let changeReceiver: Recipient | undefined;\n let changeIndex = 0;\n if (changeAmount > 0) {\n const changeAssets: Asset[] = [];\n for (const [assetId, amount] of assetChanges) {\n if (amount > 0n) {\n changeAssets.push({ assetId, amount });\n }\n }\n\n changeIndex = outputs.length;\n outputs.push({\n script:\n BigInt(changeAmount) < this.dustAmount\n ? outputAddress.subdustPkScript\n : outputAddress.pkScript,\n amount: BigInt(changeAmount),\n });\n\n changeReceiver = {\n address: address,\n amount: changeAmount,\n assets: changeAssets.length > 0 ? changeAssets : undefined,\n };\n }\n\n // create asset packet only if there are assets involved\n const assetInputs = selectedCoinsToAssetInputs(selectedCoins);\n const hasAssets =\n assetInputs.size > 0 || recipients.some((r) => r.assets && r.assets.length > 0);\n if (hasAssets) {\n const assetPacket = createAssetPacket(assetInputs, recipients, changeReceiver);\n outputs.push(Extension.create([assetPacket]).txOut());\n }\n\n const sentAmount = recipients.reduce((sum, r) => sum + r.amount, 0);\n\n // Optimistically hide selected coins from concurrent getVtxos() while\n // the offchain tx is in flight.\n this._addPendingSpends(selectedCoins);\n try {\n const { arkTxid, signedCheckpointTxs } = await this.buildAndSubmitOffchainTx(\n selectedCoins,\n outputs,\n );\n\n await this.updateDbAfterOffchainTx(\n selectedCoins,\n arkTxid,\n signedCheckpointTxs,\n sentAmount,\n BigInt(changeAmount),\n changeReceiver ? changeIndex : 0,\n offchainTapscript,\n changeReceiver?.assets,\n );\n\n return arkTxid;\n } finally {\n this._removePendingSpends(selectedCoins);\n }\n }\n\n /**\n * Build an offchain transaction from the given inputs and outputs,\n * sign it, submit to the Arkade provider, and finalize.\n * @returns The Arkade transaction id and server-signed checkpoint PSBTs (for bookkeeping)\n */\n async buildAndSubmitOffchainTx(\n inputs: ExtendedVirtualCoin[],\n outputs: TransactionOutput[],\n ): Promise<{ arkTxid: string; signedCheckpointTxs: string[] }> {\n const offchainTx = buildOffchainTx(\n inputs.map((input) => {\n return {\n ...input,\n tapLeafScript: input.forfeitTapLeafScript,\n };\n }),\n outputs,\n this.serverUnrollScript,\n );\n\n // arkTx inputs spend checkpoint outputs, so each input's\n // `witnessUtxo.script` is the checkpoint pkScript — not the\n // source VTXO contract's pkScript. Build the routing jobs from\n // the source VTXO scripts (positionally aligned to `inputs[i]`)\n // so the router can resolve each input's owning contract.\n const arkTxJobs = inputs.map((input, index) => ({\n index,\n lookupScript: VtxoScript.decode(input.tapTree).pkScript,\n }));\n const signedVirtualTx = await this._signerRouter.sign(offchainTx.arkTx, arkTxJobs);\n\n // Mark pending before submitting — if we crash between submit and\n // finalize, the next init will recover via finalizePendingTxs.\n await this.setPendingTxFlag(true);\n\n const { arkTxid, signedCheckpointTxs } = await this.arkProvider.submitTx(\n base64.encode(signedVirtualTx.toPSBT()),\n offchainTx.checkpoints.map((c) => base64.encode(c.toPSBT())),\n );\n\n const finalCheckpoints = await Promise.all(\n signedCheckpointTxs.map(async (c) => {\n const tx = Transaction.fromPSBT(base64.decode(c));\n const signedCheckpoint = await this._signerRouter.sign(\n tx,\n this.inputSigningJobsFromWitnessUtxos(tx),\n );\n return base64.encode(signedCheckpoint.toPSBT());\n }),\n );\n\n await this.arkProvider.finalizeTx(arkTxid, finalCheckpoints);\n\n try {\n await this.setPendingTxFlag(false);\n } catch (error) {\n console.error(\"Failed to clear pending tx flag:\", error);\n }\n\n return { arkTxid, signedCheckpointTxs };\n }\n\n // mark virtual outputs as spent, save change outputs if any.\n // `offchainTapscript` is the snapshot the caller captured under\n // `_txLock` before any `await`; deriving both the change-VTXO\n // metadata and `primaryAddress` from it here guarantees the local\n // record matches the pkScript the server saw on the inbound\n // transaction, even if `WalletReceiveRotator.rotate` swaps\n // `this.offchainTapscript` mid-flight.\n private async updateDbAfterOffchainTx(\n inputs: VirtualCoin[],\n arkTxid: string,\n signedCheckpointTxs: string[],\n sentAmount: number,\n changeAmount: bigint,\n changeVout: number,\n offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script,\n changeAssets?: Asset[],\n ): Promise<void> {\n const primaryAddress = offchainTapscript\n .address(this.network.hrp, this.arkServerPublicKey)\n .encode();\n\n try {\n const spentVtxos: ExtendedVirtualCoin[] = [];\n const commitmentTxIds = new Set<string>();\n let batchExpiry: number = Number.MAX_SAFE_INTEGER;\n\n if (inputs.length !== signedCheckpointTxs.length) {\n console.warn(\n `updateDbAfterOffchainTx: inputs length (${inputs.length}) differs from signedCheckpointTxs length (${signedCheckpointTxs.length})`,\n );\n }\n\n const safeLength = Math.min(inputs.length, signedCheckpointTxs.length);\n const cm = await this.getContractManager();\n const annotatedInputs = await cm.annotateVtxos(inputs);\n for (const [inputIndex, vtxo] of annotatedInputs.entries()) {\n if (inputIndex < safeLength && signedCheckpointTxs[inputIndex]) {\n const checkpoint = Transaction.fromPSBT(\n base64.decode(signedCheckpointTxs[inputIndex]),\n );\n\n spentVtxos.push({\n ...vtxo,\n virtualStatus: {\n ...vtxo.virtualStatus,\n state: \"spent\",\n },\n spentBy: checkpoint.id,\n arkTxId: arkTxid,\n isSpent: true,\n });\n } else {\n spentVtxos.push({\n ...vtxo,\n virtualStatus: {\n ...vtxo.virtualStatus,\n state: \"spent\",\n },\n arkTxId: arkTxid,\n isSpent: true,\n });\n }\n\n if (vtxo.virtualStatus.commitmentTxIds) {\n for (const id of vtxo.virtualStatus.commitmentTxIds) {\n commitmentTxIds.add(id);\n }\n }\n if (vtxo.virtualStatus.batchExpiry) {\n batchExpiry = Math.min(batchExpiry, vtxo.virtualStatus.batchExpiry);\n }\n }\n\n const createdAt = Date.now();\n\n // Only save a change virtual output for preconfirmed coins (those with a batchExpiry).\n // Inputs without a batchExpiry are already settled/unrolled and don't need tracking.\n let changeVtxo: ExtendedVirtualCoin | undefined;\n if (changeAmount > 0n && batchExpiry !== Number.MAX_SAFE_INTEGER) {\n changeVtxo = {\n txid: arkTxid,\n vout: changeVout,\n createdAt: new Date(createdAt),\n forfeitTapLeafScript: offchainTapscript.forfeit(),\n intentTapLeafScript: offchainTapscript.forfeit(),\n isUnrolled: false,\n isSpent: false,\n tapTree: offchainTapscript.encode(),\n value: Number(changeAmount),\n virtualStatus: {\n state: \"preconfirmed\",\n commitmentTxIds: Array.from(commitmentTxIds),\n batchExpiry,\n },\n status: {\n confirmed: false,\n },\n assets: changeAssets,\n script: hex.encode(offchainTapscript.pkScript),\n };\n }\n\n // Route spent rows to their owning contract bucket. The wallet's\n // primary contract is registered with the manager at boot, so\n // `addrByScript` already includes it; in a multi-contract spend\n // each input may belong to a different contract.\n const contracts = await cm.getContracts();\n const addrByScript = new Map(contracts.map((c) => [c.script, c.address]));\n\n const spentByScript = new Map<string, ExtendedVirtualCoin[]>();\n for (const v of spentVtxos) {\n if (!v.script) {\n throw new Error(\n `Wallet.updateDbAfterOffchainTx: spent VTXO ${v.txid}:${v.vout} has no script`,\n );\n }\n const arr = spentByScript.get(v.script) ?? [];\n arr.push(v);\n spentByScript.set(v.script, arr);\n }\n\n for (const [script, vtxos] of spentByScript) {\n // User-initiated send path: a wrong-script row here means the\n // wallet is about to record ownership against the wrong\n // contract — fail loudly rather than persist inconsistent state.\n validateVtxosForScript(vtxos, script, \"Wallet.updateDbAfterOffchainTx\");\n const targetAddr = addrByScript.get(script);\n if (!targetAddr) {\n throw new Error(\n `Wallet.updateDbAfterOffchainTx: no contract owns script ${script}`,\n );\n }\n await saveVtxosForContract(\n this.walletRepository,\n { script, address: targetAddr },\n vtxos,\n );\n }\n\n // Change is always primary-script by construction.\n if (changeVtxo) {\n await saveVtxosForContract(\n this.walletRepository,\n { script: changeVtxo.script!, address: primaryAddress },\n [changeVtxo],\n );\n }\n\n await this.walletRepository.saveTransactions(primaryAddress, [\n {\n key: {\n boardingTxid: \"\",\n commitmentTxid: \"\",\n arkTxid: arkTxid,\n },\n amount: sentAmount,\n type: TxType.TxSent,\n settled: false,\n createdAt,\n },\n ]);\n } catch (e) {\n console.warn(\"error saving offchain tx to repository\", e);\n throw e;\n }\n }\n\n // mark virtual outputs as spent/settled, remove boarding inputs\n private async updateDbAfterSettle(\n inputs: ExtendedCoin[],\n commitmentTxid: string,\n ): Promise<void> {\n try {\n const boardingAddress = await this.getBoardingAddress();\n\n const spentVtxos: ExtendedVirtualCoin[] = [];\n const inputArkTxIds = new Set<string>();\n const boardingUtxoToRemove = new Set<string>();\n\n const isVtxo = (input: ExtendedCoin): input is ExtendedVirtualCoin =>\n \"virtualStatus\" in input;\n\n const vtxoInputs = inputs.filter(isVtxo);\n const cm = await this.getContractManager();\n const annotatedVtxos = await cm.annotateVtxos(vtxoInputs);\n const annotatedByKey = new Map(annotatedVtxos.map((v) => [`${v.txid}:${v.vout}`, v]));\n for (const input of inputs) {\n if (isVtxo(input)) {\n // virtual output = mark it settled\n const vtxo = annotatedByKey.get(`${input.txid}:${input.vout}`)!;\n if (vtxo.arkTxId) {\n inputArkTxIds.add(vtxo.arkTxId);\n }\n spentVtxos.push({\n ...vtxo,\n virtualStatus: {\n ...vtxo.virtualStatus,\n state: \"settled\",\n },\n settledBy: commitmentTxid,\n isSpent: true,\n });\n } else {\n // boarding input = remove it\n boardingUtxoToRemove.add(`${input.txid}:${input.vout}`);\n }\n }\n\n if (spentVtxos.length > 0) {\n // Route settled rows to their owning contract bucket. In a\n // multi-contract settle the inputs may belong to several\n // contracts; the wallet's primary contract is registered with\n // the manager at boot, so its address is in `addrByScript`\n // alongside the rest.\n const contracts = await cm.getContracts();\n const addrByScript = new Map(contracts.map((c) => [c.script, c.address]));\n\n const byScript = new Map<string, ExtendedVirtualCoin[]>();\n for (const v of spentVtxos) {\n if (!v.script) {\n throw new Error(\n `Wallet.updateDbAfterSettle: spent VTXO ${v.txid}:${v.vout} has no script`,\n );\n }\n const arr = byScript.get(v.script) ?? [];\n arr.push(v);\n byScript.set(v.script, arr);\n }\n\n for (const [script, vtxos] of byScript) {\n // User-initiated settle path: refuse to record a settle\n // against the wrong script.\n validateVtxosForScript(vtxos, script, \"Wallet.updateDbAfterSettle\");\n const targetAddr = addrByScript.get(script);\n if (!targetAddr) {\n throw new Error(\n `Wallet.updateDbAfterSettle: no contract owns script ${script}`,\n );\n }\n await saveVtxosForContract(\n this.walletRepository,\n { script, address: targetAddr },\n vtxos,\n );\n }\n }\n\n if (boardingUtxoToRemove.size > 0) {\n const currentUtxos = await this.walletRepository.getUtxos(boardingAddress);\n const filtered = currentUtxos.filter(\n (u) => !boardingUtxoToRemove.has(`${u.txid}:${u.vout}`),\n );\n // Clear and re-save the filtered list\n await this.walletRepository.deleteUtxos(boardingAddress);\n if (filtered.length > 0) {\n await this.walletRepository.saveUtxos(boardingAddress, filtered);\n }\n }\n } catch (e) {\n console.warn(\"error updating repository after settle\", e);\n throw e;\n }\n }\n}\n\n/**\n * Select virtual outputs to reach a target amount, prioritizing those closer to expiry\n * @param coins List of virtual outputs to select from\n * @param targetAmount Target amount to reach in satoshis\n * @returns Selected virtual outputs and change amount\n */\nexport function selectVirtualCoins(\n coins: ExtendedVirtualCoin[],\n targetAmount: number,\n): {\n inputs: ExtendedVirtualCoin[];\n changeAmount: bigint;\n} {\n // Sort virtual outputs by expiry (ascending) and amount (descending)\n const sortedCoins = [...coins].sort((a, b) => {\n // First sort by expiry if available\n const expiryA = a.virtualStatus.batchExpiry || Number.MAX_SAFE_INTEGER;\n const expiryB = b.virtualStatus.batchExpiry || Number.MAX_SAFE_INTEGER;\n if (expiryA !== expiryB) {\n return expiryA - expiryB; // Earlier expiry first\n }\n\n // Then sort by amount\n return b.value - a.value; // Larger amount first\n });\n\n const selectedCoins: ExtendedVirtualCoin[] = [];\n let selectedAmount = 0;\n\n // Select coins until we have enough\n for (const coin of sortedCoins) {\n selectedCoins.push(coin);\n selectedAmount += coin.value;\n\n if (selectedAmount >= targetAmount) {\n break;\n }\n }\n\n if (selectedAmount === targetAmount) {\n return { inputs: selectedCoins, changeAmount: 0n };\n }\n\n // Check if we have enough\n if (selectedAmount < targetAmount) {\n throw new Error(\"Insufficient funds\");\n }\n\n const changeAmount = BigInt(selectedAmount - targetAmount);\n\n return {\n inputs: selectedCoins,\n changeAmount,\n };\n}\n\n/**\n * Wait for incoming funds to the wallet\n * @param wallet - The wallet to wait for incoming funds\n * @returns A promise that resolves the next new coins received by the wallet's address\n */\nexport async function waitForIncomingFunds(wallet: Wallet): Promise<IncomingFunds> {\n let stopFunc: (() => void) | undefined;\n\n return new Promise<IncomingFunds>((resolve) => {\n wallet\n .notifyIncomingFunds((coins: IncomingFunds) => {\n resolve(coins);\n if (stopFunc) stopFunc();\n })\n .then((stop) => {\n stopFunc = stop;\n });\n });\n}\n","export const MESSAGE_BUS_NOT_INITIALIZED = \"MessageBus not initialized\";\n\nexport class MessageBusNotInitializedError extends Error {\n constructor() {\n super(MESSAGE_BUS_NOT_INITIALIZED);\n }\n}\n\nexport class ServiceWorkerTimeoutError extends Error {\n constructor(detail: string) {\n super(detail);\n }\n}\n","/// <reference lib=\"webworker\" />\n\nimport { getActiveServiceWorker, setupServiceWorkerOnce } from \"./browser/service-worker-manager\";\nimport { ArkProvider, RestArkProvider } from \"../providers/ark\";\nimport { RestDelegatorProvider } from \"../providers/delegator\";\nimport {\n type Identity,\n type ReadonlyIdentity,\n type SerializedIdentity,\n type LegacySerializedIdentity,\n hydrateIdentity,\n isSigningSerialized,\n normalizeSerializedIdentity,\n} from \"../identity\";\nimport { ReadonlyWallet, Wallet } from \"../wallet/wallet\";\nimport type { SettlementConfig } from \"../wallet/vtxo-manager\";\nimport type { ContractWatcherConfig } from \"../contracts/contractWatcher\";\nimport { ContractRepository, WalletRepository } from \"../repositories\";\nimport { getRandomId } from \"../wallet/utils\";\nimport { MessageBusNotInitializedError, ServiceWorkerTimeoutError } from \"./errors\";\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// Generic\nexport type RequestEnvelope = {\n tag: string;\n id: string;\n broadcast?: boolean;\n};\nexport type ResponseEnvelope = {\n tag: string;\n id?: string;\n error?: Error;\n broadcast?: boolean;\n};\nexport interface MessageHandler<\n REQ extends RequestEnvelope = RequestEnvelope,\n RES extends ResponseEnvelope = ResponseEnvelope,\n> {\n /**\n * A unique identifier for the updater.\n * This is used to route messages to the correct updater.\n */\n readonly messageTag: string;\n\n /**\n * Called once when the SW is starting up\n * @param services - Providers and wallet instances available to the handler.\n * @param repositories - Repositories available to the handler.\n **/\n start(\n services: {\n arkProvider: ArkProvider;\n wallet?: Wallet;\n readonlyWallet: ReadonlyWallet;\n },\n repositories: {\n walletRepository: WalletRepository;\n },\n ): Promise<void>;\n\n /** Called once when the SW is shutting down */\n stop(): Promise<void>;\n\n /**\n * Called by the scheduler to perform a tick.\n * Can be used by the updater to perform periodic tasks or return\n * delayed responses (eg: subscriptions).\n * @param now The current time in milliseconds since the epoch.\n **/\n tick(now: number): Promise<RES[]>;\n\n /**\n * Handle routed messages from the clients\n **/\n handleMessage(message: REQ): Promise<RES | null>;\n\n /**\n * Optional opt-out from the bus-level message timeout.\n *\n * Long-running flows (e.g. settlement) surrender control to remote peers\n * and can legitimately sit idle for longer than `messageTimeoutMs`. When\n * this returns true, the bus awaits `handleMessage` without a deadline.\n * Defaults to false.\n */\n isLongRunning?(message: REQ): boolean;\n}\n\ntype Options = {\n messageHandlers: MessageHandler[];\n tickIntervalMs?: number;\n messageTimeoutMs?: number;\n /**\n * Per-operation timeout overrides. Keys are either message types\n * (e.g. \"SETTLE\") or handler tags (e.g. \"WALLET_UPDATER\"). Message-type\n * matches take precedence over tag matches. Unspecified operations use\n * `messageTimeoutMs`. These are treated as defaults: any map supplied\n * via `INITIALIZE_MESSAGE_BUS` overrides per-key and is re-applied on\n * every (re-)init.\n */\n messageTimeoutOverrides?: Record<string, number>;\n debug?: boolean;\n buildServices?: (config: Initialize[\"config\"]) => Promise<{\n arkProvider: ArkProvider;\n wallet?: Wallet;\n readonlyWallet: ReadonlyWallet;\n }>;\n};\n\n/**\n * Grace period after a handler times out during which late handler\n * completion is still delivered to the client. Once this expires,\n * the bus sends an \"Operation abandoned\" error so the message id\n * never goes silent indefinitely.\n */\nconst LATE_DELIVERY_GRACE_MS = 5 * 60_000;\n\n/**\n * Tracks one in-flight late-delivery watcher (a handler that has already\n * timed out but is still running). The `settled` flag guards against\n * double-delivery when the grace-period deadline and the handler's own\n * completion race; `stop()` iterates every live record, flips `settled`,\n * and clears the deadline so no response is posted after shutdown.\n */\ntype LateDelivery = {\n settled: boolean;\n deadline: number;\n};\n\ntype Initialize = {\n type: \"INITIALIZE_MESSAGE_BUS\";\n id: string;\n config: {\n wallet: SerializedIdentity | LegacySerializedIdentity;\n arkServer: {\n url: string;\n publicKey?: string;\n };\n delegatorUrl?: string;\n indexerUrl?: string;\n esploraUrl?: string;\n settlementConfig?: SettlementConfig | false;\n walletMode?: \"auto\" | \"static\" | \"hd\";\n watcherConfig?: Partial<Omit<ContractWatcherConfig, \"indexerProvider\">>;\n /**\n * Page-supplied per-operation timeout map. Keys are message types\n * (e.g. \"SETTLE\"). Overrides constructor-supplied\n * `messageTimeoutOverrides` per-key; re-applied on every init.\n */\n messageTimeouts?: Record<string, number>;\n };\n};\n\nexport class MessageBus {\n private handlers: Map<string, MessageHandler>;\n private tickIntervalMs: number;\n private messageTimeoutMs: number;\n private readonly constructorTimeoutOverrides: Record<string, number>;\n private messageTimeoutOverrides: Record<string, number>;\n private lateDeliveries = new Set<LateDelivery>();\n private running = false;\n private tickTimeout: number | null = null;\n private tickInProgress = false;\n private debug = false;\n private initialized = false;\n private readonly buildServicesFn: (config: Initialize[\"config\"]) => Promise<{\n arkProvider: ArkProvider;\n wallet?: Wallet;\n readonlyWallet: ReadonlyWallet;\n }>;\n private readonly boundOnMessage = this.onMessage.bind(this);\n\n /** Create the service-worker message bus with repositories and handler configuration. */\n constructor(\n private readonly walletRepository: WalletRepository,\n private readonly contractRepository: ContractRepository,\n {\n messageHandlers,\n tickIntervalMs = 10_000,\n messageTimeoutMs = 30_000,\n messageTimeoutOverrides = {},\n debug = false,\n buildServices,\n }: Options,\n ) {\n this.handlers = new Map(messageHandlers.map((u) => [u.messageTag, u]));\n this.tickIntervalMs = tickIntervalMs;\n this.messageTimeoutMs = messageTimeoutMs;\n this.constructorTimeoutOverrides = { ...messageTimeoutOverrides };\n this.messageTimeoutOverrides = { ...this.constructorTimeoutOverrides };\n this.debug = debug;\n this.buildServicesFn = buildServices ?? this.buildServices.bind(this);\n }\n\n /** Start the message bus and attach service-worker event listeners. */\n async start() {\n if (this.running) return;\n this.running = true;\n if (this.debug) console.log(\"MessageBus starting\");\n\n // Hook message routing\n self.addEventListener(\"message\", this.boundOnMessage);\n\n // activate service worker immediately\n self.addEventListener(\"install\", () => {\n self.skipWaiting();\n });\n // take control of clients immediately\n self.addEventListener(\"activate\", () => {\n self.clients.claim();\n if (this.initialized) {\n this.runTick();\n }\n });\n }\n\n /** Stop the message bus, cancel ticks, and stop all registered handlers. */\n async stop() {\n if (this.debug) console.log(\"MessageBus stopping\");\n this.running = false;\n this.tickInProgress = false;\n this.initialized = false;\n\n if (this.tickTimeout !== null) {\n self.clearTimeout(this.tickTimeout);\n this.tickTimeout = null;\n }\n\n for (const record of this.lateDeliveries) {\n record.settled = true;\n self.clearTimeout(record.deadline);\n }\n this.lateDeliveries.clear();\n\n self.removeEventListener(\"message\", this.boundOnMessage);\n\n await Promise.all(Array.from(this.handlers.values()).map((updater) => updater.stop()));\n }\n\n private scheduleNextTick() {\n if (!this.running) return;\n if (this.tickTimeout !== null) return;\n if (this.tickInProgress) return;\n\n this.tickTimeout = self.setTimeout(() => this.runTick(), this.tickIntervalMs);\n }\n\n private async runTick() {\n if (!this.running) return;\n if (this.tickInProgress) return;\n this.tickInProgress = true;\n if (this.tickTimeout !== null) {\n self.clearTimeout(this.tickTimeout);\n this.tickTimeout = null;\n }\n\n try {\n const now = Date.now();\n\n for (const updater of this.handlers.values()) {\n try {\n const tickLabel = `${updater.messageTag}:tick`;\n const response = await this.withTimeout(\n updater.tick(now),\n this.resolveTimeoutMs(tickLabel, updater.messageTag),\n tickLabel,\n );\n if (this.debug)\n console.log(`[${updater.messageTag}] outgoing tick response:`, response);\n if (response && response.length > 0) {\n self.clients\n .matchAll({\n includeUncontrolled: true,\n type: \"window\",\n })\n .then((clients) => {\n for (const message of response) {\n clients.forEach((client) => {\n client.postMessage(message);\n });\n }\n });\n }\n } catch (err) {\n if (this.debug) console.error(`[${updater.messageTag}] tick failed`, err);\n }\n }\n } finally {\n this.tickInProgress = false;\n this.scheduleNextTick();\n }\n }\n\n private async waitForInit(config: Initialize[\"config\"]) {\n if (this.initialized) {\n // Stop existing handlers before re-initializing.\n // This handles the case where CLEAR was called, which nullifies\n // handler state (readonlyWallet, etc.) without resetting the\n // initialized flag. Without this, handlers never get start()\n // called again and all messages fail with \"not initialized\".\n //\n // Clear the flag first so onMessage() rejects incoming messages\n // during the stop/start window instead of routing them to\n // half-reset handlers. Restored to true after start() completes.\n this.initialized = false;\n await Promise.all(\n Array.from(this.handlers.values()).map((h) => h.stop().catch(() => {})),\n );\n }\n // Recompute the active timeout map from scratch so a prior init's\n // keys cannot linger after re-init with a smaller map.\n this.messageTimeoutOverrides = {\n ...this.constructorTimeoutOverrides,\n ...(config.messageTimeouts ?? {}),\n };\n\n const services = await this.buildServicesFn(config);\n // Start all handlers\n for (const updater of this.handlers.values()) {\n if (this.debug) console.log(`Starting updater: ${updater.messageTag}`);\n await updater.start(services, {\n walletRepository: this.walletRepository,\n });\n }\n\n // Kick off scheduler\n this.scheduleNextTick();\n this.initialized = true;\n }\n\n private async buildServices(config: Initialize[\"config\"]): Promise<{\n arkProvider: ArkProvider;\n wallet?: Wallet;\n readonlyWallet: ReadonlyWallet;\n }> {\n const arkProvider = new RestArkProvider(config.arkServer.url);\n const storage = {\n walletRepository: this.walletRepository,\n contractRepository: this.contractRepository,\n };\n const delegatorProvider = config.delegatorUrl\n ? new RestDelegatorProvider(config.delegatorUrl)\n : undefined;\n\n const serialized = normalizeSerializedIdentity(config.wallet);\n\n if (isSigningSerialized(serialized)) {\n const identity = hydrateIdentity(serialized) as Identity;\n const wallet = await Wallet.create({\n identity,\n arkServerUrl: config.arkServer.url,\n arkServerPublicKey: config.arkServer.publicKey,\n indexerUrl: config.indexerUrl,\n esploraUrl: config.esploraUrl,\n storage,\n delegatorProvider,\n settlementConfig: config.settlementConfig,\n walletMode: config.walletMode,\n watcherConfig: config.watcherConfig,\n });\n return { wallet, arkProvider, readonlyWallet: wallet };\n }\n\n const identity = hydrateIdentity(serialized) as ReadonlyIdentity;\n const readonlyWallet = await ReadonlyWallet.create({\n identity,\n arkServerUrl: config.arkServer.url,\n arkServerPublicKey: config.arkServer.publicKey,\n indexerUrl: config.indexerUrl,\n esploraUrl: config.esploraUrl,\n storage,\n delegatorProvider,\n watcherConfig: config.watcherConfig,\n });\n return { readonlyWallet, arkProvider };\n }\n\n private onMessage(event: ExtendableMessageEvent) {\n // Keep the service worker alive while async work is pending.\n // Without this, the browser may terminate the SW mid-operation,\n // causing all pending responses to be lost silently.\n const promise = this.processMessage(event);\n if (typeof event.waitUntil === \"function\") {\n event.waitUntil(promise);\n }\n return promise;\n }\n\n private async processMessage(event: ExtendableMessageEvent) {\n const { id, tag, broadcast } = event.data as RequestEnvelope;\n\n if (tag === \"PING\") {\n this.deliverResponse(event.source, { id, tag: \"PONG\" }, { id, tag: \"PONG\" });\n return;\n }\n\n if (tag === \"INITIALIZE_MESSAGE_BUS\") {\n if (this.debug) {\n console.log(\"Init Command received\");\n }\n // Intentionally not wrapped with withTimeout: initialization\n // performs network calls (buildServices) and handler startup\n // that may legitimately exceed the message timeout.\n await this.waitForInit(event.data.config);\n this.deliverResponse(event.source, { id, tag }, { id, tag });\n if (this.debug) {\n console.log(\"MessageBus initialized\");\n }\n return;\n }\n\n if (!this.initialized) {\n if (this.debug)\n console.warn(\"Event received before initialization, dropping\", event.data);\n // Send error response so the caller's promise rejects instead of\n // hanging forever. This happens when the browser kills and restarts\n // the service worker — the new instance has initialized=false and\n // messages arrive before INITIALIZE_MESSAGE_BUS is re-sent.\n const fallbackTag = tag ?? \"unknown\";\n this.deliverResponse(\n event.source,\n {\n id,\n tag: fallbackTag,\n error: new MessageBusNotInitializedError(),\n },\n { id, tag: fallbackTag },\n );\n return;\n }\n\n if (!id || !tag) {\n if (this.debug)\n console.error(\"Invalid message received, missing required fields:\", event.data);\n const fallbackTag = tag ?? \"unknown\";\n this.deliverResponse(\n event.source,\n {\n id,\n tag: fallbackTag,\n error: new TypeError(\"Invalid message received, missing required fields\"),\n },\n { id, tag: fallbackTag },\n );\n return;\n }\n\n const messageType = this.extractMessageType(event.data);\n\n if (broadcast) {\n const updaters = Array.from(this.handlers.values());\n const entries = updaters.map((updater) => {\n const label = this.labelFor(messageType, updater.messageTag);\n const timeoutMs = this.resolveTimeoutMs(messageType, updater.messageTag);\n const handlerPromise = updater.handleMessage(event.data);\n const raced = updater.isLongRunning?.(event.data)\n ? handlerPromise\n : this.withTimeout(handlerPromise, timeoutMs, label);\n return { updater, handlerPromise, raced };\n });\n\n const results = await Promise.allSettled(entries.map((e) => e.raced));\n\n results.forEach((result, index) => {\n const { updater, handlerPromise } = entries[index];\n const handlerTag = updater.messageTag;\n const context = { id, tag: handlerTag, messageType };\n if (result.status === \"fulfilled\") {\n const response = result.value;\n // Always deliver a response so the caller's message id\n // never goes silent. Handlers returning null/undefined\n // get an explicit ack envelope.\n this.deliverResponse(\n event.source,\n response ?? { id, tag: handlerTag },\n context,\n );\n } else {\n if (this.debug)\n console.error(`[${handlerTag}] handleMessage failed`, result.reason);\n const error = toError(result.reason);\n this.deliverResponse(event.source, { id, tag: handlerTag, error }, context);\n // If the error was a timeout, keep watching the\n // underlying handler and surface its eventual result\n // under the same id.\n if (result.reason instanceof ServiceWorkerTimeoutError) {\n this.attachLateDelivery(\n handlerPromise,\n event.source,\n id,\n handlerTag,\n messageType,\n );\n }\n }\n });\n return;\n }\n\n const updater = this.handlers.get(tag);\n if (!updater) {\n if (this.debug) console.warn(`[${tag}] unknown message tag, ignoring message`);\n this.deliverResponse(\n event.source,\n {\n id,\n tag,\n error: new Error(`Unknown handler tag: ${tag}`),\n },\n { id, tag, messageType },\n );\n return;\n }\n\n const label = this.labelFor(messageType, tag);\n const timeoutMs = this.resolveTimeoutMs(messageType, tag);\n const handlerPromise = updater.handleMessage(event.data);\n const context = { id, tag, messageType };\n try {\n const response = updater.isLongRunning?.(event.data)\n ? await handlerPromise\n : await this.withTimeout(handlerPromise, timeoutMs, label);\n if (this.debug) console.log(`[${tag}] outgoing response:`, response);\n // Always deliver a response so the caller's message id never\n // goes silent. A handler returning null/undefined yields an\n // explicit ack envelope.\n this.deliverResponse(event.source, response ?? { id, tag }, context);\n } catch (err) {\n if (this.debug) console.error(`[${tag}] handleMessage failed`, err);\n const error = toError(err);\n this.deliverResponse(event.source, { id, tag, error }, context);\n // When we abandoned the handler via timeout, keep watching it\n // so the client's message id eventually gets a final response.\n if (err instanceof ServiceWorkerTimeoutError) {\n this.attachLateDelivery(handlerPromise, event.source, id, tag, messageType);\n }\n }\n }\n\n /**\n * Race `promise` against a timeout. Note: this does NOT cancel the\n * underlying work — the original promise keeps running. Call\n * `attachLateDelivery` after catching the timeout to surface the\n * eventual result so the message id does not go silent.\n */\n private withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n if (timeoutMs <= 0) return promise;\n return new Promise((resolve, reject) => {\n const timer = self.setTimeout(() => {\n reject(\n new ServiceWorkerTimeoutError(\n `Message handler timed out after ${timeoutMs}ms (${label})`,\n ),\n );\n }, timeoutMs);\n promise.then(\n (val) => {\n self.clearTimeout(timer);\n resolve(val);\n },\n (err) => {\n self.clearTimeout(timer);\n reject(err);\n },\n );\n });\n }\n\n /**\n * Extract the declared `type` from a request envelope (e.g. \"SETTLE\").\n * Not every envelope carries a type (PING/INIT are special cased\n * earlier), so this returns undefined for envelopes that lack one.\n */\n private extractMessageType(data: RequestEnvelope): string | undefined {\n const maybeType = (data as RequestEnvelope & { type?: unknown }).type;\n return typeof maybeType === \"string\" ? maybeType : undefined;\n }\n\n /**\n * Resolve the timeout for an operation. Message-type overrides take\n * precedence over handler-tag overrides, with the bus-wide default\n * (`messageTimeoutMs`) as the final fallback.\n */\n private resolveTimeoutMs(messageType: string | undefined, handlerTag: string): number {\n if (\n messageType &&\n Object.prototype.hasOwnProperty.call(this.messageTimeoutOverrides, messageType)\n ) {\n return this.messageTimeoutOverrides[messageType];\n }\n if (Object.prototype.hasOwnProperty.call(this.messageTimeoutOverrides, handlerTag)) {\n return this.messageTimeoutOverrides[handlerTag];\n }\n return this.messageTimeoutMs;\n }\n\n /**\n * Build a human-readable label for timeout errors. Format:\n * `\"<MESSAGE_TYPE> via <HANDLER_TAG>\"` when both are known, else the\n * handler tag alone. Used so timeout errors name the operation the\n * client actually triggered (e.g. SETTLE) rather than just the\n * handler that received it (e.g. WALLET_UPDATER).\n */\n private labelFor(messageType: string | undefined, handlerTag: string): string {\n return messageType ? `${messageType} via ${handlerTag}` : handlerTag;\n }\n\n /**\n * Post a response to the originating client. When `source` is null\n * (client tab closed, detached frame, etc.) the response cannot be\n * delivered; we log the drop in debug mode so it is not invisible.\n */\n private deliverResponse(\n source: ExtendableMessageEvent[\"source\"],\n response: ResponseEnvelope,\n context: { id?: string; tag: string; messageType?: string },\n ): void {\n if (!source) {\n if (this.debug)\n console.warn(`[${context.tag}] cannot deliver response: event.source is null`, {\n id: context.id,\n messageType: context.messageType,\n });\n return;\n }\n source.postMessage(response);\n }\n\n /**\n * After a handler times out the client has already received a timeout\n * error, but the handler keeps running. Attach a follow-up so the\n * handler's eventual result (or error) is delivered under the same\n * message id, or — if the handler never completes within\n * {@link LATE_DELIVERY_GRACE_MS} — an \"Operation abandoned\" error is\n * sent so the client's listener (if still attached) does not hang.\n */\n private attachLateDelivery(\n handlerPromise: Promise<ResponseEnvelope | null>,\n source: ExtendableMessageEvent[\"source\"],\n id: string,\n tag: string,\n messageType: string | undefined,\n ): void {\n const context = { id, tag, messageType };\n const record: LateDelivery = {\n settled: false,\n deadline: self.setTimeout(() => {\n if (record.settled) return;\n record.settled = true;\n this.lateDeliveries.delete(record);\n this.deliverResponse(\n source,\n {\n id,\n tag,\n error: new Error(\n `Operation abandoned: handler did not complete within ${LATE_DELIVERY_GRACE_MS}ms after timeout (${this.labelFor(messageType, tag)})`,\n ),\n },\n context,\n );\n }, LATE_DELIVERY_GRACE_MS),\n };\n this.lateDeliveries.add(record);\n\n handlerPromise.then(\n (response) => {\n if (record.settled) return;\n record.settled = true;\n self.clearTimeout(record.deadline);\n this.lateDeliveries.delete(record);\n this.deliverResponse(source, response ?? { id, tag }, context);\n },\n (err) => {\n if (record.settled) return;\n record.settled = true;\n self.clearTimeout(record.deadline);\n this.lateDeliveries.delete(record);\n this.deliverResponse(source, { id, tag, error: toError(err) }, context);\n },\n );\n }\n\n /**\n * Returns the registered SW for the path.\n * It uses the functions in `service-worker-manager.ts` module.\n * @param path\n * @return the Service Worker\n * @throws if not running in a browser environment\n */\n static async getServiceWorker(path?: string) {\n return getActiveServiceWorker(path);\n }\n\n /**\n * Set up and register the Service Worker, ensuring it's done once at most.\n * It uses the functions in `service-worker-manager.ts` module.\n * @param path\n * @return the Service Worker\n * @throws if not running in a browser environment\n */\n static async setup(path: string) {\n await setupServiceWorkerOnce(path);\n return getActiveServiceWorker(path);\n }\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n","import { ExtendedCoin, IWallet } from \".\";\nimport { FeeInfo, SettlementEvent } from \"../providers/ark\";\nimport { Estimator } from \"../arkfee\";\nimport { Address, OutScript } from \"@scure/btc-signer\";\nimport { hex } from \"@scure/base\";\nimport { networks, NetworkName } from \"../networks\";\nimport { ArkAddress } from \"../script/address\";\n\n/**\n * Ramps is a class wrapping `settle` method to provide a more convenient interface for onboarding and offboarding operations.\n *\n * @see IWallet.settle\n * @see onboard\n * @see offboard\n *\n * @example\n * ```typescript\n * const ramps = new Ramps(wallet);\n * const feeInfo = { intentFee: {}, txFeeRate: '1' };\n * await ramps.onboard(feeInfo); // onboard all boarding inputs\n * await ramps.offboard('bc1q...', feeInfo); // collaboratively exit all virtual outputs to an onchain address\n * ```\n */\nexport class Ramps {\n /**\n * Create convenience wrappers for onboarding and offboarding flows.\n *\n * @param wallet - Wallet used to query funds and execute settlement transactions\n */\n constructor(readonly wallet: IWallet) {}\n\n /**\n * Onboard boarding inputs.\n *\n * @param feeInfo - The fee info to deduct from the onboard amount.\n * @param boardingUtxos - Specific boarding inputs to onboard. If not provided, all boarding inputs will be used.\n * @param amount - Amount to onboard. If not provided, the total amount of boarding inputs will be onboarded.\n * @param eventCallback - Optional callback that receives settlement events\n * @returns The Arkade transaction id created by settlement\n * @throws Error if no boarding inputs remain after fee deduction or if `amount` exceeds available value\n * @see IWallet.getBoardingUtxos\n * @see IWallet.settle\n * @example\n * ```typescript\n * const feeInfo = { intentFee: {}, txFeeRate: '1' };\n * const ramps = new Ramps(wallet);\n * await ramps.onboard(feeInfo);\n * ```\n */\n async onboard(\n feeInfo: FeeInfo,\n boardingUtxos?: ExtendedCoin[],\n amount?: bigint,\n eventCallback?: (event: SettlementEvent) => void,\n ): ReturnType<IWallet[\"settle\"]> {\n boardingUtxos = boardingUtxos ?? (await this.wallet.getBoardingUtxos());\n\n // Calculate input fees and filter out boarding inputs where fee >= value.\n const estimator = new Estimator(feeInfo?.intentFee ?? {});\n const filteredBoardingUtxos: ExtendedCoin[] = [];\n let totalAmount = 0n;\n\n for (const utxo of boardingUtxos) {\n const inputFee = estimator.evalOnchainInput({\n amount: BigInt(utxo.value),\n });\n if (inputFee.satoshis >= utxo.value) {\n // Skip boarding inputs where spending fees are greater than or equal to the input value.\n continue;\n }\n\n filteredBoardingUtxos.push(utxo);\n totalAmount += BigInt(utxo.value) - BigInt(inputFee.satoshis);\n }\n\n if (filteredBoardingUtxos.length === 0) {\n throw new Error(\"No boarding utxos available after deducting fees\");\n }\n\n let change = 0n;\n if (amount) {\n if (amount > totalAmount) {\n throw new Error(\"Amount is greater than total amount of boarding utxos after fees\");\n }\n change = totalAmount - amount;\n }\n\n amount = amount ?? totalAmount;\n\n // Calculate offchain output fee using Estimator\n const offchainAddress = await this.wallet.getAddress();\n const offchainAddr = ArkAddress.decode(offchainAddress);\n const offchainScript = hex.encode(offchainAddr.pkScript);\n\n const outputFee = estimator.evalOffchainOutput({\n amount,\n script: offchainScript,\n });\n\n if (BigInt(outputFee.satoshis) > amount) {\n throw new Error(\n `can't deduct fees from onboard amount (${outputFee.satoshis} > ${amount})`,\n );\n }\n amount -= BigInt(outputFee.satoshis);\n\n const outputs = [\n {\n address: offchainAddress,\n amount,\n },\n ];\n\n if (change > 0n) {\n const boardingAddress = await this.wallet.getBoardingAddress();\n outputs.push({\n address: boardingAddress,\n amount: change,\n });\n }\n\n return this.wallet.settle(\n {\n inputs: filteredBoardingUtxos,\n outputs,\n },\n eventCallback,\n );\n }\n\n /**\n * Offboard virtual outputs, or collaboratively exit them to an onchain address.\n *\n * @param destinationAddress - The destination address to offboard to.\n * @param feeInfo - The fee info to deduct from the offboard amount.\n * @param amount - The amount to offboard. If not provided, the total amount of virtual outputs will be offboarded.\n * @param eventCallback - Optional callback that receives settlement events\n * @returns The Arkade transaction id created by settlement\n * @throws Error if no virtual outputs remain after fee deduction or the destination address cannot be decoded\n * @see IWallet.getVtxos\n * @see IWallet.settle\n * @example\n * ```typescript\n * const feeInfo = { intentFee: {}, txFeeRate: '1' };\n * const ramps = new Ramps(wallet);\n * await ramps.offboard('bc1q...', feeInfo);\n * ```\n */\n async offboard(\n destinationAddress: string,\n feeInfo: FeeInfo,\n amount?: bigint,\n eventCallback?: (event: SettlementEvent) => void,\n ): ReturnType<IWallet[\"settle\"]> {\n const vtxos = await this.wallet.getVtxos({\n withRecoverable: true,\n withUnrolled: false,\n });\n\n // Calculate input fees and filter out virtual outputs where fee >= value.\n const estimator = new Estimator(feeInfo?.intentFee ?? {});\n const filteredVtxos: typeof vtxos = [];\n let totalAmount = 0n;\n\n for (const vtxo of vtxos) {\n const inputFee = estimator.evalOffchainInput({\n amount: BigInt(vtxo.value),\n type: vtxo.virtualStatus.state === \"swept\" ? \"recoverable\" : \"vtxo\",\n weight: 0,\n birth: vtxo.createdAt,\n expiry: vtxo.virtualStatus.batchExpiry\n ? new Date(vtxo.virtualStatus.batchExpiry)\n : undefined,\n });\n if (inputFee.satoshis >= vtxo.value) {\n // Skip virtual outputs where spending fees are greater than or equal to the output value.\n continue;\n }\n\n filteredVtxos.push(vtxo);\n totalAmount += BigInt(vtxo.value) - BigInt(inputFee.satoshis);\n }\n\n if (filteredVtxos.length === 0) {\n throw new Error(\"No vtxos available after deducting fees\");\n }\n\n let change = 0n;\n if (amount) {\n if (amount > totalAmount) {\n throw new Error(\"Amount is greater than total amount of vtxos after fees\");\n }\n change = totalAmount - amount;\n }\n\n amount = amount ?? totalAmount;\n\n const networkNames: NetworkName[] = [\n \"bitcoin\",\n \"regtest\",\n \"testnet\",\n \"signet\",\n \"mutinynet\",\n ];\n let destinationScript: Uint8Array | undefined;\n\n for (const networkName of networkNames) {\n try {\n const network = networks[networkName];\n const addr = Address(network).decode(destinationAddress);\n destinationScript = OutScript.encode(addr);\n break;\n } catch {\n // Try next network\n continue;\n }\n }\n\n if (!destinationScript) {\n throw new Error(`Failed to decode destination address: ${destinationAddress}`);\n }\n\n const outputFee = estimator.evalOnchainOutput({\n amount,\n script: hex.encode(destinationScript),\n });\n\n if (BigInt(outputFee.satoshis) > amount) {\n throw new Error(\n `can't deduct fees from offboard amount (${outputFee.satoshis} > ${amount})`,\n );\n }\n amount -= BigInt(outputFee.satoshis);\n\n const outputs = [\n {\n address: destinationAddress,\n amount,\n },\n ];\n\n if (change > 0n) {\n const offchainAddress = await this.wallet.getAddress();\n outputs.push({\n address: offchainAddress,\n amount: change,\n });\n }\n\n return this.wallet.settle(\n {\n inputs: filteredVtxos,\n outputs,\n },\n eventCallback,\n );\n }\n}\n","import { ArkProvider, SettlementEvent } from \"../../providers/ark\";\nimport { IndexerProvider, RestIndexerProvider } from \"../../providers/indexer\";\nimport { WalletRepository } from \"../../repositories\";\nimport type {\n Contract,\n ContractEvent,\n ContractWithVtxos,\n GetContractsFilter,\n PathSelection,\n} from \"../../contracts\";\nimport type {\n CreateContractParams,\n GetAllSpendingPathsOptions,\n GetSpendablePathsOptions,\n} from \"../../contracts/contractManager\";\nimport {\n ArkTransaction,\n AssetDetails,\n BurnParams,\n ExtendedCoin,\n ExtendedVirtualCoin,\n GetVtxosFilter,\n IssuanceParams,\n IssuanceResult,\n isExpired,\n isRecoverable,\n isSpendable,\n isSubdust,\n IWallet,\n Recipient,\n ReissuanceParams,\n SendBitcoinParams,\n SettleParams,\n VirtualCoin,\n WalletBalance,\n} from \"../index\";\nimport { DelegateInfo } from \"../../providers/delegator\";\nimport { ReadonlyWallet, Wallet } from \"../wallet\";\nimport { extendCoin } from \"../utils\";\nimport { MessageHandler, RequestEnvelope, ResponseEnvelope } from \"../../worker/messageBus\";\nimport { Transaction } from \"../../utils/transaction\";\nimport { buildTransactionHistory } from \"../../utils/transactionHistory\";\nimport {\n filterVtxosForScript,\n getVtxosForContract,\n saveVtxosForContract,\n warnAndFilterVtxosForScript,\n} from \"../../contracts/vtxoOwnership\";\nimport { scriptFromArkAddress } from \"../../repositories/scriptFromAddress\";\n\nexport class WalletNotInitializedError extends Error {\n constructor() {\n super(\"Wallet handler not initialized\");\n this.name = \"WalletNotInitializedError\";\n }\n}\n\nexport class ReadonlyWalletError extends Error {\n constructor() {\n super(\"Read-only wallet: operation requires signing\");\n this.name = \"ReadonlyWalletError\";\n }\n}\n\nexport class DelegatorNotConfiguredError extends Error {\n constructor() {\n super(\"Delegator not configured\");\n this.name = \"DelegatorNotConfiguredError\";\n }\n}\n\nexport const DEFAULT_MESSAGE_TAG = \"WALLET_UPDATER\";\n\nexport type RequestInitWallet = RequestEnvelope & {\n type: \"INIT_WALLET\";\n payload: {\n /**\n * Legacy per-request key material. Ignored by the current handler —\n * identity hydration happens during INITIALIZE_MESSAGE_BUS. Retained\n * for wire compatibility with older workers that may still read it.\n * Slated for removal in the next major.\n *\n * @deprecated Identity is now carried by INITIALIZE_MESSAGE_BUS.\n */\n key?: { privateKey: string } | { publicKey: string } | {};\n arkServerUrl: string;\n arkServerPublicKey?: string;\n };\n};\nexport type ResponseInitWallet = ResponseEnvelope & {\n type: \"WALLET_INITIALIZED\";\n};\n\nexport type RequestSettle = RequestEnvelope & {\n type: \"SETTLE\";\n payload: { params?: SettleParams };\n};\nexport type ResponseSettle = ResponseEnvelope & {\n type: \"SETTLE_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestSendBitcoin = RequestEnvelope & {\n type: \"SEND_BITCOIN\";\n payload: SendBitcoinParams;\n};\nexport type ResponseSendBitcoin = ResponseEnvelope & {\n type: \"SEND_BITCOIN_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestGetAddress = RequestEnvelope & { type: \"GET_ADDRESS\" };\nexport type ResponseGetAddress = ResponseEnvelope & {\n type: \"ADDRESS\";\n payload: { address: string };\n};\n\nexport type RequestGetBoardingAddress = RequestEnvelope & {\n type: \"GET_BOARDING_ADDRESS\";\n};\nexport type ResponseGetBoardingAddress = ResponseEnvelope & {\n type: \"BOARDING_ADDRESS\";\n payload: { address: string };\n};\n\nexport type RequestGetBalance = RequestEnvelope & { type: \"GET_BALANCE\" };\nexport type ResponseGetBalance = ResponseEnvelope & {\n type: \"BALANCE\";\n payload: WalletBalance;\n};\n\nexport type RequestGetVtxos = RequestEnvelope & {\n type: \"GET_VTXOS\";\n payload: { filter?: GetVtxosFilter };\n};\nexport type ResponseGetVtxos = ResponseEnvelope & {\n type: \"VTXOS\";\n payload: { vtxos: Awaited<ReturnType<IWallet[\"getVtxos\"]>> };\n};\n\nexport type RequestGetBoardingUtxos = RequestEnvelope & {\n type: \"GET_BOARDING_UTXOS\";\n};\nexport type ResponseGetBoardingUtxos = ResponseEnvelope & {\n type: \"BOARDING_UTXOS\";\n payload: { utxos: ExtendedCoin[] };\n};\n\nexport type RequestGetTransactionHistory = RequestEnvelope & {\n type: \"GET_TRANSACTION_HISTORY\";\n};\nexport type ResponseGetTransactionHistory = ResponseEnvelope & {\n type: \"TRANSACTION_HISTORY\";\n payload: { transactions: ArkTransaction[] };\n};\n\nexport type RequestGetStatus = RequestEnvelope & { type: \"GET_STATUS\" };\nexport type ResponseGetStatus = ResponseEnvelope & {\n type: \"WALLET_STATUS\";\n payload: {\n walletInitialized: boolean;\n xOnlyPublicKey: Uint8Array | undefined;\n };\n};\n\nexport type RequestClear = RequestEnvelope & { type: \"CLEAR\" };\nexport type ResponseClear = ResponseEnvelope & {\n type: \"CLEAR_SUCCESS\";\n payload: { cleared: boolean };\n};\n\nexport type RequestSignTransaction = RequestEnvelope & {\n type: \"SIGN_TRANSACTION\";\n payload: { tx: Transaction; inputIndexes?: number[] };\n};\nexport type ResponseSignTransaction = ResponseEnvelope & {\n type: \"SIGN_TRANSACTION\";\n payload: { tx: Transaction };\n};\n\nexport type RequestReloadWallet = RequestEnvelope & { type: \"RELOAD_WALLET\" };\nexport type ResponseReloadWallet = ResponseEnvelope & {\n type: \"RELOAD_SUCCESS\";\n payload: { reloaded: boolean };\n};\n\nexport type RequestCreateContract = RequestEnvelope & {\n type: \"CREATE_CONTRACT\";\n payload: CreateContractParams;\n};\nexport type ResponseCreateContract = ResponseEnvelope & {\n type: \"CONTRACT_CREATED\";\n payload: { contract: Contract };\n};\n\nexport type RequestGetContracts = RequestEnvelope & {\n type: \"GET_CONTRACTS\";\n payload: { filter?: GetContractsFilter };\n};\nexport type ResponseGetContracts = ResponseEnvelope & {\n type: \"CONTRACTS\";\n payload: { contracts: Contract[] };\n};\n\nexport type RequestGetContractsWithVtxos = RequestEnvelope & {\n type: \"GET_CONTRACTS_WITH_VTXOS\";\n payload: { filter?: GetContractsFilter };\n};\nexport type ResponseGetContractsWithVtxos = ResponseEnvelope & {\n type: \"CONTRACTS_WITH_VTXOS\";\n payload: { contracts: ContractWithVtxos[] };\n};\n\nexport type RequestAnnotateVtxos = RequestEnvelope & {\n type: \"ANNOTATE_VTXOS\";\n payload: { vtxos: VirtualCoin[] };\n};\nexport type ResponseAnnotateVtxos = ResponseEnvelope & {\n type: \"ANNOTATED_VTXOS\";\n payload: { vtxos: ExtendedVirtualCoin[] };\n};\n\nexport type RequestUpdateContract = RequestEnvelope & {\n type: \"UPDATE_CONTRACT\";\n payload: {\n script: string;\n updates: Partial<Omit<Contract, \"id\" | \"createdAt\">>;\n };\n};\nexport type ResponseUpdateContract = ResponseEnvelope & {\n type: \"CONTRACT_UPDATED\";\n payload: { contract: Contract };\n};\n\nexport type RequestDeleteContract = RequestEnvelope & {\n type: \"DELETE_CONTRACT\";\n payload: { script: string };\n};\nexport type ResponseDeleteContract = ResponseEnvelope & {\n type: \"CONTRACT_DELETED\";\n payload: { deleted: boolean };\n};\n\nexport type RequestGetSpendablePaths = RequestEnvelope & {\n type: \"GET_SPENDABLE_PATHS\";\n payload: { options: GetSpendablePathsOptions };\n};\nexport type ResponseGetSpendablePaths = ResponseEnvelope & {\n type: \"SPENDABLE_PATHS\";\n payload: { paths: PathSelection[] };\n};\n\nexport type RequestIsContractManagerWatching = RequestEnvelope & {\n type: \"IS_CONTRACT_MANAGER_WATCHING\";\n};\nexport type ResponseIsContractManagerWatching = ResponseEnvelope & {\n type: \"CONTRACT_WATCHING\";\n payload: { isWatching: boolean };\n};\n\nexport type RequestRefreshVtxos = RequestEnvelope & {\n type: \"REFRESH_VTXOS\";\n payload?: {\n scripts?: string[];\n after?: number;\n before?: number;\n };\n};\nexport type ResponseRefreshVtxos = ResponseEnvelope & {\n type: \"REFRESH_VTXOS_SUCCESS\";\n};\n\nexport type RequestRefreshOutpoints = RequestEnvelope & {\n type: \"REFRESH_OUTPOINTS\";\n payload: {\n outpoints: { txid: string; vout: number }[];\n };\n};\nexport type ResponseRefreshOutpoints = ResponseEnvelope & {\n type: \"REFRESH_OUTPOINTS_SUCCESS\";\n};\n\nexport type RequestGetAllSpendingPaths = RequestEnvelope & {\n type: \"GET_ALL_SPENDING_PATHS\";\n payload: { options: GetAllSpendingPathsOptions };\n};\nexport type ResponseGetAllSpendingPaths = ResponseEnvelope & {\n type: \"ALL_SPENDING_PATHS\";\n payload: { paths: PathSelection[] };\n};\n\n// broadcast messages\nexport type ResponseSettleEvent = ResponseEnvelope & {\n broadcast: true;\n type: \"SETTLE_EVENT\";\n payload: SettlementEvent;\n};\nexport type ResponseRecoverVtxosEvent = ResponseEnvelope & {\n type: \"RECOVER_VTXOS_EVENT\";\n payload: SettlementEvent;\n};\nexport type ResponseRenewVtxosEvent = ResponseEnvelope & {\n type: \"RENEW_VTXOS_EVENT\";\n payload: SettlementEvent;\n};\nexport type ResponseUtxoUpdate = ResponseEnvelope & {\n broadcast: true;\n type: \"UTXO_UPDATE\";\n payload: { coins: ExtendedCoin[] };\n};\nexport type ResponseVtxoUpdate = ResponseEnvelope & {\n broadcast: true;\n type: \"VTXO_UPDATE\";\n payload: { newVtxos: ExtendedCoin[]; spentVtxos: ExtendedCoin[] };\n};\nexport type ResponseContractEvent = ResponseEnvelope & {\n tag: string;\n broadcast: true;\n type: \"CONTRACT_EVENT\";\n payload: { event: ContractEvent };\n};\n\n// Asset operations\nexport type RequestSend = RequestEnvelope & {\n type: \"SEND\";\n payload: { recipients: [Recipient, ...Recipient[]] };\n};\nexport type ResponseSend = ResponseEnvelope & {\n type: \"SEND_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestGetAssetDetails = RequestEnvelope & {\n type: \"GET_ASSET_DETAILS\";\n payload: { assetId: string };\n};\nexport type ResponseGetAssetDetails = ResponseEnvelope & {\n type: \"ASSET_DETAILS\";\n payload: { assetDetails: AssetDetails };\n};\n\nexport type RequestIssue = RequestEnvelope & {\n type: \"ISSUE\";\n payload: { params: IssuanceParams };\n};\nexport type ResponseIssue = ResponseEnvelope & {\n type: \"ISSUE_SUCCESS\";\n payload: { result: IssuanceResult };\n};\n\nexport type RequestReissue = RequestEnvelope & {\n type: \"REISSUE\";\n payload: { params: ReissuanceParams };\n};\nexport type ResponseReissue = ResponseEnvelope & {\n type: \"REISSUE_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestBurn = RequestEnvelope & {\n type: \"BURN\";\n payload: { params: BurnParams };\n};\nexport type ResponseBurn = ResponseEnvelope & {\n type: \"BURN_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestDelegate = RequestEnvelope & {\n type: \"DELEGATE\";\n payload: {\n vtxoOutpoints: { txid: string; vout: number }[];\n destination: string;\n delegateAt?: number;\n };\n};\nexport type ResponseDelegate = ResponseEnvelope & {\n type: \"DELEGATE_SUCCESS\";\n payload: {\n delegated: { txid: string; vout: number }[];\n failed: {\n outpoints: { txid: string; vout: number }[];\n error: string;\n }[];\n };\n};\n\nexport type RequestGetDelegateInfo = RequestEnvelope & {\n type: \"GET_DELEGATE_INFO\";\n};\nexport type ResponseGetDelegateInfo = ResponseEnvelope & {\n type: \"DELEGATE_INFO\";\n payload: { info: DelegateInfo };\n};\n\n// VtxoManager operations\nexport type RequestRecoverVtxos = RequestEnvelope & {\n type: \"RECOVER_VTXOS\";\n};\nexport type ResponseRecoverVtxos = ResponseEnvelope & {\n type: \"RECOVER_VTXOS_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestGetRecoverableBalance = RequestEnvelope & {\n type: \"GET_RECOVERABLE_BALANCE\";\n};\nexport type ResponseGetRecoverableBalance = ResponseEnvelope & {\n type: \"RECOVERABLE_BALANCE\";\n payload: {\n recoverable: string;\n subdust: string;\n includesSubdust: boolean;\n vtxoCount: number;\n };\n};\n\nexport type RequestGetExpiringVtxos = RequestEnvelope & {\n type: \"GET_EXPIRING_VTXOS\";\n payload: { thresholdMs?: number };\n};\nexport type ResponseGetExpiringVtxos = ResponseEnvelope & {\n type: \"EXPIRING_VTXOS\";\n payload: { vtxos: ExtendedVirtualCoin[] };\n};\n\nexport type RequestRenewVtxos = RequestEnvelope & {\n type: \"RENEW_VTXOS\";\n};\nexport type ResponseRenewVtxos = ResponseEnvelope & {\n type: \"RENEW_VTXOS_SUCCESS\";\n payload: { txid: string };\n};\n\nexport type RequestGetExpiredBoardingUtxos = RequestEnvelope & {\n type: \"GET_EXPIRED_BOARDING_UTXOS\";\n};\nexport type ResponseGetExpiredBoardingUtxos = ResponseEnvelope & {\n type: \"EXPIRED_BOARDING_UTXOS\";\n payload: { utxos: ExtendedCoin[] };\n};\n\nexport type RequestSweepExpiredBoardingUtxos = RequestEnvelope & {\n type: \"SWEEP_EXPIRED_BOARDING_UTXOS\";\n};\nexport type ResponseSweepExpiredBoardingUtxos = ResponseEnvelope & {\n type: \"SWEEP_EXPIRED_BOARDING_UTXOS_SUCCESS\";\n payload: { txid: string };\n};\n\n// WalletUpdater\nexport type WalletUpdaterRequest =\n | RequestInitWallet\n | RequestSettle\n | RequestSendBitcoin\n | RequestGetAddress\n | RequestGetBoardingAddress\n | RequestGetBalance\n | RequestGetVtxos\n | RequestGetBoardingUtxos\n | RequestGetTransactionHistory\n | RequestGetStatus\n | RequestClear\n | RequestReloadWallet\n | RequestSignTransaction\n | RequestCreateContract\n | RequestGetContracts\n | RequestGetContractsWithVtxos\n | RequestAnnotateVtxos\n | RequestUpdateContract\n | RequestDeleteContract\n | RequestGetSpendablePaths\n | RequestGetAllSpendingPaths\n | RequestIsContractManagerWatching\n | RequestRefreshVtxos\n | RequestRefreshOutpoints\n | RequestSend\n | RequestGetAssetDetails\n | RequestIssue\n | RequestReissue\n | RequestBurn\n | RequestDelegate\n | RequestGetDelegateInfo\n | RequestRecoverVtxos\n | RequestGetRecoverableBalance\n | RequestGetExpiringVtxos\n | RequestRenewVtxos\n | RequestGetExpiredBoardingUtxos\n | RequestSweepExpiredBoardingUtxos;\n\nexport type WalletUpdaterResponse = ResponseEnvelope &\n (\n | ResponseInitWallet\n | ResponseSettle\n | ResponseSettleEvent\n | ResponseSendBitcoin\n | ResponseGetAddress\n | ResponseGetBoardingAddress\n | ResponseGetBalance\n | ResponseGetVtxos\n | ResponseGetBoardingUtxos\n | ResponseGetTransactionHistory\n | ResponseGetStatus\n | ResponseClear\n | ResponseReloadWallet\n | ResponseUtxoUpdate\n | ResponseVtxoUpdate\n | ResponseSignTransaction\n | ResponseCreateContract\n | ResponseGetContracts\n | ResponseGetContractsWithVtxos\n | ResponseAnnotateVtxos\n | ResponseUpdateContract\n | ResponseDeleteContract\n | ResponseGetSpendablePaths\n | ResponseGetAllSpendingPaths\n | ResponseIsContractManagerWatching\n | ResponseRefreshVtxos\n | ResponseRefreshOutpoints\n | ResponseContractEvent\n | ResponseSend\n | ResponseGetAssetDetails\n | ResponseIssue\n | ResponseReissue\n | ResponseBurn\n | ResponseDelegate\n | ResponseGetDelegateInfo\n | ResponseRecoverVtxos\n | ResponseRecoverVtxosEvent\n | ResponseGetRecoverableBalance\n | ResponseGetExpiringVtxos\n | ResponseRenewVtxos\n | ResponseRenewVtxosEvent\n | ResponseGetExpiredBoardingUtxos\n | ResponseSweepExpiredBoardingUtxos\n );\n\nexport class WalletMessageHandler\n implements MessageHandler<WalletUpdaterRequest, WalletUpdaterResponse>\n{\n readonly messageTag: string;\n\n private wallet: Wallet | undefined;\n private readonlyWallet: ReadonlyWallet | undefined;\n\n private arkProvider: ArkProvider | undefined;\n private indexerProvider: IndexerProvider | undefined;\n private walletRepository: WalletRepository | undefined;\n\n private incomingFundsSubscription: (() => void) | undefined;\n private contractEventsSubscription: (() => void) | undefined;\n private onNextTick: (() => WalletUpdaterResponse | null)[] = [];\n\n /**\n * Instantiate a new WalletUpdater.\n * Can override the default `messageTag` allowing more than one updater to run in parallel.\n * Note that the default ServiceWorkerWallet sends messages to the default WalletUpdater tag.\n */\n constructor(options?: { messageTag?: string }) {\n this.messageTag = options?.messageTag ?? DEFAULT_MESSAGE_TAG;\n }\n\n // lifecycle methods\n async start(...params: Parameters<MessageHandler[\"start\"]>): Promise<void> {\n const [services, repositories] = params;\n this.readonlyWallet = services.readonlyWallet;\n this.wallet = services.wallet;\n this.arkProvider = services.arkProvider;\n this.walletRepository = repositories.walletRepository;\n }\n\n async stop() {\n if (this.incomingFundsSubscription) {\n this.incomingFundsSubscription();\n this.incomingFundsSubscription = undefined;\n }\n if (this.contractEventsSubscription) {\n this.contractEventsSubscription();\n this.contractEventsSubscription = undefined;\n }\n\n // Dispose the wallet to stop VtxoManager background tasks\n // (auto-renewal, boarding input polling) and ContractWatcher.\n try {\n if (this.wallet) {\n await this.wallet.dispose();\n } else if (this.readonlyWallet) {\n await this.readonlyWallet.dispose();\n }\n } catch (_) {\n // best-effort teardown\n }\n\n this.wallet = undefined;\n this.readonlyWallet = undefined;\n this.arkProvider = undefined;\n this.indexerProvider = undefined;\n }\n\n async tick(_now: number) {\n const results = await Promise.allSettled(this.onNextTick.map((fn) => fn()));\n this.onNextTick = [];\n return results\n .map((result) => {\n if (result.status === \"fulfilled\") {\n return result.value;\n } else {\n console.error(`[${this.messageTag}] tick failed`, result.reason);\n // TODO: how to deliver errors down the stream? a broadcast?\n return null;\n }\n })\n .filter((response) => response !== null);\n }\n\n private scheduleForNextTick(callback: () => WalletUpdaterResponse | null) {\n this.onNextTick.push(callback);\n }\n\n private requireWallet(): Wallet {\n if (!this.wallet) {\n throw new ReadonlyWalletError();\n }\n return this.wallet;\n }\n\n private tagged(res: Partial<WalletUpdaterResponse>): WalletUpdaterResponse {\n return {\n ...res,\n tag: this.messageTag,\n } as WalletUpdaterResponse;\n }\n\n // Flows that surrender control to the Ark server and the other participants\n // in a batch round: quiet gaps between protocol events can easily exceed\n // the bus-level messageTimeoutMs. Liveness is covered out-of-band by the\n // page-side PING / MESSAGE_BUS_NOT_INITIALIZED path triggered by concurrent\n // short requests (GET_STATUS, GET_BALANCE, ...).\n isLongRunning(message: WalletUpdaterRequest): boolean {\n return (\n message.type === \"SETTLE\" ||\n message.type === \"RECOVER_VTXOS\" ||\n message.type === \"RENEW_VTXOS\"\n );\n }\n\n async handleMessage(message: WalletUpdaterRequest): Promise<WalletUpdaterResponse> {\n const id = message.id;\n if (message.type === \"INIT_WALLET\") {\n await this.handleInitWallet(message);\n return this.tagged({\n id,\n type: \"WALLET_INITIALIZED\",\n });\n }\n if (!this.readonlyWallet) {\n return this.tagged({\n id,\n error: new WalletNotInitializedError(),\n });\n }\n try {\n switch (message.type) {\n case \"SETTLE\": {\n const response = await this.handleSettle(message);\n return this.tagged({\n id,\n ...response,\n });\n }\n\n case \"SEND_BITCOIN\": {\n const response = await this.handleSendBitcoin(message);\n return this.tagged({\n id,\n ...response,\n });\n }\n case \"GET_ADDRESS\": {\n const address = await this.readonlyWallet.getAddress();\n return this.tagged({\n id,\n type: \"ADDRESS\",\n payload: { address },\n });\n }\n case \"GET_BOARDING_ADDRESS\": {\n const address = await this.readonlyWallet.getBoardingAddress();\n return this.tagged({\n id,\n type: \"BOARDING_ADDRESS\",\n payload: { address },\n });\n }\n case \"GET_BALANCE\": {\n const balance = await this.handleGetBalance();\n return this.tagged({\n id,\n type: \"BALANCE\",\n payload: balance,\n });\n }\n case \"GET_VTXOS\": {\n const vtxos = await this.handleGetVtxos(message);\n return {\n tag: this.messageTag,\n id,\n type: \"VTXOS\",\n payload: { vtxos },\n };\n }\n case \"GET_BOARDING_UTXOS\": {\n const utxos = await this.getAllBoardingUtxos();\n return this.tagged({\n id,\n type: \"BOARDING_UTXOS\",\n payload: { utxos },\n });\n }\n case \"GET_TRANSACTION_HISTORY\": {\n const allVtxos = await this.getVtxosFromRepo();\n const transactions =\n (await this.buildTransactionHistoryFromCache(allVtxos)) ?? [];\n return this.tagged({\n id,\n type: \"TRANSACTION_HISTORY\",\n payload: { transactions },\n });\n }\n case \"GET_STATUS\": {\n const pubKey = await this.readonlyWallet.identity.xOnlyPublicKey();\n return this.tagged({\n id,\n type: \"WALLET_STATUS\",\n payload: {\n walletInitialized: true,\n xOnlyPublicKey: pubKey,\n },\n });\n }\n case \"CLEAR\": {\n await this.clear();\n return this.tagged({\n id,\n type: \"CLEAR_SUCCESS\",\n payload: { cleared: true },\n });\n }\n case \"RELOAD_WALLET\": {\n await this.reloadWallet();\n return this.tagged({\n id,\n type: \"RELOAD_SUCCESS\",\n payload: { reloaded: true },\n });\n }\n case \"SIGN_TRANSACTION\": {\n const response = await this.handleSignTransaction(message);\n return this.tagged({\n id,\n ...response,\n });\n }\n case \"CREATE_CONTRACT\": {\n const manager = await this.readonlyWallet.getContractManager();\n const contract = await manager.createContract(message.payload);\n return this.tagged({\n id,\n type: \"CONTRACT_CREATED\",\n payload: { contract },\n });\n }\n case \"GET_CONTRACTS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const contracts = await manager.getContracts(message.payload.filter);\n return this.tagged({\n id,\n type: \"CONTRACTS\",\n payload: { contracts },\n });\n }\n case \"GET_CONTRACTS_WITH_VTXOS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const contracts = await manager.getContractsWithVtxos(message.payload.filter);\n return this.tagged({\n id,\n type: \"CONTRACTS_WITH_VTXOS\",\n payload: { contracts },\n });\n }\n case \"ANNOTATE_VTXOS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const annotated = await manager.annotateVtxos(message.payload.vtxos);\n return this.tagged({\n id,\n type: \"ANNOTATED_VTXOS\",\n payload: { vtxos: annotated },\n });\n }\n case \"UPDATE_CONTRACT\": {\n const manager = await this.readonlyWallet.getContractManager();\n const contract = await manager.updateContract(\n message.payload.script,\n message.payload.updates,\n );\n return this.tagged({\n id,\n type: \"CONTRACT_UPDATED\",\n payload: { contract },\n });\n }\n case \"DELETE_CONTRACT\": {\n const manager = await this.readonlyWallet.getContractManager();\n await manager.deleteContract(message.payload.script);\n return this.tagged({\n id,\n type: \"CONTRACT_DELETED\",\n payload: { deleted: true },\n });\n }\n case \"GET_SPENDABLE_PATHS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const paths = await manager.getSpendablePaths(message.payload.options);\n return this.tagged({\n id,\n type: \"SPENDABLE_PATHS\",\n payload: { paths },\n });\n }\n case \"GET_ALL_SPENDING_PATHS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const paths = await manager.getAllSpendingPaths(message.payload.options);\n return this.tagged({\n id,\n type: \"ALL_SPENDING_PATHS\",\n payload: { paths },\n });\n }\n case \"IS_CONTRACT_MANAGER_WATCHING\": {\n const manager = await this.readonlyWallet.getContractManager();\n const isWatching = await manager.isWatching();\n return this.tagged({\n id,\n type: \"CONTRACT_WATCHING\",\n payload: { isWatching },\n });\n }\n case \"REFRESH_VTXOS\": {\n const manager = await this.readonlyWallet.getContractManager();\n await manager.refreshVtxos((message as RequestRefreshVtxos).payload);\n return this.tagged({\n id,\n type: \"REFRESH_VTXOS_SUCCESS\",\n });\n }\n case \"REFRESH_OUTPOINTS\": {\n const manager = await this.readonlyWallet.getContractManager();\n const { outpoints } = (message as RequestRefreshOutpoints).payload;\n await manager.refreshOutpoints(outpoints);\n return this.tagged({\n id,\n type: \"REFRESH_OUTPOINTS_SUCCESS\",\n });\n }\n case \"SEND\": {\n const { recipients } = (message as RequestSend).payload;\n const txid = await (this.wallet as IWallet).send(...recipients);\n return this.tagged({\n id,\n type: \"SEND_SUCCESS\",\n payload: { txid },\n });\n }\n case \"GET_ASSET_DETAILS\": {\n const { assetId } = (message as RequestGetAssetDetails).payload;\n const assetDetails =\n await this.readonlyWallet.assetManager.getAssetDetails(assetId);\n return this.tagged({\n id,\n type: \"ASSET_DETAILS\",\n payload: { assetDetails },\n });\n }\n case \"ISSUE\": {\n const { params } = (message as RequestIssue).payload;\n const result = await (this.wallet as IWallet).assetManager.issue(params);\n return this.tagged({\n id,\n type: \"ISSUE_SUCCESS\",\n payload: { result },\n });\n }\n case \"REISSUE\": {\n const { params } = (message as RequestReissue).payload;\n const txid = await (this.wallet as IWallet).assetManager.reissue(params);\n return this.tagged({\n id,\n type: \"REISSUE_SUCCESS\",\n payload: { txid },\n });\n }\n case \"BURN\": {\n const { params } = (message as RequestBurn).payload;\n const txid = await (this.wallet as IWallet).assetManager.burn(params);\n return this.tagged({\n id,\n type: \"BURN_SUCCESS\",\n payload: { txid },\n });\n }\n case \"DELEGATE\": {\n const response = await this.handleDelegate(message as RequestDelegate);\n return this.tagged({ id, ...response });\n }\n case \"GET_DELEGATE_INFO\": {\n const wallet = this.requireWallet();\n const delegatorManager = await wallet.getDelegatorManager();\n if (!delegatorManager) {\n throw new DelegatorNotConfiguredError();\n }\n const info = await delegatorManager.getDelegateInfo();\n return this.tagged({\n id,\n type: \"DELEGATE_INFO\",\n payload: { info },\n });\n }\n case \"RECOVER_VTXOS\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const txid = await vtxoManager.recoverVtxos((e) => {\n this.scheduleForNextTick(() =>\n this.tagged({\n id,\n type: \"RECOVER_VTXOS_EVENT\",\n payload: e,\n }),\n );\n });\n return this.tagged({\n id,\n type: \"RECOVER_VTXOS_SUCCESS\",\n payload: { txid },\n });\n }\n case \"GET_RECOVERABLE_BALANCE\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const balance = await vtxoManager.getRecoverableBalance();\n return this.tagged({\n id,\n type: \"RECOVERABLE_BALANCE\",\n payload: {\n recoverable: balance.recoverable.toString(),\n subdust: balance.subdust.toString(),\n includesSubdust: balance.includesSubdust,\n vtxoCount: balance.vtxoCount,\n },\n });\n }\n case \"GET_EXPIRING_VTXOS\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const vtxos = await vtxoManager.getExpiringVtxos(\n (message as RequestGetExpiringVtxos).payload.thresholdMs,\n );\n return this.tagged({\n id,\n type: \"EXPIRING_VTXOS\",\n payload: { vtxos },\n });\n }\n case \"RENEW_VTXOS\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const txid = await vtxoManager.renewVtxos((e) => {\n this.scheduleForNextTick(() =>\n this.tagged({\n id,\n type: \"RENEW_VTXOS_EVENT\",\n payload: e,\n }),\n );\n });\n return this.tagged({\n id,\n type: \"RENEW_VTXOS_SUCCESS\",\n payload: { txid },\n });\n }\n case \"GET_EXPIRED_BOARDING_UTXOS\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const utxos = await vtxoManager.getExpiredBoardingUtxos();\n return this.tagged({\n id,\n type: \"EXPIRED_BOARDING_UTXOS\",\n payload: { utxos },\n });\n }\n case \"SWEEP_EXPIRED_BOARDING_UTXOS\": {\n const wallet = this.requireWallet();\n const vtxoManager = await wallet.getVtxoManager();\n const txid = await vtxoManager.sweepExpiredBoardingUtxos();\n return this.tagged({\n id,\n type: \"SWEEP_EXPIRED_BOARDING_UTXOS_SUCCESS\",\n payload: { txid },\n });\n }\n default:\n console.error(\"Unknown message type\", message);\n throw new Error(\"Unknown message\");\n }\n } catch (error: unknown) {\n return this.tagged({ id, error: error as Error });\n }\n }\n\n // Wallet methods\n private async handleInitWallet({ payload }: RequestInitWallet) {\n const { arkServerUrl } = payload;\n this.indexerProvider = new RestIndexerProvider(arkServerUrl);\n await this.onWalletInitialized();\n }\n\n private async handleGetBalance() {\n const [boardingUtxos, allVtxos] = await Promise.all([\n this.getAllBoardingUtxos(),\n this.getVtxosFromRepo(),\n ]);\n\n // boarding\n let confirmed = 0;\n let unconfirmed = 0;\n for (const utxo of boardingUtxos) {\n if (utxo.status.confirmed) {\n confirmed += utxo.value;\n } else {\n unconfirmed += utxo.value;\n }\n }\n\n // offchain — split spendable vs swept from single repo read\n const spendableVtxos = allVtxos.filter(isSpendable);\n const sweptVtxos = allVtxos.filter((vtxo) => vtxo.virtualStatus.state === \"swept\");\n\n let settled = 0;\n let preconfirmed = 0;\n let recoverable = 0;\n for (const vtxo of spendableVtxos) {\n if (vtxo.virtualStatus.state === \"settled\") {\n settled += vtxo.value;\n } else if (vtxo.virtualStatus.state === \"preconfirmed\") {\n preconfirmed += vtxo.value;\n }\n }\n for (const vtxo of sweptVtxos) {\n if (isSpendable(vtxo)) {\n recoverable += vtxo.value;\n }\n }\n\n const totalBoarding = confirmed + unconfirmed;\n const totalOffchain = settled + preconfirmed + recoverable;\n\n // aggregate asset balances from spendable virtual outputs\n const assetBalances = new Map<string, bigint>();\n for (const vtxo of spendableVtxos) {\n if (vtxo.assets) {\n for (const a of vtxo.assets) {\n const current = assetBalances.get(a.assetId) ?? 0n;\n assetBalances.set(a.assetId, current + a.amount);\n }\n }\n }\n const assets = Array.from(assetBalances.entries()).map(([assetId, amount]) => ({\n assetId,\n amount,\n }));\n\n return {\n boarding: {\n confirmed,\n unconfirmed,\n total: totalBoarding,\n },\n settled,\n preconfirmed,\n available: settled + preconfirmed,\n recoverable,\n total: totalBoarding + totalOffchain,\n assets,\n };\n }\n private async getAllBoardingUtxos(): Promise<ExtendedCoin[]> {\n if (!this.readonlyWallet) return [];\n return this.readonlyWallet.getBoardingUtxos();\n }\n /**\n * Get spendable vtxos from the repository\n */\n private async getSpendableVtxos() {\n const vtxos = await this.getVtxosFromRepo();\n return vtxos.filter(isSpendable);\n }\n\n private async onWalletInitialized() {\n if (\n !this.readonlyWallet ||\n !this.arkProvider ||\n !this.indexerProvider ||\n !this.walletRepository\n ) {\n return;\n }\n\n // Initialize contract manager FIRST — this populates the repository\n // with full virtual output history for all contracts (one indexer call per contract)\n await this.ensureContractEventBroadcasting();\n\n // Refresh cached data (virtual outputs, boarding inputs, tx history)\n await this.refreshCachedData();\n\n // Recover pending transactions (init-only, not on reload).\n // Pending txs only exist if a send was interrupted mid-finalization.\n if (this.wallet) {\n try {\n const vtxos = await this.getVtxosFromRepo();\n const { pending, finalized } = await this.wallet.finalizePendingTxs(\n vtxos.filter(\n (vtxo) =>\n vtxo.virtualStatus.state !== \"swept\" &&\n vtxo.virtualStatus.state !== \"settled\",\n ),\n );\n console.info(\n `Recovered ${finalized.length}/${pending.length} pending transactions: ${finalized.join(\", \")}`,\n );\n } catch (error: unknown) {\n console.error(\"Error recovering pending transactions:\", error);\n }\n }\n\n // unsubscribe previous subscription if any\n if (this.incomingFundsSubscription) this.incomingFundsSubscription();\n\n const address = await this.readonlyWallet.getAddress();\n\n // subscribe for incoming funds and notify all clients when new funds arrive\n this.incomingFundsSubscription = await this.readonlyWallet.notifyIncomingFunds(\n async (funds) => {\n if (funds.type === \"vtxo\") {\n // `funds.newVtxos` / `funds.spentVtxos` are already\n // ExtendedVirtualCoin — annotation happened inside the\n // underlying Wallet's subscription handler before this\n // callback fired. Re-annotating here would only duplicate\n // work and re-expose us to `annotateVtxos` throws.\n const { newVtxos, spentVtxos } = funds;\n\n if (newVtxos.length + spentVtxos.length === 0) return;\n\n // Save virtual outputs using unified repository. The\n // event may carry rows for several scripts (other\n // contracts the wallet watches), so split by script and\n // save each bucket under its own contract address rather\n // than saving a mixed-script array under one address.\n const byScript = new Map<string, ExtendedVirtualCoin[]>();\n for (const v of [...newVtxos, ...spentVtxos]) {\n if (!v.script) {\n // Without a script we can't route the row to the\n // right contract bucket; surface the drop instead\n // of silently losing the VTXO.\n console.warn(\n `WalletMessageHandler.notifyIncomingFunds: dropping VTXO without script ${v.txid}:${v.vout}`,\n );\n continue;\n }\n const arr = byScript.get(v.script) ?? [];\n arr.push(v);\n byScript.set(v.script, arr);\n }\n let walletScript: string | undefined;\n try {\n walletScript = scriptFromArkAddress(address);\n } catch {\n walletScript = undefined;\n }\n const cm = await this.readonlyWallet!.getContractManager();\n const contracts = await cm.getContracts();\n const addrByScript = new Map(contracts.map((c) => [c.script, c.address]));\n for (const [script, vtxos] of byScript) {\n const filtered = warnAndFilterVtxosForScript(\n vtxos,\n script,\n \"WalletMessageHandler.notifyIncomingFunds\",\n );\n if (filtered.length === 0) continue;\n const targetAddress =\n script === walletScript ? address : addrByScript.get(script);\n if (!targetAddress) continue;\n if (this.walletRepository) {\n await saveVtxosForContract(\n this.walletRepository,\n { script, address: targetAddress },\n filtered,\n );\n }\n }\n\n // notify all clients about the virtual output state update\n this.scheduleForNextTick(() =>\n this.tagged({\n type: \"VTXO_UPDATE\",\n broadcast: true,\n payload: { newVtxos, spentVtxos },\n }),\n );\n }\n if (funds.type === \"utxo\") {\n const utxos = funds.coins.map((utxo) => extendCoin(this.readonlyWallet!, utxo));\n const boardingAddress = await this.readonlyWallet!.getBoardingAddress();\n // save boarding inputs using unified repository\n // TODO: remove UTXOs by address\n // await this.walletRepository.clearUtxos(boardingAddress);\n await this.walletRepository?.saveUtxos(boardingAddress, utxos);\n\n // notify all clients about the boarding input state update\n this.scheduleForNextTick(() =>\n this.tagged({\n type: \"UTXO_UPDATE\",\n broadcast: true,\n payload: { coins: utxos },\n }),\n );\n }\n },\n );\n\n // Eagerly start the VtxoManager so its background tasks (auto-renewal,\n // boarding input polling/sweep) run inside the service worker without\n // waiting for a client to send a VtxoManager message first.\n if (this.wallet) {\n try {\n await this.wallet.getVtxoManager();\n } catch (error) {\n console.error(\"Error starting VtxoManager:\", error);\n }\n }\n }\n\n /**\n * Refresh virtual outputs, boarding inputs, and transaction history from cache.\n * Shared by onWalletInitialized (full bootstrap) and reloadWallet\n * (post-refresh), avoiding duplicate subscriptions and VtxoManager restarts.\n */\n private async refreshCachedData() {\n if (!this.readonlyWallet || !this.walletRepository) {\n return;\n }\n\n // Read virtual outputs from repository (now populated by contract manager)\n const vtxos = await this.getVtxosFromRepo();\n\n // Fetch boarding inputs and save using unified repository\n const boardingAddress = await this.readonlyWallet.getBoardingAddress();\n const coins = await this.readonlyWallet.onchainProvider.getCoins(boardingAddress);\n await this.walletRepository.deleteUtxos(boardingAddress);\n await this.walletRepository.saveUtxos(\n boardingAddress,\n coins.map((utxo) => extendCoin(this.readonlyWallet!, utxo)),\n );\n\n // Build transaction history from cached virtual outputs (no indexer call)\n const address = await this.readonlyWallet.getAddress();\n const txs = await this.buildTransactionHistoryFromCache(vtxos);\n if (txs) await this.walletRepository.saveTransactions(address, txs);\n }\n\n /**\n * Force a full VTXO refresh from the indexer, then refresh cached data.\n * Used by RELOAD_WALLET to ensure fresh data without re-subscribing\n * to incoming funds or restarting the VtxoManager.\n */\n private async reloadWallet() {\n if (!this.readonlyWallet) return;\n const manager = await this.readonlyWallet.getContractManager();\n await manager.refreshVtxos();\n await this.refreshCachedData();\n }\n\n private async handleSettle(message: RequestSettle) {\n const wallet = this.requireWallet();\n const txid = await wallet.settle(message.payload.params, (e) => {\n this.scheduleForNextTick(() =>\n this.tagged({\n id: message.id,\n type: \"SETTLE_EVENT\",\n payload: e,\n }),\n );\n });\n\n if (!txid) {\n throw new Error(\"Settlement failed\");\n }\n return { type: \"SETTLE_SUCCESS\", payload: { txid } } as ResponseSettle;\n }\n\n private async handleSendBitcoin(message: RequestSendBitcoin) {\n const wallet = this.requireWallet();\n const txid = await wallet.sendBitcoin(message.payload);\n if (!txid) {\n throw new Error(\"Send bitcoin failed\");\n }\n return {\n type: \"SEND_BITCOIN_SUCCESS\",\n payload: { txid },\n } as ResponseSendBitcoin;\n }\n\n private async handleSignTransaction(message: RequestSignTransaction) {\n const wallet = this.requireWallet();\n const { tx, inputIndexes } = message.payload;\n const signature = await wallet.identity.sign(tx, inputIndexes);\n if (!signature) {\n throw new Error(\"Sign transaction failed\");\n }\n return {\n type: \"SIGN_TRANSACTION\",\n payload: { tx: signature },\n } as ResponseSignTransaction;\n }\n\n private async handleDelegate(message: RequestDelegate): Promise<ResponseDelegate> {\n const wallet = this.requireWallet();\n const delegatorManager = await wallet.getDelegatorManager();\n if (!delegatorManager) {\n throw new DelegatorNotConfiguredError();\n }\n\n const { vtxoOutpoints, destination, delegateAt } = message.payload;\n const allVtxos = await wallet.getVtxos();\n const outpointSet = new Set(vtxoOutpoints.map((o) => `${o.txid}:${o.vout}`));\n const filtered = allVtxos\n .filter((v) => outpointSet.has(`${v.txid}:${v.vout}`))\n .map((v) => ({ ...v, contractScript: v.script }));\n\n const result = await delegatorManager.delegate(\n filtered,\n destination,\n delegateAt !== undefined ? new Date(delegateAt) : undefined,\n );\n\n return {\n tag: this.messageTag,\n type: \"DELEGATE_SUCCESS\",\n payload: {\n delegated: result.delegated.map((o) => ({\n txid: o.txid,\n vout: o.vout,\n })),\n failed: result.failed.map((f) => ({\n outpoints: f.outpoints.map((o) => ({\n txid: o.txid,\n vout: o.vout,\n })),\n error: String(f.error),\n })),\n },\n };\n }\n\n private async handleGetVtxos(message: RequestGetVtxos) {\n if (!this.readonlyWallet) {\n throw new WalletNotInitializedError();\n }\n const vtxos = await this.getSpendableVtxos();\n const dustAmount = this.readonlyWallet.dustAmount;\n const includeRecoverable = message.payload.filter?.withRecoverable ?? false;\n const filteredVtxos = includeRecoverable\n ? vtxos\n : vtxos.filter((v) => {\n if (dustAmount != null && isSubdust(v, dustAmount)) {\n return false;\n }\n if (isRecoverable(v)) {\n return false;\n }\n if (isExpired(v)) {\n return false;\n }\n return true;\n });\n\n return filteredVtxos;\n }\n\n private async clear() {\n if (!this.readonlyWallet) return;\n if (this.incomingFundsSubscription) this.incomingFundsSubscription();\n if (this.contractEventsSubscription) {\n this.contractEventsSubscription();\n this.contractEventsSubscription = undefined;\n }\n\n // Dispose the wallet to stop the ContractWatcher (and its polling\n // intervals) before clearing the repositories, otherwise the poller\n // will hit a closing IndexedDB connection.\n try {\n if (this.wallet) {\n await this.wallet.dispose();\n } else {\n await this.readonlyWallet.dispose();\n }\n } catch (_) {\n // best-effort teardown\n }\n\n try {\n await this.walletRepository?.clear();\n } catch (_) {\n console.warn(\"Failed to clear vtxos from wallet repository\");\n }\n\n this.wallet = undefined;\n this.readonlyWallet = undefined;\n this.arkProvider = undefined;\n this.indexerProvider = undefined;\n }\n\n /**\n * Read all virtual outputs from the repository, aggregated across all contract\n * addresses and the wallet's primary address, with deduplication.\n */\n private async getVtxosFromRepo(): Promise<ExtendedVirtualCoin[]> {\n if (!this.walletRepository || !this.readonlyWallet) return [];\n const seen = new Set<string>();\n const allVtxos: ExtendedVirtualCoin[] = [];\n\n const addVtxos = (vtxos: ExtendedVirtualCoin[]) => {\n for (const vtxo of vtxos) {\n const key = `${vtxo.txid}:${vtxo.vout}`;\n if (!seen.has(key)) {\n seen.add(key);\n allVtxos.push(vtxo);\n }\n }\n };\n\n // Aggregate virtual outputs from all contract addresses. Address\n // buckets may carry legacy duplicate rows from other contracts; gate\n // each bucket by its owning contract script before deduplication so a\n // wrong-script row never wins the txid:vout race.\n const manager = await this.readonlyWallet.getContractManager();\n const contracts = await manager.getContracts();\n for (const contract of contracts) {\n addVtxos(await getVtxosForContract(this.walletRepository, contract));\n }\n\n // Also check the wallet's primary address. Decode it to its script\n // and apply the same script gate. Failing to decode the wallet's own\n // address is a structural bug — surfacing the error is safer than\n // silently dropping the primary bucket and zeroing the user's\n // visible balance.\n const walletAddress = await this.readonlyWallet.getAddress();\n let walletScript: string;\n try {\n walletScript = scriptFromArkAddress(walletAddress);\n } catch (e) {\n throw new Error(\n `WalletMessageHandler.getVtxosFromRepo: failed to derive script from wallet address ${walletAddress}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const walletVtxos = await this.walletRepository.getVtxos(walletAddress);\n addVtxos(filterVtxosForScript(walletVtxos, walletScript));\n\n return allVtxos;\n }\n\n /**\n * Build transaction history from cached virtual outputs without hitting the indexer.\n * Falls back to indexer only for uncached transaction timestamps.\n */\n private async buildTransactionHistoryFromCache(\n vtxos: ExtendedVirtualCoin[],\n ): Promise<ArkTransaction[] | null> {\n if (!this.readonlyWallet) return null;\n\n const { boardingTxs, commitmentsToIgnore } = await this.readonlyWallet.getBoardingTxs();\n\n // Build a lookup for cached virtual output timestamps, keyed by txid.\n // Multiple virtual outputs can share a txid (different vouts) — we keep the\n // earliest createdAt so the history ordering is stable.\n const vtxoCreatedAt = new Map<string, number>();\n for (const vtxo of vtxos) {\n const existing = vtxoCreatedAt.get(vtxo.txid);\n const ts = vtxo.createdAt.getTime();\n if (existing === undefined || ts < existing) {\n vtxoCreatedAt.set(vtxo.txid, ts);\n }\n }\n\n // Pre-fetch uncached timestamps in a single batched indexer call.\n // buildTransactionHistory needs these for spent-offchain virtual outputs with\n // no change outputs (i.e. arkTxId is set but no virtual output has txid === arkTxId).\n if (this.indexerProvider) {\n const uncachedTxids = new Set<string>();\n for (const vtxo of vtxos) {\n if (\n vtxo.isSpent &&\n vtxo.arkTxId &&\n !vtxoCreatedAt.has(vtxo.arkTxId) &&\n !vtxos.some((v) => v.txid === vtxo.arkTxId)\n ) {\n uncachedTxids.add(vtxo.arkTxId);\n }\n }\n\n if (uncachedTxids.size > 0) {\n const outpoints = [...uncachedTxids].map((txid) => ({\n txid,\n vout: 0,\n }));\n const BATCH_SIZE = 100;\n for (let i = 0; i < outpoints.length; i += BATCH_SIZE) {\n const res = await this.indexerProvider.getVtxos({\n outpoints: outpoints.slice(i, i + BATCH_SIZE),\n });\n for (const v of res.vtxos) {\n vtxoCreatedAt.set(v.txid, v.createdAt.getTime());\n }\n }\n }\n }\n\n const getTxCreatedAt = async (txid: string): Promise<number | undefined> => {\n return vtxoCreatedAt.get(txid);\n };\n\n return buildTransactionHistory(vtxos, boardingTxs, commitmentsToIgnore, getTxCreatedAt);\n }\n\n private async ensureContractEventBroadcasting() {\n if (!this.readonlyWallet) return;\n if (this.contractEventsSubscription) return;\n try {\n const manager = await this.readonlyWallet.getContractManager();\n this.contractEventsSubscription = manager.onContractEvent((event) => {\n this.scheduleForNextTick(() =>\n this.tagged({\n type: \"CONTRACT_EVENT\",\n broadcast: true,\n payload: { event },\n }),\n );\n });\n } catch (error) {\n console.error(\"Error subscribing to contract events:\", error);\n }\n }\n}\n","import {\n IWallet,\n WalletBalance,\n SendBitcoinParams,\n SettleParams,\n ArkTransaction,\n ExtendedCoin,\n ExtendedVirtualCoin,\n GetVtxosFilter,\n StorageConfig,\n IReadonlyWallet,\n IReadonlyAssetManager,\n IAssetManager,\n AssetDetails,\n IssuanceParams,\n IssuanceResult,\n ReissuanceParams,\n BurnParams,\n Recipient,\n DEFAULT_ARKADE_SERVER_URL,\n} from \"..\";\nimport { SettlementEvent } from \"../../providers/ark\";\nimport { hex } from \"@scure/base\";\nimport {\n Identity,\n ReadonlyIdentity,\n type SerializedIdentity,\n type LegacySerializedIdentity,\n serializeReadonlyIdentity,\n serializeSigningIdentity,\n} from \"../../identity\";\nimport { WalletRepository } from \"../../repositories/walletRepository\";\nimport { ContractRepository } from \"../../repositories/contractRepository\";\nimport { setupServiceWorker } from \"../../worker/browser/utils\";\nimport { IndexedDBContractRepository, IndexedDBWalletRepository } from \"../../repositories\";\nimport {\n RequestClear,\n RequestCreateContract,\n RequestDeleteContract,\n RequestGetAddress,\n RequestGetBalance,\n RequestGetBoardingAddress,\n RequestGetBoardingUtxos,\n RequestAnnotateVtxos,\n RequestGetContracts,\n RequestGetContractsWithVtxos,\n RequestGetStatus,\n RequestGetSpendablePaths,\n RequestGetTransactionHistory,\n RequestGetVtxos,\n RequestInitWallet,\n RequestIsContractManagerWatching,\n RequestRefreshVtxos,\n RequestRefreshOutpoints,\n RequestReloadWallet,\n RequestSendBitcoin,\n RequestSettle,\n ResponseSettle,\n ResponseSettleEvent,\n RequestUpdateContract,\n ResponseAnnotateVtxos,\n ResponseGetAddress,\n ResponseGetBalance,\n ResponseGetBoardingAddress,\n ResponseGetBoardingUtxos,\n ResponseGetContracts,\n ResponseGetContractsWithVtxos,\n ResponseGetStatus,\n ResponseGetSpendablePaths,\n ResponseGetTransactionHistory,\n ResponseGetVtxos,\n ResponseIsContractManagerWatching,\n ResponseReloadWallet,\n ResponseSendBitcoin,\n ResponseUpdateContract,\n ResponseCreateContract,\n ResponseContractEvent,\n WalletUpdaterRequest,\n WalletUpdaterResponse,\n RequestGetAllSpendingPaths,\n ResponseGetAllSpendingPaths,\n RequestSend,\n ResponseSend,\n RequestGetAssetDetails,\n ResponseGetAssetDetails,\n RequestIssue,\n ResponseIssue,\n RequestReissue,\n ResponseReissue,\n RequestBurn,\n ResponseBurn,\n RequestDelegate,\n ResponseDelegate,\n RequestGetDelegateInfo,\n ResponseGetDelegateInfo,\n RequestRecoverVtxos,\n ResponseRecoverVtxos,\n ResponseRecoverVtxosEvent,\n RequestGetRecoverableBalance,\n ResponseGetRecoverableBalance,\n RequestGetExpiringVtxos,\n ResponseGetExpiringVtxos,\n RequestRenewVtxos,\n ResponseRenewVtxos,\n ResponseRenewVtxosEvent,\n RequestGetExpiredBoardingUtxos,\n ResponseGetExpiredBoardingUtxos,\n RequestSweepExpiredBoardingUtxos,\n ResponseSweepExpiredBoardingUtxos,\n DEFAULT_MESSAGE_TAG,\n} from \"./wallet-message-handler\";\nimport type {\n Contract,\n ContractEventCallback,\n ContractWithVtxos,\n GetContractsFilter,\n PathSelection,\n} from \"../../contracts\";\nimport type {\n CreateContractParams,\n GetAllSpendingPathsOptions,\n GetSpendablePathsOptions,\n IContractManager,\n RefreshVtxosOptions,\n ScanResult,\n} from \"../../contracts/contractManager\";\nimport type { ContractState } from \"../../contracts/types\";\nimport type { IDelegatorManager } from \"../delegator\";\nimport type { IVtxoManager, SettlementConfig } from \"../vtxo-manager\";\nimport type { ContractWatcherConfig } from \"../../contracts/contractWatcher\";\nimport type { DelegateInfo } from \"../../providers/delegator\";\nimport { getRandomId } from \"../utils\";\nimport type { VirtualCoin } from \"..\";\nimport { MESSAGE_BUS_NOT_INITIALIZED, ServiceWorkerTimeoutError } from \"../../worker/errors\";\nimport { getArkadeServerUrl } from \"../wallet\";\n\n// Check by error message content instead of instanceof because postMessage uses the\n// structured clone algorithm which strips the prototype chain — the page\n// receives a plain Error, not the original MessageBusNotInitializedError.\nfunction isMessageBusNotInitializedError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(MESSAGE_BUS_NOT_INITIALIZED);\n}\n\ntype RequestType = WalletUpdaterRequest[\"type\"];\n\nexport type MessageTimeouts = Partial<Record<RequestType, number>>;\n\nexport type ServiceWorkerWalletMode = \"auto\" | \"static\" | \"hd\";\n\nexport const DEFAULT_MESSAGE_TIMEOUTS: Readonly<Record<RequestType, number>> = {\n // Fast reads — fail quickly\n GET_ADDRESS: 10_000,\n GET_BALANCE: 10_000,\n GET_BOARDING_ADDRESS: 10_000,\n GET_STATUS: 10_000,\n GET_DELEGATE_INFO: 10_000,\n IS_CONTRACT_MANAGER_WATCHING: 10_000,\n\n // Medium reads — may involve indexer queries\n GET_VTXOS: 20_000,\n GET_BOARDING_UTXOS: 20_000,\n GET_TRANSACTION_HISTORY: 20_000,\n GET_CONTRACTS: 20_000,\n GET_CONTRACTS_WITH_VTXOS: 20_000,\n ANNOTATE_VTXOS: 20_000,\n GET_SPENDABLE_PATHS: 20_000,\n GET_ALL_SPENDING_PATHS: 20_000,\n GET_ASSET_DETAILS: 20_000,\n GET_EXPIRING_VTXOS: 20_000,\n GET_EXPIRED_BOARDING_UTXOS: 20_000,\n GET_RECOVERABLE_BALANCE: 20_000,\n RELOAD_WALLET: 20_000,\n\n // Transactions — need more headroom.\n // SETTLE / RECOVER_VTXOS / RENEW_VTXOS go through the streaming path and\n // are treated as long-running on both sides of the bus: the values below\n // are retained only for type completeness and are never enforced.\n SEND_BITCOIN: 50_000,\n SEND: 50_000,\n SETTLE: 50_000,\n ISSUE: 50_000,\n REISSUE: 50_000,\n BURN: 50_000,\n DELEGATE: 50_000,\n RECOVER_VTXOS: 50_000,\n RENEW_VTXOS: 50_000,\n SWEEP_EXPIRED_BOARDING_UTXOS: 50_000,\n\n // Misc writes\n INIT_WALLET: 30_000,\n CLEAR: 10_000,\n SIGN_TRANSACTION: 30_000,\n CREATE_CONTRACT: 30_000,\n UPDATE_CONTRACT: 30_000,\n DELETE_CONTRACT: 10_000,\n REFRESH_VTXOS: 30_000,\n REFRESH_OUTPOINTS: 30_000,\n};\n\nconst DEDUPABLE_REQUEST_TYPES: ReadonlySet<string> = new Set([\n \"GET_ADDRESS\",\n \"GET_BALANCE\",\n \"GET_BOARDING_ADDRESS\",\n \"GET_BOARDING_UTXOS\",\n \"GET_STATUS\",\n \"GET_TRANSACTION_HISTORY\",\n \"IS_CONTRACT_MANAGER_WATCHING\",\n \"GET_DELEGATE_INFO\",\n \"GET_RECOVERABLE_BALANCE\",\n \"GET_EXPIRED_BOARDING_UTXOS\",\n \"GET_VTXOS\",\n \"GET_CONTRACTS\",\n \"GET_CONTRACTS_WITH_VTXOS\",\n \"ANNOTATE_VTXOS\",\n \"GET_SPENDABLE_PATHS\",\n \"GET_ALL_SPENDING_PATHS\",\n \"GET_ASSET_DETAILS\",\n \"GET_EXPIRING_VTXOS\",\n \"RELOAD_WALLET\",\n]);\n\nfunction getRequestDedupKey(request: WalletUpdaterRequest): string {\n const { id, tag, ...rest } = request;\n return JSON.stringify(rest);\n}\n\nfunction isSigningCapable(identity: Identity | ReadonlyIdentity): identity is Identity {\n const candidate = identity as Partial<Identity>;\n return (\n typeof candidate.signMessage === \"function\" &&\n typeof candidate.sign === \"function\" &&\n typeof candidate.signerSession === \"function\"\n );\n}\n\nclass ServiceWorkerReadonlyAssetManager implements IReadonlyAssetManager {\n constructor(\n protected readonly sendMessage: (\n msg: WalletUpdaterRequest,\n ) => Promise<WalletUpdaterResponse>,\n protected readonly messageTag: string,\n ) {}\n\n async getAssetDetails(assetId: string): Promise<AssetDetails> {\n const message: RequestGetAssetDetails = {\n tag: this.messageTag,\n type: \"GET_ASSET_DETAILS\",\n id: getRandomId(),\n payload: { assetId },\n };\n const response = await this.sendMessage(message);\n return (response as ResponseGetAssetDetails).payload.assetDetails;\n }\n}\n\nclass ServiceWorkerAssetManager extends ServiceWorkerReadonlyAssetManager implements IAssetManager {\n async issue(params: IssuanceParams): Promise<IssuanceResult> {\n const message: RequestIssue = {\n tag: this.messageTag,\n type: \"ISSUE\",\n id: getRandomId(),\n payload: { params },\n };\n const response = await this.sendMessage(message);\n return (response as ResponseIssue).payload.result;\n }\n\n async reissue(params: ReissuanceParams): Promise<string> {\n const message: RequestReissue = {\n tag: this.messageTag,\n type: \"REISSUE\",\n id: getRandomId(),\n payload: { params },\n };\n const response = await this.sendMessage(message);\n return (response as ResponseReissue).payload.txid;\n }\n\n async burn(params: BurnParams): Promise<string> {\n const message: RequestBurn = {\n tag: this.messageTag,\n type: \"BURN\",\n id: getRandomId(),\n payload: { params },\n };\n const response = await this.sendMessage(message);\n return (response as ResponseBurn).payload.txid;\n }\n}\n\n/**\n * Service Worker-based wallet implementation for browser environments.\n *\n * This wallet uses a service worker as a backend to handle wallet logic,\n * providing secure key storage and transaction signing in web applications.\n * The service worker runs in a separate thread and can persist data between\n * browser sessions.\n *\n * @example\n * ```typescript\n * // SIMPLE: Recommended approach\n * const wallet = await ServiceWorkerWallet.setup({\n * serviceWorkerPath: '/service-worker.js',\n * arkServerUrl: 'https://arkade.computer',\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...')\n * });\n *\n * // ADVANCED: Manual setup with service worker control\n * const serviceWorker = await setupServiceWorker(\"/service-worker.js\");\n * const wallet = await ServiceWorkerWallet.create({\n * serviceWorker,\n * arkServerUrl: 'https://arkade.computer',\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...')\n * });\n *\n * // Use like any other wallet\n * const address = await wallet.getAddress();\n * const balance = await wallet.getBalance();\n * ```\n */\ninterface ServiceWorkerWalletOptions {\n /** Optional Arkade server public key used to construct and validate Arkade addresses. */\n arkServerPublicKey?: string;\n /** Base URL of the Arkade server. */\n arkServerUrl?: string;\n /** Optional override for the indexer URL. */\n indexerUrl?: string;\n /** Optional override for the Esplora API URL. */\n esploraUrl?: string;\n /**\n * Repository-backed storage configuration overrides.\n * Defaults to IndexedDB if unset.\n */\n storage?: StorageConfig;\n /** Identity used to derive addresses and optionally sign operations. */\n identity: ReadonlyIdentity | Identity;\n /** Optional delegation service URL. */\n delegatorUrl?: string;\n /**\n * Override the default tag used for messages sent to and received from the service worker.\n * @see DEFAULT_MESSAGE_TAG\n */\n walletUpdaterTag?: string;\n /** Timeout used while bootstrapping the message bus inside the service worker. */\n messageBusTimeoutMs?: number;\n /** Optional settlement configuration forwarded to the worker wallet. */\n settlementConfig?: SettlementConfig | false;\n /**\n * Receive-address strategy forwarded to the worker wallet.\n *\n * Service workers can only receive serializable configuration, so the\n * descriptor-provider object form accepted by `Wallet.create()` is not\n * supported here.\n */\n walletMode?: ServiceWorkerWalletMode;\n /** Optional contract watcher configuration forwarded to the worker wallet. */\n watcherConfig?: Partial<Omit<ContractWatcherConfig, \"indexerProvider\">>;\n /**\n * Per-request timeout overrides for wallet-updater messages.\n * @see DEFAULT_MESSAGE_TIMEOUTS\n */\n messageTimeouts?: MessageTimeouts;\n}\n\n/**\n * Options for creating a service-worker wallet with an existing worker instance.\n *\n * @see ServiceWorkerReadonlyWallet.create\n * @see ServiceWorkerWallet.create\n */\nexport type ServiceWorkerWalletCreateOptions = ServiceWorkerWalletOptions & {\n /** Existing service worker instance used for messaging. */\n serviceWorker: ServiceWorker;\n};\n\n/**\n * Options for registering a service worker and then creating a wallet around it.\n *\n * @see ServiceWorkerReadonlyWallet.setup\n * @see ServiceWorkerWallet.setup\n */\nexport type ServiceWorkerWalletSetupOptions = ServiceWorkerWalletOptions & {\n /** Path to the service worker script to register. */\n serviceWorkerPath: string;\n /** Timeout while waiting for the service worker to activate. */\n serviceWorkerActivationTimeoutMs?: number;\n};\n\ntype MessageBusInitConfig = {\n wallet: SerializedIdentity | LegacySerializedIdentity;\n arkServer: {\n url: string;\n publicKey?: string;\n };\n delegatorUrl?: string;\n indexerUrl?: string;\n esploraUrl?: string;\n timeoutMs?: number;\n settlementConfig?: SettlementConfig | false;\n walletMode?: ServiceWorkerWalletMode;\n watcherConfig?: Partial<Omit<ContractWatcherConfig, \"indexerProvider\">>;\n messageTimeouts?: Record<string, number>;\n};\n\nconst initializeMessageBus = (\n serviceWorker: ServiceWorker,\n config: MessageBusInitConfig,\n timeoutMs = 2000,\n) => {\n const initCmd = {\n tag: \"INITIALIZE_MESSAGE_BUS\",\n id: getRandomId(),\n config: { ...config, timeoutMs },\n };\n\n return new Promise<void>((resolve, reject) => {\n const cleanup = () => {\n navigator.serviceWorker.removeEventListener(\"message\", onMessage);\n clearTimeout(timeoutId);\n };\n\n const onMessage = (event: any) => {\n const response = event.data;\n if (response?.id !== initCmd.id) return;\n cleanup();\n if (response.error) {\n reject(response.error);\n } else {\n resolve();\n }\n };\n\n const timeoutId = setTimeout(() => {\n cleanup();\n reject(new ServiceWorkerTimeoutError(\"MessageBus timed out\"));\n }, timeoutMs);\n\n navigator.serviceWorker.addEventListener(\"message\", onMessage);\n serviceWorker.postMessage(initCmd);\n });\n};\n\nexport class ServiceWorkerReadonlyWallet implements IReadonlyWallet {\n public readonly walletRepository: WalletRepository;\n public readonly contractRepository: ContractRepository;\n public readonly identity: ReadonlyIdentity;\n private readonly _readonlyAssetManager: IReadonlyAssetManager;\n protected initConfig: MessageBusInitConfig | null = null;\n protected initWalletPayload: RequestInitWallet[\"payload\"] | null = null;\n protected messageBusTimeoutMs?: number;\n protected messageTimeouts: Record<RequestType, number> = DEFAULT_MESSAGE_TIMEOUTS as Record<\n RequestType,\n number\n >;\n // Denormalized from options so buildInitConfig() can rebuild the init\n // envelope on demand for SDK-factory-created wallets. `create()` sets\n // these immediately after construction.\n protected arkServerUrl?: string;\n protected arkServerPublicKey?: string;\n protected delegatorUrl?: string;\n protected indexerUrl?: string;\n protected esploraUrl?: string;\n protected watcherConfig?: Partial<Omit<ContractWatcherConfig, \"indexerProvider\">>;\n protected settlementConfig?: SettlementConfig | false;\n private reinitPromise: Promise<void> | null = null;\n private pingPromise: Promise<void> | null = null;\n private inflightRequests = new Map<string, Promise<WalletUpdaterResponse>>();\n\n get assetManager(): IReadonlyAssetManager {\n return this._readonlyAssetManager;\n }\n\n protected constructor(\n public readonly serviceWorker: ServiceWorker,\n identity: ReadonlyIdentity,\n walletRepository: WalletRepository,\n contractRepository: ContractRepository,\n protected readonly messageTag: string,\n ) {\n this.identity = identity;\n this.walletRepository = walletRepository;\n this.contractRepository = contractRepository;\n this._readonlyAssetManager = new ServiceWorkerReadonlyAssetManager(\n (msg) => this.sendMessage(msg),\n messageTag,\n );\n }\n\n private getTimeoutForRequest(request: WalletUpdaterRequest): number {\n return this.messageTimeouts[request.type] ?? 30_000;\n }\n\n /**\n * Create a readonly service-worker wallet bound to an already-registered worker.\n *\n * @param options - Service worker, identity, and backend configuration\n * @returns Initialized readonly service-worker wallet\n * @throws Error if service-worker initialization fails\n */\n static async create(\n options: ServiceWorkerWalletCreateOptions,\n ): Promise<ServiceWorkerReadonlyWallet> {\n const walletRepository =\n options.storage?.walletRepository ?? new IndexedDBWalletRepository();\n\n const contractRepository =\n options.storage?.contractRepository ?? new IndexedDBContractRepository();\n\n const messageTag = options.walletUpdaterTag ?? DEFAULT_MESSAGE_TAG;\n\n // Create the wallet instance\n const wallet = new ServiceWorkerReadonlyWallet(\n options.serviceWorker,\n options.identity,\n walletRepository,\n contractRepository,\n messageTag,\n );\n\n const serializedWallet = await serializeReadonlyIdentity(options.identity);\n\n // INIT_WALLET retains the legacy `key` payload for wire compatibility\n // with older workers; the current handler does not read it.\n const publicKey = await options.identity.compressedPublicKey().then(hex.encode);\n const initWalletPayload = {\n key: { publicKey },\n arkServerUrl: getArkadeServerUrl(options),\n arkServerPublicKey: options.arkServerPublicKey,\n delegatorUrl: options.delegatorUrl,\n };\n\n // Precompute the merged timeout map so page-side waiting and\n // worker-side enforcement are derived from the same source.\n const messageTimeouts = options.messageTimeouts\n ? ({\n ...DEFAULT_MESSAGE_TIMEOUTS,\n ...options.messageTimeouts,\n } as Record<RequestType, number>)\n : (DEFAULT_MESSAGE_TIMEOUTS as Record<RequestType, number>);\n\n const busInitConfig: MessageBusInitConfig = {\n wallet: serializedWallet,\n arkServer: {\n url: getArkadeServerUrl(options),\n publicKey: options.arkServerPublicKey,\n },\n delegatorUrl: options.delegatorUrl,\n indexerUrl: options.indexerUrl,\n esploraUrl: options.esploraUrl,\n watcherConfig: options.watcherConfig,\n messageTimeouts,\n };\n\n // Bootstrap the MessageBus in the service worker\n await initializeMessageBus(\n options.serviceWorker,\n { ...busInitConfig, timeoutMs: options.messageBusTimeoutMs },\n options.messageBusTimeoutMs,\n );\n\n // Initialize the wallet handler\n const initMessage: RequestInitWallet = {\n tag: messageTag,\n type: \"INIT_WALLET\",\n id: getRandomId(),\n payload: initWalletPayload,\n };\n\n await wallet.sendMessage(initMessage);\n\n // Persist the full init config (including messageTimeouts) so\n // reinitialize() re-sends the same map to a restarted worker.\n wallet.initConfig = busInitConfig;\n wallet.initWalletPayload = initWalletPayload;\n wallet.messageBusTimeoutMs = options.messageBusTimeoutMs;\n wallet.messageTimeouts = messageTimeouts;\n\n return wallet;\n }\n\n /**\n * Simplified setup method that handles service worker registration\n * and wallet initialization automatically.\n *\n * @see ServiceWorkerReadonlyWallet.create\n *\n * @example\n * ```typescript\n * const wallet = await ServiceWorkerReadonlyWallet.setup({\n * serviceWorkerPath: '/service-worker.js',\n * arkServerUrl: 'https://arkade.computer',\n * identity: ReadonlySingleKey.fromPublicKey('your_public_key_hex')\n * });\n * ```\n */\n static async setup(\n options: ServiceWorkerWalletSetupOptions,\n ): Promise<ServiceWorkerReadonlyWallet> {\n // Register and setup the service worker\n const serviceWorker = await setupServiceWorker({\n path: options.serviceWorkerPath,\n activationTimeoutMs: options.serviceWorkerActivationTimeoutMs,\n });\n\n // Use the existing create method\n return await ServiceWorkerReadonlyWallet.create({\n ...options,\n serviceWorker,\n });\n }\n\n private sendMessageDirect(\n request: WalletUpdaterRequest,\n timeoutMs: number,\n ): Promise<WalletUpdaterResponse> {\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n clearTimeout(timeoutId);\n navigator.serviceWorker.removeEventListener(\"message\", messageHandler);\n };\n\n const timeoutId = setTimeout(() => {\n cleanup();\n reject(\n new ServiceWorkerTimeoutError(\n `Service worker message timed out (${request.type})`,\n ),\n );\n }, timeoutMs);\n\n const messageHandler = (event: MessageEvent<WalletUpdaterResponse>) => {\n const response = event.data;\n if (request.id !== response.id) {\n return;\n }\n\n cleanup();\n if (response.error) {\n reject(response.error);\n } else {\n resolve(response);\n }\n };\n\n navigator.serviceWorker.addEventListener(\"message\", messageHandler);\n this.serviceWorker.postMessage(request);\n });\n }\n\n // Like sendMessageDirect but supports streaming responses: intermediate\n // messages are forwarded via onEvent while the promise resolves on the\n // first response for which isComplete returns true. No inactivity deadline:\n // settlement-class flows surrender control to remote peers and can sit\n // idle for long stretches between protocol events. Service-worker death\n // is detected out-of-band via concurrent short requests that surface\n // MESSAGE_BUS_NOT_INITIALIZED.\n private sendMessageStreaming(\n request: WalletUpdaterRequest,\n onEvent: (response: WalletUpdaterResponse) => void,\n isComplete: (response: WalletUpdaterResponse) => boolean,\n ): Promise<WalletUpdaterResponse> {\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n navigator.serviceWorker.removeEventListener(\"message\", messageHandler);\n };\n\n const messageHandler = (event: MessageEvent<WalletUpdaterResponse>) => {\n const response = event.data;\n if (request.id !== response.id) return;\n\n if (response.error) {\n cleanup();\n reject(response.error);\n return;\n }\n\n if (isComplete(response)) {\n cleanup();\n resolve(response);\n } else {\n onEvent(response);\n }\n };\n\n navigator.serviceWorker.addEventListener(\"message\", messageHandler);\n this.serviceWorker.postMessage(request);\n });\n }\n\n protected async sendMessage(request: WalletUpdaterRequest): Promise<WalletUpdaterResponse> {\n if (!DEDUPABLE_REQUEST_TYPES.has(request.type)) {\n return this.sendMessageWithRetry(request);\n }\n\n const key = getRequestDedupKey(request);\n const existing = this.inflightRequests.get(key);\n if (existing) return existing;\n\n const promise = this.sendMessageWithRetry(request).finally(() => {\n this.inflightRequests.delete(key);\n });\n this.inflightRequests.set(key, promise);\n return promise;\n }\n\n private pingServiceWorker(): Promise<void> {\n if (this.pingPromise) return this.pingPromise;\n\n this.pingPromise = new Promise<void>((resolve, reject) => {\n const pingId = getRandomId();\n\n const cleanup = () => {\n clearTimeout(timeoutId);\n navigator.serviceWorker.removeEventListener(\"message\", onMessage);\n };\n\n const timeoutId = setTimeout(() => {\n cleanup();\n reject(new ServiceWorkerTimeoutError(\"Service worker ping timed out\"));\n }, 2_000);\n\n const onMessage = (event: MessageEvent) => {\n if (event.data?.id === pingId && event.data?.tag === \"PONG\") {\n cleanup();\n resolve();\n }\n };\n\n navigator.serviceWorker.addEventListener(\"message\", onMessage);\n this.serviceWorker.postMessage({\n id: pingId,\n tag: \"PING\",\n });\n }).finally(() => {\n this.pingPromise = null;\n });\n\n return this.pingPromise;\n }\n\n // send a message, retrying up to 2 times if the service worker was\n // killed and restarted by the OS (mobile browsers do this aggressively)\n private async sendMessageWithRetry(\n request: WalletUpdaterRequest,\n ): Promise<WalletUpdaterResponse> {\n // Skip the preflight ping during the initial INIT_WALLET call:\n // create() hasn't set initConfig yet, so reinitialize() would throw.\n if (this.initConfig) {\n try {\n await this.pingServiceWorker();\n } catch {\n await this.reinitialize();\n }\n }\n\n const timeoutMs = this.getTimeoutForRequest(request);\n const maxRetries = 2;\n for (let attempt = 0; ; attempt++) {\n try {\n return await this.sendMessageDirect(request, timeoutMs);\n } catch (error: any) {\n if (!isMessageBusNotInitializedError(error) || attempt >= maxRetries) {\n throw error;\n }\n\n await this.reinitialize();\n }\n }\n }\n\n // Like sendMessage but for streaming responses — retries with\n // reinitialize when the service worker has been killed/restarted.\n protected async sendMessageWithEvents(\n request: WalletUpdaterRequest,\n onEvent: (response: WalletUpdaterResponse) => void,\n isComplete: (response: WalletUpdaterResponse) => boolean,\n ): Promise<WalletUpdaterResponse> {\n if (this.initConfig) {\n try {\n await this.pingServiceWorker();\n } catch {\n await this.reinitialize();\n }\n }\n\n const maxRetries = 2;\n for (let attempt = 0; ; attempt++) {\n try {\n return await this.sendMessageStreaming(request, onEvent, isComplete);\n } catch (error: any) {\n if (!isMessageBusNotInitializedError(error) || attempt >= maxRetries) {\n throw error;\n }\n\n await this.reinitialize();\n }\n }\n }\n\n /**\n * Produce a serialized envelope for the wallet's identity. The base\n * class always emits a readonly envelope; `ServiceWorkerWallet`\n * overrides to emit a signing envelope.\n */\n protected async serializeIdentity(): Promise<SerializedIdentity> {\n return serializeReadonlyIdentity(this.identity);\n }\n\n /**\n * Return the cached init config, or rebuild one from live instance\n * state when the cache was never populated. Recovery path for\n * SDK-factory-created wallets; manual constructor bypasses do not\n * retain enough state here and will hit the \"never initialized\" throw.\n */\n protected async buildInitConfig(): Promise<MessageBusInitConfig> {\n if (this.initConfig) return this.initConfig;\n if (!this.arkServerUrl) {\n throw new Error(\"Cannot re-initialize: wallet was not initialized via the SDK factory\");\n }\n const wallet = await this.serializeIdentity();\n this.initConfig = {\n wallet,\n arkServer: {\n url: this.arkServerUrl,\n publicKey: this.arkServerPublicKey,\n },\n delegatorUrl: this.delegatorUrl,\n indexerUrl: this.indexerUrl,\n esploraUrl: this.esploraUrl,\n watcherConfig: this.watcherConfig,\n settlementConfig: this.settlementConfig,\n };\n return this.initConfig;\n }\n\n /** Minimal INIT_WALLET payload used on reinitialize when the cache is gone. */\n protected buildInitWalletPayload(): RequestInitWallet[\"payload\"] {\n if (this.initWalletPayload) return this.initWalletPayload;\n if (!this.arkServerUrl) {\n throw new Error(\"Cannot re-initialize: wallet was not initialized via the SDK factory\");\n }\n this.initWalletPayload = {\n // `key` is deprecated and ignored by the current handler.\n key: {},\n arkServerUrl: this.arkServerUrl,\n arkServerPublicKey: this.arkServerPublicKey,\n };\n return this.initWalletPayload;\n }\n\n private async reinitialize(): Promise<void> {\n if (this.reinitPromise) return this.reinitPromise;\n\n this.reinitPromise = (async () => {\n const config = await this.buildInitConfig();\n const payload = this.buildInitWalletPayload();\n\n await initializeMessageBus(this.serviceWorker, config, this.messageBusTimeoutMs);\n\n const initMessage: RequestInitWallet = {\n tag: this.messageTag,\n type: \"INIT_WALLET\",\n id: getRandomId(),\n payload,\n };\n\n await this.sendMessageDirect(initMessage, this.getTimeoutForRequest(initMessage));\n })().finally(() => {\n this.reinitPromise = null;\n });\n\n return this.reinitPromise;\n }\n\n /** Clear cached wallet state from both the page and service worker storage. */\n async clear() {\n const message: RequestClear = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"CLEAR\",\n };\n // Clear page-side storage to maintain parity with SW\n try {\n const address = await this.getAddress();\n await this.walletRepository.deleteVtxos(address);\n } catch (_) {\n console.warn(\"Failed to clear vtxos from wallet repository\");\n }\n\n await this.sendMessage(message);\n }\n\n async getAddress(): Promise<string> {\n const message: RequestGetAddress = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_ADDRESS\",\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetAddress).payload.address;\n } catch (error) {\n throw new Error(`Failed to get address: ${error}`);\n }\n }\n\n async getBoardingAddress(): Promise<string> {\n const message: RequestGetBoardingAddress = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_BOARDING_ADDRESS\",\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetBoardingAddress).payload.address;\n } catch (error) {\n throw new Error(`Failed to get boarding address: ${error}`);\n }\n }\n\n async getBalance(): Promise<WalletBalance> {\n const message: RequestGetBalance = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_BALANCE\",\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetBalance).payload;\n } catch (error) {\n throw new Error(`Failed to get balance: ${error}`);\n }\n }\n\n async getBoardingUtxos(): Promise<ExtendedCoin[]> {\n const message: RequestGetBoardingUtxos = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_BOARDING_UTXOS\",\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetBoardingUtxos).payload.utxos;\n } catch (error) {\n throw new Error(`Failed to get boarding UTXOs: ${error}`);\n }\n }\n\n /**\n * Return service-worker wallet status, including connectivity and sync state.\n *\n * @returns Current service-worker wallet status payload including `walletInitalized` and `xOnlyPublicKey`\n */\n async getStatus(): Promise<ResponseGetStatus[\"payload\"]> {\n const message: RequestGetStatus = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_STATUS\",\n };\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetStatus).payload;\n } catch (error) {\n throw new Error(`Failed to get status: ${error}`);\n }\n }\n\n async getTransactionHistory(): Promise<ArkTransaction[]> {\n const message: RequestGetTransactionHistory = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_TRANSACTION_HISTORY\",\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetTransactionHistory).payload.transactions;\n } catch (error) {\n throw new Error(`Failed to get transaction history: ${error}`);\n }\n }\n\n async getVtxos(filter?: GetVtxosFilter): Promise<ExtendedVirtualCoin[]> {\n const message: RequestGetVtxos = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"GET_VTXOS\",\n payload: { filter },\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseGetVtxos).payload.vtxos;\n } catch (error) {\n throw new Error(`Failed to get vtxos: ${error}`);\n }\n }\n\n /**\n * Trigger a wallet reload inside the service worker.\n *\n * @returns `true` when the wallet was reloaded\n */\n async reload(): Promise<boolean> {\n const message: RequestReloadWallet = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"RELOAD_WALLET\",\n };\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseReloadWallet).payload.reloaded;\n } catch (error) {\n throw new Error(`Failed to reload wallet: ${error}`);\n }\n }\n\n async getContractManager(): Promise<IContractManager> {\n const wallet = this;\n\n const sendContractMessage = async <T extends WalletUpdaterRequest>(\n message: T,\n ): Promise<WalletUpdaterResponse> => {\n return wallet.sendMessage(message as WalletUpdaterRequest);\n };\n\n const messageTag = this.messageTag;\n\n const manager: IContractManager = {\n async createContract(params: CreateContractParams): Promise<Contract> {\n const message: RequestCreateContract = {\n type: \"CREATE_CONTRACT\",\n id: getRandomId(),\n tag: messageTag,\n payload: params,\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseCreateContract).payload.contract;\n } catch (e) {\n throw new Error(\"Failed to create contract\");\n }\n },\n\n async getContracts(filter?: GetContractsFilter): Promise<Contract[]> {\n const message: RequestGetContracts = {\n type: \"GET_CONTRACTS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { filter },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseGetContracts).payload.contracts;\n } catch (e) {\n throw new Error(\"Failed to get contracts\");\n }\n },\n\n async getContractsWithVtxos(filter: GetContractsFilter): Promise<ContractWithVtxos[]> {\n const message: RequestGetContractsWithVtxos = {\n type: \"GET_CONTRACTS_WITH_VTXOS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { filter },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseGetContractsWithVtxos).payload.contracts;\n } catch (e) {\n throw new Error(\"Failed to get contracts with vtxos\");\n }\n },\n\n async annotateVtxos(vtxos: VirtualCoin[]): Promise<ExtendedVirtualCoin[]> {\n if (vtxos.length === 0) return [];\n const message: RequestAnnotateVtxos = {\n type: \"ANNOTATE_VTXOS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { vtxos },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseAnnotateVtxos).payload.vtxos;\n } catch (e) {\n throw new Error(\"Failed to annotate vtxos\");\n }\n },\n\n async updateContract(\n script: string,\n updates: Partial<Omit<Contract, \"script\" | \"createdAt\">>,\n ): Promise<Contract> {\n const message: RequestUpdateContract = {\n type: \"UPDATE_CONTRACT\",\n id: getRandomId(),\n tag: messageTag,\n payload: { script, updates },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseUpdateContract).payload.contract;\n } catch (e) {\n throw new Error(\"Failed to update contract\");\n }\n },\n\n async setContractState(script: string, state: ContractState): Promise<void> {\n const message: RequestUpdateContract = {\n type: \"UPDATE_CONTRACT\",\n id: getRandomId(),\n tag: messageTag,\n payload: { script, updates: { state } },\n };\n try {\n await sendContractMessage(message);\n return;\n } catch (e) {\n throw new Error(\"Failed to update contract state\");\n }\n },\n\n async deleteContract(script: string): Promise<void> {\n const message: RequestDeleteContract = {\n type: \"DELETE_CONTRACT\",\n id: getRandomId(),\n tag: messageTag,\n payload: { script },\n };\n try {\n await sendContractMessage(message);\n return;\n } catch (e) {\n throw new Error(\"Failed to delete contract\");\n }\n },\n\n async getSpendablePaths(options: GetSpendablePathsOptions): Promise<PathSelection[]> {\n const message: RequestGetSpendablePaths = {\n type: \"GET_SPENDABLE_PATHS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { options },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseGetSpendablePaths).payload.paths;\n } catch (e) {\n throw new Error(\"Failed to get spendable paths\");\n }\n },\n\n async getAllSpendingPaths(\n options: GetAllSpendingPathsOptions,\n ): Promise<PathSelection[]> {\n const message: RequestGetAllSpendingPaths = {\n type: \"GET_ALL_SPENDING_PATHS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { options },\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseGetAllSpendingPaths).payload.paths;\n } catch (e) {\n throw new Error(\"Failed to get all spending paths\");\n }\n },\n\n onContractEvent(callback: ContractEventCallback): () => void {\n const messageHandler = (event: MessageEvent) => {\n const response = event.data as WalletUpdaterResponse;\n if (response.type !== \"CONTRACT_EVENT\") {\n return;\n }\n if (response.tag !== messageTag) {\n return;\n }\n callback((response as ResponseContractEvent).payload.event);\n };\n\n navigator.serviceWorker.addEventListener(\"message\", messageHandler);\n\n return () => {\n navigator.serviceWorker.removeEventListener(\"message\", messageHandler);\n };\n },\n\n async refreshVtxos(opts?: RefreshVtxosOptions): Promise<void> {\n const message: RequestRefreshVtxos = {\n type: \"REFRESH_VTXOS\",\n id: getRandomId(),\n tag: messageTag,\n payload: opts,\n };\n await sendContractMessage(message);\n },\n\n async refreshOutpoints(outpoints: { txid: string; vout: number }[]): Promise<void> {\n const message: RequestRefreshOutpoints = {\n type: \"REFRESH_OUTPOINTS\",\n id: getRandomId(),\n tag: messageTag,\n payload: { outpoints },\n };\n await sendContractMessage(message);\n },\n\n scanContracts(): Promise<ScanResult> {\n // `scanContracts` takes a `materialize(index)` callback,\n // which cannot cross the service-worker postMessage boundary\n // (functions are not structured-cloneable). Service-worker\n // wallets must drive recovery through the worker's own\n // restore message protocol, not this proxy method.\n return Promise.reject(\n new Error(\n \"scanContracts is not available on the service-worker \" +\n \"contract-manager proxy: its materialize() callback \" +\n \"cannot be sent across the worker message boundary. \" +\n \"Use the wallet's restore entrypoint instead.\",\n ),\n );\n },\n\n async isWatching(): Promise<boolean> {\n const message: RequestIsContractManagerWatching = {\n type: \"IS_CONTRACT_MANAGER_WATCHING\",\n id: getRandomId(),\n tag: messageTag,\n };\n try {\n const response = await sendContractMessage(message);\n return (response as ResponseIsContractManagerWatching).payload.isWatching;\n } catch (e) {\n throw new Error(\"Failed to check if contract manager is watching\");\n }\n },\n\n dispose(): void {\n return;\n },\n\n [Symbol.dispose](): void {\n // no-op\n return;\n },\n };\n\n return manager;\n }\n}\n\nexport class ServiceWorkerWallet extends ServiceWorkerReadonlyWallet implements IWallet {\n public readonly walletRepository: WalletRepository;\n public readonly contractRepository: ContractRepository;\n public readonly identity: Identity;\n private readonly _assetManager: IAssetManager;\n private readonly hasDelegator: boolean;\n\n protected constructor(\n public readonly serviceWorker: ServiceWorker,\n identity: Identity,\n walletRepository: WalletRepository,\n contractRepository: ContractRepository,\n messageTag: string,\n hasDelegator: boolean,\n ) {\n super(serviceWorker, identity, walletRepository, contractRepository, messageTag);\n this.identity = identity;\n this.walletRepository = walletRepository;\n this.contractRepository = contractRepository;\n this._assetManager = new ServiceWorkerAssetManager(\n (msg) => this.sendMessage(msg),\n messageTag,\n );\n this.hasDelegator = hasDelegator;\n }\n\n get assetManager(): IAssetManager {\n return this._assetManager;\n }\n\n protected async serializeIdentity(): Promise<SerializedIdentity> {\n return serializeSigningIdentity(this.identity);\n }\n\n static async create(options: ServiceWorkerWalletCreateOptions): Promise<ServiceWorkerWallet> {\n const walletRepository =\n options.storage?.walletRepository ?? new IndexedDBWalletRepository();\n\n const contractRepository =\n options.storage?.contractRepository ?? new IndexedDBContractRepository();\n\n if (!isSigningCapable(options.identity)) {\n throw new Error(\n \"ServiceWorkerWallet.create() requires a signing Identity; got a ReadonlyIdentity\",\n );\n }\n const identity: Identity = options.identity;\n const serializedWallet = serializeSigningIdentity(identity);\n\n const messageTag = options.walletUpdaterTag ?? DEFAULT_MESSAGE_TAG;\n\n // Create the wallet instance\n const wallet = new ServiceWorkerWallet(\n options.serviceWorker,\n identity,\n walletRepository,\n contractRepository,\n messageTag,\n !!options.delegatorUrl,\n );\n\n // INIT_WALLET retains the legacy `key` payload for wire compatibility\n // with older workers; the current handler does not read it, and only\n // SingleKey-style identities can populate it. Kept optional so seed /\n // mnemonic identities simply omit it.\n const legacyPrivateKey =\n serializedWallet.type === \"single-key\" ? serializedWallet.privateKey : null;\n const initWalletPayload = {\n key: legacyPrivateKey ? { privateKey: legacyPrivateKey } : {},\n arkServerUrl: getArkadeServerUrl(options),\n arkServerPublicKey: options.arkServerPublicKey,\n delegatorUrl: options.delegatorUrl,\n };\n\n // Precompute the merged timeout map so page-side waiting and\n // worker-side enforcement are derived from the same source.\n const messageTimeouts = options.messageTimeouts\n ? ({\n ...DEFAULT_MESSAGE_TIMEOUTS,\n ...options.messageTimeouts,\n } as Record<RequestType, number>)\n : (DEFAULT_MESSAGE_TIMEOUTS as Record<RequestType, number>);\n\n const busInitConfig: MessageBusInitConfig = {\n wallet: serializedWallet,\n arkServer: {\n url: getArkadeServerUrl(options),\n publicKey: options.arkServerPublicKey,\n },\n delegatorUrl: options.delegatorUrl,\n indexerUrl: options.indexerUrl,\n esploraUrl: options.esploraUrl,\n settlementConfig: options.settlementConfig,\n walletMode: options.walletMode,\n watcherConfig: options.watcherConfig,\n messageTimeouts,\n };\n\n await initializeMessageBus(\n options.serviceWorker,\n { ...busInitConfig, timeoutMs: options.messageBusTimeoutMs },\n options.messageBusTimeoutMs,\n );\n // Initialize the service worker with the config\n const initMessage: RequestInitWallet = {\n tag: messageTag,\n type: \"INIT_WALLET\",\n id: getRandomId(),\n payload: initWalletPayload,\n };\n\n // Initialize the service worker\n await wallet.sendMessage(initMessage);\n\n // Persist the full init config (including messageTimeouts) so\n // reinitialize() re-sends the same map to a restarted worker.\n wallet.initConfig = busInitConfig;\n wallet.initWalletPayload = initWalletPayload;\n wallet.messageBusTimeoutMs = options.messageBusTimeoutMs;\n wallet.messageTimeouts = messageTimeouts;\n\n return wallet;\n }\n\n /**\n * Simplified setup method that handles service worker registration\n * and wallet initialization automatically.\n *\n * @example\n * ```typescript\n * const wallet = await ServiceWorkerWallet.setup({\n * serviceWorkerPath: '/service-worker.js',\n * arkServerUrl: 'https://arkade.computer',\n * identity: MnemonicIdentity.fromMnemonic('abandon abandon...')\n * });\n * ```\n */\n static async setup(options: ServiceWorkerWalletSetupOptions): Promise<ServiceWorkerWallet> {\n // Register and setup the service worker\n const serviceWorker = await setupServiceWorker({\n path: options.serviceWorkerPath,\n activationTimeoutMs: options.serviceWorkerActivationTimeoutMs,\n });\n\n // Use the existing create method\n return ServiceWorkerWallet.create({\n ...options,\n serviceWorker,\n });\n }\n\n async sendBitcoin(params: SendBitcoinParams): Promise<string> {\n const message: RequestSendBitcoin = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"SEND_BITCOIN\",\n payload: params,\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseSendBitcoin).payload.txid;\n } catch (error) {\n throw new Error(`Failed to send bitcoin: ${error}`);\n }\n }\n\n async settle(\n params?: SettleParams,\n callback?: (event: SettlementEvent) => void,\n ): Promise<string> {\n const message: RequestSettle = {\n id: getRandomId(),\n tag: this.messageTag,\n type: \"SETTLE\",\n payload: { params },\n };\n\n try {\n const response = await this.sendMessageWithEvents(\n message,\n (resp) => callback?.((resp as ResponseSettleEvent).payload),\n (resp) => resp.type === \"SETTLE_SUCCESS\",\n );\n return (response as ResponseSettle).payload.txid;\n } catch (error) {\n throw new Error(`Settlement failed: ${error}`);\n }\n }\n\n async send(...recipients: [Recipient, ...Recipient[]]): Promise<string> {\n const message: RequestSend = {\n tag: this.messageTag,\n type: \"SEND\",\n id: getRandomId(),\n payload: { recipients },\n };\n\n try {\n const response = await this.sendMessage(message);\n return (response as ResponseSend).payload.txid;\n } catch (error) {\n throw new Error(`Send failed: ${error}`);\n }\n }\n\n async getDelegatorManager(): Promise<IDelegatorManager | undefined> {\n if (!this.hasDelegator) {\n return undefined;\n }\n\n const wallet = this;\n const messageTag = this.messageTag;\n\n const manager: IDelegatorManager = {\n async delegate(vtxos, destination, delegateAt?) {\n const message: RequestDelegate = {\n tag: messageTag,\n type: \"DELEGATE\",\n id: getRandomId(),\n payload: {\n vtxoOutpoints: vtxos.map((v) => ({\n txid: v.txid,\n vout: v.vout,\n })),\n destination,\n delegateAt: delegateAt?.getTime(),\n },\n };\n\n try {\n const response = await wallet.sendMessage(message);\n const payload = (response as ResponseDelegate).payload;\n return {\n delegated: payload.delegated,\n failed: payload.failed.map((f) => ({\n outpoints: f.outpoints,\n error: f.error,\n })),\n };\n } catch (error) {\n throw new Error(`Delegation failed: ${error}`);\n }\n },\n\n async getDelegateInfo(): Promise<DelegateInfo> {\n const message: RequestGetDelegateInfo = {\n type: \"GET_DELEGATE_INFO\",\n id: getRandomId(),\n tag: messageTag,\n };\n try {\n const response = await wallet.sendMessage(message);\n return (response as ResponseGetDelegateInfo).payload.info;\n } catch (e) {\n throw new Error(\"Failed to get delegate info\");\n }\n },\n };\n\n return manager;\n }\n\n async getVtxoManager(): Promise<IVtxoManager> {\n const wallet = this;\n const messageTag = this.messageTag;\n\n const manager: IVtxoManager = {\n async recoverVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string> {\n const message: RequestRecoverVtxos = {\n tag: messageTag,\n type: \"RECOVER_VTXOS\",\n id: getRandomId(),\n };\n try {\n const response = await wallet.sendMessageWithEvents(\n message,\n (resp) => eventCallback?.((resp as ResponseRecoverVtxosEvent).payload),\n (resp) => resp.type === \"RECOVER_VTXOS_SUCCESS\",\n );\n return (response as ResponseRecoverVtxos).payload.txid;\n } catch (e) {\n throw new Error(`Failed to recover vtxos: ${e}`);\n }\n },\n\n async getRecoverableBalance() {\n const message: RequestGetRecoverableBalance = {\n tag: messageTag,\n type: \"GET_RECOVERABLE_BALANCE\",\n id: getRandomId(),\n };\n try {\n const response = await wallet.sendMessage(message);\n const payload = (response as ResponseGetRecoverableBalance).payload;\n return {\n recoverable: BigInt(payload.recoverable),\n subdust: BigInt(payload.subdust),\n includesSubdust: payload.includesSubdust,\n vtxoCount: payload.vtxoCount,\n };\n } catch (e) {\n throw new Error(`Failed to get recoverable balance: ${e}`);\n }\n },\n\n async getExpiringVtxos(thresholdMs?) {\n const message: RequestGetExpiringVtxos = {\n tag: messageTag,\n type: \"GET_EXPIRING_VTXOS\",\n id: getRandomId(),\n payload: { thresholdMs },\n };\n try {\n const response = await wallet.sendMessage(message);\n return (response as ResponseGetExpiringVtxos).payload.vtxos;\n } catch (e) {\n throw new Error(`Failed to get expiring vtxos: ${e}`);\n }\n },\n\n async renewVtxos(eventCallback?: (event: SettlementEvent) => void): Promise<string> {\n const message: RequestRenewVtxos = {\n tag: messageTag,\n type: \"RENEW_VTXOS\",\n id: getRandomId(),\n };\n try {\n const response = await wallet.sendMessageWithEvents(\n message,\n (resp) => eventCallback?.((resp as ResponseRenewVtxosEvent).payload),\n (resp) => resp.type === \"RENEW_VTXOS_SUCCESS\",\n );\n return (response as ResponseRenewVtxos).payload.txid;\n } catch (e) {\n throw new Error(`Failed to renew vtxos: ${e}`);\n }\n },\n\n async getExpiredBoardingUtxos() {\n const message: RequestGetExpiredBoardingUtxos = {\n tag: messageTag,\n type: \"GET_EXPIRED_BOARDING_UTXOS\",\n id: getRandomId(),\n };\n try {\n const response = await wallet.sendMessage(message);\n return (response as ResponseGetExpiredBoardingUtxos).payload.utxos;\n } catch (e) {\n throw new Error(`Failed to get expired boarding utxos: ${e}`);\n }\n },\n\n async sweepExpiredBoardingUtxos(): Promise<string> {\n const message: RequestSweepExpiredBoardingUtxos = {\n tag: messageTag,\n type: \"SWEEP_EXPIRED_BOARDING_UTXOS\",\n id: getRandomId(),\n };\n try {\n const response = await wallet.sendMessage(message);\n return (response as ResponseSweepExpiredBoardingUtxos).payload.txid;\n } catch (e) {\n throw new Error(`Failed to sweep expired boarding utxos: ${e}`);\n }\n },\n\n async dispose(): Promise<void> {\n return;\n },\n };\n\n return manager;\n }\n}\n","import { p2tr } from \"@scure/btc-signer\";\nimport { P2TR } from \"@scure/btc-signer/payment.js\";\nimport { Coin, DEFAULT_NETWORK_NAME, SendBitcoinParams } from \".\";\nimport { Identity } from \"../identity\";\nimport { getNetwork, Network, NetworkName } from \"../networks\";\nimport { ESPLORA_URL, EsploraProvider, OnchainProvider } from \"../providers/onchain\";\nimport { AnchorBumper, findP2AOutput, P2A } from \"../utils/anchor\";\nimport { TxWeightEstimator } from \"../utils/txSizeEstimator\";\nimport { Transaction } from \"../utils/transaction\";\nimport { DUST_AMOUNT } from \"./utils\";\n\n/**\n * Onchain Bitcoin wallet implementation for traditional Bitcoin transactions.\n *\n * This wallet handles regular Bitcoin transactions on the blockchain without\n * using the Arkade protocol. It supports P2TR (Pay-to-Taproot) addresses and\n * provides basic Bitcoin wallet functionality.\n *\n * @example\n * ```typescript\n * const wallet = await OnchainWallet.create(identity, 'mainnet');\n * const balance = await wallet.getBalance();\n * const txid = await wallet.send({\n * address: 'bc1...',\n * amount: 50000\n * });\n * ```\n */\nexport class OnchainWallet implements AnchorBumper {\n static MIN_FEE_RATE = 1; // sat/vbyte\n\n readonly onchainP2TR: P2TR;\n readonly provider: OnchainProvider;\n readonly network: Network;\n\n private constructor(\n private identity: Identity,\n network: Network,\n onchainP2TR: P2TR,\n provider: OnchainProvider,\n ) {\n this.network = network;\n this.onchainP2TR = onchainP2TR;\n this.provider = provider;\n }\n\n /**\n * Create an onchain wallet for the given identity and Bitcoin network.\n *\n * @param identity - Identity used to derive the Taproot key and sign transactions\n * @param networkName - Bitcoin network name, @see NetworkName\n * @param provider - Optional onchain provider override, @see OnchainProvider\n * @returns Configured onchain wallet\n * @defaultValue `provider = new EsploraProvider('https://mempool.space/api')`\n * @throws Error if the configured identity cannot produce a valid x-only public key\n */\n static async create(\n identity: Identity,\n networkName: NetworkName = DEFAULT_NETWORK_NAME,\n provider?: OnchainProvider,\n ): Promise<OnchainWallet> {\n const pubkey = await identity.xOnlyPublicKey();\n if (!pubkey) {\n throw new Error(\"Invalid configured public key\");\n }\n\n const network = getNetwork(networkName);\n const onchainProvider = provider || new EsploraProvider(ESPLORA_URL[networkName]);\n const onchainP2TR = p2tr(pubkey, undefined, network);\n\n return new OnchainWallet(identity, network, onchainP2TR, onchainProvider);\n }\n\n get address(): string {\n return this.onchainP2TR.address || \"\";\n }\n\n /**\n * Fetch spendable onchain outputs for the wallet address.\n *\n * @returns Spendable onchain outputs for the wallet address\n * @see getBalance\n */\n async getCoins(): Promise<Coin[]> {\n return this.provider.getCoins(this.address);\n }\n\n /**\n * Return the wallet's total onchain balance in satoshis.\n *\n * @returns Confirmed plus unconfirmed onchain balance\n * @see getCoins\n */\n async getBalance(): Promise<number> {\n const coins = await this.getCoins();\n const onchainConfirmed = coins\n .filter((coin) => coin.status.confirmed)\n .reduce((sum, coin) => sum + coin.value, 0);\n const onchainUnconfirmed = coins\n .filter((coin) => !coin.status.confirmed)\n .reduce((sum, coin) => sum + coin.value, 0);\n const onchainTotal = onchainConfirmed + onchainUnconfirmed;\n return onchainTotal;\n }\n\n /**\n * Iteratively selects coins and estimates transaction fees until convergence.\n *\n * This method handles the circular dependency between output selection and fee\n * estimation: the fee depends on transaction size, which depends on the number\n * of inputs (selected outputs) and whether a change output is needed.\n *\n * The algorithm iterates up to 10 times, refining the fee estimate based on\n * the actual transaction structure. It resolves dust oscillation loops that\n * occur when the change amount hovers near the dust threshold—adding/removing\n * the change output causes the fee to fluctuate, preventing convergence.\n * When a lower fee is computed (indicating the change output was dropped),\n * the function accepts this state to guarantee termination.\n *\n * @param coins - Available onchain outputs to select from\n * @param amount - Target send amount in satoshis\n * @param feeRate - Fee rate in sat/vbyte\n * @param recipientAddress - Destination address for size estimation\n * @returns Selected inputs, change amount, and calculated fee\n * @throws Error if fee estimation fails to converge within max iterations\n */\n private estimateFeesAndSelectCoins(\n coins: Coin[],\n amount: number,\n feeRate: number,\n recipientAddress: string,\n ): { inputs: Coin[]; changeAmount: bigint; fee: number } {\n const MAX_ITERATIONS = 10;\n let fee = 0;\n\n for (let i = 0; i < MAX_ITERATIONS; i++) {\n const totalNeeded = amount + fee;\n\n const selected = selectCoins(coins, totalNeeded);\n\n const estimator = TxWeightEstimator.create();\n\n for (const _ of selected.inputs) {\n estimator.addKeySpendInput();\n }\n\n estimator.addOutputAddress(recipientAddress, this.network);\n\n if (selected.changeAmount >= BigInt(DUST_AMOUNT)) {\n estimator.addOutputAddress(this.address, this.network);\n }\n\n const newFee = Number(estimator.vsize().value) * feeRate;\n const roundedNewFee = Math.ceil(newFee);\n\n // Prevent oscillation loops when change falls just below the dust limit.\n // If removing the change output reduces the fee below our budget,\n // we accept the valid transaction state to guarantee convergence.\n if (roundedNewFee <= fee) {\n return { ...selected, fee: roundedNewFee };\n }\n\n fee = roundedNewFee;\n }\n\n throw new Error(\"Fee estimation failed: could not converge\");\n }\n\n /**\n * Send bitcoin to a single onchain address.\n *\n * @param params - destination `address`, `amount` (in satoshis), and optional `feeRate` override (other fields ignored)\n * @returns Broadcast transaction id\n * @throws Error if the amount is non-positive, below dust, or cannot be funded\n * @see SendBitcoinParams\n */\n async send(params: SendBitcoinParams): Promise<string> {\n if (params.amount <= 0) {\n throw new Error(\"Amount must be positive\");\n }\n if (params.amount < DUST_AMOUNT) {\n throw new Error(\"Amount is below dust limit\");\n }\n\n const coins = await this.getCoins();\n let feeRate = params.feeRate;\n if (!feeRate) {\n feeRate = await this.provider.getFeeRate();\n }\n\n if (!feeRate || feeRate < OnchainWallet.MIN_FEE_RATE) {\n feeRate = OnchainWallet.MIN_FEE_RATE;\n }\n\n const { inputs, changeAmount } = this.estimateFeesAndSelectCoins(\n coins,\n params.amount,\n feeRate,\n params.address,\n );\n\n if (!inputs) {\n throw new Error(\"Fee estimation failed\");\n }\n\n // Create transaction\n let tx = new Transaction();\n\n // Add inputs\n for (const input of inputs) {\n tx.addInput({\n txid: input.txid,\n index: input.vout,\n witnessUtxo: {\n script: this.onchainP2TR.script,\n amount: BigInt(input.value),\n },\n tapInternalKey: this.onchainP2TR.tapInternalKey,\n });\n }\n\n // Add payment output\n tx.addOutputAddress(params.address, BigInt(params.amount), this.network);\n\n if (changeAmount >= BigInt(DUST_AMOUNT)) {\n tx.addOutputAddress(this.address, changeAmount, this.network);\n }\n\n // Sign inputs and Finalize\n tx = await this.identity.sign(tx);\n tx.finalize();\n\n // Broadcast\n const txid = await this.provider.broadcastTransaction(tx.hex);\n return txid;\n }\n\n /**\n * CPFP-bump a parent transaction that contains a pay-to-anchor output.\n *\n * @param parent - Parent transaction containing a pay-to-anchor output\n * @returns Tuple of parent transaction id and child transaction id\n * @throws Error if the parent transaction has no pay-to-anchor output or bumping cannot be funded\n * @see send\n */\n async bumpP2A(parent: Transaction): Promise<[string, string]> {\n const parentVsize = parent.vsize;\n\n let child = new Transaction({\n version: 3,\n allowLegacyWitnessUtxo: true,\n });\n child.addInput(findP2AOutput(parent)); // throws if not found\n\n const childVsize = TxWeightEstimator.create()\n .addKeySpendInput(true)\n .addP2AInput()\n .addOutputAddress(this.address, this.network)\n .vsize().value;\n\n const packageVSize = parentVsize + Number(childVsize);\n\n let feeRate = await this.provider.getFeeRate();\n if (!feeRate || feeRate < OnchainWallet.MIN_FEE_RATE) {\n feeRate = OnchainWallet.MIN_FEE_RATE;\n }\n const fee = Math.ceil(feeRate * packageVSize);\n if (!fee) {\n throw new Error(\n `invalid fee, got ${fee} with vsize ${packageVSize}, feeRate ${feeRate}`,\n );\n }\n\n // Select onchain outputs\n const coins = await this.getCoins();\n const selected = selectCoins(coins, fee, true);\n\n for (const input of selected.inputs) {\n child.addInput({\n txid: input.txid,\n index: input.vout,\n witnessUtxo: {\n script: this.onchainP2TR.script,\n amount: BigInt(input.value),\n },\n tapInternalKey: this.onchainP2TR.tapInternalKey,\n });\n }\n\n child.addOutputAddress(this.address, P2A.amount + selected.changeAmount, this.network);\n\n // Sign inputs and Finalize\n child = await this.identity.sign(child);\n for (let i = 1; i < child.inputsLength; i++) {\n child.finalizeIdx(i);\n }\n\n try {\n await this.provider.broadcastTransaction(parent.hex, child.hex);\n } catch (error) {\n console.error(error);\n } finally {\n return [parent.hex, child.hex];\n }\n }\n}\n\n/**\n * Select coins to reach a target amount, prioritizing those closer to expiry\n * @param coins List of coins to select from\n * @param targetAmount Target amount to reach in satoshis\n * @param forceChange If true, ensure the coin selection will require a change output\n * @returns Selected coins and change amount, or null if insufficient funds\n */\nexport function selectCoins(\n coins: Coin[],\n targetAmount: number,\n forceChange: boolean = false,\n): {\n inputs: Coin[];\n changeAmount: bigint;\n} {\n if (isNaN(targetAmount)) {\n throw new Error(\"Target amount is NaN, got \" + targetAmount);\n }\n\n if (targetAmount < 0) {\n throw new Error(\"Target amount is negative, got \" + targetAmount);\n }\n\n if (targetAmount === 0) {\n return { inputs: [], changeAmount: 0n };\n }\n\n // Sort coins by amount (descending)\n const sortedCoins = [...coins].sort((a, b) => b.value - a.value);\n\n const selectedCoins: Coin[] = [];\n let selectedAmount = 0;\n\n // Select coins until we have enough\n for (const coin of sortedCoins) {\n selectedCoins.push(coin);\n selectedAmount += coin.value;\n\n if (forceChange ? selectedAmount > targetAmount : selectedAmount >= targetAmount) {\n break;\n }\n }\n\n if (selectedAmount === targetAmount) {\n return { inputs: selectedCoins, changeAmount: 0n };\n }\n\n if (selectedAmount < targetAmount) {\n throw new Error(\"Insufficient funds\");\n }\n\n const changeAmount = BigInt(selectedAmount - targetAmount);\n\n return {\n inputs: selectedCoins,\n changeAmount,\n };\n}\n","import { Address, OutScript, Transaction } from \"@scure/btc-signer\";\nimport { sha256 } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\nimport type { ElectrumWS } from \"ws-electrumx-client\";\nimport type { Network, NetworkName } from \"../networks\";\nimport type { Coin } from \"../wallet\";\nimport type { ExplorerTransaction, OnchainProvider } from \"./onchain\";\n\n/**\n * Default WebSocket Electrum endpoints. Mainnet, mutinynet, and signet\n * point at Ark Labs–operated Fulcrum 2.1 deployments (which support\n * `blockchain.transaction.broadcast_package` for atomic 1P1C TRUC\n * relay; see `ElectrumOnchainProvider.broadcastTransaction`). Testnet\n * defaults to Blockstream's public Fulcrum because Ark doesn't host\n * it. Regtest assumes the `electrum-ws` websocat bridge from\n * `vulpemventures/nigiri`.\n *\n * @example\n * ```typescript\n * import { ElectrumWS } from \"ws-electrumx-client\";\n * import { ELECTRUM_WS_URL, ElectrumOnchainProvider, networks } from \"@arkade-os/sdk\";\n *\n * const ws = new ElectrumWS(ELECTRUM_WS_URL.bitcoin);\n * const provider = new ElectrumOnchainProvider(ws, networks.bitcoin);\n * ```\n */\nexport const ELECTRUM_WS_URL: Record<NetworkName, string> = {\n bitcoin: \"wss://electrum.arkade.sh\",\n testnet: \"wss://electrum.blockstream.info:60004\",\n signet: \"wss://electrum.signet.arkade.sh\",\n mutinynet: \"wss://electrum.mutinynet.arkade.sh\",\n regtest: \"ws://localhost:50003\",\n};\n\n/**\n * Hostnames for Electrum endpoints reachable over raw TCP. Provided as\n * a reference for Node-side consumers — the SDK's\n * {@link ElectrumOnchainProvider} only speaks WebSocket because it has\n * to run in browsers, so this map is informational only and not\n * consumed by any built-in provider.\n *\n * Public Ark Labs Fulcrum instances expose:\n * - port 50001 — plain TCP (Electrum protocol)\n * - port 50002 — TCP + TLS (Electrum protocol)\n * - port 50003 — WebSocket (Electrum-over-WS, see {@link ELECTRUM_WS_URL})\n */\nexport const ELECTRUM_TCP_HOST: Record<NetworkName, string | null> = {\n bitcoin: \"electrum.arkade.sh\",\n testnet: null,\n signet: \"electrum.signet.arkade.sh\",\n mutinynet: \"electrum.mutinynet.arkade.sh\",\n regtest: \"localhost\",\n};\n\n// Electrum protocol method names\nconst BroadcastTransaction = \"blockchain.transaction.broadcast\";\nconst BroadcastPackageMethod = \"blockchain.transaction.broadcast_package\";\nconst EstimateFee = \"blockchain.estimatefee\";\nconst GetBlockHeader = \"blockchain.block.header\";\nconst GetHistoryMethod = \"blockchain.scripthash.get_history\";\nconst GetTransactionMethod = \"blockchain.transaction.get\";\nconst GetTransactionMerkleMethod = \"blockchain.transaction.get_merkle\";\nconst SubscribeStatusMethod = \"blockchain.scripthash\";\nconst SubscribeHeadersMethod = \"blockchain.headers\";\nconst GetRelayFeeMethod = \"blockchain.relayfee\";\nconst ListUnspentMethod = \"blockchain.scripthash.listunspent\";\n\nconst MISSING_TRANSACTION = \"missingtransaction\";\nconst MAX_FETCH_TRANSACTIONS_ATTEMPTS = 5;\n\n// Bitcoin block header is 80 bytes\nconst BLOCK_HEADER_SIZE = 80;\n\nexport type TransactionHistory = {\n tx_hash: string;\n height: number;\n fee?: number;\n};\n\nexport type BlockHeader = {\n height: number;\n hex: string;\n};\n\nexport type Unspent = {\n txid: string;\n vout: number;\n witnessUtxo: {\n script: Uint8Array;\n value: bigint;\n };\n};\n\ntype UnspentElectrum = {\n height: number;\n tx_pos: number;\n tx_hash: string;\n value: number;\n};\n\ntype VerboseTransaction = {\n txid: string;\n confirmations: number;\n blockhash?: string;\n blocktime?: number;\n time?: number;\n /** Raw transaction hex. Bitcoin Core's getrawtransaction <tx> 1 always\n * includes this; we use it to derive exact satoshi amounts instead of\n * multiplying the floating-point `value` field by 1e8. */\n hex?: string;\n vout: {\n n: number;\n value: number;\n scriptPubKey: {\n addresses?: string[];\n address?: string;\n hex: string;\n };\n }[];\n vin: {\n txid: string;\n vout: number;\n }[];\n};\n\ntype HeaderSubscribeResult = {\n height: number;\n hex: string;\n};\n\n/**\n * Server response for `blockchain.transaction.broadcast_package` (verbose=false).\n * `errors` is null/undefined on success and populated when at least one\n * transaction in the package was rejected by the mempool. The exact error\n * shape mirrors bitcoind's `submitpackage` RPC and varies across Core\n * versions.\n */\ntype BroadcastPackageResult = {\n success: boolean;\n errors?: Array<Record<string, unknown>> | null;\n};\n\n/**\n * Parse a raw block header (80 bytes hex = 160 chars) to extract fields.\n * Bitcoin block header layout:\n * - version: 4 bytes (LE)\n * - prevHash: 32 bytes\n * - merkleRoot: 32 bytes\n * - timestamp: 4 bytes (LE)\n * - bits: 4 bytes\n * - nonce: 4 bytes\n */\nfunction parseBlockHeader(headerHex: string): {\n hash: string;\n timestamp: number;\n} {\n const headerBytes = hex.decode(headerHex);\n if (headerBytes.length !== BLOCK_HEADER_SIZE) {\n throw new Error(\n `Invalid block header size: ${headerBytes.length}, expected ${BLOCK_HEADER_SIZE}`,\n );\n }\n\n // timestamp is at offset 68 (4+32+32), 4 bytes little-endian\n const view = new DataView(headerBytes.buffer, headerBytes.byteOffset);\n const timestamp = view.getUint32(68, true);\n\n // block hash = double SHA256 of header, reversed\n const hash1 = sha256(headerBytes);\n const hash2 = sha256(hash1);\n const hashStr = hex.encode(new Uint8Array(hash2).reverse());\n\n return { hash: hashStr, timestamp };\n}\n\n/**\n * WebSocket-based Electrum chain source using ws-electrumx-client.\n * Provides low-level methods for the Electrum protocol.\n *\n * @example\n * ```typescript\n * import { ElectrumWS } from \"ws-electrumx-client\";\n * import { WsElectrumChainSource } from \"./providers/electrum\";\n * import { networks } from \"./networks\";\n *\n * const ws = new ElectrumWS(\"wss://electrum.blockstream.info:50004\");\n * const chain = new WsElectrumChainSource(ws, networks.bitcoin);\n *\n * const history = await chain.fetchHistories([script]);\n * await chain.close();\n * ```\n */\nexport class WsElectrumChainSource {\n // Cached chain tip kept fresh by the headers subscription. Initialized\n // lazily on first call to subscribeHeaders().\n private cachedTip: HeaderSubscribeResult | null = null;\n private headersSubscribePromise: Promise<HeaderSubscribeResult> | null = null;\n\n constructor(\n private ws: ElectrumWS,\n private network: Network,\n ) {}\n\n /**\n * Send N requests in parallel and aggregate the results, replacement\n * for `ws.batchRequest`. The library's batchRequest is implemented as\n * `Promise.all` over individual request promises — when one element\n * rejects, the others remain pending. When their (often error)\n * responses arrive later, the library rejects them too, and nobody is\n * awaiting them: the rejections become unhandled and crash the test\n * runner / pollute production logs.\n *\n * `safeBatchRequest` issues each request through `ws.request` (so each\n * has its own request-promise lifecycle), waits for all of them via\n * `Promise.allSettled` (every promise gets an explicit handler), and\n * then surfaces the first error if any failed. Same wall-clock cost\n * as the library's batch (parallel send), no orphan rejections.\n *\n * Use this in place of `ws.batchRequest` for any call where one or\n * more elements may legitimately error (e.g. electrs index lag\n * surfacing as `missingheight` for a subset of heights/txids).\n */\n async safeBatchRequest<T>(requests: { method: string; params: unknown[] }[]): Promise<T[]> {\n if (requests.length === 0) return [];\n const settled = await Promise.allSettled(\n requests.map((req) =>\n this.ws.request<T>(\n req.method,\n ...(req.params as Parameters<typeof this.ws.request>[1][]),\n ),\n ),\n );\n for (const r of settled) {\n if (r.status === \"rejected\") throw r.reason;\n }\n return settled.map((r) => (r as PromiseFulfilledResult<T>).value);\n }\n\n async fetchTransactions(txids: string[]): Promise<{ txID: string; hex: string }[]> {\n const requests = txids.map((txid) => ({\n method: GetTransactionMethod,\n params: [txid],\n }));\n for (let i = 0; i < MAX_FETCH_TRANSACTIONS_ATTEMPTS; i++) {\n try {\n const responses = await this.safeBatchRequest<string>(requests);\n return responses.map((hexStr, i) => ({\n txID: txids[i],\n hex: hexStr,\n }));\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.toLowerCase().includes(MISSING_TRANSACTION)) {\n console.warn(\"missing transaction error, retrying\");\n await new Promise((resolve) => setTimeout(resolve, 1000));\n continue;\n }\n throw e;\n }\n }\n throw new Error(\"Unable to fetch transactions: \" + txids);\n }\n\n async fetchVerboseTransaction(txid: string): Promise<VerboseTransaction> {\n return this.ws.request<VerboseTransaction>(GetTransactionMethod, txid, true);\n }\n\n async fetchVerboseTransactions(txids: string[]): Promise<VerboseTransaction[]> {\n if (txids.length === 0) return [];\n const requests = txids.map((txid) => ({\n method: GetTransactionMethod,\n params: [txid, true],\n }));\n return this.safeBatchRequest<VerboseTransaction>(requests);\n }\n\n /**\n * Look up the block height of a confirmed transaction without relying\n * on the verbose-tx endpoint. `blockchain.transaction.get_merkle` is\n * part of the standard SPV protocol and is supported by both Fulcrum\n * and electrs (whereas `blockchain.transaction.get` with verbose=true\n * is Fulcrum-only). Returns `null` when the tx is in the mempool —\n * electrs in that case rejects with a \"not yet in a block\" error.\n */\n async fetchTxMerkle(txid: string): Promise<{ blockHeight: number } | null> {\n let result: { block_height: number } | undefined;\n try {\n result = await this.ws.request<{ block_height: number }>(\n GetTransactionMerkleMethod,\n txid,\n );\n } catch (err) {\n // electrs/Fulcrum raise specific errors when the tx isn't yet in\n // a block — either \"not in a block\" wording, or \"missingheight\"\n // when get_merkle hits the same index-lag race that block.header\n // hits (the tx is reportedly confirmed but the height isn't\n // queryable yet). Map both to mempool/unknown; everything else\n // (auth failure, network outage, malformed response) must surface\n // so callers can fail rather than silently treat the tx as\n // unconfirmed forever.\n if (isTxNotInBlockError(err) || isMissingHeightError(err)) return null;\n throw err;\n }\n if (!result || typeof result.block_height !== \"number\" || result.block_height <= 0) {\n return null;\n }\n return { blockHeight: result.block_height };\n }\n\n async unsubscribeScriptStatus(script: Uint8Array): Promise<void> {\n await this.ws.unsubscribe(SubscribeStatusMethod, toScriptHash(script)).catch(() => {});\n }\n\n async subscribeScriptStatus(\n script: Uint8Array,\n callback: (scripthash: string, status: string | null) => void,\n ): Promise<void> {\n const scriptHash = toScriptHash(script);\n await this.ws.subscribe(\n SubscribeStatusMethod,\n (scripthash: unknown, status: unknown) => {\n if (scripthash === scriptHash) {\n callback(scripthash as string, status as string | null);\n }\n },\n scriptHash,\n );\n }\n\n async fetchHistories(scripts: Uint8Array[]): Promise<TransactionHistory[][]> {\n const scriptsHashes = scripts.map((s) => toScriptHash(s));\n return this.safeBatchRequest<TransactionHistory[]>(\n scriptsHashes.map((s) => ({\n method: GetHistoryMethod,\n params: [s],\n })),\n );\n }\n\n async fetchHistory(script: Uint8Array): Promise<TransactionHistory[]> {\n const scriptHash = toScriptHash(script);\n return this.ws.request<TransactionHistory[]>(GetHistoryMethod, scriptHash);\n }\n\n async fetchBlockHeaders(heights: number[]): Promise<BlockHeader[]> {\n const responses = await this.safeBatchRequest<string>(\n heights.map((h) => ({ method: GetBlockHeader, params: [h] })),\n );\n return responses.map((hexStr, i) => ({\n height: heights[i],\n hex: hexStr,\n }));\n }\n\n async fetchBlockHeader(height: number): Promise<BlockHeader> {\n const headerHex = await this.ws.request<string>(GetBlockHeader, height);\n return { height, hex: headerHex };\n }\n\n /**\n * Returns the current chain tip and keeps it fresh via a single\n * server-side subscription. Subsequent calls return the cached tip\n * (updated by background notifications) without round-tripping to the\n * server. Previously each call issued `blockchain.headers.subscribe` as\n * a regular request, leaving a stale subscription on the server every\n * time — under polling that adds up. ws-electrumx-client deduplicates\n * `subscribe()` by method+params, so registering once is enough.\n */\n async subscribeHeaders(): Promise<HeaderSubscribeResult> {\n if (this.cachedTip) return this.cachedTip;\n if (this.headersSubscribePromise) return this.headersSubscribePromise;\n\n this.headersSubscribePromise = new Promise<HeaderSubscribeResult>((resolve, reject) => {\n let resolved = false;\n this.ws\n .subscribe(SubscribeHeadersMethod, (header: unknown) => {\n if (!isHeaderSubscribeResult(header)) return;\n this.cachedTip = header;\n if (!resolved) {\n resolved = true;\n resolve(header);\n }\n })\n .catch((err) => {\n if (!resolved) {\n resolved = true;\n reject(err);\n }\n });\n });\n\n try {\n return await this.headersSubscribePromise;\n } catch (err) {\n // Allow the next call to retry from scratch.\n this.headersSubscribePromise = null;\n throw err;\n }\n }\n\n async estimateFees(targetNumberBlocks: number): Promise<number> {\n const feeRate = await this.ws.request<number>(EstimateFee, targetNumberBlocks);\n return feeRate;\n }\n\n async broadcastTransaction(txHex: string): Promise<string> {\n return this.ws.request<string>(BroadcastTransaction, txHex);\n }\n\n /**\n * Submit a package of raw transactions atomically via Fulcrum's\n * `blockchain.transaction.broadcast_package` method, the on-the-wire\n * equivalent of bitcoind's `submitpackage` RPC.\n *\n * Required for TRUC (BIP 431) 1P1C relay where the parent has zero\n * (or below-minfee) fee and depends on the child to pay for both via\n * CPFP — sequential broadcast cannot work in that case because the\n * parent would be rejected from the mempool on its own.\n *\n * @param txHexes - Topologically sorted raw transactions; child must\n * be the last element. Currently must be a 1P1C pair\n * (length 2). Parents may not depend on each other.\n * @returns The child transaction id (the last entry in the array),\n * computed locally — `broadcast_package` itself returns\n * `{success, errors}` rather than a txid.\n * @throws If the server does not implement `broadcast_package` (e.g.\n * ElectrumX, or older Fulcrum, or Fulcrum backed by bitcoind\n * < v28.0.0). Callers must surface this clearly to users —\n * this method does NOT silently fall back to sequential\n * broadcasts because doing so would let TRUC packages fail\n * in subtle ways.\n * @throws If the server returns `success=false`, surfacing the\n * underlying mempool rejection in the error message.\n */\n async broadcastPackage(txHexes: string[]): Promise<string> {\n const result = await this.ws.request<BroadcastPackageResult>(\n BroadcastPackageMethod,\n txHexes,\n false,\n );\n if (!result.success) {\n const detail = result.errors ? JSON.stringify(result.errors) : \"unknown error\";\n throw new Error(`Package broadcast rejected: ${detail}`);\n }\n // The child txid is not in the response — derive it from the raw\n // bytes (double-SHA256 of the serialized tx, reversed).\n return childTxidFromHex(txHexes[txHexes.length - 1]);\n }\n\n async getRelayFee(): Promise<number> {\n return this.ws.request<number>(GetRelayFeeMethod);\n }\n\n async close(): Promise<void> {\n try {\n await this.ws.close(\"close\");\n } catch (e) {\n console.debug(\"error closing ws:\", e);\n }\n }\n\n waitForAddressReceivesTx(addr: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const script = OutScript.encode(Address(this.network).decode(addr));\n this.subscribeScriptStatus(script, (_, status) => {\n if (status !== null) {\n resolve();\n }\n }).catch(reject);\n });\n }\n\n async listUnspents(addr: string): Promise<Unspent[]> {\n const script = OutScript.encode(Address(this.network).decode(addr));\n const scriptHash = toScriptHash(script);\n const unspentsFromElectrum = await this.ws.request<UnspentElectrum[]>(\n ListUnspentMethod,\n scriptHash,\n );\n const txs = await this.fetchTransactions(unspentsFromElectrum.map((u) => u.tx_hash));\n\n return unspentsFromElectrum.map((u, index) => {\n const tx = Transaction.fromRaw(hex.decode(txs[index].hex), {\n allowUnknownOutputs: true,\n });\n const output = tx.getOutput(u.tx_pos);\n if (!output.script || output.amount === undefined) {\n throw new Error(`Missing output data for ${u.tx_hash}:${u.tx_pos}`);\n }\n return {\n txid: u.tx_hash,\n vout: u.tx_pos,\n witnessUtxo: {\n script: output.script,\n value: output.amount,\n },\n };\n });\n }\n\n /**\n * Get the address string for a script output, if decodable.\n */\n addressForScript(scriptHex: string): string | undefined {\n try {\n const script = hex.decode(scriptHex);\n return Address(this.network).encode(OutScript.decode(script));\n } catch {\n return undefined;\n }\n }\n}\n\n/**\n * Electrum-based implementation of the {@link OnchainProvider} interface.\n *\n * Built around the subset of the Electrum protocol that both **Fulcrum**\n * and **electrs** support — listunspent, get_history, transaction.get\n * (non-verbose), transaction.get_merkle, block.header,\n * headers.subscribe, scripthash.subscribe, estimatefee, relayfee, and\n * broadcast. The verbose form of `transaction.get` is **not** used (it's\n * Fulcrum-only and rejected by electrs); confirmation status is derived\n * from `transaction.get_merkle` plus parsed block headers.\n *\n * Output amounts are derived from parsed raw transaction bytes (exact\n * bigints), never the floating-point `value` fields some servers return.\n *\n * Atomic 1P1C package broadcast (TRUC / BIP 431) is supported via\n * Fulcrum's `blockchain.transaction.broadcast_package`. There is **no\n * fallback** to sequential parent-then-child broadcasts — TRUC packages\n * with a zero-fee parent would silently fail, so the call surfaces an\n * error against servers that don't support the method.\n *\n * @example Default URL via {@link ELECTRUM_WS_URL}\n * ```typescript\n * import { ElectrumWS } from \"ws-electrumx-client\";\n * import {\n * ElectrumOnchainProvider,\n * ELECTRUM_WS_URL,\n * networks,\n * } from \"@arkade-os/sdk\";\n *\n * const ws = new ElectrumWS(ELECTRUM_WS_URL.bitcoin);\n * const provider = new ElectrumOnchainProvider(ws, networks.bitcoin);\n *\n * const coins = await provider.getCoins(\"bc1q...\");\n * await provider.close();\n * ```\n *\n * @example Custom server\n * ```typescript\n * const ws = new ElectrumWS(\"wss://my-fulcrum.example:50004\");\n * const provider = new ElectrumOnchainProvider(ws, networks.bitcoin);\n * ```\n */\nexport class ElectrumOnchainProvider implements OnchainProvider {\n private chain: WsElectrumChainSource;\n\n constructor(\n private ws: ElectrumWS,\n private network: Network,\n ) {\n this.chain = new WsElectrumChainSource(ws, network);\n }\n\n async getCoins(address: string): Promise<Coin[]> {\n const script = this.encodeAddress(address);\n const scriptHash = toScriptHash(script);\n const unspents = await this.ws.request<UnspentElectrum[]>(ListUnspentMethod, scriptHash);\n\n return unspents.map((u) => ({\n txid: u.tx_hash,\n vout: u.tx_pos,\n value: u.value,\n status: {\n confirmed: u.height > 0,\n block_height: u.height > 0 ? u.height : undefined,\n },\n }));\n }\n\n async getFeeRate(): Promise<number | undefined> {\n // electrum returns BTC/kB, we need sat/vB\n // 1 BTC = 100_000_000 sat, 1 kB = 1000 bytes\n // sat/vB = (BTC/kB) * 100_000_000 / 1000 = (BTC/kB) * 100_000\n const feePerKb = await this.chain.estimateFees(1);\n if (feePerKb < 0) {\n // -1 means the daemon cannot estimate\n return undefined;\n }\n return Math.max(1, Math.ceil(feePerKb * 100_000));\n }\n\n /**\n * Broadcast a single transaction or a TRUC (BIP 431) 1P1C package\n * atomically.\n *\n * **Server requirements for 1P1C packages:** the backing Electrum\n * server must implement `blockchain.transaction.broadcast_package`\n * (Fulcrum ≥ 1.10) and be backed by bitcoind ≥ v28.0.0. ElectrumX\n * does not implement this method. There is **no fallback** to\n * sequential parent-then-child broadcast: TRUC packages typically\n * have a zero-fee parent and would be rejected from the mempool on\n * their own, so a fallback would silently fail in subtle ways.\n * Callers receiving a \"method not found\" error here should route\n * through a different provider for that submission.\n *\n * @param txs - One transaction (single broadcast) or two\n * topologically-sorted transactions (parent first,\n * child last) for 1P1C package relay.\n * @returns The broadcast txid (or the child txid for 1P1C packages).\n */\n async broadcastTransaction(...txs: string[]): Promise<string> {\n if (txs.length === 1) {\n return this.chain.broadcastTransaction(txs[0]);\n }\n if (txs.length === 2) {\n return this.chain.broadcastPackage(txs);\n }\n throw new Error(\"Only 1 or 1P1C package can be broadcast\");\n }\n\n async getTxOutspends(txid: string): Promise<{ spent: boolean; txid: string }[]> {\n // Step 1: fetch the creating tx to get its output scripts (1 round trip)\n const [txResult] = await this.chain.fetchTransactions([txid]);\n const tx = Transaction.fromRaw(hex.decode(txResult.hex), {\n allowUnknownOutputs: true,\n });\n\n const outputCount = tx.outputsLength;\n const outputScriptHashes: (string | undefined)[] = [];\n for (let i = 0; i < outputCount; i++) {\n const output = tx.getOutput(i);\n outputScriptHashes.push(output.script ? toScriptHash(output.script) : undefined);\n }\n\n const validScriptHashes = outputScriptHashes.filter((h): h is string => h !== undefined);\n\n const results: { spent: boolean; txid: string }[] = Array.from(\n { length: outputCount },\n () => ({ spent: false, txid: \"\" }),\n );\n\n if (validScriptHashes.length === 0) return results;\n\n // Step 2: batch listunspent for all output scripthashes (1 round trip)\n // This tells us exactly which txid:vout pairs are still unspent.\n const unspentBatch = await this.chain.safeBatchRequest<UnspentElectrum[]>(\n validScriptHashes.map((sh) => ({\n method: ListUnspentMethod,\n params: [sh],\n })),\n );\n\n const unspentSet = new Set<string>();\n let validIdx = 0;\n for (let i = 0; i < outputCount; i++) {\n if (outputScriptHashes[i] !== undefined) {\n for (const u of unspentBatch[validIdx]) {\n unspentSet.add(`${u.tx_hash}:${u.tx_pos}`);\n }\n validIdx++;\n }\n }\n\n // Step 3: batch get_history only for spent outputs (1 round trip)\n const spentIndices: number[] = [];\n const spentScriptHashes: string[] = [];\n for (let i = 0; i < outputCount; i++) {\n const sh = outputScriptHashes[i];\n if (sh && !unspentSet.has(`${txid}:${i}`)) {\n spentIndices.push(i);\n spentScriptHashes.push(sh);\n }\n }\n\n if (spentIndices.length === 0) return results;\n\n const histories = await this.chain.safeBatchRequest<TransactionHistory[]>(\n spentScriptHashes.map((sh) => ({\n method: GetHistoryMethod,\n params: [sh],\n })),\n );\n\n // For each spent output find the spender in its history.\n // Common case: history has exactly 2 entries (creating + spending tx).\n // Ambiguous case (same script reused): batch-fetch all candidates at once.\n const ambiguousIndices: number[] = [];\n const ambiguousCandidates: string[][] = [];\n\n for (let j = 0; j < spentIndices.length; j++) {\n const i = spentIndices[j];\n const candidates = histories[j].map((h) => h.tx_hash).filter((hash) => hash !== txid);\n\n if (candidates.length === 1) {\n // Fast path: one candidate = the spender\n results[i] = { spent: true, txid: candidates[0] };\n } else if (candidates.length > 1) {\n ambiguousIndices.push(i);\n ambiguousCandidates.push(candidates);\n }\n // candidates.length === 0 → mempool eviction, treat as unspent\n }\n\n // Step 4 (rare): batch-fetch all ambiguous candidate txs at once\n if (ambiguousIndices.length > 0) {\n const allCandidateTxids = [...new Set(ambiguousCandidates.flat())];\n const fetched = await this.chain.fetchTransactions(allCandidateTxids);\n const txMap = new Map(fetched.map((t) => [t.txID, t.hex]));\n\n for (let j = 0; j < ambiguousIndices.length; j++) {\n const i = ambiguousIndices[j];\n for (const candidateTxid of ambiguousCandidates[j]) {\n const rawHex = txMap.get(candidateTxid);\n if (!rawHex) continue;\n const candidateTx = Transaction.fromRaw(hex.decode(rawHex), {\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n });\n let found = false;\n for (let k = 0; k < candidateTx.inputsLength; k++) {\n const input = candidateTx.getInput(k);\n if (input.txid && hex.encode(input.txid) === txid && input.index === i) {\n results[i] = { spent: true, txid: candidateTxid };\n found = true;\n break;\n }\n }\n if (found) break;\n }\n }\n }\n\n return results;\n }\n\n async getTransactions(address: string): Promise<ExplorerTransaction[]> {\n const script = this.encodeAddress(address);\n const history = await this.chain.fetchHistory(script);\n if (history.length === 0) return [];\n return this.historyToExplorerTxs(history);\n }\n\n /**\n * Resolve a list of `{tx_hash, height}` entries (as returned by the\n * scripthash history endpoint) into ExplorerTransaction shape **without\n * using the verbose-tx endpoint**, which only Fulcrum implements. We\n * reconstruct everything the verbose response would have given us:\n * - vouts ← parse the raw tx (exact sat amounts, no float precision risk)\n * - block_time ← batch-fetch the block headers for the heights present\n * - addresses ← decode each output's scriptPubKey via @scure/btc-signer\n */\n private async historyToExplorerTxs(\n history: TransactionHistory[],\n ): Promise<ExplorerTransaction[]> {\n const txids = history.map((h) => h.tx_hash);\n const rawTxs = await this.chain.fetchTransactions(txids);\n const rawHexByTxid = new Map(rawTxs.map((t) => [t.txID, t.hex]));\n\n // De-duplicated batch lookup of block headers (now safe — see\n // safeBatchRequest above). Heights whose headers fail to resolve\n // surface via the wrapper's first-error throw; we tolerate that\n // here by falling back to per-height calls under Promise.allSettled\n // so one missing header doesn't poison the whole history mapping.\n // The old verbose-tx code had the same tolerance via\n // `vtx.blocktime || vtx.time || 0`.\n const confirmedHeights = [...new Set(history.map((h) => h.height).filter((h) => h > 0))];\n const blockTimeByHeight = new Map<number, number>();\n if (confirmedHeights.length > 0) {\n try {\n const headers = await this.chain.fetchBlockHeaders(confirmedHeights);\n for (const header of headers) {\n blockTimeByHeight.set(header.height, parseBlockHeader(header.hex).timestamp);\n }\n } catch {\n const settled = await Promise.allSettled(\n confirmedHeights.map((h) => this.chain.fetchBlockHeader(h)),\n );\n settled.forEach((res) => {\n if (res.status === \"fulfilled\") {\n blockTimeByHeight.set(\n res.value.height,\n parseBlockHeader(res.value.hex).timestamp,\n );\n }\n // Rejections leave the height absent → block_time = 0.\n });\n }\n }\n\n return history.map((entry) =>\n this.buildExplorerTx(entry, rawHexByTxid.get(entry.tx_hash), blockTimeByHeight),\n );\n }\n\n /**\n * Build an ExplorerTransaction from a history entry plus the raw tx hex\n * (when known) and a height→block_time map. Parse errors propagate —\n * silently returning an empty vout would hide real outputs (e.g. a\n * deposit) and is far worse for protocol-level money handling than\n * failing the whole batch.\n */\n private buildExplorerTx(\n entry: TransactionHistory,\n rawHex: string | undefined,\n blockTimeByHeight: Map<number, number>,\n ): ExplorerTransaction {\n const vout: ExplorerTransaction[\"vout\"] = [];\n if (rawHex) {\n let tx: Transaction;\n try {\n tx = Transaction.fromRaw(hex.decode(rawHex), {\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n });\n } catch (err) {\n throw new Error(\n `Failed to parse raw tx for ${entry.tx_hash}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const scriptHex = output.script ? hex.encode(output.script) : \"\";\n vout.push({\n scriptpubkey_address: scriptHex\n ? (this.chain.addressForScript(scriptHex) ?? \"\")\n : \"\",\n value: (output.amount ?? 0n).toString(),\n });\n }\n }\n\n return {\n txid: entry.tx_hash,\n vout,\n status: {\n confirmed: entry.height > 0,\n block_time: blockTimeByHeight.get(entry.height) ?? 0,\n },\n };\n }\n\n /**\n * Decode `address` into its scriptPubKey, throwing a clear error if the\n * input is malformed. @scure/btc-signer raises a generic decode error\n * which is hard to map back to user input — this wraps it.\n */\n private encodeAddress(address: string): Uint8Array {\n try {\n return OutScript.encode(Address(this.network).decode(address));\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new Error(`Invalid address ${address}: ${reason}`);\n }\n }\n\n async getTxStatus(\n txid: string,\n ): Promise<{ confirmed: false } | { confirmed: true; blockTime: number; blockHeight: number }> {\n // Use `transaction.get_merkle` rather than the verbose `transaction.get`\n // because electrs (used by mempool.space, blockstream.info, and the\n // nigiri regtest) doesn't implement verbose. get_merkle is part of the\n // standard SPV protocol and supported by every Electrum server.\n const merkle = await this.chain.fetchTxMerkle(txid);\n if (!merkle) return { confirmed: false };\n\n // Header lookup can transiently race with electrs's index right\n // after a fresh block — listunspent/get_merkle expose the new\n // height before block.header(N) is queryable. Tolerate that the\n // same way historyToExplorerTxs does: confirmation status and\n // height are still authoritative; only block_time degrades.\n let blockTime = 0;\n try {\n const header = await this.chain.fetchBlockHeader(merkle.blockHeight);\n blockTime = parseBlockHeader(header.hex).timestamp;\n } catch (err) {\n if (!isMissingHeightError(err)) throw err;\n }\n return {\n confirmed: true,\n blockHeight: merkle.blockHeight,\n blockTime,\n };\n }\n\n async getChainTip(): Promise<{\n height: number;\n time: number;\n hash: string;\n }> {\n const tip = await this.chain.subscribeHeaders();\n const { hash, timestamp } = parseBlockHeader(tip.hex);\n\n return {\n height: tip.height,\n time: timestamp,\n hash,\n };\n }\n\n async watchAddresses(\n addresses: string[],\n eventCallback: (txs: ExplorerTransaction[]) => void,\n ): Promise<() => void> {\n const scripts = addresses.map((addr) => this.encodeAddress(addr));\n const scriptHashes = scripts.map(toScriptHash);\n // O(1) scripthash → script lookup, kept in sync with the\n // scripts/scriptHashes arrays. Server notifications hit this on\n // every push, so the previous indexOf was O(n) per event.\n const scriptByHash = new Map<string, Uint8Array>(\n scriptHashes.map((h, i) => [h, scripts[i]]),\n );\n\n // Track known history per script to detect new txs.\n const knownTxids = new Map<string, Set<string>>();\n\n // Initialize known-set in parallel — for a wallet watching many\n // addresses this avoids n sequential round trips on first call.\n const initialHistories = await Promise.all(scripts.map((s) => this.chain.fetchHistory(s)));\n initialHistories.forEach((history, i) => {\n knownTxids.set(scriptHashes[i], new Set(history.map((h) => h.tx_hash)));\n });\n\n // Per-scripthash mutex serializing concurrent notifications so\n // two pushes for the same address can't fetch history in parallel\n // and emit duplicate events. Each call chains onto the previous\n // one's tail; failures are swallowed to keep the chain alive.\n const inFlight = new Map<string, Promise<void>>();\n\n const processStatusChange = async (scripthash: string): Promise<void> => {\n const script = scriptByHash.get(scripthash);\n if (!script) return;\n\n const history = await this.chain.fetchHistory(script);\n const known = knownTxids.get(scripthash) ?? new Set<string>();\n const newEntries = history.filter((entry) => !known.has(entry.tx_hash));\n\n if (newEntries.length === 0) return;\n\n // Map the new history entries through the same non-verbose\n // pipeline getTransactions uses, so subscribe-driven and\n // poll-driven callers see ExplorerTransactions of identical shape.\n // The dedupe set is updated ONLY after delivery succeeds —\n // otherwise a failed fetch or callback would permanently mark\n // these txids as seen and the next notification wouldn't\n // re-deliver them.\n const explorerTxs = await this.historyToExplorerTxs(newEntries);\n eventCallback(explorerTxs);\n for (const entry of newEntries) known.add(entry.tx_hash);\n knownTxids.set(scripthash, known);\n };\n\n const handleStatusChange = (scripthash: string): Promise<void> => {\n const previous = inFlight.get(scripthash) ?? Promise.resolve();\n const next = previous.then(() => processStatusChange(scripthash));\n // Keep the chain alive even when one link rejects.\n inFlight.set(\n scripthash,\n next.catch(() => undefined),\n );\n return next;\n };\n\n // Register all subscriptions in parallel; if any one fails, tear\n // down the others so we don't leak server-side subscriptions on\n // a connection the caller never gets a stop() handle for.\n const subscribed: Uint8Array[] = [];\n try {\n await Promise.all(\n scripts.map(async (script) => {\n await this.chain.subscribeScriptStatus(script, (scripthash, status) => {\n if (status !== null) {\n handleStatusChange(scripthash).catch(console.error);\n }\n });\n subscribed.push(script);\n }),\n );\n } catch (err) {\n await Promise.allSettled(subscribed.map((s) => this.chain.unsubscribeScriptStatus(s)));\n throw err;\n }\n\n return () => {\n for (const script of scripts) {\n this.chain.unsubscribeScriptStatus(script).catch(() => {});\n }\n };\n }\n\n /** Close the underlying WebSocket connection. */\n async close(): Promise<void> {\n await this.chain.close();\n }\n}\n\nfunction toScriptHash(script: Uint8Array): string {\n return hex.encode(sha256(script).reverse());\n}\n\nfunction isHeaderSubscribeResult(v: unknown): v is HeaderSubscribeResult {\n if (typeof v !== \"object\" || v === null) return false;\n const obj = v as Record<string, unknown>;\n return typeof obj.height === \"number\" && typeof obj.hex === \"string\";\n}\n\n/**\n * Recognise the \"block header not yet indexable\" failure shape returned by\n * electrum servers (electrs in particular) when `block.header(N)` runs\n * against a height that's already in `listunspent`/`get_merkle` but hasn't\n * been indexed yet. Surfaced as `missingheight`. Tolerated by callers so\n * the index-lag race doesn't poison confirmed-status reads; genuine\n * failures (auth/network) propagate.\n */\nfunction isMissingHeightError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : typeof err === \"string\" ? err : \"\";\n return msg.toLowerCase().includes(\"missingheight\");\n}\n\n/**\n * Recognise the \"transaction not in a block yet\" failure shape returned by\n * electrum servers when `blockchain.transaction.get_merkle` is asked about a\n * mempool tx. electrs surfaces this as the strings below; Fulcrum mirrors\n * the wording. We match conservatively so genuine errors (auth, network,\n * malformed response) still propagate.\n */\nfunction isTxNotInBlockError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : typeof err === \"string\" ? err : \"\";\n const normalized = msg.toLowerCase();\n return (\n normalized.includes(\"not yet in a block\") ||\n normalized.includes(\"not in a block\") ||\n normalized.includes(\"not in block\") ||\n normalized.includes(\"no confirmed transaction\")\n );\n}\n\n/**\n * Compute the txid of a serialized transaction. For segwit transactions\n * (every Ark transaction), the broadcast hex includes witness data, but\n * the txid is the double-SHA256 of the legacy (witness-stripped)\n * serialization. Hashing the raw broadcast bytes directly would yield\n * the wtxid instead — silently breaking any caller that tracks the tx\n * by id (round settlement, forfeit monitoring, exit paths).\n *\n * Delegating to `Transaction.fromRaw(...).id` lets @scure/btc-signer\n * handle the witness-stripping correctly.\n */\nfunction childTxidFromHex(txHex: string): string {\n const tx = Transaction.fromRaw(hex.decode(txHex), {\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n });\n return tx.id;\n}\n","import { p2tr, p2wpkh, Address, OutScript, RawWitness, SigHash } from \"@scure/btc-signer\";\nimport { type BTC_NETWORK, concatBytes, hash160, sha256x2 } from \"@scure/btc-signer/utils.js\";\nimport { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { equalBytes } from \"@noble/curves/utils.js\";\nimport { base64 } from \"@scure/base\";\nimport type { Identity } from \"../identity\";\nimport { Transaction } from \"../utils/transaction\";\nimport { craftToSpendTx, OP_RETURN_EMPTY_PKSCRIPT } from \"../intent\";\n\nconst TAG_BIP322 = \"BIP0322-signed-message\";\n\n/**\n * BIP-322 simple message signing and verification.\n *\n * Supports P2TR (Taproot) signing and verification, P2WPKH verification,\n * and legacy P2PKH verification (Bitcoin Core signmessage format).\n *\n * Reuses the same toSpend/toSign transaction construction as Intent proofs,\n * but with the standard BIP-322 tagged hash (\"BIP0322-signed-message\")\n * instead of the Arkade-specific tag.\n *\n * @see https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\n *\n * @example\n * ```typescript\n * // Sign a message (P2TR)\n * const signature = await BIP322.sign(\"Hello Bitcoin!\", identity);\n *\n * // Verify a signature (P2TR or P2WPKH)\n * const valid = BIP322.verify(\"Hello Bitcoin!\", signature, \"bc1p...\");\n * const valid2 = BIP322.verify(\"Hello Bitcoin!\", signature, \"bc1q...\");\n * ```\n */\nexport namespace BIP322 {\n /**\n * Sign a message using the BIP-322 simple signature scheme.\n *\n * Constructs the standard BIP-322 toSpend and toSign transactions,\n * signs via the Identity interface, and returns the base64-encoded\n * witness stack.\n *\n * @param message - The message to sign\n * @param identity - Identity instance (holds the private key internally)\n * @param network - Optional Bitcoin network for P2TR address derivation\n * @returns Base64-encoded BIP-322 simple signature (witness stack)\n */\n export async function sign(\n message: string,\n identity: Identity,\n network?: BTC_NETWORK,\n ): Promise<string> {\n const xOnlyPubKey = await identity.xOnlyPublicKey();\n const payment = p2tr(xOnlyPubKey, undefined, network);\n\n // Build BIP-322 toSpend using shared construction with BIP-322 tag\n const toSpend = craftToSpendTx(message, payment.script, TAG_BIP322);\n\n // Build BIP-322 toSign: version 0, single input spending toSpend, OP_RETURN output\n const toSign = craftBIP322ToSignP2TR(toSpend, payment.script, xOnlyPubKey);\n\n // Sign with identity (handles P2TR key-spend internally)\n const signed = await identity.sign(toSign, [0]);\n\n // Finalize and extract witness\n signed.finalizeIdx(0);\n const input = signed.getInput(0);\n if (!input.finalScriptWitness) {\n throw new Error(\"BIP-322: failed to produce witness after signing\");\n }\n\n return base64.encode(RawWitness.encode(input.finalScriptWitness));\n }\n\n /**\n * Verify a BIP-322 signature for a P2TR, P2WPKH, or legacy P2PKH address.\n *\n * For segwit addresses (P2TR, P2WPKH), reconstructs the BIP-322\n * toSpend/toSign transactions and verifies the witness signature.\n *\n * For P2PKH addresses, verifies using the Bitcoin Core legacy\n * `signmessage` format (compact recoverable ECDSA signature).\n *\n * @param message - The original message that was signed\n * @param signature - Base64-encoded signature (BIP-322 witness or legacy compact)\n * @param address - P2TR, P2WPKH, or P2PKH address of the signer\n * @param network - Optional Bitcoin network for address decoding\n * @returns true if the signature is valid\n */\n export function verify(\n message: string,\n signature: string,\n address: string,\n network?: BTC_NETWORK,\n ): boolean {\n let decoded;\n\n try {\n decoded = Address(network).decode(address);\n } catch {\n return false;\n }\n\n // Legacy P2PKH: signature is base64 of 65 raw bytes, not a witness\n if (decoded.type === \"pkh\") {\n try {\n return verifyLegacy(message, base64.decode(signature), decoded.hash);\n } catch {\n return false;\n }\n }\n\n // BIP-322 simple: signature is base64 of RawWitness\n let pkScript;\n let witnessItems;\n\n try {\n pkScript = OutScript.encode(decoded);\n witnessItems = RawWitness.decode(base64.decode(signature));\n } catch {\n return false;\n }\n\n if (witnessItems.length === 0) {\n return false;\n }\n\n if (decoded.type === \"tr\") {\n return verifyP2TR(message, witnessItems, pkScript, decoded.pubkey);\n }\n if (decoded.type === \"wpkh\") {\n return verifyP2WPKH(message, witnessItems, pkScript, decoded.hash);\n }\n\n throw new Error(`BIP-322 verify: unsupported address type '${decoded.type}'`);\n }\n}\n\nfunction verifyP2TR(\n message: string,\n witnessItems: Uint8Array[],\n pkScript: Uint8Array,\n pubkey: Uint8Array,\n): boolean {\n // P2TR key-spend witness is exactly [schnorr_signature].\n // Multiple items indicates a script-path spend, which BIP-322 simple doesn't cover.\n if (witnessItems.length !== 1) {\n return false;\n }\n const sig = witnessItems[0];\n if (sig.length !== 64 && sig.length !== 65) {\n return false;\n }\n\n // BIP-322 simple only allows SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).\n const sighashType = sig.length === 65 ? sig[64] : SigHash.DEFAULT;\n if (sighashType !== SigHash.DEFAULT && sighashType !== SigHash.ALL) {\n return false;\n }\n\n const toSpend = craftToSpendTx(message, pkScript, TAG_BIP322);\n const toSign = craftBIP322ToSignP2TR(toSpend, pkScript, pubkey);\n\n const sighash = toSign.preimageWitnessV1(0, [pkScript], sighashType, [0n]);\n\n const rawSig = sig.length === 65 ? sig.subarray(0, 64) : sig;\n return schnorr.verify(rawSig, sighash, pubkey);\n}\n\nfunction verifyP2WPKH(\n message: string,\n witnessItems: Uint8Array[],\n pkScript: Uint8Array,\n addressHash: Uint8Array,\n): boolean {\n // P2WPKH witness: [der_signature || sighash_byte, compressed_pubkey]\n if (witnessItems.length !== 2) {\n return false;\n }\n\n const sigWithHash = witnessItems[0];\n const pubkey = witnessItems[1];\n\n if (pubkey.length !== 33 || sigWithHash.length < 2) {\n return false;\n }\n\n // Verify the pubkey matches the address hash\n const derived = p2wpkh(pubkey);\n if (!equalBytes(derived.hash, addressHash)) {\n return false;\n }\n\n // Extract sighash type (last byte) and DER signature\n const sighashType = sigWithHash[sigWithHash.length - 1];\n const derSig = sigWithHash.subarray(0, sigWithHash.length - 1);\n\n // Build toSpend and toSign\n const toSpend = craftToSpendTx(message, pkScript, TAG_BIP322);\n const toSign = craftBIP322ToSignSimple(toSpend, pkScript);\n\n // BIP-143 scriptCode for P2WPKH: equivalent P2PKH script\n const scriptCode = OutScript.encode({ type: \"pkh\", hash: addressHash });\n const sighash = toSign.preimageWitnessV0(0, scriptCode, sighashType, 0n);\n\n return secp256k1.verify(derSig, sighash, pubkey, {\n prehash: false,\n format: \"der\",\n });\n}\n\n/**\n * Verify a legacy Bitcoin Core signmessage signature for a P2PKH address.\n *\n * The signature is 65 bytes: [recovery_flag, r(32), s(32)].\n * The recovery flag encodes both the recovery ID and whether the key is\n * compressed: flag = 27 + recovery_id (+ 4 if compressed).\n */\nfunction verifyLegacy(message: string, sigBytes: Uint8Array, addressHash: Uint8Array): boolean {\n if (sigBytes.length !== 65) {\n return false;\n }\n\n const flag = sigBytes[0];\n if (flag < 27 || flag > 34) {\n return false;\n }\n\n const compressed = flag >= 31;\n const recoveryId = compressed ? flag - 31 : flag - 27;\n\n const compactSig = sigBytes.subarray(1, 65);\n const msgHash = bitcoinMessageHash(message);\n\n try {\n const sig = secp256k1.Signature.fromBytes(compactSig, \"compact\").addRecoveryBit(recoveryId);\n const point = sig.recoverPublicKey(msgHash);\n const pubkeyBytes = point.toBytes(compressed);\n\n return equalBytes(hash160(pubkeyBytes), addressHash);\n } catch {\n return false;\n }\n}\n\n/**\n * Compute the Bitcoin message hash: SHA256d(magic_prefix + CompactSize(len) + message).\n */\nfunction bitcoinMessageHash(message: string): Uint8Array {\n const MAGIC = new TextEncoder().encode(\"\\x18Bitcoin Signed Message:\\n\");\n const msgBytes = new TextEncoder().encode(message);\n return sha256x2(concatBytes(MAGIC, encodeCompactSize(msgBytes.length), msgBytes));\n}\n\nfunction encodeCompactSize(n: number): Uint8Array {\n if (n < 253) return new Uint8Array([n]);\n if (n <= 0xffff) {\n const buf = new Uint8Array(3);\n buf[0] = 253;\n buf[1] = n & 0xff;\n buf[2] = (n >> 8) & 0xff;\n return buf;\n }\n const buf = new Uint8Array(5);\n buf[0] = 254;\n buf[1] = n & 0xff;\n buf[2] = (n >> 8) & 0xff;\n buf[3] = (n >> 16) & 0xff;\n buf[4] = (n >> 24) & 0xff;\n return buf;\n}\n\n/**\n * Build the BIP-322 \"toSign\" transaction for P2TR key-spend.\n */\nfunction craftBIP322ToSignP2TR(\n toSpend: Transaction,\n pkScript: Uint8Array,\n tapInternalKey: Uint8Array,\n): Transaction {\n const tx = new Transaction({ version: 0 });\n\n tx.addInput({\n txid: toSpend.id,\n index: 0,\n sequence: 0,\n witnessUtxo: {\n script: pkScript,\n amount: 0n,\n },\n tapInternalKey,\n sighashType: SigHash.DEFAULT,\n });\n\n tx.addOutput({\n amount: 0n,\n script: OP_RETURN_EMPTY_PKSCRIPT,\n });\n\n return tx;\n}\n\n/**\n * Build the BIP-322 \"toSign\" transaction (generic, no key metadata).\n *\n * Used for P2WPKH verification where the toSign only needs\n * the witnessUtxo, not tapInternalKey.\n */\nfunction craftBIP322ToSignSimple(toSpend: Transaction, pkScript: Uint8Array): Transaction {\n const tx = new Transaction({ version: 0 });\n\n tx.addInput({\n txid: toSpend.id,\n index: 0,\n sequence: 0,\n witnessUtxo: {\n script: pkScript,\n amount: 0n,\n },\n });\n\n tx.addOutput({\n amount: 0n,\n script: OP_RETURN_EMPTY_PKSCRIPT,\n });\n\n return tx;\n}\n","import { base64, hex } from \"@scure/base\";\nimport { SigHash, TaprootControlBlock } from \"@scure/btc-signer\";\nimport { TransactionInputUpdate } from \"@scure/btc-signer/psbt.js\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport { ChainTx, ChainTxType, IndexerProvider } from \"../providers/indexer\";\nimport { AnchorBumper } from \"../utils/anchor\";\nimport { OnchainProvider } from \"../providers/onchain\";\nimport { ExtendedVirtualCoin, Outpoint } from \".\";\nimport { ConditionCSVMultisigTapscript, CSVMultisigTapscript } from \"../script/tapscript\";\nimport { VtxoScript } from \"../script/base\";\nimport { TxWeightEstimator } from \"../utils/txSizeEstimator\";\nimport { Wallet } from \"./wallet\";\nimport { Transaction } from \"../utils/transaction\";\nimport { DUST_AMOUNT } from \"./utils\";\n\nexport namespace Unroll {\n export enum StepType {\n UNROLL,\n WAIT,\n DONE,\n }\n\n /**\n * Unroll step where the transaction has to be broadcasted in a 1C1P package\n */\n export type UnrollStep = {\n tx: Transaction;\n pkg: [parent: string, child: string];\n };\n\n /**\n * Wait step where the transaction has to be confirmed onchain\n */\n export type WaitStep = {\n txid: string;\n };\n\n /**\n * Done step where the unrolling process is complete\n */\n export type DoneStep = {\n vtxoTxid: string;\n };\n\n export type Step =\n | ({\n type: StepType.DONE;\n } & DoneStep)\n | ({\n type: StepType.UNROLL;\n } & UnrollStep)\n | ({\n type: StepType.WAIT;\n } & WaitStep);\n\n /**\n * Manages the unrolling process of a virtual output back to the Bitcoin blockchain.\n *\n * The Session class implements an async iterator that processes the unrolling steps:\n * 1. **WAIT**: Waits for a transaction to be confirmed onchain (if it's in mempool)\n * 2. **UNROLL**: Broadcasts the next transaction in the chain to the blockchain\n * 3. **DONE**: Indicates the unrolling process is complete\n *\n * The unrolling process works by traversing the transaction chain from the root (most recent)\n * to the leaf (oldest), broadcasting each transaction that isn't already onchain.\n *\n * @example\n * ```typescript\n * const session = await Unroll.Session.create(vtxoOutpoint, bumper, explorer, indexer);\n *\n * // iterate over the steps\n * for await (const doneStep of session) {\n * switch (doneStep.type) {\n * case Unroll.StepType.WAIT:\n * console.log(`Transaction ${doneStep.txid} confirmed`);\n * break;\n * case Unroll.StepType.UNROLL:\n * console.log(`Broadcasting transaction ${doneStep.tx.id}`);\n * break;\n * case Unroll.StepType.DONE:\n * console.log(`Unrolling complete for virtual output ${doneStep.vtxoTxid}`);\n * break;\n * }\n * }\n * ```\n **/\n export class Session implements AsyncIterable<Step> {\n /** Create an unroll session from a virtual output outpoint and its dependency chain. */\n constructor(\n readonly toUnroll: Outpoint & { chain: ChainTx[] },\n readonly bumper: AnchorBumper,\n readonly explorer: OnchainProvider,\n readonly indexer: IndexerProvider,\n ) {}\n\n /** Create an unroll session by loading the virtual output chain from the indexer. */\n static async create(\n toUnroll: Outpoint,\n bumper: AnchorBumper,\n explorer: OnchainProvider,\n indexer: IndexerProvider,\n ): Promise<Session> {\n const { chain } = await indexer.getVtxoChain(toUnroll);\n return new Session({ ...toUnroll, chain }, bumper, explorer, indexer);\n }\n\n /**\n * Get the next step to be executed\n * @returns The next step to be executed + the function to execute it\n */\n async next(): Promise<Step & { do: () => Promise<void> }> {\n let nextTxToBroadcast: ChainTx | undefined;\n\n const chain = this.toUnroll.chain;\n\n // Iterate through the chain from the end (root) to the beginning (leaf)\n for (let i = chain.length - 1; i >= 0; i--) {\n const chainTx = chain[i];\n\n // Skip commitment transactions as they are always onchain\n if (\n chainTx.type === ChainTxType.COMMITMENT ||\n chainTx.type === ChainTxType.UNSPECIFIED\n ) {\n continue;\n }\n\n try {\n // Check if the transaction is confirmed onchain\n const txInfo = await this.explorer.getTxStatus(chainTx.txid);\n\n // If found but not confirmed, it means the tx is in the mempool\n // An unilateral exit is running, we must wait for it to be confirmed\n if (!txInfo.confirmed) {\n return {\n type: StepType.WAIT,\n txid: chainTx.txid,\n do: doWait(this.explorer, chainTx.txid),\n };\n }\n } catch (e) {\n // If the tx is not found, it's offchain, let's break\n nextTxToBroadcast = chainTx;\n break;\n }\n }\n\n if (!nextTxToBroadcast) {\n return {\n type: StepType.DONE,\n vtxoTxid: this.toUnroll.txid,\n do: () => Promise.resolve(),\n };\n }\n\n // Get the virtual transaction data\n const virtualTxs = await this.indexer.getVirtualTxs([nextTxToBroadcast.txid]);\n\n if (virtualTxs.txs.length === 0) {\n throw new Error(`Tx ${nextTxToBroadcast.txid} not found`);\n }\n\n const tx = Transaction.fromPSBT(base64.decode(virtualTxs.txs[0]));\n\n // finalize the tree transaction\n if (nextTxToBroadcast.type === ChainTxType.TREE) {\n const input = tx.getInput(0);\n if (!input) {\n throw new Error(\"Input not found\");\n }\n const tapKeySig = input.tapKeySig;\n if (!tapKeySig) {\n throw new Error(\"Tap key sig not found\");\n }\n tx.updateInput(0, {\n finalScriptWitness: [tapKeySig],\n });\n } else {\n // finalize Arkade transaction\n tx.finalize();\n }\n\n const pkg = await this.bumper.bumpP2A(tx);\n return {\n type: StepType.UNROLL,\n tx,\n pkg,\n do: doUnroll(this.explorer, pkg),\n };\n }\n\n /**\n * Iterate over the steps to be executed and execute them\n * @returns An async iterator over the executed steps\n */\n async *[Symbol.asyncIterator](): AsyncIterator<Step> {\n let lastStep: StepType | undefined;\n do {\n if (lastStep !== undefined) {\n // wait 1 second before trying the next step in order to give time to the\n // explorer to update the tx status\n await sleep(1_000);\n }\n const step = await this.next();\n await step.do();\n yield step;\n lastStep = step.type;\n } while (lastStep !== StepType.DONE);\n }\n }\n\n /**\n * Complete the unroll of a virtual output by broadcasting the transaction that spends the CSV path.\n * @param wallet the wallet owning the virtual output(s)\n * @param vtxoTxids the txids of the virtual output(s) to complete unroll\n * @param outputAddress the address to send the unrolled funds to\n * @throws if the virtual output(s) are not fully unrolled, if the txids are not found, if the tx is not confirmed, if no exit path is found or not available\n * @returns the txid of the transaction spending the unrolled funds\n */\n export async function completeUnroll(\n wallet: Wallet,\n vtxoTxids: string[],\n outputAddress: string,\n ): Promise<string> {\n const signedTx = await prepareUnrollTransaction(wallet, vtxoTxids, outputAddress);\n await wallet.onchainProvider.broadcastTransaction(signedTx.hex);\n return signedTx.id;\n }\n}\n\n/**\n * Prepares the transaction that spends the CSV path to complete unrolling a VTXO.\n * @param wallet the wallet owning the VTXO(s)\n * @param vtxoTxIds the txids of the VTXO(s) to complete unroll\n * @param outputAddress the address to send the unrolled funds to\n * @throws if the VTXO(s) are not fully unrolled, if the txids are not found, if the tx is not confirmed, if no exit path is found or not available\n * @returns the transaction spending the unrolled funds\n */\nexport async function prepareUnrollTransaction(\n wallet: Wallet,\n vtxoTxIds: string[],\n outputAddress: string,\n): Promise<Transaction> {\n const chainTip = await wallet.onchainProvider.getChainTip();\n\n let vtxos = await wallet.getVtxos({ withUnrolled: true });\n vtxos = vtxos.filter((vtxo) => vtxoTxIds.includes(vtxo.txid));\n\n if (vtxos.length === 0) {\n throw new Error(\"No vtxos to complete unroll\");\n }\n\n const inputs: TransactionInputUpdate[] = [];\n let totalAmount = 0n;\n const txWeightEstimator = TxWeightEstimator.create();\n for (const vtxo of vtxos) {\n if (!vtxo.isUnrolled) {\n throw new Error(\n `Vtxo ${vtxo.txid}:${vtxo.vout} is not fully unrolled, use unroll first`,\n );\n }\n\n const txStatus = await wallet.onchainProvider.getTxStatus(vtxo.txid);\n if (!txStatus.confirmed) {\n throw new Error(`tx ${vtxo.txid} is not confirmed`);\n }\n\n const exit = availableExitPath(\n { height: txStatus.blockHeight, time: txStatus.blockTime },\n chainTip,\n vtxo,\n );\n if (!exit) {\n throw new Error(`no available exit path found for vtxo ${vtxo.txid}:${vtxo.vout}`);\n }\n\n const spendingLeaf = VtxoScript.decode(vtxo.tapTree).findLeaf(hex.encode(exit.script));\n if (!spendingLeaf) {\n throw new Error(`spending leaf not found for vtxo ${vtxo.txid}:${vtxo.vout}`);\n }\n\n totalAmount += BigInt(vtxo.value);\n const sequence = timelockToSequence(exit.params.timelock);\n inputs.push({\n txid: vtxo.txid,\n index: vtxo.vout,\n tapLeafScript: [spendingLeaf],\n sequence,\n witnessUtxo: {\n amount: BigInt(vtxo.value),\n script: VtxoScript.decode(vtxo.tapTree).pkScript,\n },\n sighashType: SigHash.DEFAULT,\n });\n txWeightEstimator.addTapscriptInput(\n 64,\n spendingLeaf[1].length,\n TaprootControlBlock.encode(spendingLeaf[0]).length,\n );\n }\n\n const tx = new Transaction({ version: 2 });\n for (const input of inputs) {\n tx.addInput(input);\n }\n\n txWeightEstimator.addOutputAddress(outputAddress, wallet.network);\n\n let feeRate = await wallet.onchainProvider.getFeeRate();\n if (!feeRate || feeRate < Wallet.MIN_FEE_RATE) {\n feeRate = Wallet.MIN_FEE_RATE;\n }\n // Esplora returns a `number` and bitcoind regtest sometimes reports\n // fractional sat/vB (e.g. 1.006). `BigInt(1.006)` throws RangeError\n // — round up so we always pay AT LEAST the advertised rate and\n // satisfy BigInt's integer requirement.\n const feeAmount = txWeightEstimator.vsize().fee(BigInt(Math.ceil(feeRate)));\n if (feeAmount > totalAmount) {\n throw new Error(\"fee amount is greater than the total amount\");\n }\n\n const sendAmount = totalAmount - feeAmount;\n if (sendAmount < BigInt(DUST_AMOUNT)) {\n throw new Error(\"send amount is less than dust amount\");\n }\n\n tx.addOutputAddress(outputAddress, sendAmount, wallet.network);\n\n const signedTx = await wallet.identity.sign(tx);\n signedTx.finalize();\n return signedTx;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction doUnroll(\n onchainProvider: OnchainProvider,\n pkg: Unroll.UnrollStep[\"pkg\"],\n): () => Promise<void> {\n return () => onchainProvider.broadcastTransaction(...pkg).then(() => undefined);\n}\n\nfunction doWait(onchainProvider: OnchainProvider, txid: string): () => Promise<void> {\n return () => {\n return new Promise((resolve, reject) => {\n const interval = setInterval(async () => {\n try {\n const txInfo = await onchainProvider.getTxStatus(txid);\n if (txInfo.confirmed) {\n clearInterval(interval);\n resolve();\n }\n } catch (e) {\n clearInterval(interval);\n reject(e);\n }\n }, 5_000);\n });\n };\n}\n\ntype BlockTime = {\n height: number;\n time: number;\n};\n\nfunction availableExitPath(\n confirmedAt: BlockTime,\n current: BlockTime,\n vtxo: ExtendedVirtualCoin,\n): CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type | undefined {\n const exits = VtxoScript.decode(vtxo.tapTree).exitPaths();\n for (const exit of exits) {\n if (exit.params.timelock.type === \"blocks\") {\n if (current.height >= confirmedAt.height + Number(exit.params.timelock.value)) {\n return exit;\n }\n } else {\n if (current.time >= confirmedAt.time + Number(exit.params.timelock.value)) {\n return exit;\n }\n }\n }\n\n return undefined;\n}\n","import { hex } from \"@scure/base\";\nimport { Contract } from \"./types\";\nimport { contractHandlers } from \"./handlers\";\nimport { DEFAULT_ARKADE_HRP } from \"../wallet\";\n\n/**\n * Prefix for arkcontract strings.\n */\nconst ARKCONTRACT_PREFIX = \"arkcontract\";\n\n/**\n * Encode a contract to the arkcontract string format.\n *\n * Format: arkcontract={type}&{key1}={value1}&{key2}={value2}...\n *\n * This format is compatible with NArk and allows contracts to be\n * shared/imported across different Arkade SDKs.\n *\n * @example\n * ```typescript\n * const contract: Contract = {\n * type: \"vhtlc\",\n * params: { sender: \"ab12...\", receiver: \"cd34...\", ... },\n * // ...\n * };\n *\n * const encoded = encodeArkContract(contract);\n * // \"arkcontract=vhtlc&sender=ab12...&receiver=cd34...&...\"\n * ```\n */\nexport function encodeArkContract(contract: Contract): string {\n const params = new URLSearchParams();\n\n // Add contract type first\n params.set(ARKCONTRACT_PREFIX, contract.type);\n\n // Add all params\n for (const [key, value] of Object.entries(contract.params)) {\n params.set(key, value);\n }\n\n return params.toString();\n}\n\n/**\n * Parsed result from decoding an arkcontract string.\n *\n * This is a low-level representation. For type-safe contract creation,\n * use `contractFromArkContract` or `contractFromArkContractWithAddress`\n * which validate params through the handler system.\n */\nexport interface ParsedArkContract {\n /** Contract type (e.g., \"vhtlc\", \"default\") */\n type: string;\n\n /** All key-value pairs from the string */\n data: Record<string, string>;\n}\n\n/**\n * Decode an arkcontract string into raw type and data.\n *\n * This is a low-level function that parses the URL-encoded format.\n * For creating typed Contract objects, use `contractFromArkContract`\n * or `contractFromArkContractWithAddress` instead.\n *\n * @param encoded - The arkcontract string\n * @returns Parsed type and key-value data\n * @throws If the string is not a valid arkcontract\n *\n * @example\n * ```typescript\n * const parsed = decodeArkContract(\"arkcontract=vhtlc&sender=ab12...\");\n * // { type: \"vhtlc\", data: { sender: \"ab12...\", ... } }\n * ```\n */\nexport function decodeArkContract(encoded: string): ParsedArkContract {\n const params = new URLSearchParams(encoded);\n\n // Extract type from the arkcontract key\n const type = params.get(ARKCONTRACT_PREFIX);\n if (!type) {\n throw new Error(`Invalid arkcontract string: missing '${ARKCONTRACT_PREFIX}' key`);\n }\n\n // Build data object from all other params\n const data: Record<string, string> = {};\n for (const [key, value] of params.entries()) {\n if (key !== ARKCONTRACT_PREFIX) {\n data[key] = value;\n }\n }\n\n return { type, data };\n}\n\n/**\n * Create a Contract from an arkcontract string.\n *\n * This requires a handler to be registered for the contract type.\n *\n * @param encoded - The arkcontract string\n * @param options - Additional options for the contract\n * @returns A Contract object\n * @throws If the string is invalid or no handler exists for the type\n *\n * @example\n * ```typescript\n * const contract = contractFromArkContract(\n * \"arkcontract=vhtlc&sender=ab12...\",\n * {\n * label: \"Lightning Receive\",\n * }\n * );\n * ```\n */\nexport function contractFromArkContract(\n encoded: string,\n options: {\n label?: string;\n state?: \"active\" | \"inactive\";\n metadata?: Record<string, unknown>;\n } = {},\n): Omit<Contract, \"script\" | \"address\"> & {\n script?: string;\n address?: string;\n} {\n const parsed = decodeArkContract(encoded);\n const handler = contractHandlers.get(parsed.type);\n\n if (!handler) {\n throw new Error(`No handler registered for contract type '${parsed.type}'`);\n }\n\n // Separate params from runtime data\n // This is type-specific - the handler knows which keys are params\n // For now, we treat all data as params\n const params = parsed.data;\n\n return {\n label: options.label,\n type: parsed.type,\n params,\n state: options.state || \"active\",\n createdAt: Date.now(),\n metadata: options.metadata,\n };\n}\n\n/**\n * Create a full Contract with derived script and address.\n *\n * @param encoded - The arkcontract string\n * @param serverPubKey - Server public key (for address derivation)\n * @param addressPrefix - Address prefix (e.g., \"tark\" for testnet)\n * @param options - Additional options\n * @returns A complete Contract object\n */\nexport function contractFromArkContractWithAddress(\n encoded: string,\n serverPubKey: Uint8Array,\n addressPrefix: string = DEFAULT_ARKADE_HRP,\n options: {\n label?: string;\n state?: \"active\" | \"inactive\";\n metadata?: Record<string, unknown>;\n } = {},\n): Contract {\n const parsed = decodeArkContract(encoded);\n const handler = contractHandlers.getOrThrow(parsed.type);\n\n const params = parsed.data;\n const vtxoScript = handler.createScript(params);\n\n return {\n label: options.label,\n type: parsed.type,\n params,\n script: hex.encode(vtxoScript.pkScript),\n address: vtxoScript.address(addressPrefix, serverPubKey).encode(),\n state: options.state || \"active\",\n createdAt: Date.now(),\n metadata: options.metadata,\n };\n}\n\n/**\n * Check if a string is an arkcontract.\n */\nexport function isArkContract(str: string): boolean {\n return str.startsWith(ARKCONTRACT_PREFIX + \"=\");\n}\n"]}