@satora/swap 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/bitcoin-reader-electrum-2N4LJCGD.cjs +9 -0
  2. package/dist/{bitcoin-reader-electrum-VCQ5TQ44.cjs.map → bitcoin-reader-electrum-2N4LJCGD.cjs.map} +1 -1
  3. package/dist/bitcoin-reader-electrum-VLYRII3T.js +9 -0
  4. package/dist/bitcoin-reader-esplora-CAR4P52J.cjs +16 -0
  5. package/dist/bitcoin-reader-esplora-CAR4P52J.cjs.map +1 -0
  6. package/dist/{bitcoin-reader-esplora-CGPF4H5Y.js → bitcoin-reader-esplora-LC673MQT.js} +4 -2
  7. package/dist/{chunk-WQMAL2VD.js → chunk-34OYIFOU.js} +764 -141
  8. package/dist/chunk-34OYIFOU.js.map +1 -0
  9. package/dist/{chunk-4NVWIR74.cjs → chunk-3633KDTW.cjs} +1128 -505
  10. package/dist/chunk-3633KDTW.cjs.map +1 -0
  11. package/dist/{chunk-LSCRTQOS.js → chunk-CUYLQTRF.js} +15 -20
  12. package/dist/chunk-CUYLQTRF.js.map +1 -0
  13. package/dist/{chunk-INHFP222.cjs → chunk-CY5M5X6S.cjs} +28 -30
  14. package/dist/chunk-CY5M5X6S.cjs.map +1 -0
  15. package/dist/{chunk-JZTF4JNH.cjs → chunk-EI5ILLQ3.cjs} +2 -2
  16. package/dist/{chunk-JZTF4JNH.cjs.map → chunk-EI5ILLQ3.cjs.map} +1 -1
  17. package/dist/{chunk-5DQHR3RO.cjs → chunk-FJS6RGUR.cjs} +16 -21
  18. package/dist/chunk-FJS6RGUR.cjs.map +1 -0
  19. package/dist/{chunk-3ZMSZSAV.js → chunk-I2NF63VZ.js} +27 -29
  20. package/dist/chunk-I2NF63VZ.js.map +1 -0
  21. package/dist/{chunk-JHZHRY7S.js → chunk-K2Q4JWB6.js} +2 -2
  22. package/dist/{chunk-JHZHRY7S.js.map → chunk-K2Q4JWB6.js.map} +1 -1
  23. package/dist/{chunk-TT3J2OOS.js → chunk-KMBGRQS7.js} +5 -5
  24. package/dist/{chunk-TT3J2OOS.js.map → chunk-KMBGRQS7.js.map} +1 -1
  25. package/dist/{chunk-Q4TOBBAN.cjs → chunk-LZQZYSOZ.cjs} +5 -5
  26. package/dist/{chunk-Q4TOBBAN.cjs.map → chunk-LZQZYSOZ.cjs.map} +1 -1
  27. package/dist/delegate.cjs +2 -2
  28. package/dist/delegate.js +1 -1
  29. package/dist/{dist-SHY7I6SH.js → dist-3N76II5O.js} +16 -4
  30. package/dist/dist-KQINAMDC.cjs +406 -0
  31. package/dist/{dist-MHRQ5FFV.cjs.map → dist-KQINAMDC.cjs.map} +1 -1
  32. package/dist/{fundSwap-UBCHMUP4-BEMQNSFQ.cjs → fundSwap-2D4IPYU4-4NELKB3Q.cjs} +7 -7
  33. package/dist/{fundSwap-UBCHMUP4-BEMQNSFQ.cjs.map → fundSwap-2D4IPYU4-4NELKB3Q.cjs.map} +1 -1
  34. package/dist/{fundSwap-UBCHMUP4-WBLYE6MC.js → fundSwap-2D4IPYU4-CDM3WRUF.js} +3 -3
  35. package/dist/index.cjs +41 -23
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.js +29 -11
  38. package/dist/index.js.map +1 -1
  39. package/dist/node.cjs +26 -5
  40. package/dist/node.cjs.map +1 -1
  41. package/dist/node.js +26 -5
  42. package/dist/node.js.map +1 -1
  43. package/dist/types/cjs/pure/api/client.d.cts +1 -0
  44. package/dist/types/cjs/pure/client.d.cts +44 -12
  45. package/dist/types/cjs/pure/compose-quote.d.cts +14 -1
  46. package/dist/types/cjs/pure/create/bitcoin-payout.d.cts +17 -0
  47. package/dist/types/cjs/pure/create/evm-to-arkade.d.cts +0 -5
  48. package/dist/types/cjs/pure/create/evm-to-lightning.d.cts +0 -8
  49. package/dist/types/cjs/pure/create/funding-terms.d.cts +2 -1
  50. package/dist/types/cjs/pure/create/index.d.cts +2 -1
  51. package/dist/types/cjs/pure/create/payment-safety.d.cts +2 -0
  52. package/dist/types/cjs/pure/create/payout-slippage.d.cts +29 -0
  53. package/dist/types/cjs/pure/create/spark-to-evm.d.cts +7 -0
  54. package/dist/types/cjs/pure/create/types.d.cts +102 -3
  55. package/dist/types/cjs/pure/esplora.d.cts +2 -0
  56. package/dist/types/cjs/pure/evm/funding-pins.d.cts +2 -0
  57. package/dist/types/cjs/pure/generated/api.d.cts +352 -2
  58. package/dist/types/cjs/pure/index.d.cts +6 -4
  59. package/dist/types/cjs/pure/refund/onchain.d.cts +4 -0
  60. package/dist/types/cjs/pure/storage/index.d.cts +1 -1
  61. package/dist/types/cjs/pure/storage/types.d.cts +22 -0
  62. package/dist/types/cjs/pure/swap-verification.d.cts +3 -1
  63. package/dist/types/cjs/pure/tokens.d.cts +5 -0
  64. package/dist/types/cjs/pure/types/chain.d.cts +2 -2
  65. package/dist/types/cjs/pure/types/index.d.cts +1 -0
  66. package/dist/types/cjs/pure/types/promo-code.d.cts +15 -0
  67. package/dist/types/cjs/pure/types/quote.d.cts +7 -0
  68. package/dist/types/cjs/pure/types/referral-fee.d.cts +8 -0
  69. package/dist/types/cjs/pure/version.d.cts +4 -4
  70. package/dist/types/cjs/swap/client.d.cts +2 -0
  71. package/dist/types/cjs/swap/contracts/bitcoin-reader-esplora.d.cts +5 -0
  72. package/dist/types/esm/pure/api/client.d.ts +1 -0
  73. package/dist/types/esm/pure/client.d.ts +44 -12
  74. package/dist/types/esm/pure/compose-quote.d.ts +14 -1
  75. package/dist/types/esm/pure/create/bitcoin-payout.d.ts +17 -0
  76. package/dist/types/esm/pure/create/evm-to-arkade.d.ts +0 -5
  77. package/dist/types/esm/pure/create/evm-to-lightning.d.ts +0 -8
  78. package/dist/types/esm/pure/create/funding-terms.d.ts +2 -1
  79. package/dist/types/esm/pure/create/index.d.ts +2 -1
  80. package/dist/types/esm/pure/create/payment-safety.d.ts +2 -0
  81. package/dist/types/esm/pure/create/payout-slippage.d.ts +29 -0
  82. package/dist/types/esm/pure/create/spark-to-evm.d.ts +7 -0
  83. package/dist/types/esm/pure/create/types.d.ts +102 -3
  84. package/dist/types/esm/pure/esplora.d.ts +2 -0
  85. package/dist/types/esm/pure/evm/funding-pins.d.ts +2 -0
  86. package/dist/types/esm/pure/generated/api.d.ts +352 -2
  87. package/dist/types/esm/pure/index.d.ts +6 -4
  88. package/dist/types/esm/pure/refund/onchain.d.ts +4 -0
  89. package/dist/types/esm/pure/storage/index.d.ts +1 -1
  90. package/dist/types/esm/pure/storage/types.d.ts +22 -0
  91. package/dist/types/esm/pure/swap-verification.d.ts +3 -1
  92. package/dist/types/esm/pure/tokens.d.ts +5 -0
  93. package/dist/types/esm/pure/types/chain.d.ts +2 -2
  94. package/dist/types/esm/pure/types/index.d.ts +1 -0
  95. package/dist/types/esm/pure/types/promo-code.d.ts +15 -0
  96. package/dist/types/esm/pure/types/quote.d.ts +7 -0
  97. package/dist/types/esm/pure/types/referral-fee.d.ts +8 -0
  98. package/dist/types/esm/pure/version.d.ts +4 -4
  99. package/dist/types/esm/swap/client.d.ts +2 -0
  100. package/dist/types/esm/swap/contracts/bitcoin-reader-esplora.d.ts +5 -0
  101. package/package.json +2 -2
  102. package/dist/bitcoin-reader-electrum-4PNSDHIA.js +0 -9
  103. package/dist/bitcoin-reader-electrum-VCQ5TQ44.cjs +0 -9
  104. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs +0 -14
  105. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs.map +0 -1
  106. package/dist/chunk-3ZMSZSAV.js.map +0 -1
  107. package/dist/chunk-4NVWIR74.cjs.map +0 -1
  108. package/dist/chunk-5DQHR3RO.cjs.map +0 -1
  109. package/dist/chunk-INHFP222.cjs.map +0 -1
  110. package/dist/chunk-LSCRTQOS.js.map +0 -1
  111. package/dist/chunk-WQMAL2VD.js.map +0 -1
  112. package/dist/dist-MHRQ5FFV.cjs +0 -394
  113. /package/dist/{bitcoin-reader-electrum-4PNSDHIA.js.map → bitcoin-reader-electrum-VLYRII3T.js.map} +0 -0
  114. /package/dist/{bitcoin-reader-esplora-CGPF4H5Y.js.map → bitcoin-reader-esplora-LC673MQT.js.map} +0 -0
  115. /package/dist/{dist-SHY7I6SH.js.map → dist-3N76II5O.js.map} +0 -0
  116. /package/dist/{fundSwap-UBCHMUP4-WBLYE6MC.js.map → fundSwap-2D4IPYU4-CDM3WRUF.js.map} +0 -0
