@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
@@ -38,6 +38,7 @@ export interface Asset {
38
38
  * ```
39
39
  */
40
40
  export declare const Asset: {
41
+ readonly BTC_SPARK: Asset;
41
42
  readonly BTC_LIGHTNING: Asset;
42
43
  readonly BTC_ARKADE: Asset;
43
44
  readonly BTC_ONCHAIN: Asset;
@@ -192,3 +193,7 @@ export declare function getCctpBridgeTokens(): BridgeTokenInfo[];
192
193
  * Excludes source chains (those already have USDT0 tokens from the backend).
193
194
  */
194
195
  export declare function getUsdt0BridgeTokens(): BridgeTokenInfo[];
196
+ /** Bitcoin on native Spark. */
197
+ export declare function isSpark(token: {
198
+ chain: string;
199
+ }): boolean;
@@ -12,7 +12,7 @@
12
12
  * Hand-written rather than re-exported from codegen so the SDK surface stays
13
13
  * decoupled; the union widens additively as new bridge chains land.
14
14
  */
15
- export type Chain = "Arkade" | "Lightning" | "Bitcoin" | "Solana" | "Tron" | "1" | "137" | "42161" | "30" | "31" | "10" | "8453" | "43114" | "130" | "59144" | "146" | "480" | "143" | "1329" | "50" | "999" | "57073";
15
+ export type Chain = "Arkade" | "Lightning" | "Spark" | "Bitcoin" | "Solana" | "Tron" | "1" | "137" | "42161" | "30" | "31" | "10" | "8453" | "43114" | "130" | "59144" | "146" | "480" | "143" | "1329" | "50" | "999" | "57073";
16
16
  /**
17
17
  * The chain identifiers the **server** actually speaks on the wire — mirrors
18
18
  * `crate::Chain` and the generated `components["schemas"]["Chain"]`. Bridge
@@ -20,4 +20,4 @@ export type Chain = "Arkade" | "Lightning" | "Bitcoin" | "Solana" | "Tron" | "1"
20
20
  * carried in `bridge_target_chain`. Use this for anything sent to / received
21
21
  * from the server; use {@link Chain} for the SDK's public surface.
22
22
  */
23
- export type WireChain = "Arkade" | "Lightning" | "Bitcoin" | "1" | "137" | "42161" | "30" | "31";
23
+ export type WireChain = "Arkade" | "Lightning" | "Spark" | "Bitcoin" | "1" | "137" | "42161" | "30" | "31";
@@ -10,6 +10,7 @@ export type { Chain, WireChain } from "./chain.js";
10
10
  export { type ChainConfigEntry, type ChainConfigResponse, fromWireChainConfigResponse, type TokenRef, type WireChainConfigResponse, } from "./chain-config.js";
11
11
  export { type BridgeRate, type BridgeRouter, type DexQuoteAmount, type DexQuoteResponse, fromWireDexQuoteResponse, type Token, type TokenAmount, type WireDexQuoteResponse, } from "./dex-quote.js";
12
12
  export { fromWireNetworkFeePairEntry, fromWireNetworkFeesResponse, type NetworkFee, type NetworkFeePairEntry, type NetworkFeesResponse, type WireNetworkFeesResponse, } from "./network-fees.js";
13
+ export type { AppliedPromo } from "./promo-code.js";
13
14
  export { fromWireQuoteResponse, type QuoteResponse, type WireQuoteResponse, } from "./quote.js";
14
15
  export { fromWireReferralFeeResponse, type ReferralFeeResponse, type WireReferralFeeResponse, } from "./referral-fee.js";
15
16
  export { fromWireSwapPairsResponse, type SwapPairInfo, type SwapPairsResponse, type WireSwapPairsResponse, } from "./swap-pairs.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The promo code a quote was priced with, on `QuoteResponse.promo` and
3
+ * `ReferralFeeResponse.promo`. The quote's `protocol_fee_rate` and
4
+ * `max_amount` already include it.
5
+ */
6
+ export interface AppliedPromo {
7
+ code: string;
8
+ /**
9
+ * The promo's base fee as a decimal fraction (`0.001` = 0.1%). The swap's
10
+ * base fee is the lower of it and the route's; any extra fee is added on top.
11
+ */
12
+ fee_rate: number;
13
+ /** Largest swap the code applies to, in sats. Lifts the route maximum when higher. */
14
+ max_amount_sats: number;
15
+ }
@@ -1,3 +1,4 @@
1
+ import type { AppliedPromo } from "./promo-code.js";
1
2
  /**
2
3
  * `QuoteResponse` — end-to-end pricing for a swap between BTC and an
3
4
  * EVM/Arkade/Lightning target.
@@ -57,6 +58,11 @@ export interface QuoteResponse {
57
58
  * request, or for inbound CCTP swaps.
58
59
  */
59
60
  bridge_fee?: number | null;
61
+ /**
62
+ * The promo code this quote was priced with, when `promoCode` was passed.
63
+ * `protocol_fee_rate` and `max_amount` already include it.
64
+ */
65
+ promo?: AppliedPromo;
60
66
  }
61
67
  /**
62
68
  * Wire payload shape for `GET /quote` — matches the OpenAPI-generated
@@ -75,6 +81,7 @@ export interface WireQuoteResponse {
75
81
  net_source_amount: string;
76
82
  net_target_amount: string;
77
83
  bridge_fee?: number | null;
84
+ promo?: AppliedPromo | null;
78
85
  }
79
86
  /**
80
87
  * Translate the wire payload into the SDK-facing type.
@@ -1,3 +1,4 @@
1
+ import type { AppliedPromo } from "./promo-code.js";
1
2
  /**
2
3
  * `ReferralFeeResponse` — the referral / extra-fee delta for a referral code.
3
4
  *
@@ -20,12 +21,19 @@ export interface ReferralFeeResponse {
20
21
  * means the pair fee applies.
21
22
  */
22
23
  base_fee_rate?: number;
24
+ /**
25
+ * The promo, when a `promoCode` was passed. The base fee is the **lower**
26
+ * of its `fee_rate` and `base_fee_rate ?? fee_percentage`; `extra_fee_rate`
27
+ * is still added on top.
28
+ */
29
+ promo?: AppliedPromo;
23
30
  /** Partner label for the referral code, when registered. Informational. */
24
31
  referral_label?: string;
25
32
  }
26
33
  export interface WireReferralFeeResponse {
27
34
  extra_fee_rate: number;
28
35
  base_fee_rate?: number | null;
36
+ promo?: AppliedPromo | null;
29
37
  referral_label?: string | null;
30
38
  }
31
39
  export declare function fromWireReferralFeeResponse(wire: WireReferralFeeResponse): ReferralFeeResponse;
@@ -1,8 +1,8 @@
1
1
  export declare const SDK_NAME = "swap";
2
- export declare const SDK_VERSION = "1.11.1";
3
- export declare const SDK_COMMIT_HASH = "082a5f12e1766f59a5ff63bef69e81ce27453535";
2
+ export declare const SDK_VERSION = "1.13.0";
3
+ export declare const SDK_COMMIT_HASH = "2a9d67ccaf674a45dad1053243942d6043b9c0f0";
4
4
  /** @deprecated Retained for source compatibility; requests no longer send it. */
5
- export declare const SATORA_SERVER_VERSION = "0.3.29";
6
- export declare const CLIENT_AGENT = "swap/1.11.1";
5
+ export declare const SATORA_SERVER_VERSION = "0.3.31";
6
+ export declare const CLIENT_AGENT = "swap/1.13.0";
7
7
  export declare const DEFAULT_AA_BUNDLER_URL = "https://arb-mainnet.g.alchemy.com/v2/ZaG_75AoAHzPqzmys5jpD";
8
8
  export declare const DEFAULT_AA_POLICY_ID = "878b1c90-5b53-4c9c-8892-6d7659dd2e72";
@@ -225,6 +225,8 @@ export declare class Client {
225
225
  /** Delegated to the legacy client (migration checkpoint). */
226
226
  createLightningToEvmSwap(...args: Parameters<LegacyClient["createLightningToEvmSwap"]>): ReturnType<LegacyClient["createLightningToEvmSwap"]>;
227
227
  /** Delegated to the legacy client (migration checkpoint). */
228
+ createSparkToEvmSwap(...args: Parameters<LegacyClient["createSparkToEvmSwap"]>): ReturnType<LegacyClient["createSparkToEvmSwap"]>;
229
+ /** Delegated to the legacy client (migration checkpoint). */
228
230
  createLightningToBitcoinSwap(...args: Parameters<LegacyClient["createLightningToBitcoinSwap"]>): ReturnType<LegacyClient["createLightningToBitcoinSwap"]>;
229
231
  /** Delegated to the legacy client (migration checkpoint). */
230
232
  createBitcoinToLightningSwap(...args: Parameters<LegacyClient["createBitcoinToLightningSwap"]>): ReturnType<LegacyClient["createBitcoinToLightningSwap"]>;
@@ -9,6 +9,11 @@
9
9
  */
10
10
  import type { BitcoinHtlcFacts } from "./bitcoin.js";
11
11
  import type { BitcoinChainReader } from "./bitcoin-manager.js";
12
+ /**
13
+ * Most outputs a client's funding is counted from, as the server's on-chain
14
+ * HTLC watcher counts it.
15
+ */
16
+ export declare const MAX_FUNDING_OUTPUTS = 2;
12
17
  /** The slice of esplora's tx JSON we read. */
13
18
  type EsploraTx = {
14
19
  vin: Array<{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@satora/swap",
3
- "version": "1.11.1",
3
+ "version": "1.13.0",
4
4
  "description": "Satora swap client",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -68,7 +68,7 @@
68
68
  "@biomejs/biome": "2.3.15",
69
69
  "tsup": "^8.5.1",
70
70
  "typescript": "^5.7.0",
71
- "vitest": "^3.0.0",
71
+ "vitest": "^4.1.11",
72
72
  "@types/better-sqlite3": "^7.6.13",
73
73
  "@lendasat/lendaswap-sdk-pure": "2.8.1"
74
74
  },
@@ -1,9 +0,0 @@
1
- import {
2
- electrumReader
3
- } from "./chunk-3ZMSZSAV.js";
4
- import "./chunk-LSCRTQOS.js";
5
- import "./chunk-DGUM43GV.js";
6
- export {
7
- electrumReader
8
- };
9
- //# sourceMappingURL=bitcoin-reader-electrum-4PNSDHIA.js.map
@@ -1,9 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
- var _chunkINHFP222cjs = require('./chunk-INHFP222.cjs');
4
- require('./chunk-5DQHR3RO.cjs');
5
- require('./chunk-JEQ2X3Z6.cjs');
6
-
7
-
8
- exports.electrumReader = _chunkINHFP222cjs.electrumReader;
9
- //# sourceMappingURL=bitcoin-reader-electrum-VCQ5TQ44.cjs.map
@@ -1,14 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
-
5
-
6
- var _chunk5DQHR3ROcjs = require('./chunk-5DQHR3RO.cjs');
7
- require('./chunk-JEQ2X3Z6.cjs');
8
-
9
-
10
-
11
-
12
-
13
- exports.DEFAULT_ESPLORA_URLS = _chunk5DQHR3ROcjs.DEFAULT_ESPLORA_URLS; exports.esploraReader = _chunk5DQHR3ROcjs.esploraReader; exports.htlcFactsFromEsploraTxs = _chunk5DQHR3ROcjs.htlcFactsFromEsploraTxs; exports.resolveMinConfirmations = _chunk5DQHR3ROcjs.resolveMinConfirmations;
14
- //# sourceMappingURL=bitcoin-reader-esplora-6RH7S4BR.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/bitcoin-reader-esplora-6RH7S4BR.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,yRAAC","file":"/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/bitcoin-reader-esplora-6RH7S4BR.cjs"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/contracts/bitcoin-reader-electrum.ts"],"sourcesContent":["/**\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 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 // Among all txs paying the address, the one paying the MOST is the\n // funding candidate — same rule as the pure SDK's UTXO lookup. The\n // address is public, so a stray dust payment (whether it landed before\n // or after the real funding) must not be mistaken for the funding and\n // observe the swap as underfunded/invalid.\n let funding: (typeof txs)[number] | undefined;\n let fundedSats = 0;\n for (const candidate of txs) {\n let paid = 0;\n for (const i of outputIndicesPaying(candidate.tx))\n paid += Number(candidate.tx.getOutput(i).amount ?? 0n);\n if (paid > fundedSats) {\n funding = candidate;\n fundedSats = paid;\n }\n }\n if (!funding) return { funding: \"absent\", fundedSats: 0 };\n const fundedVouts = outputIndicesPaying(funding.tx);\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 hex.encode(input.txid) === funding.entry.tx_hash &&\n input.index !== undefined &&\n fundedVouts.includes(input.index)\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: 0/1 read straight off the\n // confirmed flag; deeper policies need the tip to compute depth.\n const height = funding.entry.height;\n const isConfirmed = height > 0;\n let deepEnough: boolean;\n if (isConfirmed) {\n if (required <= 1) {\n deepEnough = true;\n } else {\n const tip = await client.request<{ height: number }>(\n \"blockchain.headers.subscribe\",\n [],\n );\n deepEnough = tip.height - height + 1 >= required;\n }\n } else {\n deepEnough = required === 0;\n }\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"],"mappings":";;;;;AAmBA,SAAS,cAAc;AACvB,SAAS,WAAW;AACpB,YAAY,SAAS;AAsCrB,IAAM,kBAAkB;AAAA,EACtB,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,KAAK;AACP;AAEA,SAAS,mBAAmB,SAAgC;AAC1D,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAW;AAAA,IACb,KAAK;AAAA,IACL,KAAK;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