@@ -1,4 +1,5 @@
1
1
  // src/contracts/bitcoin-reader-esplora.ts
2
+ var MAX_FUNDING_OUTPUTS = 2;
2
3
  function resolveMinConfirmations(source) {
3
4
  return (typeof source === "function" ? source() : source) ?? 0;
4
5
  }
@@ -15,27 +16,20 @@ function htlcFactsFromEsploraTxs(txs, address, opts) {
15
16
  spendWitness: spend.witness ?? []
16
17
  };
17
18
  }
18
- const paidSats = (tx) => tx.vout.filter((vout) => vout.scriptpubkey_address === address).reduce((sum, vout) => sum + (vout.value ?? 0), 0);
19
- let funding;
20
- let fundedSats = 0;
21
- for (const tx of txs) {
22
- const paid = paidSats(tx);
23
- if (paid > fundedSats) {
24
- funding = tx;
25
- fundedSats = paid;
26
- }
27
- }
28
- if (funding) {
19
+ const outputs = txs.flatMap(
20
+ (tx) => tx.vout.filter((vout) => vout.scriptpubkey_address === address).map((vout) => ({ tx, sats: vout.value ?? 0 }))
21
+ ).filter((output) => output.sats > 0).sort((a, b) => b.sats - a.sats).slice(0, MAX_FUNDING_OUTPUTS);
22
+ if (outputs.length > 0) {
29
23
  const minConf = opts?.minConfirmations ?? 0;
30
- let deepEnough;
31
- if (funding.status?.confirmed) {
32
- deepEnough = minConf <= 1 || opts?.tipHeight !== void 0 && funding.status.block_height !== void 0 && opts.tipHeight - funding.status.block_height + 1 >= minConf;
33
- } else {
34
- deepEnough = minConf === 0;
35
- }
24
+ const deepEnough = (tx) => {
25
+ if (tx.status?.confirmed) {
26
+ return minConf <= 1 || opts?.tipHeight !== void 0 && tx.status.block_height !== void 0 && opts.tipHeight - tx.status.block_height + 1 >= minConf;
27
+ }
28
+ return minConf === 0;
29
+ };
36
30
  return {
37
- funding: deepEnough ? "confirmed" : "mempool",
38
- fundedSats
31
+ funding: outputs.every((output) => deepEnough(output.tx)) ? "confirmed" : "mempool",
32
+ fundedSats: outputs.reduce((sum, output) => sum + output.sats, 0)
39
33
  };
40
34
  }
41
35
  return { funding: "absent", fundedSats: 0 };
@@ -82,9 +76,10 @@ function esploraReader(esploraUrls, fetchImpl = fetch, policy) {
82
76
  }
83
77
 
84
78
  export {
79
+ MAX_FUNDING_OUTPUTS,
85
80
  resolveMinConfirmations,
86
81
  htlcFactsFromEsploraTxs,
87
82
  DEFAULT_ESPLORA_URLS,
88
83
  esploraReader
89
84
  };
90
- //# sourceMappingURL=chunk-LSCRTQOS.js.map
85
+ //# sourceMappingURL=chunk-CUYLQTRF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contracts/bitcoin-reader-esplora.ts"],"sourcesContent":["/**\n * A esplora-backed {@link BitcoinChainReader} — the concrete chain source the\n * {@link BitcoinContractManager} uses in production.\n *\n * Kept separate from the manager so the manager stays free of any HTTP/esplora\n * dependency (and unit-testable against a fake reader). A single\n * `GET /address/{addr}/txs` yields both the funding state and the spending\n * input's witness, so no extra round-trips are needed.\n */\n\nimport type { BitcoinHtlcFacts } from \"./bitcoin.js\";\nimport type { BitcoinChainReader } from \"./bitcoin-manager.js\";\n\n/**\n * Most outputs a client's funding is counted from, as the server's on-chain\n * HTLC watcher counts it.\n */\nexport const MAX_FUNDING_OUTPUTS = 2;\n\n/** The slice of esplora's tx JSON we read. */\ntype EsploraTx = {\n vin: Array<{\n witness?: string[];\n prevout?: { scriptpubkey_address?: string } | null;\n }>;\n vout: Array<{ scriptpubkey_address?: string; value?: number }>;\n status?: { confirmed?: boolean; block_height?: number };\n};\n\n/** A depth already resolved to a number, for the pure classifier below. */\nexport type BitcoinConfirmationPolicy = {\n minConfirmations?: number;\n};\n\n/** A depth, or a getter resolved per read so it can change without a rebuild. */\nexport type MinConfirmationsSource = number | (() => number | undefined);\n\n/**\n * When a funding tx counts as `confirmed` for observation purposes.\n *\n * `minConfirmations: 0` (the default) accepts an UNCONFIRMED funding, so a swap\n * claims as soon as the funding hits the mempool instead of waiting ~10min for\n * a block. This TRUSTS the funder not to double-spend: claiming publishes the\n * preimage, so a funder who then replaces its funding tx could take both legs.\n * Our own server therefore broadcasts HTLC fundings without signalling RBF.\n * Note that a non-signalling tx is still replaceable by full-RBF miners — set\n * `1` (or more) for a policy that doesn't rely on the funder's good behaviour;\n * values above 1 make the reader fetch the tip height to compute depth.\n */\nexport type BitcoinReaderPolicy = {\n minConfirmations?: MinConfirmationsSource;\n};\n\nexport function resolveMinConfirmations(\n source: MinConfirmationsSource | undefined,\n): number {\n return (typeof source === \"function\" ? source() : source) ?? 0;\n}\n\n/**\n * Reduce an address's esplora tx history to HTLC facts. If a tx spends an output\n * at the address, that's the resolving spend (its witness classifies claim vs\n * refund); otherwise a tx paying the address is the funding, gated by the\n * confirmation policy (see {@link BitcoinConfirmationPolicy}).\n */\nexport function htlcFactsFromEsploraTxs(\n txs: EsploraTx[],\n address: string,\n opts?: BitcoinConfirmationPolicy & { tipHeight?: number },\n): BitcoinHtlcFacts {\n for (const tx of txs) {\n const spend = tx.vin.find(\n (vin) => vin.prevout?.scriptpubkey_address === address,\n );\n if (spend)\n return {\n funding: \"confirmed\",\n fundedSats: 0, // already spent — the amount no longer matters\n spendWitness: spend.witness ?? [],\n };\n }\n // The funding is counted from the outputs paying the address, the\n // largest first and at most MAX_FUNDING_OUTPUTS of them, as the server's\n // watcher counts it: a client that sent too little can top up with a\n // second transaction. Largest first also keeps a stray dust payment (the\n // address is public) from being mistaken for the funding and observing\n // the swap as underfunded/invalid. The server may count fewer outputs (it\n // leaves out a second one not worth its claim fee), but its own leg is\n // verified independently before anything is claimed.\n const outputs = txs\n .flatMap((tx) =>\n tx.vout\n .filter((vout) => vout.scriptpubkey_address === address)\n .map((vout) => ({ tx, sats: vout.value ?? 0 })),\n )\n .filter((output) => output.sats > 0)\n .sort((a, b) => b.sats - a.sats)\n .slice(0, MAX_FUNDING_OUTPUTS);\n if (outputs.length > 0) {\n const minConf = opts?.minConfirmations ?? 0;\n const deepEnough = (tx: EsploraTx): boolean => {\n if (tx.status?.confirmed) {\n return (\n minConf <= 1 ||\n (opts?.tipHeight !== undefined &&\n tx.status.block_height !== undefined &&\n opts.tipHeight - tx.status.block_height + 1 >= minConf)\n );\n }\n return minConf === 0;\n };\n return {\n funding: outputs.every((output) => deepEnough(output.tx))\n ? \"confirmed\"\n : \"mempool\",\n fundedSats: outputs.reduce((sum, output) => sum + output.sats, 0),\n };\n }\n return { funding: \"absent\", fundedSats: 0 };\n}\n\n/**\n * Public esplora endpoints tried in rotation (mainnet). blockstream.info runs the\n * reference esplora, so it's API-compatible with mempool.space; spreading calls\n * across both halves the per-provider load and survives one being throttled.\n */\nexport const DEFAULT_ESPLORA_URLS = [\n \"https://mempool.space/api\",\n \"https://blockstream.info/api\",\n];\n\n/**\n * Build a {@link BitcoinChainReader} over one or more esplora REST endpoints.\n * With several, each call starts at a rotating endpoint (to spread load across\n * providers) and fails over to the rest on error — so a throttled or failing\n * provider doesn't stall tracking.\n */\nexport function esploraReader(\n esploraUrls: string | string[],\n fetchImpl: typeof fetch = fetch,\n policy?: BitcoinReaderPolicy,\n): BitcoinChainReader {\n const bases = (Array.isArray(esploraUrls) ? esploraUrls : [esploraUrls]).map(\n (url) => url.replace(/\\/+$/, \"\"),\n );\n let start = 0;\n return {\n async getHtlcFacts(address, minConfirmations) {\n const required =\n minConfirmations ?? resolveMinConfirmations(policy?.minConfirmations);\n const from = start++ % bases.length; // rotate the primary to spread load\n let lastError: unknown;\n for (let i = 0; i < bases.length; i++) {\n const base = bases[(from + i) % bases.length];\n try {\n const res = await fetchImpl(\n `${base}/address/${encodeURIComponent(address)}/txs`,\n );\n if (!res.ok) throw new Error(`esplora ${res.status} at ${base}`);\n const txs = (await res.json()) as EsploraTx[];\n // Depth policies beyond 1 need the tip to compute confirmations;\n // 0 and 1 read straight off the tx's confirmed flag.\n let tipHeight: number | undefined;\n if (required > 1) {\n const tip = await fetchImpl(`${base}/blocks/tip/height`);\n if (!tip.ok) throw new Error(`esplora ${tip.status} at ${base}`);\n tipHeight = Number(await tip.text());\n }\n return htlcFactsFromEsploraTxs(txs, address, {\n minConfirmations: required,\n tipHeight,\n });\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError ?? new Error(\"no esplora endpoints configured\");\n },\n };\n}\n"],"mappings":";AAiBO,IAAM,sBAAsB;AAoC5B,SAAS,wBACd,QACQ;AACR,UAAQ,OAAO,WAAW,aAAa,OAAO,IAAI,WAAW;AAC/D;AAQO,SAAS,wBACd,KACA,SACA,MACkB;AAClB,aAAW,MAAM,KAAK;AACpB,UAAM,QAAQ,GAAG,IAAI;AAAA,MACnB,CAAC,QAAQ,IAAI,SAAS,yBAAyB;AAAA,IACjD;AACA,QAAI;AACF,aAAO;AAAA,QACL,SAAS;AAAA,QACT,YAAY;AAAA;AAAA,QACZ,cAAc,MAAM,WAAW,CAAC;AAAA,MAClC;AAAA,EACJ;AASA,QAAM,UAAU,IACb;AAAA,IAAQ,CAAC,OACR,GAAG,KACA,OAAO,CAAC,SAAS,KAAK,yBAAyB,OAAO,EACtD,IAAI,CAAC,UAAU,EAAE,IAAI,MAAM,KAAK,SAAS,EAAE,EAAE;AAAA,EAClD,EACC,OAAO,CAAC,WAAW,OAAO,OAAO,CAAC,EAClC,KAAK,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAC9B,MAAM,GAAG,mBAAmB;AAC/B,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,UAAU,MAAM,oBAAoB;AAC1C,UAAM,aAAa,CAAC,OAA2B;AAC7C,UAAI,GAAG,QAAQ,WAAW;AACxB,eACE,WAAW,KACV,MAAM,cAAc,UACnB,GAAG,OAAO,iBAAiB,UAC3B,KAAK,YAAY,GAAG,OAAO,e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AAwB,KAAK,SAAS;AAAA,YAC3C,kBAAkB;AAAA,YAClB;AAAA,UACF,CAAC;AAAA,QACH,SAAS,OAAO;AACd,sBAAY;AAAA,QACd;AAAA,MACF;AACA,YAAM,aAAa,IAAI,MAAM,iCAAiC;AAAA,IAChE;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunk5DQHR3ROcjs = require('./chunk-5DQHR3RO.cjs');
3
+
4
+ var _chunkFJS6RGURcjs = require('./chunk-FJS6RGUR.cjs');
4
5
 
5
6
  // src/contracts/bitcoin-reader-electrum.ts
6
7
  var _sha2js = require('@noble/hashes/sha2.js');
@@ -67,23 +68,20 @@ function electrumReader(client, opts) {
67
68
  }
68
69
  return indices;
69
70
  };
70
- let funding;
71
- let fundedSats = 0;
72
- for (const candidate of txs) {
73
- let paid = 0;
74
- for (const i of outputIndicesPaying(candidate.tx))
75
- paid += Number(_nullishCoalesce(candidate.tx.getOutput(i).amount, () => ( 0n)));
76
- if (paid > fundedSats) {
77
- funding = candidate;
78
- fundedSats = paid;
79
- }
80
- }
81
- if (!funding) return { funding: "absent", fundedSats: 0 };
82
- const fundedVouts = outputIndicesPaying(funding.tx);
71
+ const outputs = txs.flatMap(
72
+ (candidate) => outputIndicesPaying(candidate.tx).map((vout) => ({
73
+ candidate,
74
+ vout,
75
+ sats: Number(_nullishCoalesce(candidate.tx.getOutput(vout).amount, () => ( 0n)))
76
+ }))
77
+ ).filter((output) => output.sats > 0).sort((a, b) => b.sats - a.sats).slice(0, _chunkFJS6RGURcjs.MAX_FUNDING_OUTPUTS);
78
+ if (outputs.length === 0) return { funding: "absent", fundedSats: 0 };
83
79
  for (const { tx } of txs) {
84
80
  for (let i = 0; i < tx.inputsLength; i++) {
85
81
  const input = tx.getInput(i);
86
- if (input.txid && _base.hex.encode(input.txid) === funding.entry.tx_hash && input.index !== void 0 && fundedVouts.includes(input.index)) {
82
+ if (input.txid && input.index !== void 0 && outputs.some(
83
+ (output) => _base.hex.encode(input.txid) === output.candidate.entry.tx_hash && input.index === output.vout
84
+ )) {
87
85
  return {
88
86
  funding: "confirmed",
89
87
  fundedSats: 0,
@@ -95,27 +93,27 @@ function electrumReader(client, opts) {
95
93
  }
96
94
  }
97
95
  }
98
- const height = funding.entry.height;
99
- const isConfirmed = height > 0;
96
+ const heights = outputs.map((output) => output.candidate.entry.height);
100
97
  let deepEnough;
101
- if (isConfirmed) {
102
- if (required <= 1) {
103
- deepEnough = true;
104
- } else {
105
- const tip = await client.request(
106
- "blockchain.headers.subscribe",
107
- []
108
- );
109
- deepEnough = tip.height - height + 1 >= required;
110
- }
111
- } else {
98
+ if (heights.some((height) => height <= 0)) {
112
99
  deepEnough = required === 0;
100
+ } else if (required <= 1) {
101
+ deepEnough = true;
102
+ } else {
103
+ const tip = await client.request(
104
+ "blockchain.headers.subscribe",
105
+ []
106
+ );
107
+ deepEnough = heights.every(
108
+ (height) => tip.height - height + 1 >= required
109
+ );
113
110
  }
111
+ const fundedSats = outputs.reduce((sum, output) => sum + output.sats, 0);
114
112
  return { funding: deepEnough ? "confirmed" : "mempool", fundedSats };
115
113
  }
116
114
  return {
117
115
  async getHtlcFacts(address, minConfirmations) {
118
- const required = _nullishCoalesce(minConfirmations, () => ( _chunk5DQHR3ROcjs.resolveMinConfirmations.call(void 0, _optionalChain([opts, 'optionalAccess', _3 => _3.minConfirmations]))));
116
+ const required = _nullishCoalesce(minConfirmations, () => ( _chunkFJS6RGURcjs.resolveMinConfirmations.call(void 0, _optionalChain([opts, 'optionalAccess', _3 => _3.minConfirmations]))));
119
117
  try {
120
118
  return await getHtlcFactsElectrum(address, required);
121
119
  } catch (error) {
@@ -154,4 +152,4 @@ function electrumReader(client, opts) {
154
152
 
155
153
 
156
154
  exports.electrumReader = electrumReader;
157
- //# sourceMappingURL=chunk-INHFP222.cjs.map
155
+ //# sourceMappingURL=chunk-CY5M5X6S.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/chunk-CY5M5X6S.cjs","../src/contracts/bitcoin-reader-electrum.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACcA,+CAAuB;AACvB,mCAAoB;AACpB,6FAAqB;AAuCrB,IAAM,gBAAA,EAAkB;AAAA,EACtB,MAAA,EAAQ,MAAA;AAAA,EACR,UAAA,EAAY,GAAA;AAAA,EACZ,UAAA,EAAY,GAAA;AAAA,EACZ,GAAA,EAAK;AACP,CAAA;AAEA,SAAS,kBAAA,CAAmB,OAAA,EAAgC;AAC1D,EAAA,OAAA,CAAQ,OAAA,EAAS;AAAA,IACf,KAAK,SAAA;AACH,MAAA,OAAW,GAAA,CAAA,OAAA;AAAA,IACb,KAAK,SAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,OAAW,GAAA,CAAA,YAAA;AAAA,IACb,KAAK,SAAA;AACH,MAAA,OAAO,eAAA;AAAA,EACX;AACF;AAGA,SAAS,YAAA,CAAa,MAAA,EAA4B;AAChD,EAAA,OAAO,SAAA,CAAI,MAAA,CAAO,4BAAA,MAAa,CAAA,CAAE,OAAA,CA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;AACR,IAAA;AACoB,MAAA;AACvB,QAAA;AACC,QAAA;AACH,MAAA;AACqB,MAAA;AACoB,QAAA;AACzC,MAAA;AACF,IAAA;AACuE,IAAA;AACJ,IAAA;AACrE,EAAA;AAEO,EAAA;AACyC,IAAA;AAEQ,MAAA;AAChD,MAAA;AACiD,QAAA;AACrC,MAAA;AACO,QAAA;AACb,QAAA;AACN,UAAA;AACyC,UAAA;AAC3C,QAAA;AACsD,QAAA;AACxD,MAAA;AACF,IAAA;AAE6B,IAAA;AAIvB,MAAA;AACA,MAAA;AAC0C,QAAA;AAC9B,MAAA;AACN,QAAA;AACN,UAAA;AACyC,UAAA;AAC3C,QAAA;AACa,QAAA;AAAC,QAAA;AAChB,MAAA;AAC+B,MAAA;AAGkC,MAAA;AACvD,QAAA;AACN,UAAA;AACyC,UAAA;AAC3C,QAAA;AACD,MAAA;AAC4D,MAAA;AAC/D,IAAA;AACF,EAAA;AACF;AD3G2E;AACA;AACA;AACA","file":"/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/chunk-CY5M5X6S.cjs","sourcesContent":[null,"/**\n * An Electrum-backed {@link BitcoinChainReader} — reads HTLC facts from our own\n * Fulcrum over WebSocket instead of public esplora REST endpoints.\n *\n * Two advantages over the esplora reader:\n *\n * - **Freshness**: our Fulcrum sees a transaction the moment its bitcoind\n * accepts it, while public explorers index with a lag — the exact lag that\n * made a server-funding hint's targeted verify come back \"absent\" and park\n * the claim on the 60s at-risk poller.\n * - **Push**: implements the reader's optional `subscribe` capability via\n * `blockchain.scripthash.subscribe`, so the manager reconciles the moment\n * an HTLC address's history changes instead of waiting for a poll tick.\n *\n * Reads fall back to a wrapped reader (typically the esplora one) whenever the\n * Electrum server errors, so a Fulcrum outage degrades to today's behavior\n * rather than blinding the tracker.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { hex } from \"@scure/base\";\nimport * as btc from \"@scure/btc-signer\";\nimport type { BitcoinHtlcFacts } from \"./bitcoin.js\";\nimport type { BitcoinChainReader } from \"./bitcoin-manager.js\";\nimport {\n type BitcoinReaderPolicy,\n MAX_FUNDING_OUTPUTS,\n resolveMinConfirmations,\n} from \"./bitcoin-reader-esplora.js\";\n\n/** One entry of `blockchain.scripthash.get_history`. */\ntype ElectrumHistoryEntry = {\n tx_hash: string;\n /** Block height; 0 for mempool, -1 for mempool with unconfirmed parents. */\n height: number;\n};\n\n/**\n * The Electrum client surface this reader needs. The pure SDK's\n * `ElectrumWsClient` satisfies it; tests inject a fake.\n */\nexport type ElectrumRpc = {\n request<T>(method: string, params: unknown[]): Promise<T>;\n subscribeScriptHash(\n scripthash: string,\n onChange: (status: string | null) => void,\n ): Promise<string | null>;\n unsubscribeScriptHash(\n scripthash: string,\n onChange: (status: string | null) => void,\n ): void;\n};\n\nexport type ElectrumReaderNetwork =\n | \"mainnet\"\n | \"testnet\"\n | \"signet\"\n | \"regtest\";\n\n/** btc-signer only ships mainnet/testnet; regtest differs in bech32 prefix. */\nconst REGTEST_NETWORK = {\n bech32: \"bcrt\",\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n} as const;\n\nfunction toBtcSignerNetwork(network: ElectrumReaderNetwork) {\n switch (network) {\n case \"mainnet\":\n return btc.NETWORK;\n case \"testnet\":\n case \"signet\":\n return btc.TEST_NETWORK;\n case \"regtest\":\n return REGTEST_NETWORK;\n }\n}\n\n/** Electrum scripthash: sha256 of the output script, reversed, hex. */\nfunction scriptHashOf(script: Uint8Array): string {\n return hex.encode(sha256(script).reverse());\n}\n\n/**\n * Build a {@link BitcoinChainReader} over an Electrum connection, with push\n * support and an optional fallback reader for outages.\n */\nexport function electrumReader(\n client: ElectrumRpc,\n opts?: BitcoinReaderPolicy & {\n /** Network the HTLC addresses live on; defaults to mainnet. */\n network?: ElectrumReaderNetwork;\n /** Reader consulted when the Electrum server errors (e.g. esplora). */\n fallback?: BitcoinChainReader;\n },\n): BitcoinChainReader {\n const network = opts?.network ?? \"mainnet\";\n const fallback = opts?.fallback;\n\n const scriptFor = (address: string): Uint8Array => {\n const decoded = btc.Address(toBtcSignerNetwork(network)).decode(address);\n if (!decoded) throw new Error(`Unrecognised Bitcoin address: ${address}`);\n return btc.OutScript.encode(decoded);\n };\n\n async function getHtlcFactsElectrum(\n address: string,\n required: number,\n ): Promise<BitcoinHtlcFacts> {\n const script = scriptFor(address);\n const scripthash = scriptHashOf(script);\n const history = await client.request<ElectrumHistoryEntry[]>(\n \"blockchain.scripthash.get_history\",\n [scripthash],\n );\n if (!history || history.length === 0)\n return { funding: \"absent\", fundedSats: 0 };\n\n // HTLC addresses see at most a handful of txs (fund + resolve), so\n // fetching each raw tx is cheap.\n const txs = await Promise.all(\n history.map(async (entry) => {\n const raw = await client.request<string>(\"blockchain.transaction.get\", [\n entry.tx_hash,\n ]);\n return {\n entry,\n tx: btc.Transaction.fromRaw(hex.decode(raw), {\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n disableScriptCheck: true,\n }),\n };\n }),\n );\n\n const scriptHex = hex.encode(script);\n const outputIndicesPaying = (tx: btc.Transaction): number[] => {\n const indices: number[] = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n const out = tx.getOutput(i);\n if (out.script && hex.encode(out.script) === scriptHex) indices.push(i);\n }\n return indices;\n };\n\n // The funding is counted from the outputs paying the address, the\n // largest first and at most MAX_FUNDING_OUTPUTS of them, as the server's\n // watcher counts it: a client that sent too little can top up with a\n // second transaction. Largest first also keeps a stray dust payment (the\n // address is public, so one can land before or after the real funding)\n // from being mistaken for the funding and observing the swap as\n // underfunded/invalid. The server's own leg is verified independently\n // before anything is claimed.\n const outputs = txs\n .flatMap((candidate) =>\n outputIndicesPaying(candidate.tx).map((vout) => ({\n candidate,\n vout,\n sats: Number(candidate.tx.getOutput(vout).amount ?? 0n),\n })),\n )\n .filter((output) => output.sats > 0)\n .sort((a, b) => b.sats - a.sats)\n .slice(0, MAX_FUNDING_OUTPUTS);\n if (outputs.length === 0) return { funding: \"absent\", fundedSats: 0 };\n\n // A tx spending one of the funding outputs is the resolving spend; its\n // witness classifies claim vs refund.\n for (const { tx } of txs) {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (\n input.txid &&\n input.index !== undefined &&\n outputs.some(\n (output) =>\n hex.encode(input.txid as Uint8Array) ===\n output.candidate.entry.tx_hash && input.index === output.vout,\n )\n ) {\n return {\n funding: \"confirmed\",\n fundedSats: 0, // already spent — the amount no longer matters\n spendWitness: (input.finalScriptWitness ?? []).map((item) =>\n hex.encode(item),\n ),\n };\n }\n }\n }\n\n // Same depth policy as the esplora reader, for every counted output:\n // 0/1 read straight off the confirmed flag; deeper policies need the tip\n // to compute depth.\n const heights = outputs.map((output) => output.candidate.entry.height);\n let deepEnough: boolean;\n if (heights.some((height) => height <= 0)) {\n deepEnough = required === 0;\n } else if (required <= 1) {\n deepEnough = true;\n } else {\n const tip = await client.request<{ height: number }>(\n \"blockchain.headers.subscribe\",\n [],\n );\n deepEnough = heights.every(\n (height) => tip.height - height + 1 >= required,\n );\n }\n const fundedSats = outputs.reduce((sum, output) => sum + output.sats, 0);\n return { funding: deepEnough ? \"confirmed\" : \"mempool\", fundedSats };\n }\n\n return {\n async getHtlcFacts(address, minConfirmations) {\n const required =\n minConfirmations ?? resolveMinConfirmations(opts?.minConfirmations);\n try {\n return await getHtlcFactsElectrum(address, required);\n } catch (error) {\n if (!fallback) throw error;\n console.warn(\n \"electrumReader: falling back to secondary reader:\",\n error instanceof Error ? error.message : error,\n );\n return fallback.getHtlcFacts(address, minConfirmations);\n }\n },\n\n subscribe(address, onChange) {\n // An address the configured network can't decode (e.g. a signet address\n // under a mainnet-configured reader) must not throw out of register()\n // and abort tracking — degrade to the poll cadence instead.\n let scripthash: string;\n try {\n scripthash = scriptHashOf(scriptFor(address));\n } catch (error) {\n console.warn(\n \"electrumReader: subscribe skipped (address decode failed):\",\n error instanceof Error ? error.message : error,\n );\n return () => {};\n }\n const handler = () => onChange();\n // Best-effort: if the subscription fails the tracker's poll cadence\n // remains the backstop, so the error is logged, not thrown.\n client.subscribeScriptHash(scripthash, handler).catch((error) => {\n console.warn(\n \"electrumReader: scripthash subscribe failed:\",\n error instanceof Error ? error.message : error,\n );\n });\n return () => client.unsubscribeScriptHash(scripthash, handler);\n },\n };\n}\n"]}
@@ -108,7 +108,7 @@ var _chunk4FGIWZAVcjs = require('./chunk-4FGIWZAV.cjs');
108
108
 
109
109
  var _chunkW34QUYVCcjs = require('./chunk-W34QUYVC.cjs');
110
110
 
111
- // ../../../ts-pure-sdk/dist/chunk-5VUYBHVC.js
111
+ // ../../../ts-pure-sdk/dist/chunk-MDUAHEZT.js
112
112
  var require_constants = _chunkW34QUYVCcjs.__commonJS.call(void 0, {
113
113
  "../ts-sdk/node_modules/.pnpm/semver@7.8.1/node_modules/semver/internal/constants.js"(exports, module) {
114
114
  var SEMVER_SPEC_VERSION = "2.0.0";
@@ -8557,4 +8557,4 @@ async function submitCctpInboundUserOp(context, params) {
8557
8557
 
8558
8558
 
8559
8559
  exports.fetchAttestation = fetchAttestation; exports.hasCctpMessage = hasCctpMessage; exports.trackCctpMessage = trackCctpMessage; exports.createSwapSmartAccountClient = createSwapSmartAccountClient; exports.simulateBatchCalls = simulateBatchCalls; exports.keccak_256 = keccak_256; exports.normalizeBytes32 = normalizeBytes32; exports.encodeApproveCallData = encodeApproveCallData; exports.encodeCreateSwapCallData = encodeCreateSwapCallData; exports.encodeHtlcErc20RefundCallData = encodeHtlcErc20RefundCallData; exports.encodeHtlcNativeRefundCallData = encodeHtlcNativeRefundCallData; exports.depositorIsSender = depositorIsSender; exports.refundForAsOwnRefund = refundForAsOwnRefund; exports.encodeHtlcErc20RefundBySigCallData = encodeHtlcErc20RefundBySigCallData; exports.encodeHtlcNativeRefundBySigCallData = encodeHtlcNativeRefundBySigCallData; exports.encodeHtlcErc20RehashCallData = encodeHtlcErc20RehashCallData; exports.encodeHtlcNativeRehashCallData = encodeHtlcNativeRehashCallData; exports.encodeHtlcErc20IsActiveCallData = encodeHtlcErc20IsActiveCallData; exports.htlcSwapKey = htlcSwapKey; exports.HTLC_SWAP_STATE = HTLC_SWAP_STATE; exports.encodeHtlcSwapsCallData = encodeHtlcSwapsCallData; exports.encodeHtlcErc20CreateCallData = encodeHtlcErc20CreateCallData; exports.buildEvmHtlcCallData = buildEvmHtlcCallData; exports.decodeSwapCreatedLog = decodeSwapCreatedLog; exports.findSwapRehashed = findSwapRehashed; exports.findSwapCreated = findSwapCreated; exports.NATIVE_TOKEN_ADDRESS = NATIVE_TOKEN_ADDRESS; exports.keccak2562 = keccak2562; exports.buildRedeemDigest = buildRedeemDigest; exports.buildNativeRedeemDigest = buildNativeRedeemDigest; exports.computeCoordinatorCallsHash = computeCoordinatorCallsHash; exports.encodeRedeemAndExecute = encodeRedeemAndExecute; exports.encodeNativeRefundTo = encodeNativeRefundTo; exports.encodeRefundTo = encodeRefundTo; exports.encodeDepositsCallData = encodeDepositsCallData; exports.buildCollabRefundEvmDigest = buildCollabRefundEvmDigest; exports.buildCollabRefundEvmTypedData = buildCollabRefundEvmTypedData; exports.PERMIT2_ADDRESS = PERMIT2_ADDRESS; exports.buildPermit2FundingDigest = buildPermit2FundingDigest; exports.buildPermit2TypedData = buildPermit2TypedData; exports.encodeExecuteAndCreateWithPermit2 = encodeExecuteAndCreateWithPermit2; exports.buildEip2612PermitDigest = buildEip2612PermitDigest; exports.checkFundingPayload = checkFundingPayload; exports.buildCctpInboundBatch = buildCctpInboundBatch; exports.addressToBytes32Hex = addressToBytes32Hex; exports.submitCctpInboundBalanceUserOp = submitCctpInboundBalanceUserOp; exports.submitCctpInboundUserOp = submitCctpInboundUserOp;
8560
- //# sourceMappingURL=chunk-JZTF4JNH.cjs.map
8560
+ //# sourceMappingURL=chunk-EI5ILLQ3.cjs.map