@satora/swap 1.10.0 → 1.10.2
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.
- package/dist/{chunk-FXGBP464.cjs → chunk-2LGHF7A3.cjs} +114 -99
- package/dist/chunk-2LGHF7A3.cjs.map +1 -0
- package/dist/{chunk-JAQ7MTJH.cjs → chunk-OJNQCRHU.cjs} +5 -5
- package/dist/{chunk-JAQ7MTJH.cjs.map → chunk-OJNQCRHU.cjs.map} +1 -1
- package/dist/{chunk-OWK4QVCF.js → chunk-S4T4GK5G.js} +22 -7
- package/dist/{chunk-OWK4QVCF.js.map → chunk-S4T4GK5G.js.map} +1 -1
- package/dist/{chunk-SEHIFNWW.js → chunk-VBNBVJLB.js} +5 -5
- package/dist/{chunk-SEHIFNWW.js.map → chunk-VBNBVJLB.js.map} +1 -1
- package/dist/delegate.cjs +2 -2
- package/dist/delegate.js +1 -1
- package/dist/{dist-SFQUB46D.js → dist-L5LHQNRK.js} +3 -3
- package/dist/dist-MMYSP6LP.cjs +394 -0
- package/dist/{dist-VCEMHI5A.cjs.map → dist-MMYSP6LP.cjs.map} +1 -1
- package/dist/index.cjs +10 -10
- package/dist/index.js +3 -3
- package/dist/types/cjs/pure/version.d.cts +4 -4
- package/dist/types/esm/pure/version.d.ts +4 -4
- package/package.json +1 -1
- package/dist/chunk-FXGBP464.cjs.map +0 -1
- package/dist/dist-VCEMHI5A.cjs +0 -394
- /package/dist/{dist-SFQUB46D.js.map → dist-L5LHQNRK.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/chunk-2LGHF7A3.cjs","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/globals/global.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/utils.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/errors/errors.js","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/chaining-functions.js","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/debug.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/promise.js","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/temp-transaction.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/globals/constants.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/combine.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/keyrange.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/workaround-undefined-primkey.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/entity/Entity.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/cmp.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/table/table-helpers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/prop-modification.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/apply-update-spec.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/table/table.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/Events.js","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/make-class-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/table/table-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/collection/collection-helpers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/collection/collection.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/collection/collection-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/compare-functions.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/where-clause/where-clause-helpers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/where-clause/where-clause.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/where-clause/where-clause-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/event-wrappers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/globals/global-events.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/transaction/transaction.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/transaction/transaction-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/index-spec.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/table-schema.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/quirks.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/get-key-extractor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/dbcore-indexeddb.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/generate-middleware-stacks.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/version/schema-helpers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/version/version.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/version/version-constructor.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/globals/connections.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/database-enumerator.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/vip.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/node_modules/.pnpm/safari-14-idb-fix@3.0.0/node_modules/safari-14-idb-fix/dist/index.js","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/rangeset.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/extend-observability-set.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/obs-sets-overlap.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/cache.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/signalSubscribers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/dexie-open.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/yield-support.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/transaction-helpers.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/virtual-index-middleware.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/get-object-diff.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/get-effective-keys.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/hooks/hooks-middleware.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/dbcore/cache-existing-values-middleware.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/is-cachable-context.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/is-cachable-request.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/observability-middleware.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/adjust-optimistic-request-from-failures.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/is-within-range.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/apply-optimistic-ops.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/are-ranges-equal.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/is-super-range.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/find-compatible-query.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/subscribe-cachentry.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/cache/cache-middleware.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/helpers/vipify.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/dexie.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/observable/observable.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/dexie-dom-dependencies.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/live-query.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/classes/dexie/dexie-static-props.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/propagate-locally.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/live-query/enable-broadcast.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/support-bfcache.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/propmods/add.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/propmods/remove.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/functions/propmods/replace-prefix.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/index.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/src/index-umd.ts","../../../node_modules/.pnpm/openapi-fetch@0.17.0/node_modules/openapi-fetch/src/index.js","../../../../ts-pure-sdk/src/api/client.ts","../../../../ts-pure-sdk/src/arkade.ts","../../../../ts-pure-sdk/src/arkade-address.ts","../../../../ts-pure-sdk/src/bolt11.ts","../../../../ts-pure-sdk/src/cctp/fee.ts","../../../../ts-pure-sdk/src/cctp/utils.ts","../../../../ts-pure-sdk/src/cctp-inbound/approveAndBurn.ts","../../../../ts-pure-sdk/src/cctp-inbound/burn.ts","../../../../ts-pure-sdk/src/cctp-inbound/chainMap.ts","../../../../ts-pure-sdk/src/cctp-inbound/fundSwap.ts","../../../../ts-pure-sdk/src/cctp-inbound/client.ts","../../../../ts-pure-sdk/src/cctp-inbound/eip2612.ts","../../../../ts-pure-sdk/src/evm/signing.ts","../../../../ts-pure-sdk/src/cctp-inbound/permit2.ts","../../../../ts-pure-sdk/src/cctp-inbound/recover.ts","../../../../ts-pure-sdk/src/usdt0-bridge/constants.ts","../../../../ts-pure-sdk/src/usdt0-bridge/tracking.ts","../../../../ts-pure-sdk/src/usdt0-bridge/utils.ts","../../../../ts-pure-sdk/src/tokens.ts","../../../../ts-pure-sdk/src/compose-quote.ts","../../../../ts-pure-sdk/src/signer/index.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/src/pbkdf2.ts","../../../node_modules/.pnpm/@scure+bip39@2.0.1/node_modules/@scure/bip39/index.js","../../../node_modules/.pnpm/@scure+bip39@2.0.1/node_modules/@scure/bip39/wordlists/english.js","../../../../ts-pure-sdk/src/swap-verification.ts","../../../../ts-pure-sdk/src/refund/arkade.ts","../../../../ts-pure-sdk/src/arkade-submit.ts","../../../../ts-pure-sdk/src/refund/onchain.ts","../../../../ts-pure-sdk/src/create/retry.ts","../../../../ts-pure-sdk/src/create/arkade.ts","../../../../ts-pure-sdk/src/create/arkade-to-lightning.ts","../../../../ts-pure-sdk/src/create/bitcoin.ts","../../../../ts-pure-sdk/src/create/bitcoin-to-arkade.ts","../../../../ts-pure-sdk/src/create/bitcoin-to-lightning.ts","../../../../ts-pure-sdk/src/create/funding-terms.ts","../../../../ts-pure-sdk/src/create/evm-to-arkade.ts","../../../../ts-pure-sdk/src/create/evm-to-bitcoin.ts","../../../../ts-pure-sdk/src/create/evm-to-lightning.ts","../../../../ts-pure-sdk/src/create/lightning-to-arkade.ts","../../../../ts-pure-sdk/src/create/lightning-to-bitcoin.ts","../../../../ts-pure-sdk/src/create/lightning-to-evm.ts","../../../../ts-pure-sdk/src/electrum-ws.ts","../../../../ts-pure-sdk/src/esplora.ts","../../../../ts-pure-sdk/src/evm/kernel.ts","../../../../ts-pure-sdk/src/evm/key-signer.ts","../../../../ts-pure-sdk/src/evm/native.ts","../../../../ts-pure-sdk/src/evm/refund-call.ts","../../../../ts-pure-sdk/src/redeem/gasless.ts","../../../../ts-pure-sdk/src/redeem/ethereum.ts","../../../../ts-pure-sdk/src/redeem/types.ts","../../../../ts-pure-sdk/src/redeem/arkade.ts","../../../../ts-pure-sdk/src/redeem/arkade-condition.ts","../../../../ts-pure-sdk/src/redeem/rif-relay.ts","../../../../ts-pure-sdk/src/redeem/userop-claim.ts","../../../../ts-pure-sdk/src/redeem/signer-claim.ts","../../../../ts-pure-sdk/src/redeem/index.ts","../../../../ts-pure-sdk/src/refund/collab-arkade-evm.ts","../../../../ts-pure-sdk/src/storage/types.ts","../../../../ts-pure-sdk/src/storage/index.ts","../../../../ts-pure-sdk/src/types/chain-config.ts","../../../../ts-pure-sdk/src/types/dex-quote.ts","../../../../ts-pure-sdk/src/types/network-fees.ts","../../../../ts-pure-sdk/src/types/quote.ts","../../../../ts-pure-sdk/src/types/referral-fee.ts","../../../../ts-pure-sdk/src/types/swap-pairs.ts","../../../../ts-pure-sdk/src/usdt0-bridge/tron.ts","../../../../ts-pure-sdk/src/ws.ts","../../../../ts-pure-sdk/src/client.ts","../../../../ts-pure-sdk/src/escrow/index.ts","../../../../ts-pure-sdk/src/price-calculations.ts","../../../node_modules/.pnpm/dexie@4.4.4/node_modules/dexie/import-wrapper.mjs","../../../../ts-pure-sdk/src/storage/idb.ts","../../../../ts-pure-sdk/src/usd-price.ts"],"names":["d","b","__assign","asap","concat","DexieError","_a","type","resolve","reject","props","Entity","cmp","keys","PropModification","Table","task","trans","Promise","i","add","args","Collection","count","direction","WhereClause","addRange","ranges","Transaction","p","db","tables","keyPath","compound","result","req","openCursor","query","ev","hasGetAll","hasIdb3Features","oldVersion","tableChange","Version","remove","indexedDB","Dexie","RangeSet","mergeRanges","target","rangesOverlap","safari14Workaround","index","primaryKey","dxTrans","cache","key","state","Observable","liveQuery","_Dexie","Debug.debug","Debug.setDebug","replacePrefix","fetch","error","final","joiner","clean","address","hex","selector","addressHex","keccak256Hex","needsBridge","wordlist","p2tr","htlcAddress","returned","bech32","REGTEST_NETWORK","BROADCAST_TIMEOUT_MS","shape","word","normalizeBytes32","secondsToTimelock","parseXOnlyPubKey","MIN_RECONNECT_MS","MAX_RECONNECT_MS","self","lock"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6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;AAGJ,IAAA;AACE,IAAA;AACH,IAAA;AAEM,MAAA;AACJ,MAAA;AAAoC,QAAA;AACtC,IAAA;AACF,EAAA;AACO,EAAA;AACT;ACvFM;AAKG;AACD,EAAA;AACM,IAAA;AACH,EAAA;AACX;AACS;AACC,EAAA;AACA,EAAA;AACA,EAAA;AACI,IAAA;AACH,EAAA;AACX;AACS;AACE,EAAA;AACD,EAAA;AACI,IAAA;AACd;AASgB;AACJ,EAAA;AACJ,EAAA;AACM,IAAA;AACH,EAAA;AACX;AACM;AAEI,EAAA;AAGC,EAAA;AACX;AACS;AACA,EAAA;AACK,IAAA;AACVC,EAAAA;AACQ,IAAA;AACA,MAAA;AACP,EAAA;AACM,EAAA;AACX;AAcgB;AACJ,EAAA;AACF,EAAA;AACN,EAAA;AACO,EAAA;AACX;AAcgB;AACZ,EAAA;AACM,EAAA;AACC,EAAA;AACX;AAIgB;AACR,EAAA;AACA,IAAA;AACJ,EAAA;AAEI,IAAA;AACJ,EAAA;AACO,EAAA;AACX;AACM;AAwBU;AACL,EAAA;AACX;ACtIa;A5GuhRH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A4GrhRL,GAAA;AHj/DC;AAEA;AAEA;AAEA;AAEA;AA6BG;AACD,EAAA;AACA,EAAA;AACN,EAAA;AACA,EAAA;AACA,EAAA;AACO,EAAA;AACT;AAwBa;AACF,EAAA;AACA,EAAA;AAED,EAAA;AACD,IAAA;AACA,IAAA;AACP,EAAA;AzGi9UQ;AACA;AACA;AACA;AACA;AACA;AACA;AyG98UD,EAAA;AACC,IAAA;AACA,IAAA;AACN,IAAA;AACF,EAAA;AzGg9UQ;AACA;AACA;AACA;AACA;AACA;AACA;AyG78UD,EAAA;AACC,IAAA;AACK,IAAA;AACT,MAAA;AACF,IAAA;AACM,IAAA;AACA,IAAA;AACN,IAAA;AACF,EAAA;AzG+8UQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AyG58UD,EAAA;AACD,IAAA;AACA,IAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACF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A;AACL,IAAA;AACI,IAAA;AAEC,EAAA;AAET;AA8Ba;AACX,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AxJkhbQ;AACA;AACA;AACA;AACA;AwJ/gbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJihbQ;AACA;AACA;AACA;AACA;AwJ9gbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJghbQ;AACA;AACA;AACA;AACA;AACA;AwJ7gbR,EAAA;AACE,IAAA;AACF,EAAA;AxJ+gbQ;AACA;AACA;AACA;AACA;AwJ5gbR,EAAA;AACO,IAAA;AACA,MAAA;AACA,MAAA;AAAA,IAAA;AAEL,IAAA;AACF,EAAA;AxJ8gbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ3gbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJ6gbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ1gbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJ4gbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJzgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJ2gbQ;AACA;AACA;AACA;AACA;AwJxgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJ0gbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJvgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJygbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJtgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJwgbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJrgbR,EAAA;AACM,IAAA;AACF,MAAA;AACF,IAAA;AACK,IAAA;AACL,IAAA;AACF,EAAA;AxJugbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJpgbD,EAAA;AACA,IAAA;AACL,IAAA;AACF,EAAA;AxJsgbQ;AACA;AACA;AACA;AACA;AACA;AwJngbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJqgbQ;AACA;AACA;AACA;AACA;AACA;AwJlgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJogbQ;AACA;AACA;AACA;AACA;AwJjgbR,EAAA;AACO,IAAA;AACL,IAAA;AACF,EAAA;AxJmgbQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJhgbF,EAAA;AACA,IAAA;AACF,MAAA;AACE,QAAA;AAAA,MAAA;AAEJ,IAAA;AAEI,IAAA;AAEA,IAAA;AAEF,MAAA;AACF,IAAA;AAEE,MAAA;AACI,MAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AAEE,MAAA;AACI,MAAA;AACF,QAAA;AACF,MAAA;AAEE,QAAA;AAEA,QAAA;AACF,MAAA;AACF,IAAA;AAEE,MAAA;AACF,IAAA;AAEA,IAAA;AACE,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AAGA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AAAe,MAAA;AAEjB,MAAA;AACA,MAAA;AACA,MAAA;AAAK,IAAA;AAET,EAAA;AACF;AA6BM;AAEO;AACF,EAAA;AACA,EAAA;AACT,EAAA;AxJ09aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJx9aC,EAAA;AAIA,EAAA;AACA,EAAA;AACT,EAAA;AACA,EAAA;AACA,EAAA;AACS,EAAA;AxJu9aD;AACA;AACA;AACA;AACA;AACA;AACA;AwJp9aR,E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A;AACA;AACA;AACA;AACA;AwJl8aR,EAAA;AACE,IAAA;AACF,EAAA;AxJo8aQ;AACA;AACA;AACA;AACA;AACA;AACA;AwJj8aR,EAAA;AACE,IAAA;AACF,EAAA;AxJm8aQ;AACA;AACA;AACA;AACA;AACA;AACA;AwJh8aF,EAAA;AACA,IAAA;AACA,IAAA;AACF,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AxJk8aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ/7aR,EAAA;AACE,IAAA;AACF,EAAA;AxJi8aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ97aR,EAAA;AACQ,IAAA;AACN,IAAA;AACF,EAAA;AxJg8aQ;AACA;AACA;AACA;AACA;AwJ77aR,EAAA;AACE,IAAA;AACF,EAAA;AxJ+7aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ57aR,EAAA;AAOQ,IAAA;AAGA,IAAA;AACA,IAAA;AAGN,IAAA;AACF,EAAA;AxJo7aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJj7aR,EAAA;AAKQ,IAAA;AACN,IAAA;AACF,EAAA;AAEM,EAAA;AAKA,IAAA;AACE,MAAA;AACA,MAAA;AACF,QAAA;AACF,MAAA;AACA,MAAA;AACE,QAAA;AACmF,MAAA;AAGvF,IAAA;AACI,IAAA;AACE,IAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACF,IAAA;AACF,MAAA;AACE,QAAA;AACD,MAAA;AACD,MAAA;AACF,IAAA;AAIE,MAAA;AACE,QAAA;AACA,QAAA;AAEA,QAAA;AACD,MAAA;AACD,MAAA;AACF,IAAA;AACF,EAAA;AxJo6aQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJj6aR,EAAA;AACQ,IAAA;AACA,IAAA;AAIJ,IA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,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AAEA,IAAA;AACF,EAAA;AxJ2vaQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJxvaF,EAAA;AACE,IAAA;AACJ,MAAA;AACD,IAAA;AACG,IAAA;AACF,MAAA;AACF,IAAA;AACK,IAAA;AACH,MAAA;AACF,IAAA;AAEA,IAAA;AACF,EAAA;AxJyvaQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJtvaF,EAAA;AACC,IAAA;AACH,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AxJwvaQ;AACA;AACA;AACA;AACA;AwJrvaF,EAAA;AACC,IAAA;AACH,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AAEM,EAAA;AACC,IAAA;AACH,MAAA;AACF,IAAA;AACM,IAAA;AACR,EAAA;AAEM,EAAA;AACC,IAAA;AACH,MAAA;AACF,IAAA;AACM,IAAA;AACR,EAAA;AxJqvaQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJlvaF,EAAA;AAGE,IAAA;AACD,IAAA;AACH,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AAEK,IAAA;AACJ,MAAA;AACD,IAAA;AACG,IAAA;AACF,MAAA;AACF,IAAA;AACK,IAAA;AACH,MAAA;AACF,IAAA;AAEM,IAAA;AACD,IAAA;AACH,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AAAe,MAAA;AAElB,IAAA;AAED,IAAA;AACE,MAAA;AACA,MAAA;AAIA,MAAA;AACA,MAAA;AAEM,QAAA;AACA,QAAA;AACA,QAAA;AAAk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AAEvC,EAAA;AxJygYQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJtgYF,EAAA;AAGJ,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AAAmC,IAAA;AAEvC,EAAA;AxJsgYQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJlgYF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJkgYQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ9/XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJ8/XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ1/XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJ0/XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJt/XF,EAAA;AAGJ,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AAAmC,IAAA;AAEvC,EAAA;AxJs/XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJl/XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJk/XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ9+XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJ8+XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ1+XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJ0+XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJt+XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJs+XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJn+XF,EAAA;AAGJ,IAAA;AACF,EAAA;AxJm+XQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AwJ/9XF,EAAA;AASE,IAAA;AACD,IAAA;AACH,MAAA;AACE,QAAA;AAAc,MAAA;AAElB,IAAA;AAEM,IAAA;AAGJ,IAAA;AAIA,MAAA;AACE,QAAA;AAAmD,MAAA;AAEvD,IAAA;AAGM,IAAA;AACA,IAAA;AAEA,IAAA;AACJ,MAAA;AACD,IAAA;AACI,IAAA;AACH,MAAA;AACA,MAAA;AACE,QAAA;AAA0D,MAAA;AAE9D,IAAA;AAEM,IAAA;AAiBA,IAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACA,sBAAA;AAAS,IAAA;AAIL,IAAA;AACN,IAAA;AACM,IAAA;AAC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IAAA;AACE,MAAA;AACI,MAAA;AAEJ,MAAA;AACI,MAAA;AAEJ,MAAA;AACD,IAAA;AACH,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AACD,IAAA;AACF,EAAA;AACF;A7Jy6rBU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/swap/swap/client-sdk/ts-sdk/packages/swap/dist/chunk-2LGHF7A3.cjs","sourcesContent":[null,"/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : global;\n","import { _global } from '../globals/global';\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise) {\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _global };\n\nexport function extend<T extends object, X extends object>(\n obj: T,\n extension: X\n): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props(proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n (typeof Reflect === 'undefined' ? keys : Reflect.ownKeys)(extension).forEach(\n (key) => {\n setProp(proto, key, extension[key]);\n }\n );\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(\n obj,\n prop,\n extend(\n functionOrGetSet &&\n hasOwn(functionOrGetSet, 'get') &&\n typeof functionOrGetSet.get === 'function'\n ? {\n get: functionOrGetSet.get,\n set: functionOrGetSet.set,\n configurable: true,\n }\n : { value: functionOrGetSet, configurable: true, writable: true },\n options\n )\n );\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, 'constructor', Child);\n return {\n extend: props.bind(null, Child.prototype),\n };\n },\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || ((proto = getProto(obj)) && getPropertyDescriptor(proto, prop));\n}\n\nconst _slice = [].slice;\nexport function slice(args, start?, end?) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert(b) {\n if (!b) throw new Error('Assertion Failed');\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn);\n else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject<T, R>(\n array: T[],\n extractor: (x: T, idx: number) => [string, R]\n): { [name: string]: R } {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn: (...args: any[]) => void, onerror, args?): void {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj == null\n ? undefined\n : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === '')\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath)))\n obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath)) {\n // Don't create intermediate objects when we're just deleting a\n // non-existing path. Otherwise delByKeyPath() would have the\n // side-effect of adding empty objects along the path.\n if (value === undefined) return;\n innerObj = obj[currentKeyPath] = {};\n }\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function (kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten<T>(a: (T | T[])[]): T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n 'BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey'\n .split(',')\n .concat(\n flatten(\n [8, 16, 32, 64].map((num) =>\n ['Int', 'Uint', 'Float'].map((t) => t + num + 'Array')\n )\n )\n )\n .filter((t) => _global[t]);\nconst intrinsicTypes = new Set(intrinsicTypeNames.map((t) => _global[t]));\n\n/** Deep clone a simple object tree.\n *\n * Copies object tree deeply, but does not deep-copy arrays,\n * typed arrays, Dates or other intrinsic types.\n *\n * Does not check for cyclic references.\n *\n * This function is 6 times faster than structuredClone() on chromium 111.\n *\n * This function can safely be used for cloning ObservabilitySets and RangeSets.\n *\n * @param o Object to clone\n * @returns Cloned object\n */\nexport function cloneSimpleObjectTree<T extends object>(o: T): T {\n const rv = {} as T;\n for (const k in o)\n if (hasOwn(o, k)) {\n const v = o[k];\n rv[k] =\n !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor)\n ? v\n : cloneSimpleObjectTree(v);\n }\n return rv;\n}\n\nexport function objectIsEmpty(o: object) {\n for (const k in o) if (hasOwn(o, k)) return false;\n return true;\n}\n\nlet circularRefs: null | WeakMap<any, any> = null;\n\n/** Deep clone an object or array.\n *\n *\n * @param any\n * @returns\n */\nexport function deepClone<T>(any: T): T {\n circularRefs = new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone<T>(x: T): T {\n if (!x || typeof x !== 'object') return x;\n let rv = circularRefs.get(x); // Resolve circular references\n if (rv) return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n } else if (intrinsicTypes.has(x.constructor)) {\n // For performance, we're less strict than structuredClone - we're only\n // cloning arrays and custom objects.\n // Typed arrays, Dates etc are not cloned.\n rv = x;\n } else {\n // We're nicer to custom classes than what structuredClone() is -\n // we preserve the proto of each object.\n const proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n}\n\nconst { toString } = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol =\n typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';\nexport const getIteratorOf =\n typeof iteratorSymbol === 'symbol'\n ? function (x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n }\n : function () {\n return null;\n };\nexport const asyncIteratorSymbol =\n typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for('Symbol.asyncIterator')\n : '@asyncIterator';\n\nexport function delArrayItem(a: any[], x: any) {\n const i = a.indexOf(x);\n if (i >= 0) a.splice(i, 1);\n return i >= 0;\n}\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf(arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string')\n return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while (((x = it.next()), !x.done)) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction =\n typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : () => false;\n","import { derive, setProp } from '../functions/utils';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait',\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone',\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: 'Database version changed by other database connection',\n DatabaseClosed: 'Database has been closed',\n Abort: 'Transaction aborted',\n TransactionInactive: 'Transaction has already completed or failed',\n MissingAPI:\n 'IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb',\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError(name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError)\n .from(Error)\n .extend({\n toString: function () {\n return this.name + ': ' + this.message;\n },\n });\n\nfunction getMultiErrorMessage(msg, failures) {\n return (\n msg +\n '. Errors: ' +\n Object.keys(failures)\n .map((key) => failures[key].toString())\n .filter((v, i, s) => s.indexOf(v) === i) // Only unique error strings\n .join('\\n')\n );\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError(msg, failures, successCount, failedKeys) {\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError(msg, failures) {\n this.name = 'BulkError';\n this.failures = Object.keys(failures).map((pos) => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce(\n (obj, name) => ((obj[name] = name + 'Error'), obj),\n {}\n);\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj, name) => {\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + 'Error';\n function DexieError(msgOrInner, inner) {\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n}, {});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name) => {\n obj[name + 'Error'] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError(domError, message) {\n if (\n !domError ||\n domError instanceof DexieError ||\n domError instanceof TypeError ||\n domError instanceof SyntaxError ||\n !domError.name ||\n !exceptionMap[domError.name]\n )\n return domError;\n var rv = new exceptionMap[domError.name](\n message || domError.message,\n domError\n );\n if ('stack' in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, 'stack', {\n get: function () {\n return this.inner.stack;\n },\n });\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name) => {\n if (['Syntax', 'Type', 'Range'].indexOf(name) === -1)\n obj[name + 'Error'] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import { extend } from './utils';\n\nexport function nop() {}\nexport function mirror(val) {\n return val;\n}\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess\n ? callBoth(onsuccess, this.onsuccess)\n : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess\n ? callBoth(onsuccess, this.onsuccess)\n : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess\n ? callBoth(onsuccess, this.onsuccess)\n : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined\n ? res2 === undefined\n ? undefined\n : res2\n : extend(res, res2);\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug =\n typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n}\n\nexport function deprecated<T>(what: string, fn: (...args) => T) {\n return function () {\n console.warn(\n `${what} is deprecated. See https://dexie.org/docs/Deprecations}`\n );\n return fn.apply(this, arguments);\n } as (...args) => T;\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport { _global } from '../globals/global';\nimport {\n tryCatch,\n props,\n setProp,\n getPropertyDescriptor,\n getArrayOf,\n extend,\n getProto,\n} from '../functions/utils';\nimport { nop, callBoth, mirror } from '../functions/chaining-functions';\nimport { debug } from './debug';\nimport { exceptions } from '../errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled).\n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\nconst ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] =\n typeof Promise === 'undefined'\n ? []\n : (() => {\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest('SHA-512', new Uint8Array([0]));\n return [nativeP, getProto(nativeP), globalP];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise =\n resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nfunction schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n}\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n\nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop,\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function DexiePromise(fn) {\n if (typeof this !== 'object')\n throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n\n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n\n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function () {\n var psd = PSD,\n microTaskId = totalEchoes;\n\n function then(onFulfilled, onRejected) {\n var possibleAwait =\n !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(\n this,\n new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\n resolve,\n reject,\n psd\n )\n );\n });\n if (this._consoleTask) rv._consoleTask = this._consoleTask;\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp(\n this,\n 'then',\n value && value.prototype === INTERNAL\n ? thenProp // Restore to original property descriptor.\n : {\n get: function () {\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set, // Keep a setter that is prepared to restore original.\n }\n );\n },\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(\n this,\n new Listener(null, null, onFulfilled, onRejected, PSD)\n );\n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function'\n ? this.then(null, (err) =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err)\n )\n : this.then(null, (err) =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err)\n );\n },\n\n finally: function (onFinally) {\n return this.then(\n (value) => {\n return DexiePromise.resolve(onFinally()).then(() => value);\n },\n (err) => {\n return DexiePromise.resolve(onFinally()).then(() => PromiseReject(err));\n }\n );\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity\n ? new DexiePromise((resolve, reject) => {\n var handle = setTimeout(\n () => reject(new exceptions.Timeout(msg)),\n ms\n );\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n })\n : this;\n },\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops(DexiePromise, {\n all: function () {\n var values = getArrayOf\n .apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits\n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a, i) =>\n DexiePromise.resolve(a).then((x) => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject)\n );\n });\n },\n\n resolve: (value) => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function')\n return new DexiePromise((resolve, reject) => {\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n return rv;\n },\n\n reject: PromiseReject,\n\n race: function () {\n var values = getArrayOf\n .apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map((value) => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: () => PSD,\n set: (value) => (PSD = value),\n },\n\n totalEchoes: { get: () => totalEchoes },\n\n //task: {get: ()=>task},\n\n newPSD: newScope,\n\n usePSD: usePSD,\n\n scheduler: {\n get: () => asap,\n set: (value) => {\n asap = value;\n },\n },\n\n rejectionMapper: {\n get: () => rejectionMapper,\n set: (value) => {\n rejectionMapper = value;\n }, // Map reject failures\n },\n\n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope(\n (resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(() => {\n this.unhandleds.length === 0\n ? resolve()\n : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n },\n zoneProps,\n resolve,\n reject\n );\n });\n },\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled)\n setProp(DexiePromise, 'allSettled', function () {\n const possiblePromises = getArrayOf\n .apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise((resolve) => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) =>\n DexiePromise.resolve(p)\n .then(\n (value) => (results[i] = { status: 'fulfilled', value }),\n (reason) => (results[i] = { status: 'rejected', reason })\n )\n .then(() => --remaining || resolve(results))\n );\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined')\n setProp(DexiePromise, 'any', function () {\n const possiblePromises = getArrayOf\n .apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) =>\n DexiePromise.resolve(p).then(\n (value) => resolve(value),\n (failure) => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }\n )\n );\n });\n });\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\n if (NativePromise.withResolvers)\n DexiePromise.withResolvers = NativePromise.withResolvers;\n}\n\n/**\n * Take a potentially misbehaving resolver function and make sure\n * onFulfilled and onRejected are only called once.\n *\n * Makes no guarantees about asynchrony.\n */\nfunction executePromiseTask(promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(\n (value) => {\n if (promise._state !== null) return; // Already settled\n if (value === promise)\n throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise\n ? value._then(resolve, reject)\n : value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n },\n handleRejection.bind(null, promise)\n ); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners(promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject)(\n promise._value\n );\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n}\n\nfunction callListener(cb, promise, listener) {\n try {\n // Call callback and resolve our listener with it's return value.\n var ret,\n value = promise._value;\n\n if (!promise._state && rejectingErrors.length) rejectingErrors = [];\n // cb is onResolved\n ret =\n debug && promise._consoleTask\n ? promise._consoleTask.run(() => cb(value))\n : cb(value);\n if (!promise._state && rejectingErrors.indexOf(value) === -1) {\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\n/* The callback to schedule with queueMicrotask().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n usePSD(globalPSD, () => {\n // Make sure to reset the async context to globalPSD before\n // executing any of the microtick subscribers.\n beginMicroTickScope() && endMicroTickScope();\n });\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach((p) => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i]();\n}\n\nfunction run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some((p) => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i)\n if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject(reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\n\nexport function wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0 }; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // When > 0, zoneLeaveEcho is queued. When 0 and task.echoes is also 0, nothing is queued.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\nvar zone_id_counter = 0;\nexport function newScope(fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise\n ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {\n value: DexiePromise,\n configurable: true,\n writable: true,\n },\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n }\n : {};\n if (props) extend(psd, props);\n\n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits() {\n if (!task.awaits) return false;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n return true;\n}\n\nif (('' + nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync(possiblePromise) {\n if (\n task.echoes &&\n possiblePromise &&\n possiblePromise.constructor === NativePromise\n ) {\n incrementExpectedAwaits();\n return possiblePromise.then(\n (x) => {\n decrementExpectedAwaits();\n return x;\n },\n (e) => {\n decrementExpectedAwaits();\n return rejection(e);\n }\n );\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n //if (task.echoes === 1) console.warn(\"Cancelling echoing of async context.\");\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.awaits = task.id = 0; // Cancel echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length - 1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone(targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (\n bEnteringZone\n ? task.echoes && (!zoneEchoes++ || targetZone !== PSD)\n : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)\n ) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n queueMicrotask(\n bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho\n );\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot() {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise\n ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, 'Promise'),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n }\n : {};\n}\n\nexport function usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function'\n ? fn\n : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n if (cleanup) queueMicrotask(decrementExpectedAwaits);\n }\n };\n}\n\n/** Execute callback in global context */\nexport function execInGlobalContext(cb) {\n if (Promise === NativePromise && task.echoes === 0) {\n if (zoneEchoes === 0) {\n cb();\n } else {\n enqueueNativeMicroTask(cb);\n }\n } else {\n setTimeout(cb, 0);\n }\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport { DexiePromise };\n","import { PSD, rejection, newScope } from '../helpers/promise';\nimport { DexieOptions } from '../public/types/dexie-constructor';\nimport { errnames, exceptions } from '../errors';\nimport { nop } from './chaining-functions';\nimport { Transaction } from '../classes/transaction';\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n */\nexport function tempTransaction(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any\n) {\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!db.idbdb || (!db._state.openComplete && !PSD.letThrough && !db._vip)) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._state.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() =>\n tempTransaction(db, mode, storeNames, fn)\n );\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (\n ex.name === errnames.InvalidState &&\n db.isOpen() &&\n --db._state.PR1398_maxLoop > 0\n ) {\n console.warn('Dexie: Need to reopen db');\n db.close({ disableAutoOpen: false });\n return db.open().then(() => tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans\n ._promise(mode, (resolve, reject) => {\n return newScope(() => {\n // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n })\n .then((result) => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n if (mode === 'readwrite')\n try {\n trans.idbtrans.commit();\n } catch {}\n return mode === 'readonly'\n ? result\n : trans._completion.then(() => result);\n }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","export const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n 'Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.';\nexport const STRING_EXPECTED = 'String expected.';\nexport const DEFAULT_MAX_CONNECTIONS = 1000;\nexport const dexieStackFrameFilter = (frame) =>\n !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1\n ? filter2\n ? function () {\n return (\n filter1.apply(this, arguments) && filter2.apply(this, arguments)\n );\n }\n : filter1\n : filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false,\n};\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true,\n};\n","import { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(\n keyPath: string | ArrayLike<string>\n) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === 'string' && !/\\./.test(keyPath)\n ? (obj: object) => {\n if (obj[keyPath] === undefined && keyPath in obj) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\n}\n","import { exceptions } from '../../errors';\n\nexport function Entity() {\n throw exceptions.Type(\n `Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.`\n );\n}\n","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(a: Uint8Array, b: Uint8Array) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array\n | BigInt64Array\n | BigUint64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\n}\n","import { DBCoreMutateResponse } from '../../public/types/dbcore';\nimport { Table } from './table';\n\nexport function builtInDeletionTrigger(\n table: Table,\n keys: null | readonly any[],\n res: DBCoreMutateResponse\n): DBCoreMutateResponse | Promise<DBCoreMutateResponse> {\n // Delete related document updates. Otherwise, if a row with same ID is created\n // again, its document would not be empty.\n // Document providers will get notified on the main table's row deletion and destroy\n // document. Sync of this action is outside of the Y.js scope but will be handled\n // by the dexie cloud sync layer or equivalent sync layer.\n const { yProps } = table.schema;\n if (!yProps) return res;\n if (keys && res.numFailures > 0)\n keys = keys.filter((_, i) => !res.failures[i]);\n return Promise.all(\n yProps.map(({ updatesTable }) =>\n keys\n ? table.db.table(updatesTable).where('k').anyOf(keys).delete()\n : table.db.table(updatesTable).clear()\n )\n ).then(() => res);\n}\n","import { isArray } from '../functions/utils';\nimport { PropModSpec } from '../public/types/prop-modification';\n\n/** Consistent change propagation across offline synced data.\n *\n * This class is executed client- and server side on sync, making\n * an operation consistent across sync for full consistency and accuracy.\n *\n * Example: An object represents a bank account with a balance.\n * One offline user adds $ 1.00 to the balance.\n * Another user (online) adds $ 2.00 to the balance.\n * When first user syncs, the balance becomes the sum of every operation (3.00).\n *\n * -- initial: balance is 0\n * 1. db.bankAccounts.update(1, { balance: new ProdModification({add: 100})}) // user 1 (offline)\n * 2. db.bankAccounts.update(1, { balance: new ProdModification({add: 200})}) // user 2 (online)\n * -- before user 1 syncs, balance is 200 (representing money with integers * 100 to avoid rounding issues)\n * <user 1 syncs>\n * -- balance is 300\n *\n * When new operations are added, they need to be added to:\n * 1. PropModSpec interface\n * 2. Here in PropModification with the logic they represent\n * 3. (Optionally) a sugar function for it, such as const mathAdd = (amount: number | BigInt) => new PropModification({mathAdd: amount})\n */\nexport class PropModification {\n ['@@propmod']: PropModSpec;\n execute(value: any): any {\n const spec = this['@@propmod'];\n // add (mathematical or set-wise)\n if (spec.add !== undefined) {\n const term = spec.add;\n // Set-addition on array representing a set of primitive types (strings, numbers)\n if (isArray(term)) {\n return [...(isArray(value) ? value : []), ...term].sort();\n }\n // Mathematical addition:\n if (typeof term === 'number') return (Number(value) || 0) + term; // if value is not convertible to number, return 0 + term\n if (typeof term === 'bigint') {\n try {\n return BigInt(value) + term;\n } catch {\n return BigInt(0) + term; // Unlike Number(value) that can return NaN, BigInt(value) throws if value is not BigInt, Number or numeric string\n }\n }\n throw new TypeError(`Invalid term ${term}`);\n }\n\n // remove (mathematical or set-wise)\n if (spec.remove !== undefined) {\n const subtrahend = spec.remove;\n // Set-addition on array representing a set of primitive types (strings, numbers)\n if (isArray(subtrahend)) {\n return isArray(value)\n ? value.filter((item) => !subtrahend.includes(item)).sort()\n : [];\n }\n // Mathematical addition:\n if (typeof subtrahend === 'number') return Number(value) - subtrahend;\n if (typeof subtrahend === 'bigint') {\n try {\n return BigInt(value) - subtrahend;\n } catch {\n return BigInt(0) - subtrahend; // Unlike Number(value) that can return NaN, BigInt(value) throws if value is not BigInt, Number or numeric string\n }\n }\n throw new TypeError(`Invalid subtrahend ${subtrahend}`);\n }\n\n // Replace a prefix:\n const prefixToReplace = spec.replacePrefix?.[0];\n if (\n prefixToReplace &&\n typeof value === 'string' &&\n value.startsWith(prefixToReplace)\n ) {\n return spec.replacePrefix[1] + value.substring(prefixToReplace.length);\n }\n return value;\n }\n\n constructor(spec: PropModSpec) {\n this['@@propmod'] = spec;\n }\n}\n","import { getByKeyPath, keys, setByKeyPath } from './utils';\nimport { PropModification } from '../helpers/prop-modification';\n\nexport function applyUpdateSpec(\n obj: any,\n changes: { [keyPath: string]: any }\n): boolean {\n const keyPaths = keys(changes);\n const numKeys = keyPaths.length;\n let anythingModified = false;\n for (let i = 0; i < numKeys; ++i) {\n const keyPath = keyPaths[i];\n const value = changes[keyPath];\n const origValue = getByKeyPath(obj, keyPath);\n if (value instanceof PropModification) {\n setByKeyPath(obj, keyPath, value.execute(origValue));\n anythingModified = true;\n } else if (origValue !== value) {\n setByKeyPath(obj, keyPath, value); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport {\n DexiePromise as Promise,\n PSD,\n newScope,\n rejection,\n beginMicroTickScope,\n endMicroTickScope,\n} from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport {\n isArray,\n keys,\n getByKeyPath,\n setByKeyPath,\n extend,\n getProto,\n} from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from '../../public/types/promise-extended';\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\nimport { Entity } from '../entity/Entity';\nimport { UpdateSpec } from '../../public';\nimport { cmp } from '../../functions/cmp';\nimport { builtInDeletionTrigger } from './table-helpers';\nimport { applyUpdateSpec } from '../../functions/apply-update-spec';\n\n/** class Table\n *\n * https://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable<any, IndexableType> {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (\n idbtrans: IDBTransaction,\n dxTrans: Transaction\n ) => PromiseLike<any> | void,\n writeLocked?: boolean | string\n ): PromiseExtended<any> {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n // @ts-ignore: Use Chrome's Async Stack Tagging API to allow tracing and simplify debugging for dexie users.\n const task =\n debug &&\n typeof console !== 'undefined' &&\n // @ts-ignore\n console.createTask &&\n // @ts-ignore\n console.createTask(\n `Dexie: ${mode === 'readonly' ? 'read' : 'write'} ${this.name}`\n );\n\n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\n 'Table ' + tableName + ' not part of transaction'\n );\n return fn(trans.idbtrans, trans) as Promise<any>;\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n let p =\n trans && trans.db._novip === this.db._novip\n ? trans === PSD.trans\n ? trans._promise(mode, checkTableInTransaction, writeLocked)\n : newScope(\n () =>\n trans._promise(mode, checkTableInTransaction, writeLocked),\n { trans: trans, transless: PSD.transless || PSD }\n )\n : tempTransaction(\n this.db,\n mode,\n [this.name],\n checkTableInTransaction\n );\n if (task) {\n // Dexie.debug = true so we trace errors\n p._consoleTask = task;\n p = p.catch((err) => {\n console.trace(err);\n return rejection(err);\n });\n }\n return p;\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n *\n * https://dexie.org/docs/Table/Table.get()\n *\n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(\n cb\n );\n if (keyOrCrit == null)\n return rejection(new exceptions.Type(`Invalid argument to Table.get()`));\n\n return this._trans('readonly', (trans) => {\n return this.core\n .get({ trans, key: keyOrCrit })\n .then((res) => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n *\n * https://dexie.org/docs/Table/Table.where()\n *\n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value}\n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this.where(keyPaths[0]).equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes\n .concat(this.schema.primKey)\n .filter((ix) => {\n if (\n ix.compound &&\n keyPaths.every((keyPath) => ix.keyPath.indexOf(keyPath) >= 0)\n ) {\n for (let i = 0; i < keyPaths.length; ++i) {\n if (keyPaths.indexOf(ix.keyPath[i]) === -1) return false;\n }\n return true;\n }\n return false;\n })\n .sort((a, b) => a.keyPath.length - b.keyPath.length)[0];\n\n if (compoundIndex && this.db._maxKey !== maxString) {\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(\n 0,\n keyPaths.length\n );\n return this.where(keyPathsInValidOrder).equals(\n keyPathsInValidOrder.map((kp) => indexOrCrit[kp])\n );\n }\n\n if (!compoundIndex && debug)\n console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit from a ` +\n `compound index [${keyPaths.join('+')}]`\n );\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n\n function equals(a, b) {\n return cmp(a, b) === 0; // Works with all indexable types including binary keys.\n }\n\n const [idx, filterFunction] = keyPaths.reduce(\n ([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index // filter::=null if not needed, otherwise combine function filter\n ? combine(\n prevFilterFn,\n index && index.multi\n ? (x) => {\n const prop = getByKeyPath(x, keyPath);\n return (\n isArray(prop) &&\n prop.some((item) => equals(value, item))\n );\n }\n : (x) => equals(value, getByKeyPath(x, keyPath))\n )\n : prevFilterFn,\n ];\n },\n [null, null]\n );\n\n return idx\n ? this.where(idx.name)\n .equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction)\n : compoundIndex\n ? this.filter(filterFunction) // Has compound but browser bad. Allow filter.\n : this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n *\n * https://dexie.org/docs/Table/Table.filter()\n *\n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n *\n * https://dexie.org/docs/Table/Table.count()\n *\n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n *\n * https://dexie.org/docs/Table/Table.offset()\n *\n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n *\n * https://dexie.org/docs/Table/Table.limit()\n *\n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n *\n * https://dexie.org/docs/Table/Table.each()\n *\n **/\n each(\n callback: (\n obj: any,\n cursor: { key: IndexableType; primaryKey: IndexableType }\n ) => any\n ) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n *\n * https://dexie.org/docs/Table/Table.toArray()\n *\n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n *\n * https://dexie.org/docs/Table/Table.toCollection()\n *\n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n *\n * https://dexie.org/docs/Table/Table.orderBy()\n *\n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(\n this,\n isArray(index) ? `[${index.join('+')}]` : index\n )\n );\n }\n\n /** Table.reverse()\n *\n * https://dexie.org/docs/Table/Table.reverse()\n *\n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n *\n * https://dexie.org/docs/Table/Table.mapToClass()\n *\n **/\n mapToClass(constructor: Function) {\n const { db, name: tableName } = this;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = class extends (constructor as any) {\n get db() {\n return db;\n }\n table() {\n return tableName;\n }\n };\n }\n // Collect all inherited property names (including method names) by\n // walking the prototype chain. This is to avoid overwriting them from\n // database data - so application code can rely on inherited props never\n // becoming shadowed by database object props.\n const inheritedProps = new Set<string>();\n for (let proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach((propName) =>\n inheritedProps.add(propName)\n );\n }\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n const readHook = (obj: Object) => {\n if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.\n // Create a new object that derives from constructor:\n const res = Object.create(constructor.prototype);\n // Clone members (but never those that collide with a property in the prototype\n // hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):\n for (let m in obj)\n if (!inheritedProps.has(m))\n try {\n res[m] = obj[m];\n } catch (_) {}\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook('reading', readHook);\n return constructor;\n }\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n *\n * https://dexie.org/docs/Table/Table.add()\n *\n **/\n add(obj, key?: IndexableType): PromiseExtended<IndexableType> {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', (trans) => {\n return this.core.mutate({\n trans,\n type: 'add',\n keys: key != null ? [key] : null,\n values: [objToAdd],\n });\n })\n .then((res) =>\n res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult\n )\n .then((lastResult) => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try {\n setByKeyPath(obj, keyPath, lastResult);\n } catch (_) {}\n }\n return lastResult;\n });\n }\n\n /** Table.upsert()\n *\n * https://dexie.org/docs/Table/Table.upsert()\n *\n **/\n upsert(\n key: IndexableType,\n modifications: { [keyPath: string]: any }\n ): PromiseExtended<boolean> {\n const { keyPath } = this.schema.primKey;\n return this._trans('readwrite', (trans) => {\n return this.core.get({ trans, key }).then((existing) => {\n const obj = existing ?? {};\n applyUpdateSpec(obj, modifications);\n if (keyPath) setByKeyPath(obj, keyPath, key);\n return this.core\n .mutate({\n trans,\n type: 'put',\n values: [obj],\n keys: [key],\n upsert: true,\n updates: { keys: [key], changeSpecs: [modifications] },\n })\n .then((res) =>\n res.numFailures ? Promise.reject(res.failures[0]) : !!existing\n );\n });\n });\n }\n\n /** Table.update()\n *\n * https://dexie.org/docs/Table/Table.update()\n *\n **/\n update(\n keyOrObject,\n modifications:\n | { [keyPath: string]: any }\n | ((\n obj: any,\n ctx: { value: any; primKey: IndexableType }\n ) => void | boolean)\n ): PromiseExtended<number> {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined)\n return rejection(\n new exceptions.InvalidArgument(\n 'Given object does not contain its primary key'\n )\n );\n /*// object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly. TODO: Document this change!\n if (!Object.isFrozen(keyOrObject)) try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }*/\n return this.where(':id').equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(':id').equals(keyOrObject).modify(modifications);\n }\n }\n\n /** Table.put()\n *\n * https://dexie.org/docs/Table/Table.put()\n *\n **/\n put(obj, key?: IndexableType): PromiseExtended<IndexableType> {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', (trans) =>\n this.core.mutate({\n trans,\n type: 'put',\n values: [objToAdd],\n keys: key != null ? [key] : null,\n })\n )\n .then((res) =>\n res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult\n )\n .then((lastResult) => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try {\n setByKeyPath(obj, keyPath, lastResult);\n } catch (_) {}\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n *\n * https://dexie.org/docs/Table/Table.delete()\n *\n **/\n delete(key: IndexableType): PromiseExtended<void> {\n return this._trans('readwrite', (trans) =>\n this.core\n .mutate({ trans, type: 'delete', keys: [key] })\n .then((res) => builtInDeletionTrigger(this, [key], res))\n .then((res) =>\n res.numFailures ? Promise.reject(res.failures[0]) : undefined\n )\n );\n }\n\n /** Table.clear()\n *\n * https://dexie.org/docs/Table/Table.clear()\n *\n **/\n clear() {\n return this._trans('readwrite', (trans) =>\n this.core\n .mutate({ trans, type: 'deleteRange', range: AnyRange })\n .then((res) => builtInDeletionTrigger(this, null, res))\n ).then((res) =>\n res.numFailures ? Promise.reject(res.failures[0]) : undefined\n );\n }\n\n /** Table.bulkGet()\n *\n * https://dexie.org/docs/Table/Table.bulkGet()\n *\n * @param keys\n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', (trans) => {\n return this.core\n .getMany({\n keys,\n trans,\n })\n .then((result) => result.map((res) => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n *\n * https://dexie.org/docs/Table/Table.bulkAdd()\n *\n **/\n bulkAdd(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray<IndexableType> | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options =\n options || (keys ? undefined : (keysOrOptions as { allKeys?: boolean }));\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', (trans) => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\n 'bulkAdd(): keys argument invalid on tables with inbound keys'\n );\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\n 'Arguments objects and keys must have the same length'\n );\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToAdd =\n keyPath && auto\n ? objects.map(workaroundForUndefinedPrimKey(keyPath))\n : objects;\n return this.core\n .mutate({\n trans,\n type: 'add',\n keys: keys as IndexableType[],\n values: objectsToAdd,\n wantResults,\n })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`,\n failures\n );\n });\n });\n }\n\n /** Table.bulkPut()\n *\n * https://dexie.org/docs/Table/Table.bulkPut()\n *\n **/\n bulkPut(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray<IndexableType> | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options =\n options || (keys ? undefined : (keysOrOptions as { allKeys?: boolean }));\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', (trans) => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\n 'bulkPut(): keys argument invalid on tables with inbound keys'\n );\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\n 'Arguments objects and keys must have the same length'\n );\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToPut =\n keyPath && auto\n ? objects.map(workaroundForUndefinedPrimKey(keyPath))\n : objects;\n\n return this.core\n .mutate({\n trans,\n type: 'put',\n keys: keys as IndexableType[],\n values: objectsToPut,\n wantResults,\n })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`,\n failures\n );\n });\n });\n }\n\n /** Table.bulkUpdate()\n *\n * https://dexie.org/docs/Table.Table.bulkUpdate()\n */\n bulkUpdate(\n keysAndChanges: readonly { key: any; changes: UpdateSpec<any> }[]\n ): PromiseExtended<number> {\n const coreTable = this.core;\n const keys = keysAndChanges.map((entry) => entry.key);\n const changeSpecs = keysAndChanges.map((entry) => entry.changes);\n const offsetMap: number[] = [];\n return this._trans('readwrite', (trans) => {\n return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keysAndChanges.forEach(({ key, changes }, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const keyPath of Object.keys(changes)) {\n const value = changes[keyPath];\n if (keyPath === this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\n `Cannot update primary key in bulkUpdate()`\n );\n }\n } else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n const numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys,\n changeSpecs,\n },\n })\n .then(({ numFailures, failures }) => {\n if (numFailures === 0) return numEntries;\n // Failure. bulkPut() may have a subset of keys\n // so we must translate returned 'failutes' into the offsets of given argument:\n for (const offset of Object.keys(failures)) {\n const mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n const failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\n `${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,\n failures\n );\n });\n });\n });\n }\n\n /** Table.bulkDelete()\n *\n * https://dexie.org/docs/Table/Table.bulkDelete()\n *\n **/\n bulkDelete(keys: ReadonlyArray<IndexableType>): PromiseExtended<void> {\n const numKeys = keys.length;\n return this._trans('readwrite', (trans) => {\n return this.core\n .mutate({ trans, type: 'delete', keys: keys as IndexableType[] })\n .then((res) => builtInDeletionTrigger(this, keys, res));\n }).then(({ numFailures, lastResult, failures }) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`,\n failures\n );\n });\n }\n}\n","import { keys, isArray, asap } from '../functions/utils';\nimport {\n nop,\n mirror,\n reverseStoppableEventChain,\n} from '../functions/chaining-functions';\nimport { exceptions } from '../errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length,\n args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof eventName === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n\n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) {\n return fn !== cb;\n });\n context.fire = context.subscribers.reduce(\n chainFunction,\n defaultFunction\n );\n },\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument('Invalid event config');\n });\n }\n}\n","import { arrayToObject, derive } from './utils';\n\nexport function makeClassConstructor<TConstructor>(\n prototype: Object,\n constructor: Function\n) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({ prototype });\n return constructor as any as TConstructor;\n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport {\n hookCreatingChain,\n pureFunctionChain,\n nop,\n mirror,\n hookUpdatingChain,\n hookDeletingChain,\n} from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (\n name: string,\n tableSchema: TableSchema,\n optionalTrans?: Transaction\n ): Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n *\n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor(db: Dexie) {\n return makeClassConstructor<TableConstructor>(\n Table.prototype,\n\n function Table(\n this: Table,\n name: string,\n tableSchema: TableSchema,\n trans?: Transaction\n ) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name]\n ? db._allTables[name].hook\n : (Events(null, {\n creating: [hookCreatingChain, nop],\n reading: [pureFunctionChain, mirror],\n updating: [hookUpdatingChain, nop],\n deleting: [hookDeletingChain, nop],\n }) as TableHooks);\n }\n );\n}\n","import { combine } from '../../functions/combine';\nimport { exceptions } from '../../errors';\nimport { hasOwn } from '../../functions/utils';\nimport { wrap } from '../../helpers/promise';\nimport { Collection } from './';\nimport {\n DBCoreCursor,\n DBCoreTable,\n DBCoreTransaction,\n DBCoreTableSchema,\n DBCoreRangeType,\n} from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection['_ctx'];\n\nexport function isPlainKeyRange(\n ctx: CollectionContext,\n ignoreLimitFilter?: boolean\n) {\n return (\n !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter)\n );\n}\n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter(\n ctx: CollectionContext,\n factory,\n isLimitFilter?\n) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? () => combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(\n ctx: CollectionContext,\n coreSchema: DBCoreTableSchema\n) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index)\n throw new exceptions.Schema(\n 'KeyPath ' +\n ctx.index +\n ' on object store ' +\n coreSchema.name +\n ' is not indexed'\n );\n return index;\n}\n\nexport function openCursor(\n ctx: CollectionContext,\n coreTable: DBCoreTable,\n trans: DBCoreTransaction\n) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index,\n range: ctx.range,\n },\n });\n}\n\nexport function iter(\n ctx: CollectionContext,\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable\n): Promise<any> {\n const filter = ctx.replayFilter\n ? combine(ctx.filter, ctx.replayFilter())\n : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter),\n fn,\n !ctx.keysOnly && ctx.valueMapper\n );\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (\n !filter ||\n filter(\n cursor,\n advance,\n (result) => cursor.stop(result),\n (err) => cursor.fail(err)\n )\n ) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]')\n key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n };\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(\n openCursor(ctx, coreTable, coreTrans),\n ctx.algorithm,\n union,\n !ctx.keysOnly && ctx.valueMapper\n ),\n ]);\n }\n}\n\nfunction iterate(\n cursorPromise: Promise<DBCoreCursor>,\n filter,\n fn,\n valueMapper\n): Promise<any> {\n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x, c, a) => fn(valueMapper(x), c, a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n\n return cursorPromise.then((cursor) => {\n if (cursor) {\n return cursor.start(() => {\n var c = () => cursor.continue();\n if (\n !filter ||\n filter(\n cursor,\n (advancer) => (c = advancer),\n (val) => {\n cursor.stop(val);\n c = nop;\n },\n (e) => {\n cursor.fail(e);\n c = nop;\n }\n )\n )\n wrappedFn(cursor.value, cursor, (advancer) => (c = advancer));\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from '../../public/types/collection';\nimport { Dexie } from '../dexie';\nimport { Table } from '../table';\nimport {\n IndexableType,\n IndexableTypeArrayReadonly,\n} from '../../public/types/indexable-type';\nimport { PromiseExtended } from '../../public/types/promise-extended';\nimport {\n iter,\n isPlainKeyRange,\n getIndexOrStore,\n addReplayFilter,\n addFilter,\n addMatchFilter,\n} from './collection-helpers';\nimport { rejection } from '../../helpers/promise';\nimport { combine } from '../../functions/combine';\nimport {\n extend,\n hasOwn,\n deepClone,\n keys,\n setByKeyPath,\n getByKeyPath,\n} from '../../functions/utils';\nimport { ModifyError } from '../../errors';\nimport { ThenShortcut } from '../../public/types/then-shortcut';\nimport { Transaction } from '../transaction';\nimport {\n DBCoreCursor,\n DBCoreTransaction,\n DBCoreRangeType,\n DBCoreMutateResponse,\n DBCoreKeyRange,\n} from '../../public/types/dbcore';\nimport { cmp } from '../../functions/cmp';\nimport { PropModification } from '../../helpers/prop-modification';\nimport { UpdateSpec } from '../../public/types/update-spec';\nimport { builtInDeletionTrigger } from '../table/table-helpers';\nimport { applyUpdateSpec } from '../../functions/apply-update-spec';\n\n/** class Collection\n *\n * https://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: 'next' | 'prev';\n unique: '' | 'unique';\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number;\n limit: number;\n error: any; // If set, any promise must be rejected with this error\n or: Collection;\n valueMapper: (any) => any;\n };\n\n _ondirectionchange?: Function;\n\n _read<T>(\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike<T>,\n cb?\n ): PromiseExtended<T> {\n var ctx = this._ctx;\n return ctx.error\n ? ctx.table._trans(null, rejection.bind(null, ctx.error))\n : ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write<T>(\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike<T>\n ): PromiseExtended<T> {\n var ctx = this._ctx;\n return ctx.error\n ? ctx.table._trans(null, rejection.bind(null, ctx.error))\n : ctx.table._trans('readwrite', fn, 'locked'); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction\n ): Promise<any> {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n *\n * https://dexie.org/docs/Collection/Collection.clone()\n *\n **/\n clone(props?): this {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n\n /** Collection.raw()\n *\n * https://dexie.org/docs/Collection/Collection.raw()\n *\n **/\n raw(): this {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n *\n * https://dexie.org/docs/Collection/Collection.each()\n *\n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended<void> {\n var ctx = this._ctx;\n\n return this._read((trans) => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n *\n * https://dexie.org/docs/Collection/Collection.count()\n *\n **/\n count(cb?) {\n return this._read((trans) => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable\n .count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range,\n },\n })\n .then((count) => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(\n ctx,\n () => {\n ++count;\n return false;\n },\n trans,\n coreTable\n ).then(() => count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n *\n * https://dexie.org/docs/Collection/Collection.sortBy()\n *\n **/\n sortBy(keyPath: string): PromiseExtended<any[]>;\n sortBy<R>(\n keyPath: string,\n thenShortcut: ThenShortcut<any[], R>\n ): PromiseExtended<R>;\n sortBy(keyPath: string, cb?: ThenShortcut<any[], any>) {\n const parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === 'next' ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return cmp(aVal, bVal) * order;\n }\n return this.toArray(function (a) {\n return a.slice().sort(sorter);\n }).then(cb);\n }\n\n /** Collection.toArray()\n *\n * https://dexie.org/docs/Collection/Collection.toArray()\n *\n **/\n toArray(cb?): PromiseExtended<any[]> {\n return this._read((trans) => {\n var ctx = this._ctx;\n if (isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimization using IDBObjectStore.getAll() or IDBKeyRange.getAll().\n // For reverse queries on IDB 3.0+ browsers, uses getAll(options) with direction.\n const { valueMapper } = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core\n .query({\n trans,\n limit: ctx.limit,\n values: true,\n direction: ctx.dir === 'prev' ? 'prev' : undefined,\n query: {\n index,\n range: ctx.range,\n },\n })\n .then(({ result }) =>\n valueMapper ? result.map(valueMapper) : result\n );\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, (item) => a.push(item), trans, ctx.table.core).then(\n () => a\n );\n }\n }, cb);\n }\n\n /** Collection.offset()\n *\n * https://dexie.org/docs/Collection/Collection.offset()\n *\n **/\n offset(offset: number): Collection {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) {\n --offsetLeft;\n return false;\n }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => --offsetLeft < 0;\n });\n }\n return this;\n }\n\n /** Collection.limit()\n *\n * https://dexie.org/docs/Collection/Collection.limit()\n *\n **/\n limit(numRows: number): Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(\n this._ctx,\n () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n },\n true\n );\n return this;\n }\n\n /** Collection.until()\n *\n * https://dexie.org/docs/Collection/Collection.until()\n *\n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n }\n\n /** Collection.first()\n *\n * https://dexie.org/docs/Collection/Collection.first()\n *\n **/\n first(cb?) {\n return this.limit(1)\n .toArray(function (a) {\n return a[0];\n })\n .then(cb);\n }\n\n /** Collection.last()\n *\n * https://dexie.org/docs/Collection/Collection.last()\n *\n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n *\n * https://dexie.org/docs/Collection/Collection.filter()\n *\n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// <param name=\"jsFunctionFilter\" type=\"Function\">function(val){return true/false}</param>\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n\n /** Collection.and()\n *\n * https://dexie.org/docs/Collection/Collection.and()\n *\n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n *\n * https://dexie.org/docs/Collection/Collection.or()\n *\n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n *\n * https://dexie.org/docs/Collection/Collection.reverse()\n *\n **/\n reverse() {\n this._ctx.dir = this._ctx.dir === 'prev' ? 'next' : 'prev';\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n }\n\n /** Collection.desc()\n *\n * https://dexie.org/docs/Collection/Collection.desc()\n *\n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n *\n * https://dexie.org/docs/Collection/Collection.eachKey()\n *\n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.key, cursor);\n });\n }\n\n /** Collection.eachUniqueKey()\n *\n * https://dexie.org/docs/Collection/Collection.eachUniqueKey()\n *\n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = 'unique';\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n *\n * https://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n *\n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.primaryKey, cursor);\n });\n }\n\n /** Collection.keys()\n *\n * https://dexie.org/docs/Collection/Collection.keys()\n *\n **/\n keys(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n })\n .then(function () {\n return a;\n })\n .then(cb);\n }\n\n /** Collection.primaryKeys()\n *\n * https://dexie.org/docs/Collection/Collection.primaryKeys()\n *\n **/\n primaryKeys(cb?): PromiseExtended<IndexableType[]> {\n var ctx = this._ctx;\n if (isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimization using IDBObjectStore.getAllKeys() or IDBKeyRange.getAllKeys().\n // For reverse queries on IDB 3.0+ browsers, uses getAllKeys(options) with direction.\n return this._read((trans) => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n direction: ctx.dir === 'prev' ? 'prev' : undefined,\n query: {\n index,\n range: ctx.range,\n },\n });\n })\n .then(({ result }) => result)\n .then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n })\n .then(function () {\n return a;\n })\n .then(cb);\n }\n\n /** Collection.uniqueKeys()\n *\n * https://dexie.org/docs/Collection/Collection.uniqueKeys()\n *\n **/\n uniqueKeys(cb?) {\n this._ctx.unique = 'unique';\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n *\n * https://dexie.org/docs/Collection/Collection.firstKey()\n *\n **/\n firstKey(cb?) {\n return this.limit(1)\n .keys(function (a) {\n return a[0];\n })\n .then(cb);\n }\n\n /** Collection.lastKey()\n *\n * https://dexie.org/docs/Collection/Collection.lastKey()\n *\n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n *\n * https://dexie.org/docs/Collection/Collection.distinct()\n *\n **/\n distinct() {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor: DBCoreCursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n\n //\n // Methods that mutate storage\n //\n\n /** Collection.modify()\n *\n * https://dexie.org/docs/Collection/Collection.modify()\n *\n **/\n modify(\n changes:\n | UpdateSpec<any>\n | ((\n obj: any,\n ctx: { value: any; primKey: IndexableType }\n ) => void | boolean)\n ): PromiseExtended<number> {\n var ctx = this._ctx;\n return this._write((trans) => {\n var modifyer: (\n obj: any,\n ctx: { value: any; primKey: IndexableType }\n ) => void | boolean;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n modifyer = changes as (\n obj: any,\n ctx: { value: any; primKey: IndexableType }\n ) => void | boolean;\n } else {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n modifyer = (item) => applyUpdateSpec(item, changes);\n }\n\n const coreTable = ctx.table.core;\n const { outbound, extractKey } = coreTable.schema.primaryKey;\n let limit = 200;\n const modifyChunkSize = this.db._options.modifyChunkSize;\n if (modifyChunkSize) {\n if (typeof modifyChunkSize == 'object') {\n limit =\n modifyChunkSize[coreTable.name] || modifyChunkSize['*'] || 200;\n } else {\n limit = modifyChunkSize;\n }\n }\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (\n expectedCount: number,\n res: DBCoreMutateResponse\n ) => {\n const { failures, numFailures } = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n };\n const isUnconditionalDelete = changes === deleteCallback; // Collection.delete() calls this.\n return this.clone()\n .primaryKeys()\n .then((keys) => {\n const criteria = isPlainKeyRange(ctx) &&\n ctx.limit === Infinity &&\n (typeof changes !== 'function' || isUnconditionalDelete) && {\n index: ctx.index,\n range: ctx.range,\n };\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n const keysInChunk = keys.slice(offset, offset + count);\n return (\n isUnconditionalDelete\n ? Promise.resolve([])\n : coreTable.getMany({\n trans,\n keys: keysInChunk,\n cache: 'immutable', // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n })\n ).then((values) => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = isUnconditionalDelete ? keysInChunk : [];\n if (!isUnconditionalDelete)\n for (let i = 0; i < count; ++i) {\n const origValue = values[i];\n const ctx = {\n value: deepClone(origValue),\n primKey: keys[offset + i],\n };\n if (modifyer.call(ctx, ctx.value, ctx) !== false) {\n if (ctx.value == null) {\n // Deleted\n deleteKeys.push(keys[offset + i]);\n } else if (\n !outbound &&\n cmp(extractKey(origValue), extractKey(ctx.value)) !== 0\n ) {\n // Changed primary key of inbound\n deleteKeys.push(keys[offset + i]);\n addValues.push(ctx.value);\n } else {\n // Changed value\n putValues.push(ctx.value);\n if (outbound) putKeys.push(keys[offset + i]);\n }\n }\n }\n\n return Promise.resolve(\n addValues.length > 0 &&\n coreTable\n .mutate({ trans, type: 'add', values: addValues })\n .then((res) => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n )\n .then(\n () =>\n (putValues.length > 0 ||\n (criteria && typeof changes === 'object')) &&\n coreTable\n .mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function' && changes,\n isAdditionalChunk: offset > 0,\n })\n .then((res) => applyMutateResult(putValues.length, res))\n )\n .then(\n () =>\n (deleteKeys.length > 0 ||\n (criteria && isUnconditionalDelete)) &&\n coreTable\n .mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria,\n isAdditionalChunk: offset > 0,\n })\n .then((res) =>\n builtInDeletionTrigger(ctx.table, deleteKeys, res)\n )\n .then((res) => applyMutateResult(deleteKeys.length, res))\n )\n .then(() => {\n return (\n keys.length > offset + count && nextChunk(offset + limit)\n );\n });\n });\n };\n\n return nextChunk(0).then(() => {\n if (totalFailures.length > 0)\n throw new ModifyError(\n 'Error modifying one or more objects',\n totalFailures,\n successCount,\n failedKeys as IndexableTypeArrayReadonly\n );\n\n return keys.length;\n });\n });\n });\n }\n\n /** Collection.delete()\n *\n * https://dexie.org/docs/Collection/Collection.delete()\n *\n **/\n delete(): PromiseExtended<number> {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (\n isPlainKeyRange(ctx) &&\n !ctx.table.schema.yProps && // No Y documents on this table (requires special care)\n (ctx.isPrimKey || range.type === DBCoreRangeType.Any)\n ) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write((trans) => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const { primaryKey } = ctx.table.core.schema;\n const coreRange = range;\n\n return ctx.table.core\n .count({ trans, query: { index: primaryKey, range: coreRange } })\n .then((count) => {\n return ctx.table.core\n .mutate({ trans, type: 'deleteRange', range: coreRange })\n .then(({ failures, numFailures }) => {\n if (numFailures)\n throw new ModifyError(\n 'Could not delete some values',\n Object.keys(failures).map((pos) => failures[pos]),\n count - numFailures\n );\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => (ctx.value = null);\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new (\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange\n ): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n *\n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor<CollectionConstructor>(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange\n ) {\n this.db = db;\n let keyRange = AnyRange,\n error = null;\n if (keyRangeGenerator)\n try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey:\n !whereCtx.index ||\n (table.schema.primKey.keyPath &&\n whereCtx.index === table.schema.primKey.name),\n range: keyRange,\n keysOnly: false,\n dir: 'next',\n unique: '',\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null,\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport {\n simpleCompare,\n simpleCompareReverse,\n} from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(\n collectionOrWhereClause: Collection | WhereClause,\n err,\n T?\n) {\n var collection =\n collectionOrWhereClause instanceof WhereClause\n ? new collectionOrWhereClause.Collection(collectionOrWhereClause)\n : collectionOrWhereClause;\n\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection(whereClause, () => rangeEqual('')).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === 'next'\n ? (s: string) => s.toUpperCase()\n : (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === 'next'\n ? (s: string) => s.toLowerCase()\n : (s: string) => s.toUpperCase();\n}\n\nexport function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0)\n return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0)\n return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0)\n return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === 'next')\n return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === 'prev')\n return key.substr(0, upperNeedle.length);\n return llp < 0\n ? null\n : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1);\n}\n\nexport function addIgnoreCaseAlgorithm(\n whereClause: WhereClause,\n match,\n needles,\n suffix\n) {\n /// <param name=\"needles\" type=\"Array\" elementType=\"String\"></param>\n var upper,\n lower,\n compare,\n upperNeedles,\n lowerNeedles,\n direction,\n nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every((s) => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = dir === 'next' ? simpleCompare : simpleCompareReverse;\n var needleBounds = needles\n .map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n })\n .sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) {\n return nb.upper;\n });\n lowerNeedles = needleBounds.map(function (nb) {\n return nb.lower;\n });\n direction = dir;\n nextKeySuffix = dir === 'next' ? '' : suffix;\n }\n initDirection('next');\n\n var c = new whereClause.Collection(whereClause, () =>\n createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix)\n );\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// <param name=\"cursor\" type=\"IDBCursor\"></param>\n /// <param name=\"advance\" type=\"Function\"></param>\n /// <param name=\"resolve\" type=\"Function\"></param>\n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(\n key,\n lowerKey,\n upperNeedles[i],\n lowerNeedles[i],\n compare,\n direction\n );\n if (casing === null && lowestPossibleCasing === null)\n firstPossibleNeedle = i + 1;\n else if (\n lowestPossibleCasing === null ||\n compare(lowestPossibleCasing, casing) > 0\n ) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () {\n cursor.continue(lowestPossibleCasing + nextKeySuffix);\n });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange(\n lower: IndexableType,\n upper: IndexableType,\n lowerOpen?: boolean,\n upperOpen?: boolean\n): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen,\n };\n}\n\nexport function rangeEqual(value: IndexableType): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value,\n };\n}\n","import { WhereClause as IWhereClause } from '../../public/types/where-clause';\nimport { Collection } from '../collection';\nimport { Table } from '../table';\nimport { IndexableType } from '../../public/types/indexable-type';\nimport {\n emptyCollection,\n fail,\n addIgnoreCaseAlgorithm,\n createRange,\n rangeEqual,\n} from './where-clause-helpers';\nimport {\n INVALID_KEY_ARGUMENT,\n STRING_EXPECTED,\n maxString,\n minKey,\n} from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection } from '../../public/types/collection';\n\n/** class WhereClause\n *\n * https://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n };\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.between()\n *\n **/\n between(\n lower: IndexableType,\n upper: IndexableType,\n includeLower?: boolean,\n includeUpper?: boolean\n ) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if (\n this._cmp(lower, upper) > 0 ||\n (this._cmp(lower, upper) === 0 &&\n (includeLower || includeUpper) &&\n !(includeLower && includeUpper))\n )\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this.Collection(this, () =>\n createRange(lower, upper, !includeLower, !includeUpper)\n );\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.equals()\n *\n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.above()\n *\n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n *\n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () =>\n createRange(value, undefined, false)\n );\n }\n\n /** WhereClause.below()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.below()\n *\n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () =>\n createRange(undefined, value, false, true)\n );\n }\n\n /** WhereClause.belowOrEqual()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n *\n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.startsWith()\n *\n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n *\n **/\n startsWithIgnoreCase(str: string) {\n if (str === '') return this.startsWith(str);\n return addIgnoreCaseAlgorithm(\n this,\n (x, a) => x.indexOf(a[0]) === 0,\n [str],\n maxString\n );\n }\n\n /** WhereClause.equalsIgnoreCase()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n *\n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], '');\n }\n\n /** WhereClause.anyOfIgnoreCase()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n *\n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, '');\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n *\n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(\n this,\n (x, a) => a.some((n) => x.indexOf(n) === 0),\n set,\n maxString\n );\n }\n\n /** WhereClause.anyOf()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.anyOf()\n *\n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try {\n set.sort(compare);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () =>\n createRange(set[0], set[set.length - 1])\n );\n\n c._ondirectionchange = (direction) => {\n compare = direction === 'next' ? this._ascending : this._descending;\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n cursor.continue(set[i]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.notEqual()\n *\n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange(\n [\n [minKey, value],\n [value, this.db._maxKey],\n ],\n { includeLowers: false, includeUppers: false }\n );\n }\n\n /** WhereClause.noneOf()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.noneOf()\n *\n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try {\n set.sort(this._ascending);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) =>\n res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]],\n null\n );\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, {\n includeLowers: false,\n includeUppers: false,\n });\n }\n\n /** WhereClause.inAnyRange()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n *\n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType; 1: IndexableType }>,\n options?: { includeLowers?: boolean; includeUppers?: boolean }\n ) {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (\n !ranges.every(\n (range) =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0\n )\n ) {\n return fail(\n this,\n 'First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower',\n exceptions.InvalidArgument\n );\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0,\n l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l) ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) {\n return sortDirection(a[0], b[0]);\n }\n\n // Join overlapping ranges\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers\n ? (key) => ascending(key, set[rangePos][1]) > 0\n : (key) => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers\n ? (key) => descending(key, set[rangePos][0]) > 0\n : (key) => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(this, () =>\n createRange(\n set[0][0],\n set[set.length - 1][1],\n !includeLowers,\n !includeUppers\n )\n );\n\n c._ondirectionchange = (direction) => {\n if (direction === 'next') {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (\n this._cmp(key, set[rangePos][1]) === 0 ||\n this._cmp(key, set[rangePos][0]) === 0\n ) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n *\n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n *\n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every((s) => typeof s === 'string')) {\n return fail(this, 'startsWithAnyOf() only works with strings');\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map((str: string) => [str, str + maxString]));\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\nimport { cmp } from '../../functions/cmp';\n\nexport interface WhereClauseConstructor {\n new (table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n *\n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor<WhereClauseConstructor>(\n WhereClause.prototype,\n\n function WhereClause(\n this: WhereClause,\n table: Table,\n index?: string,\n orCollection?: Collection\n ) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === ':id' ? null : index,\n or: orCollection,\n };\n this._cmp = this._ascending = cmp;\n this._descending = (a, b) => cmp(b, a);\n this._max = (a, b) => (cmp(a, b) > 0 ? a : b);\n this._min = (a, b) => (cmp(a, b) < 0 ? a : b);\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange) throw new exceptions.MissingAPI();\n }\n );\n}\n","import { wrap } from '../helpers/promise';\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler(resolve) {\n return wrap(function (event) {\n resolve(event.target.result);\n });\n}\n\nexport function hookedEventRejectHandler(reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n\n var req = event.target,\n err = req.error,\n ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject(err);\n return false;\n });\n}\n\nexport function hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function (event) {\n var req = event.target,\n ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nexport function preventDefault(event) {\n if (event.stopPropagation)\n // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault)\n // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)((e) => {\n errorList.push(e);\n done && done();\n });\n}\n","import Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME =\n 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(\n null,\n DEXIE_STORAGE_MUTATED_EVENT_NAME\n) as GlobalDexieEvents;\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from '../../helpers/promise';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n *\n * https://dexie.org/docs/Transaction/Transaction\n *\n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: IDBTransactionDurability;\n idbtrans: IDBTransaction;\n storeNames: string[];\n explicit?: boolean;\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: { [tableName: string]: Table };\n\n _reculock: number;\n _blockedFuncs: { 0: () => any; 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n *\n * Internal method.\n */\n _lock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n }\n\n /** Transaction._unlock()\n *\n * Internal method.\n */\n _unlock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try {\n usePSD(fnAndPSD[1], fnAndPSD[0]);\n } catch (e) {}\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n *\n * Internal method.\n */\n _locked() {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n\n /** Transaction.create()\n *\n * Internal method.\n *\n */\n create(idbtrans?: IDBTransaction & { [prop: string]: any }) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case 'DatabaseClosedError':\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case 'MissingAPIError':\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans =\n idbtrans ||\n ((this.db.core\n ? this.db.core.transaction(\n this.storeNames,\n this.mode as 'readwrite' | 'readonly',\n { durability: this.chromeTransactionDurability }\n )\n : idbdb.transaction(this.storeNames, this.mode, {\n durability: this.chromeTransactionDurability,\n })) as IDBTransaction);\n\n idbtrans.onerror = wrap((ev) => {\n preventDefault(ev); // Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap((ev) => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on('abort').fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans['mutatedParts']);\n }\n });\n return this;\n }\n\n /** Transaction._promise()\n *\n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike<any> | void,\n bWriteLock?: string | boolean\n ): DexiePromise {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly('Transaction is readonly'));\n\n if (!this.active) return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([\n () => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n },\n PSD,\n ]);\n });\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n *\n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n *\n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): https://dexie.org/docs/Dexie/Dexie.waitFor()\n *\n **/\n waitFor(promiseLike: PromiseLike<any>) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) root._waitingQueue.shift()();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n })();\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise\n .then(\n (res) => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n (err) => root._waitingQueue.push(wrap(reject.bind(null, err)))\n )\n .finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n }\n\n /** Transaction.abort()\n *\n * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n *\n * https://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = this._memoizedTables || (this._memoizedTables = {});\n if (hasOwn(memoizedTables, tableName)) return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\n 'Table ' + tableName + ' not part of transaction'\n );\n }\n\n const transactionBoundTable = new this.db.Table(\n tableName,\n tableSchema,\n this\n );\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor<T extends Transaction = Transaction> {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: IDBTransactionDurability,\n parent?: Transaction\n ): T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n *\n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor<TransactionConstructor<Transaction>>(\n Transaction.prototype,\n function Transaction(\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: IDBTransactionDurability,\n parent?: Transaction\n ) {\n if (mode !== 'readonly')\n storeNames.forEach((storeName) => {\n // Uncollapse storeName to include Y update tables in case deletion of a record - then we must also delete its Y updates.\n const yProps = dbschema[storeName]?.yProps;\n if (yProps)\n storeNames = storeNames.concat(yProps.map((p) => p.updatesTable));\n });\n\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, 'complete', 'error', 'abort');\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n\n this._completion.then(\n () => {\n this.active = false;\n this.on.complete.fire();\n },\n (e) => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent\n ? this.parent._reject(e)\n : wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n }\n );\n }\n );\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean,\n type?: string\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src:\n (unique && !isPrimKey ? '&' : '') +\n (multi ? '*' : '') +\n (auto ? '++' : '') +\n nameFromKeyPath(keyPath),\n type,\n };\n}\n\nexport function nameFromKeyPath(keyPath?: string | string[]): string {\n return typeof keyPath === 'string'\n ? keyPath\n : keyPath\n ? '[' + [].join.call(keyPath, '+') + ']'\n : '';\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema(\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, (index) => [index.name, index]),\n };\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn =\n indexedDB &&\n (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n};\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor(\n keyPath: null | string | string[]\n): (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return (obj) => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return (obj) => obj[keyPath];\n } else {\n return (obj) => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from '../public/types/dbcore';\nimport { isArray } from '../functions/utils';\nimport {\n eventRejectHandler,\n preventDefault,\n} from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\n\nexport function arrayify<T>(arrayLike: {\n length: number;\n [index: number]: T;\n}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick<T, Prop extends keyof T>(\n obj: T,\n props: Prop[]\n): Pick<T, Prop> {\n const result = {} as Pick<T, Prop>;\n props.forEach((prop) => (result[prop] = obj[prop]));\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null\n ? ':id'\n : typeof keyPath === 'string'\n ? keyPath\n : `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore(\n db: IDBDatabase,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction\n): DBCore {\n function extractSchema(\n db: IDBDatabase,\n trans: IDBTransaction\n ): { schema: DBCoreSchema; hasGetAll: boolean; hasIdb3Features: boolean } {\n const tables = arrayify(db.objectStoreNames);\n const tempStore: Partial<{ getAll: any; getAllRecords: any }> =\n tables.length > 0 ? trans.objectStore(tables[0]) : {};\n return {\n schema: {\n name: db.name,\n tables: tables\n .map((table) => trans.objectStore(table))\n .map((store) => {\n const { keyPath, autoIncrement } = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: { [keyPathAlias: string]: DBCoreIndex } = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath),\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames)\n .map((indexName) => store.index(indexName))\n .map((index) => {\n const { name, unique, multiEntry, keyPath } = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath),\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) =>\n indexByKeyPath[getKeyPathAlias(keyPath)],\n };\n indexByKeyPath[':id'] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n }),\n },\n hasGetAll:\n tables.length > 0 &&\n 'getAll' in tempStore &&\n !(\n typeof navigator !== 'undefined' &&\n /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604\n ), // Bug with getAll() on Safari ver<604. See discussion following PR #579\n hasIdb3Features: 'getAllRecords' in tempStore,\n };\n }\n\n function makeIDBKeyRange(range: DBCoreKeyRange): IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never)\n throw new Error('Cannot convert never type to IDBKeyRange');\n const { lower, upper, lowerOpen, upperOpen } = range;\n const idbRange =\n lower === undefined\n ? upper === undefined\n ? null //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n : IdbKeyRange.upperBound(upper, !!upperOpen) // below\n : upper === undefined\n ? IdbKeyRange.lowerBound(lower, !!lowerOpen) // above\n : IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate({ trans, type, keys, values, range }) {\n return new Promise<DBCoreMutateResponse>((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === 'put' || type === 'add';\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error('Invalid operation type: ' + type);\n\n const { length } = keys || values || { length: 1 }; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\n 'Given keys array must have same length as given values array.'\n );\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({\n numFailures: 0,\n failures: {},\n results: [],\n lastResult: undefined,\n });\n\n let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n\n const failures: { [operationNumber: number]: Error } = [];\n let numFailures = 0;\n const errorHandler = (event) => {\n ++numFailures;\n preventDefault(event);\n };\n\n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({\n numFailures,\n failures,\n results: [],\n lastResult: undefined,\n }); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n reqs.push((req = store.clear())); // Deleting the Any range is equivalent to store.clear()\n else reqs.push((req = store.delete(makeIDBKeyRange(range))));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut\n ? outbound\n ? [values, keys]\n : [values, null]\n : [keys, null];\n\n if (isAddOrPut) {\n for (let i = 0; i < length; ++i) {\n reqs.push(\n (req = (\n args2 && args2[i] !== undefined\n ? store[type](args1[i], args2[i])\n : store[type](args1[i])\n ) as IDBRequest)\n );\n req.onerror = errorHandler;\n }\n } else {\n for (let i = 0; i < length; ++i) {\n reqs.push((req = store[type](args1[i]) as IDBRequest));\n req.onerror = errorHandler;\n }\n }\n }\n const done = (event) => {\n const lastResult = event.target.result;\n reqs.forEach(\n (req, i) => req.error != null && (failures[i] = req.error)\n );\n resolve({\n numFailures,\n failures,\n results: type === 'delete' ? keys : reqs.map((req) => req.result),\n lastResult,\n });\n };\n\n req.onerror = (event) => {\n // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n\n req.onsuccess = done;\n });\n }\n\n function openCursor({\n trans,\n values,\n query,\n reverse,\n unique,\n }: DBCoreOpenCursorRequest): Promise<DBCoreCursor> {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const { index, range } = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ? store : store.index(index.name);\n // direction\n const direction = reverse\n ? unique\n ? 'prevunique'\n : 'prev'\n : unique\n ? 'nextunique'\n : 'next';\n // request\n const req =\n values || !('openKeyCursor' in source)\n ? source.openCursor(makeIDBKeyRange(range), direction)\n : source.openKeyCursor(makeIDBKeyRange(range), direction);\n\n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap((ev) => {\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey)\n _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = () => {\n throw new Error('Cursor not started');\n };\n const doThrowCursorIsStopped = () => {\n throw new Error('Cursor not stopped');\n };\n (cursor as any).trans = trans;\n cursor.stop =\n cursor.continue =\n cursor.continuePrimaryKey =\n cursor.advance =\n doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() =>\n gotOne-- ? this.continue() : this.stop()\n ).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise<void>(\n (resolveIteration, rejectIteration) => {\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = (value) => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop =\n cursor.continue =\n cursor.continuePrimaryKey =\n cursor.advance =\n doThrowCursorIsStopped;\n resolveIteration(value);\n };\n }\n );\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = () => {\n throw new Error('Cursor behind last entry');\n };\n cursor.stop();\n }\n };\n req.onsuccess = wrap((ev) => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject);\n });\n }\n\n function query(hasGetAll: boolean, hasIdb3Features: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise<DBCoreQueryResponse>((resolve, reject) => {\n resolve = wrap(resolve);\n const { trans, values, limit, query } = request;\n // Normalize direction once - undefined means 'next'\n const direction = request.direction ?? 'next';\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const { index, range } = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({ result: [] });\n\n // Use getAll/getAllKeys with direction option (IDB 3.0)\n // This is 2-5x faster than cursor iteration for reverse queries\n if (hasIdb3Features) {\n const options = {\n query: idbKeyRange,\n count: nonInfinitLimit,\n direction,\n };\n const req = values\n ? (source as any).getAll(options)\n : (source as any).getAllKeys(options);\n req.onsuccess = (event) => resolve({ result: event.target.result });\n req.onerror = eventRejectHandler(reject);\n } else if (hasGetAll && direction === 'next') {\n const req = values\n ? (source as any).getAll(idbKeyRange, nonInfinitLimit)\n : (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = (event: any) =>\n resolve({ result: event.target.result });\n req.onerror = eventRejectHandler(reject);\n } else {\n // Fallback: use cursor for non-default direction when IDB 3.0 features not available\n let count = 0;\n const req =\n values || !('openKeyCursor' in source)\n ? source.openCursor(idbKeyRange, direction)\n : source.openKeyCursor(idbKeyRange, direction);\n const result = [];\n req.onsuccess = () => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({ result });\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({ result });\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n\n return {\n name: tableName,\n schema: tableSchema,\n\n mutate,\n\n getMany({ trans, keys }) {\n return new Promise<any[]>((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & { _pos?: number };\n\n const successHandler = (event) => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n\n for (let i = 0; i < length; ++i) {\n const key = keys[i];\n if (key != null) {\n req = store.get(keys[i]);\n req._pos = i;\n req.onsuccess = successHandler;\n req.onerror = errorHandler;\n ++keyCount;\n }\n }\n if (keyCount === 0) resolve(result);\n });\n },\n\n get({ trans, key }) {\n return new Promise<any>((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = (event) => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll, hasIdb3Features),\n\n openCursor,\n\n count({ query, trans }) {\n const { index, range } = query;\n return new Promise<number>((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap((ev) =>\n resolve((ev.target as IDBRequest).result)\n );\n req.onerror = eventRejectHandler(reject);\n });\n },\n };\n }\n\n const { schema, hasGetAll, hasIdb3Features } = extractSchema(db, tmpTrans);\n const tables = schema.tables.map((tableSchema) =>\n createDbCoreTable(tableSchema)\n );\n const tableMap: { [name: string]: DBCoreTable } = {};\n tables.forEach((table) => (tableMap[table.name] = table));\n return {\n stack: 'dbcore',\n\n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema,\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack<TStack extends { stack: string }>(\n stackImpl: { stack: string },\n middlewares: Middleware<{ stack: string }>[]\n): TStack {\n return middlewares.reduce(\n (down, { create }) => ({ ...down, ...create(down) }),\n stackImpl\n ) as TStack;\n}\n\nfunction createMiddlewareStacks(\n middlewares: {\n [StackName in keyof DexieStacks]?: Middleware<DexieStacks[StackName]>[];\n },\n idbdb: IDBDatabase,\n { IDBKeyRange, indexedDB }: DexieDOMDependencies,\n tmpTrans: IDBTransaction\n): { [StackName in keyof DexieStacks]?: DexieStacks[StackName] } {\n const dbcore = createMiddlewareStack<DBCore>(\n createDBCore(idbdb, IDBKeyRange, tmpTrans),\n middlewares.dbcore\n );\n\n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore,\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(\n db._middlewares,\n idbdb,\n db._deps,\n tmpTrans\n );\n db.core = stacks.dbcore!;\n db.tables.forEach((table) => {\n const tableName = table.name;\n if (db.core.schema.tables.some((tbl) => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { _global } from '../../globals/global';\nimport {\n setProp,\n keys,\n slice,\n isArray,\n shallowClone,\n isAsyncFunction,\n defineProperty,\n getPropertyDescriptor,\n} from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, {\n PSD,\n newScope,\n NativePromise,\n decrementExpectedAwaits,\n incrementExpectedAwaits,\n} from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\nimport { debug } from '../../helpers/debug';\nimport { PromiseExtended } from '../../public/types/promise-extended';\n\nexport function setApiOnPlace(\n db: Dexie,\n objs: Object[],\n tableNames: string[],\n dbschema: DbSchema\n) {\n tableNames.forEach((tableName) => {\n const schema = dbschema[tableName];\n objs.forEach((obj) => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || ('value' in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) {\n return this.table(tableName);\n },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n },\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach((obj) => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(\n db: Dexie,\n oldVersion: number,\n idbUpgradeTrans: IDBTransaction,\n reject\n) {\n const globalSchema = db._dbSchema;\n if (\n idbUpgradeTrans.objectStoreNames.contains('$meta') &&\n !globalSchema.$meta\n ) {\n globalSchema.$meta = createTableSchema(\n '$meta',\n parseIndexSyntax('')[0],\n []\n );\n db._storeNames.push('$meta');\n }\n const trans = db._createTransaction(\n 'readwrite',\n db._storeNames,\n globalSchema\n );\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach((tableName) => {\n createTable(\n idbUpgradeTrans,\n tableName,\n globalSchema[tableName].primKey,\n globalSchema[tableName].indexes\n );\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n return getExistingVersion(db, trans, oldVersion)\n .then((oldVersion) =>\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans)\n )\n .catch(rejectTransaction);\n }\n });\n}\n\nexport type UpgradeQueueItem = (\n idbtrans: IDBTransaction\n) => PromiseLike<any> | void;\n\nexport function patchCurrentVersion(\n db: Dexie,\n idbUpgradeTrans: IDBTransaction\n) {\n createMissingTables(db._dbSchema, idbUpgradeTrans);\n if (\n idbUpgradeTrans.db.version % 10 === 0 &&\n !idbUpgradeTrans.objectStoreNames.contains('$meta')\n ) {\n // Rolled over to the next 10-ies due to many schema upgrades without bumping version.\n // No problem! We pin the database to its expected version by adding the $meta table so that next\n // time the programmer bumps the version and attaches, an upgrader, that upgrader will indeed run,\n // as well any further upgraders coming after that.\n idbUpgradeTrans.db\n .createObjectStore('$meta')\n .add(Math.ceil(idbUpgradeTrans.db.version / 10 - 1), 'version');\n }\n const globalSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n adjustToExistingIndexNames(db, db._dbSchema, idbUpgradeTrans);\n const diff = getSchemaDiff(globalSchema, db._dbSchema);\n for (const tableChange of diff.change) {\n if (tableChange.change.length || tableChange.recreate) {\n console.warn(\n `Unable to patch indexes of table ${tableChange.name} because it has changes on the type of index or primary key.`\n );\n return;\n }\n const store = idbUpgradeTrans.objectStore(tableChange.name);\n tableChange.add.forEach((idx) => {\n if (debug)\n console.debug(\n `Dexie upgrade patch: Creating missing index ${tableChange.name}.${idx.src}`\n );\n addIndex(store, idx);\n });\n }\n}\n\nfunction getExistingVersion(\n db: Dexie,\n trans: Transaction,\n oldVersion: number\n): PromiseExtended<number> {\n // In normal case, existing version is the native installed version divided by 10.\n // However, in case more than 10 schema changes have been made on the same version (such as while\n // developing an app), the native version may have passed beyond a multiple of 10 within the same version.\n // When that happens, a table $meta will have been created, containing a single entry with key \"version\"\n // and the value of the real old version to use when running upgraders going forward.\n if (trans.storeNames.includes('$meta')) {\n return trans\n .table('$meta')\n .get('version')\n .then((metaVersion) => {\n return metaVersion != null ? metaVersion : oldVersion;\n });\n } else {\n return Promise.resolve(oldVersion);\n }\n}\n\nfunction updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction\n) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = (db._dbSchema = buildGlobalSchema(\n db,\n db.idbdb,\n idbUpgradeTrans\n ));\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter((v) => v._cfg.version >= oldVersion);\n if (versToRun.length === 0) {\n // Important not to continue at this point.\n // Coming here means we've already patched schema in patchCurrentVersion() after having\n // incremented native version to a value above the declared highest version.\n // When being in this mode, it means that there might be different versions the db competing\n // about it with different version of the schema. Therefore, we must avoid deleting tables\n // or indexes here so that both versions can co-exist until the application has been upgraded to\n // a version that declares no lower than the native version.\n // If after that, a downgrade happens again, we'll end up here again, accepting both versions\n // And we'll stay in this state until app developer releases a new declared version.\n return Promise.resolve();\n }\n\n versToRun.forEach((version) => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables\n diff.add.forEach((tuple) => {\n createTable(\n idbUpgradeTrans,\n tuple[0],\n tuple[1].primKey,\n tuple[1].indexes\n );\n });\n // Change tables\n diff.change.forEach((change) => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\n 'Not yet support for changing primary key'\n );\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach((idx) => addIndex(store, idx));\n // Update indexes\n change.change.forEach((idx) => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach((idxName) => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach((table) => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(\n db,\n [db.Transaction.prototype],\n keys(upgradeSchema),\n upgradeSchema\n );\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return returnValue && typeof returnValue.then === 'function'\n ? Promise.resolve(returnValue)\n : promiseFollowed.then(() => returnValue);\n }\n });\n queue.push((idbtrans) => {\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(\n db,\n [db.Transaction.prototype],\n db._storeNames,\n db._dbSchema\n );\n trans.schema = db._dbSchema;\n });\n // Maintain the $meta table after this version's tables and indexes has been created and content upgraders have run.\n queue.push((idbtrans) => {\n if (db.idbdb.objectStoreNames.contains('$meta')) {\n if (Math.ceil(db.idbdb.version / 10) === version._cfg.version) {\n // Remove $meta table if it's no more needed - we are in line with the native version\n db.idbdb.deleteObjectStore('$meta');\n delete db._dbSchema.$meta;\n db._storeNames = db._storeNames.filter((name) => name !== '$meta');\n } else {\n // We're still not in line with the native version. Make sure to update the virtual version\n // to the successfully run version\n idbtrans.objectStore('$meta').put(version._cfg.version, 'version');\n }\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length\n ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue)\n : Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[];\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string;\n recreate: boolean;\n del: string[];\n add: IndexSpec[];\n change: IndexSpec[];\n}\n\nexport function getSchemaDiff(\n oldSchema: DbSchema,\n newSchema: DbSchema\n): SchemaDiff {\n const diff: SchemaDiff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [], // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: [],\n };\n if (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n '' + (oldDef.primKey.keyPath || '') !==\n '' + (newDef.primKey.keyPath || '') ||\n // Compare the autoIncrement flag also\n oldDef.primKey.auto !== newDef.primKey.auto\n ) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (\n change.del.length > 0 ||\n change.add.length > 0 ||\n change.change.length > 0\n ) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\n\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath\n ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto }\n : { autoIncrement: primKey.auto }\n );\n indexes.forEach((idx) => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(\n newSchema: DbSchema,\n idbtrans: IDBTransaction\n) {\n keys(newSchema).forEach((tableName) => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n if (debug) console.debug('Dexie: Creating missing table', tableName);\n createTable(\n idbtrans,\n tableName,\n newSchema[tableName].primKey,\n newSchema[tableName].indexes\n );\n }\n });\n}\n\nexport function deleteRemovedTables(\n newSchema: DbSchema,\n idbtrans: IDBTransaction\n) {\n [].slice\n .call(idbtrans.db.objectStoreNames)\n .forEach(\n (storeName) =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName)\n );\n}\n\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, {\n unique: idx.unique,\n multiEntry: idx.multi,\n });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach((storeName) => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || '',\n true,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== 'string',\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== 'string',\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n db.verno = idbdb.version / 10;\n const globalSchema = (db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans));\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function verifyInstalledSchema(\n db: Dexie,\n tmpTrans: IDBTransaction\n): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(\n diff.add.length ||\n diff.change.some((ch) => ch.add.length || ch.change.length)\n );\n}\n\nexport function adjustToExistingIndexNames(\n db: Dexie,\n schema: DbSchema,\n idbtrans: IDBTransaction\n) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName =\n typeof keyPath === 'string'\n ? keyPath\n : '[' + slice(keyPath).join('+') + ']';\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (\n typeof navigator !== 'undefined' &&\n /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope &&\n _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604\n ) {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n const typeSplit = index.split(':');\n const type = typeSplit[1]?.trim();\n index = typeSplit[0].trim();\n const name = index.replace(/([&*]|\\+\\+)/g, ''); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name)\n ? name.match(/^\\[(.*)\\]$/)[1].split('+')\n : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0,\n type\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport {\n removeTablesApi,\n setApiOnPlace,\n parseIndexSyntax,\n} from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { TableSchema } from '../../public/types/table-schema';\n\n/** class Version\n *\n * https://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number;\n storesSource: { [tableName: string]: string | null };\n dbschema: DbSchema;\n tables: {};\n contentUpgrade: Function | null;\n };\n\n _createTableSchema(\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n ): TableSchema {\n return createTableSchema(name, primKey, indexes);\n }\n\n _parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return parseIndexSyntax(primKeyAndIndexes);\n }\n\n _parseStoresSpec(\n stores: { [tableName: string]: string | null },\n outSchema: DbSchema\n ): any {\n keys(stores).forEach((tableName) => {\n if (stores[tableName] !== null) {\n let indexes = this._parseIndexSyntax(stores[tableName]);\n\n const primKey = indexes.shift();\n if (!primKey) {\n // {table: ':Y'} not supported.\n throw new exceptions.Schema(\n 'Invalid schema for table ' + tableName + ': ' + stores[tableName]\n );\n }\n\n primKey.unique = true;\n if (primKey.multi)\n throw new exceptions.Schema('Primary key cannot be multiEntry*');\n indexes.forEach((idx) => {\n if (idx.auto)\n throw new exceptions.Schema(\n 'Only primary key can be marked as autoIncrement (++)'\n );\n if (!idx.keyPath)\n throw new exceptions.Schema(\n 'Index must have a name and cannot be an empty string'\n );\n });\n const tblSchema = this._createTableSchema(tableName, primKey, indexes);\n outSchema[tableName] = tblSchema;\n }\n });\n }\n\n stores(stores: { [key: string]: string | null }): this {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource\n ? extend(this._cfg.storesSource, stores)\n : stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string } = {};\n let dbschema: DbSchema = {};\n versions.forEach((version) => {\n // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = version._cfg.dbschema = {};\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(\n db,\n [db._allTables, db, db.Transaction.prototype, this._cfg.tables],\n keys(dbschema),\n dbschema\n );\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(\n upgradeFunction: (trans: Transaction) => PromiseLike<any> | void\n ): this {\n this._cfg.contentUpgrade = promisableChain(\n this._cfg.contentUpgrade || nop,\n upgradeFunction\n );\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new (versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n *\n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor<VersionConstructor>(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null,\n };\n }\n );\n}\n","import { type Dexie } from '../classes/dexie';\n\nexport const connections = createConnectionsManager();\n\nfunction createConnectionsManager() {\n if (\n typeof FinalizationRegistry !== 'undefined' &&\n typeof WeakRef !== 'undefined'\n ) {\n const _refs = new Set<WeakRef<Dexie>>();\n const _registry = new FinalizationRegistry((ref: WeakRef<Dexie>) => {\n _refs.delete(ref);\n });\n\n const toArray = (): ReadonlyArray<Dexie> => {\n return Array.from(_refs)\n .map((ref) => ref.deref())\n .filter((db): db is Dexie => db !== undefined);\n };\n\n const add = (db: Dexie) => {\n const ref = new WeakRef(db._novip);\n _refs.add(ref);\n _registry.register(db._novip, ref, ref);\n if (_refs.size > db._options.maxConnections) {\n // Remove the oldest connection (the one that was added first)\n const oldestRef = _refs.values().next().value;\n _refs.delete(oldestRef);\n _registry.unregister(oldestRef);\n }\n };\n\n const remove = (db: Dexie | undefined) => {\n if (!db) return;\n const iterator = _refs.values();\n let result = iterator.next();\n\n while (!result.done) {\n const ref = result.value;\n if (ref.deref() === db._novip) {\n _refs.delete(ref);\n _registry.unregister(ref);\n return; // Early return once deleted\n }\n result = iterator.next();\n }\n };\n return { toArray, add, remove };\n } else {\n const connections: Dexie[] = [];\n const toArray = (): ReadonlyArray<Dexie> => connections;\n const add = (db: Dexie) => {\n connections.push(db._novip);\n };\n const remove = (db: Dexie | undefined) => {\n if (!db) return;\n const index = connections.indexOf(db._novip);\n if (index !== -1) {\n connections.splice(index, 1);\n }\n };\n return { toArray, add, remove };\n }\n}\n","import { Dexie } from '../classes/dexie/dexie';\nimport { Table } from '../public/types/table';\nimport { DBNAMES_DB } from '../globals/constants';\nimport { DexieDOMDependencies } from '../public/types/dexie-dom-dependencies';\nimport { nop } from '../functions/chaining-functions';\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB['_dbNamesDB'];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB['_dbNamesDB'] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: 'name' });\n }\n return dbNamesDB.table('dbnames') as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === 'function';\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n infos\n // Select name prop of infos:\n .map((info) => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter((name) => name !== DBNAMES_DB)\n )\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({ name }).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip(fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n}\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import { cmp } from '../functions/cmp';\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from '../public/types/rangeset';\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n *\n */\n\nfunction isEmptyRange(\n node: IntervalTree | { from: IndexableType; to: IndexableType }\n): node is EmptyRange {\n return !('from' in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function (fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(\n this,\n arguments.length\n ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree }\n : { d: 0 }\n );\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && 'd' in fromOrTree) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | { from: IndexableType; to: IndexableType }) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach((key) => addRange(this, key, key));\n return this;\n },\n hasKey(key: IndexableType) {\n const node = getRangeSetIterator(this).next(key).value;\n return node && cmp(node.from, key) <= 0 && cmp(node.to, key) >= 0;\n },\n\n [iteratorSymbol](): Iterator<\n IntervalTreeNode,\n undefined,\n IndexableType | undefined\n > {\n return getRangeSetIterator(this);\n },\n});\n\nfunction addRange(\n target: IntervalTree,\n from: IndexableType,\n to: IndexableType\n) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n\n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(\n target: IntervalTree,\n newSet: IntervalTree | { from: IndexableType; to: IndexableType }\n) {\n function _addRangeSet(\n target: IntervalTree,\n {\n from,\n to,\n l,\n r,\n }:\n | IntervalTreeNode\n | { from: IndexableType; to: IndexableType; l?: undefined; r?: undefined }\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if (!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator<IntervalTreeNode, undefined, IndexableType | undefined> {\n let state: RangeSetIteratorState = isEmptyRange(node)\n ? null\n : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator<IntervalTreeNode, undefined, IndexableType>;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? 'r' : diff < -1 ? 'l' : '';\n if (r) {\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n //\n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n //\n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L]\n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === 'r' ? 'l' : 'r'; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r];\n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick<IntervalTreeNode, 'l' | 'r'>) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import {\n cloneSimpleObjectTree,\n deepClone,\n keys,\n objectIsEmpty,\n} from '../functions/utils';\nimport { mergeRanges, RangeSet } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach((part) => {\n if (target[part]) mergeRanges(target[part], newSet[part]);\n else target[part] = cloneSimpleObjectTree(newSet[part]); // Somewhat faster\n });\n return target;\n}\n","import { rangesOverlap } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function obsSetsOverlap(os1: ObservabilitySet, os2: ObservabilitySet) {\n return (\n os1.all ||\n os2.all ||\n Object.keys(os1).some(\n (key) => os2[key] && rangesOverlap(os2[key], os1[key])\n )\n );\n}\n","import { type GlobalQueryCache } from '../../public/types/cache';\n\nexport const cache: GlobalQueryCache = {};\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport { extendObservabilitySet } from '../extend-observability-set';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { cache } from './cache';\n\nlet unsignaledParts: ObservabilitySet = {};\nlet isTaskEnqueued = false;\n\nexport function signalSubscribersLazily(\n part: ObservabilitySet,\n optimistic = false\n) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(() => {\n isTaskEnqueued = false;\n const parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts, false);\n }, 0);\n }\n}\n\nexport function signalSubscribersNow(\n updatedParts: ObservabilitySet,\n deleteAffectedCacheEntries = false\n) {\n const queriesToSignal = new Set<() => void>();\n if (updatedParts.all) {\n // Signal all subscribers to requery.\n for (const tblCache of Object.values(cache)) {\n collectTableSubscribers(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n } else {\n for (const key in updatedParts) {\n const parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n const [, dbName, tableName] = parts;\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (tblCache)\n collectTableSubscribers(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n }\n }\n // Now when affected cache entries are removed, signal collected subscribers to requery.\n queriesToSignal.forEach((requery) => requery());\n}\n\nfunction collectTableSubscribers(\n tblCache: TblQueryCache,\n updatedParts: ObservabilitySet,\n outQueriesToSignal: Set<() => void>,\n deleteAffectedCacheEntries: boolean\n) {\n const updatedEntryLists: [string, CacheEntry[]][] = [];\n for (const [indexName, entries] of Object.entries(tblCache.queries.query)) {\n const filteredEntries: CacheEntry[] = [];\n for (const entry of entries) {\n if (obsSetsOverlap(updatedParts, entry.obsSet)) {\n // This query is affected by the mutation. Remove it from cache\n // and signal all subscribers to requery.\n entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery));\n } else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n // Collect cache entries to be updated\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (const [indexName, filteredEntries] of updatedEntryLists) {\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n}\n","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport {\n eventRejectHandler,\n preventDefault,\n} from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/connections';\nimport {\n runUpgraders,\n readGlobalSchema,\n adjustToExistingIndexNames,\n verifyInstalledSchema,\n patchCurrentVersion,\n} from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\nimport safari14Workaround from 'safari-14-idb-fix';\nimport { type ObservabilitySet } from '../../public/types/db-events';\nimport { RangeSet } from '../../helpers/rangeset';\nimport {\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n globalEvents,\n} from '../../globals/global-events';\nimport { signalSubscribersNow } from '../../live-query/cache/signalSubscribers';\n\nexport function dexieOpen(db: Dexie) {\n const state = db._state;\n const { indexedDB } = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then<Dexie>(() =>\n state.dbOpenError ? rejection(state.dbOpenError) : db\n );\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n let nativeVerToOpen = Math.round(db.verno * 10);\n let schemaPatchMode = false;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller)\n throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n\n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: IDBTransaction | null = null,\n wasCreated = false;\n\n const tryOpenDB = () =>\n new Promise((resolve, reject) => {\n throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\n const dbName = db.name;\n\n const req =\n state.autoSchema || !nativeVerToOpen\n ? indexedDB.open(dbName)\n : indexedDB.open(dbName, nativeVerToOpen);\n if (!req) throw new exceptions.MissingAPI(); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap((e) => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) {\n // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject(\n new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`)\n );\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n const oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n if (schemaPatchMode) {\n patchCurrentVersion(db, upgradeTransaction);\n }\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n\n req.onsuccess = wrap(() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = (db.idbdb = req.result);\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0)\n try {\n const tmpTrans = idbdb.transaction(\n safariMultiStoreFix(objectStoreNames),\n 'readonly'\n );\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans) && !schemaPatchMode) {\n console.warn(\n `Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this.`\n );\n idbdb.close();\n nativeVerToOpen = idbdb.version + 1;\n schemaPatchMode = true;\n return resolve(tryOpenDB()); // Try again with new version (nativeVerToOpen\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n\n connections.add(db);\n\n idbdb.onversionchange = wrap((ev) => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on('versionchange').fire(ev);\n });\n\n idbdb.onclose = wrap(() => {\n // Resolve issue #2186: Once Dexie.on.close is triggered, Dexie.isOpen() is still true.\n // Let the code path be the same as for db.close() so that db.isOpen() returns false\n // and every other state is reset the same way.\n db.close({ disableAutoOpen: false });\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n }, reject);\n }).catch((err) => {\n switch (err?.name) {\n case 'UnknownError':\n if (state.PR1398_maxLoop > 0) {\n // Bug in Chrome after clearing site data\n // https://github.com/dexie/Dexie.js/issues/543#issuecomment-1795736695\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n }\n break;\n case 'VersionError':\n if (nativeVerToOpen > 0) {\n nativeVerToOpen = 0;\n return tryOpenDB();\n }\n break;\n }\n return Promise.reject(err);\n });\n\n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([\n openCanceller,\n (typeof navigator === 'undefined'\n ? Promise.resolve()\n : safari14Workaround()\n ).then(tryOpenDB),\n ])\n .then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(() => db.on.ready.fire(db.vip))).then(\n function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(\n promisableChain,\n nop\n );\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(() => remainders(db.vip))).then(\n fireRemainders\n );\n }\n }\n );\n })\n .finally(() => {\n if (state.openCanceller === openCanceller) {\n // Only modify state if not cancelled in the mean time.\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n })\n .catch((err) => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch {}\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection(err);\n })\n .finally(() => {\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n })\n .then(() => {\n if (wasCreated) {\n // Propagate full range on primary keys and indexes on all tables now that the DB is ready and opened,\n // and all upgraders and on('ready') subscribers have run.\n const everything: ObservabilitySet = {};\n db.tables.forEach((table) => {\n table.schema.indexes.forEach((idx) => {\n if (idx.name)\n everything[`idb://${db.name}/${table.name}/${idx.name}`] =\n new RangeSet(-Infinity, [[[]]]);\n });\n everything[`idb://${db.name}/${table.name}/`] = everything[\n `idb://${db.name}/${table.name}/:dels`\n ] = new RangeSet(-Infinity, [[[]]]);\n });\n // Database was created. If another tab had it open when it was deleted and reopened, that tab must be updated now.\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything);\n // Wipe the cache and trigger optimistic queries:\n signalSubscribersNow(everything, true);\n }\n // Resolve the db.open() with the db instance.\n return db;\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator(iterator: Iterator<any>) {\n var callNext = (result) => iterator.next(result),\n doThrow = (error) => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any) => any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done\n ? value\n : !value || typeof value.then !== 'function'\n ? isArray(value)\n ? Promise.all(value).then(onSuccess, onError)\n : onSuccess(value)\n : value.then(onSuccess, onError);\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { errnames, exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits,\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(\n mode: TransactionMode,\n _tableArgs_,\n scopeFunc\n) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument('Too few arguments');\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: () => PromiseLike<any> | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(\n mode,\n storeNames,\n db._dbSchema,\n parentTransaction\n );\n trans.explicit = true;\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless,\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n // @ts-ignore Mark the idbtrans object with \"_explicit\". DBCore middleware won't have access to Dexie trans but will need to have this info.\n trans.idbtrans._explicit = true;\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (\n ex.name === errnames.InvalidState &&\n db.isOpen() &&\n --db._state.PR1398_maxLoop > 0\n ) {\n console.warn('Dexie: Need to reopen db');\n db.close({ disableAutoOpen: false });\n return db\n .open()\n .then(() =>\n enterTransactionScope(db, mode, storeNames, null, scopeFunc)\n );\n }\n return rejection(ex);\n }\n }\n\n // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (\n typeof returnValue.next === 'function' &&\n typeof returnValue.throw === 'function'\n ) {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (\n returnValue && typeof returnValue.then === 'function'\n ? // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then((x) =>\n trans.active\n ? x // Transaction still active. Continue.\n : rejection(\n new exceptions.PrematureCommit(\n 'Transaction committed too early. See http://bit.ly/2kdckMn'\n )\n )\n )\n : // No promise returned. Wait for all outstanding promises before continuing.\n promiseFollowed.then(() => returnValue)\n )\n .then((x) => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n })\n .catch((e) => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n}\n","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from '../public/types/dbcore';\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n\n /** LowLevelIndex represents the actual IndexedDB index behind it */\n lowLevelIndex: DBCoreIndex;\n}\n\n// Move into some util:\nexport function pad(a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i = 0; i < count; ++i) result.push(value);\n return result;\n}\n\nexport function createVirtualIndexMiddleware(down: DBCore): DBCore {\n return {\n ...down,\n table(tableName: string) {\n const table = down.table(tableName);\n const { schema } = table;\n const indexLookup: { [indexAlias: string]: VirtualIndex[] } = {};\n const allVirtualIndexes: VirtualIndex[] = [];\n\n function addVirtualIndexes(\n keyPath: null | string | string[],\n keyTail: number,\n lowLevelIndex: DBCoreIndex\n ): VirtualIndex {\n const keyPathAlias = getKeyPathAlias(keyPath);\n const indexList = (indexLookup[keyPathAlias] =\n indexLookup[keyPathAlias] || []);\n const keyLength =\n keyPath == null\n ? 0\n : typeof keyPath === 'string'\n ? 1\n : keyPath.length;\n const isVirtual = keyTail > 0;\n const virtualIndex = {\n ...lowLevelIndex,\n name: isVirtual\n ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})`\n : lowLevelIndex.name,\n lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique,\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath =\n keyLength === 2\n ? keyPath[0] // This is a compound [a, b]. Add a virtual normal index a.\n : keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a, b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n\n const primaryKey = addVirtualIndexes(\n schema.primaryKey.keyPath,\n 0,\n schema.primaryKey\n );\n indexLookup[':id'] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n\n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n\n function translateRange(\n range: DBCoreKeyRange,\n keyTail: number\n ): DBCoreKeyRange {\n return {\n type:\n range.type === DBCoreRangeType.Equal\n ? DBCoreRangeType.Range\n : range.type,\n lower: pad(\n range.lower,\n range.lowerOpen ? down.MAX_KEY : down.MIN_KEY,\n keyTail\n ),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(\n range.upper,\n range.upperOpen ? down.MIN_KEY : down.MAX_KEY,\n keyTail\n ),\n upperOpen: true, // doesn't matter true or false\n };\n }\n\n function translateRequest(req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest(\n req: DBCoreOpenCursorRequest\n ): DBCoreOpenCursorRequest;\n function translateRequest(req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual\n ? {\n ...req,\n query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail),\n },\n }\n : req;\n }\n\n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex,\n },\n\n count(req) {\n return table.count(translateRequest(req));\n },\n\n query(req) {\n return table.query(translateRequest(req));\n },\n\n openCursor(req) {\n const { keyTail, isVirtual, keyLength } = req.query\n .index as VirtualIndex;\n if (!isVirtual) return table.openCursor(req);\n\n function createVirtualCursor(cursor: DBCoreCursor): DBCoreCursor {\n function _continue(key?: any) {\n key != null\n ? cursor.continue(\n pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)\n )\n : req.unique\n ? cursor.continue(\n cursor.key\n .slice(0, keyLength)\n .concat(\n req.reverse ? down.MIN_KEY : down.MAX_KEY,\n keyTail\n )\n )\n : cursor.continue();\n }\n const virtualCursor = Object.create(cursor, {\n continue: { value: _continue },\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(\n pad(key, down.MAX_KEY, keyTail),\n primaryKey\n );\n },\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n },\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1\n ? key[0] // Cursor.key should not be an array.\n : key.slice(0, keyLength); // Cursor.key should be first part of array.\n },\n },\n value: {\n get() {\n return cursor.value;\n },\n },\n });\n return virtualCursor;\n }\n\n return table\n .openCursor(translateRequest(req))\n .then((cursor) => cursor && createVirtualCursor(cursor));\n },\n };\n return result;\n },\n };\n}\n\nexport const virtualIndexMiddleware: Middleware<DBCore> = {\n stack: 'dbcore',\n name: 'VirtualIndexMiddleware',\n level: 1,\n create: createVirtualIndexMiddleware,\n};\n","import { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from '../public/types/dbcore';\n\nexport function getEffectiveKeys(\n primaryKey: DBCoreIndex,\n req:\n | (Pick<DBCoreAddRequest | DBCorePutRequest, 'type' | 'values'> & {\n keys?: any[];\n })\n | Pick<DBCoreDeleteRequest, 'keys' | 'type'>\n) {\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey);\n}\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange,\n} from '../public/types/dbcore';\nimport { nop } from '../functions/chaining-functions';\nimport { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from '../functions/get-object-diff';\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware<DBCore> = {\n stack: 'dbcore',\n name: 'HooksMiddleware',\n level: 2,\n create: (downCore: DBCore) =>\n ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const { primaryKey } = downTable.schema;\n\n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req): Promise<DBCoreMutateResponse> {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const { deleting, creating, updating } =\n dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise(\n 'readwrite',\n () => addPutOrDelete(req),\n true\n );\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise(\n 'readwrite',\n () => addPutOrDelete(req),\n true\n );\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise(\n 'readwrite',\n () => addPutOrDelete(req),\n true\n );\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise(\n 'readwrite',\n () => deleteRange(req),\n true\n );\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n function addPutOrDelete(\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest\n ): Promise<DBCoreMutateResponse> {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error('Keys missing');\n // Clone Request and set keys arg\n req =\n req.type === 'add' || req.type === 'put'\n ? { ...req, keys }\n : { ...req };\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n\n return getExistingValues(downTable, req, keys).then(\n (existingValues) => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (\n req.type === 'add' ||\n existingValue === undefined\n ) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(\n ctx,\n key,\n req.values[i],\n dxTrans\n );\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(\n existingValue,\n req.values[i]\n );\n const additionalChanges = updating.fire.call(\n ctx,\n objectDiff,\n key,\n existingValue,\n dxTrans\n );\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach((keyPath) => {\n if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] =\n additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(\n requestedValue,\n keyPath,\n additionalChanges[keyPath]\n );\n }\n });\n }\n }\n return ctx;\n });\n return downTable\n .mutate(req)\n .then(({ failures, results, numFailures, lastResult }) => {\n for (let i = 0; i < keys.length; ++i) {\n const primKey = results ? results[i] : keys[i];\n const ctx = contexts[i];\n if (primKey == null) {\n ctx.onerror && ctx.onerror(failures[i]);\n } else {\n ctx.onsuccess &&\n ctx.onsuccess(\n req.type === 'put' && existingValues[i] // the put resulted in an update\n ? req.values[i] // update hooks expects existing value\n : primKey // create hooks expects primary key\n );\n }\n }\n return { failures, results, numFailures, lastResult };\n })\n .catch((error) => {\n contexts.forEach(\n (ctx) => ctx.onerror && ctx.onerror(error)\n );\n return Promise.reject(error);\n });\n }\n );\n }\n\n function deleteRange(\n req: DBCoreDeleteRangeRequest\n ): Promise<DBCoreMutateResponse> {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n\n function deleteNextChunk(\n trans: DBCoreTransaction,\n range: DBCoreKeyRange,\n limit: number\n ) {\n // Query what keys in the DB within the given range\n return downTable\n .query({\n trans,\n values: false,\n query: { index: primaryKey, range },\n limit,\n })\n .then(({ result }) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({\n type: 'delete',\n keys: result,\n trans,\n }).then((res) => {\n if (res.numFailures > 0)\n return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {\n failures: [],\n numFailures: 0,\n lastResult: undefined,\n } as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(\n trans,\n {\n ...range,\n lower: result[result.length - 1],\n lowerOpen: true,\n },\n limit\n );\n }\n });\n });\n }\n },\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore,\n};\n\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === 'add'\n ? Promise.resolve([])\n : table.getMany({\n trans: req.trans,\n keys: effectiveKeys,\n cache: 'immutable',\n });\n}\n","import { deepClone } from '../functions/utils';\nimport { DBCore } from '../public/types/dbcore';\nimport { Middleware } from '../public/types/middleware';\nimport Promise from '../helpers/promise';\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: readonly any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware<DBCore> = {\n stack: 'dbcore',\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans['_cache'],\n req.cache === 'clone'\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans['_cache'] = {\n keys: req.keys,\n values: req.cache === 'clone' ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== 'add') req.trans['_cache'] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { DBCore, DBCoreTable } from '../../public/types/dbcore';\nimport { LiveQueryContext } from '../live-query';\n\nexport function isCachableContext(ctx: LiveQueryContext, table: DBCoreTable) {\n return (\n ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound\n );\n}\n","import {\n DBCoreCountRequest,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\n\nexport function isCachableRequest(\n type: string,\n req: Partial<\n DBCoreQueryRequest &\n DBCoreCountRequest &\n DBCoreGetManyRequest &\n DBCoreGetRequest &\n DBCoreOpenCursorRequest\n >\n) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n}\n","import { LiveQueryContext } from '.';\nimport { getFromTransactionCache } from '../dbcore/cache-existing-values-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { exceptions } from '../errors';\nimport { cmp } from '../functions/cmp';\nimport { isArray, keys } from '../functions/utils';\nimport { PSD } from '../helpers/promise';\nimport { RangeSet } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from '../public/types/dbcore';\nimport { Middleware } from '../public/types/middleware';\nimport { isCachableContext } from './cache/is-cachable-context';\nimport { isCachableRequest } from './cache/is-cachable-request';\nimport { extendObservabilitySet } from './extend-observability-set';\n\nexport const observabilityMiddleware: Middleware<DBCore> = {\n stack: 'dbcore',\n level: 0,\n name: 'Observability',\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n transaction: (stores, mode, options) => {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(\n `Readwrite transaction in liveQuery context. Querier source: ${(PSD as LiveQueryContext).querier}`\n );\n }\n return core.transaction(stores, mode, options);\n },\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey, indexes } = schema;\n const { extractKey, outbound } = primaryKey;\n const indexesWithAutoIncPK =\n primaryKey.autoIncrement &&\n indexes.filter(\n (index) =>\n index.compound &&\n (index.keyPath as string[]).includes(primaryKey.keyPath as string)\n );\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet('');\n const delsRangeSet = getRangeSet(':dels');\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === 'deleteRange'\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === 'delete'\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [\n getEffectiveKeys(primaryKey, req).filter((id) => id),\n req.values,\n ] // keys except autoIncremented - they will be added later on.\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n\n const oldCache = req.trans['_cache'];\n\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n // Individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs =\n type === 'delete' || keys.length === newObjs.length\n ? getFromTransactionCache(keys, oldCache)\n : null;\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs) {\n // add, delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() and primaryKeys() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // keys is a DBCoreKeyRange object. Transform it to [from,to]-style range.\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n // (above/below-style ranges are not supported in RangeSet.ts, so we must replace open ends\n // with core.MIN_KEY and core.MAX_KEY respectively. This is what solves issue #2067!\n const range = {\n from: keys.lower ?? core.MIN_KEY,\n to: keys.upper ?? core.MAX_KEY,\n };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach((idx) =>\n getRangeSet(idx.name).add(FULL_RANGE)\n );\n }\n\n return table.mutate(req).then((res) => {\n // Merge the mutated parts from the request into the transaction's mutatedParts\n // now when the request went fine.\n if (keys && (req.type === 'add' || req.type === 'put')) {\n // Less than 50 requests (keys truthy) (otherwise we've added full range anyway)\n // autoincrement means we might not have got all keys until now\n pkRangeSet.addKeys(res.results);\n if (indexesWithAutoIncPK) {\n // Dexie Issue 1946:\n // If an auto-incremented primary key is part of a compound index,\n // we need to compute the resulting value of that index after inserting\n // the rows.\n indexesWithAutoIncPK.forEach((idx) => {\n // Extract values of this compound index where primary key is not yet set:\n const idxVals = req.values.map((v) => idx.extractKey(v));\n // Find the position of the primary key in the index:\n const pkPos = (idx.keyPath as string[]).findIndex(\n (prop) => prop === primaryKey.keyPath\n );\n // Update idxVals with the resulting primary keys to complete the index value:\n for (let i = 0, len = res.results!.length; i < len; ++i) {\n idxVals[i][pkPos] = res.results![i];\n }\n // Add the updated index to the rangeset:\n getRangeSet(idx.name).addKeys(idxVals);\n });\n }\n }\n trans.mutatedParts = extendObservabilitySet(\n trans.mutatedParts || {},\n mutatedParts\n );\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(\n range.lower ?? core.MIN_KEY,\n range.upper ?? core.MAX_KEY\n ),\n ];\n\n const readSubscribers: {\n [method in Exclude<\n keyof DBCoreTable,\n 'name' | 'schema' | 'mutate'\n >]: (req: any) => [DBCoreIndex, RangeSet];\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n };\n\n keys(readSubscribers).forEach(\n (method: 'get' | 'getMany' | 'count' | 'query' | 'openCursor') => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD as LiveQueryContext;\n const isLiveQuery = !!subscr;\n let cachable =\n isCachableContext(PSD as LiveQueryContext, table) &&\n isCachableRequest(method, req);\n const obsSet = cachable\n ? (req.obsSet = {}) // Implicit read transaction - track changes for this query only for the request's duration\n : subscr; // Explicit read transaction - track changes across entire live query\n\n if (isLiveQuery) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet('');\n const delsRangeSet = getRangeSet(':dels');\n const [queriedIndex, queriedRanges] =\n readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n if (\n method === 'query' &&\n queriedIndex.isPrimaryKey &&\n !(req as DBCoreQueryRequest).values\n ) {\n // A pure primay-key based Collection where only .primaryKeys() is requested. Don't wakeup on other changes than added or deleted primary keys within queried range.\n delsRangeSet.add(queriedRanges);\n } else {\n getRangeSet(queriedIndex.name || '').add(queriedRanges);\n }\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === 'count') {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === 'query' &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === 'query') {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({\n result: resultingKeys,\n }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === 'openCursor') {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest)\n .values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues &&\n pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n }\n );\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: readonly any[] | undefined,\n newObjs: readonly any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || '');\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) =>\n ix.multiEntry && isArray(key)\n ? // multiEntry and the old property was an array - add each array entry to the rangeSet:\n key.forEach((key) => rangeSet.addKey(key))\n : // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n","import { delArrayItem, isArray } from '../../functions/utils';\nimport { TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreMutateRequest,\n DBCoreMutateResponse,\n} from '../../public/types/dbcore';\n\nexport function adjustOptimisticFromFailures(\n tblCache: TblQueryCache,\n req: DBCoreMutateRequest,\n res: DBCoreMutateResponse\n): DBCoreMutateRequest {\n if (res.numFailures === 0) return req;\n if (req.type === 'deleteRange') {\n // numFailures > 0 means the deleteRange operation failed in its whole.\n return null;\n }\n\n const numBulkOps = req.keys\n ? req.keys.length\n : 'values' in req && req.values\n ? req.values.length\n : 1;\n if (res.numFailures === numBulkOps) {\n // Same number of failures as the number of ops. This means that all ops failed.\n return null;\n }\n\n const clone: DBCoreMutateRequest = { ...req };\n\n if (isArray(clone.keys)) {\n clone.keys = clone.keys.filter((_, i) => !(i in res.failures));\n }\n if ('values' in clone && isArray(clone.values)) {\n clone.values = clone.values.filter((_, i) => !(i in res.failures));\n }\n return clone;\n}\n","import { cmp } from '../../functions/cmp';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function isAboveLower(key: IndexableType, range: DBCoreKeyRange) {\n return range.lower === undefined\n ? true // lower is less than anything because it is undefined\n : range.lowerOpen\n ? cmp(key, range.lower) > 0 // lowerOpen: Exclude lower bound\n : cmp(key, range.lower) >= 0; // !lowerOpen: Include lower bound\n}\n\nexport function isBelowUpper(key: IndexableType, range: DBCoreKeyRange) {\n return range.upper === undefined\n ? true // upper is greater than anything because it is undefined\n : range.upperOpen\n ? cmp(key, range.upper) < 0 // upperOpen: Exclude upper bound\n : cmp(key, range.upper) <= 0; // !upperOpen: Include upper bound\n}\n\nexport function isWithinRange(key: IndexableType, range: DBCoreKeyRange) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n}\n","import { cmp } from '../../functions/cmp';\nimport { isArray } from '../../functions/utils';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { CacheEntry } from '../../public/types/cache';\nimport {\n DBCoreMutateRequest,\n DBCoreQueryRequest,\n DBCoreTable,\n} from '../../public/types/dbcore';\nimport { isWithinRange } from './is-within-range';\n\nexport function applyOptimisticOps(\n result: any[],\n req: DBCoreQueryRequest,\n ops: DBCoreMutateRequest[] | undefined,\n table: DBCoreTable,\n cacheEntry: CacheEntry,\n immutable: boolean\n): any[] {\n if (!ops || ops.length === 0) return result;\n const index = req.query.index;\n const { multiEntry } = index;\n const queryRange = req.query.range;\n const primaryKey = table.schema.primaryKey;\n const extractPrimKey = primaryKey.extractKey!;\n const extractIndex = index.extractKey!;\n const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey!;\n\n let finalResult = ops.reduce((result, op) => {\n let modifedResult = result;\n const includedValues: any[] = [];\n if (op.type === 'add' || op.type === 'put') {\n const includedPKs = new RangeSet(); // For ignoring duplicates\n for (let i = op.values.length - 1; i >= 0; --i) {\n // backwards to prioritize last value of same PK\n const value = op.values[i];\n const pk = extractPrimKey(value);\n if (includedPKs.hasKey(pk)) continue;\n const key = extractIndex(value);\n if (\n multiEntry && isArray(key)\n ? key.some((k) => isWithinRange(k, queryRange))\n : isWithinRange(key, queryRange)\n ) {\n includedPKs.addKey(pk);\n includedValues.push(value);\n }\n }\n }\n switch (op.type) {\n case 'add': {\n const existingKeys = new RangeSet().addKeys(\n req.values ? result.map((v) => extractPrimKey(v)) : result\n );\n\n modifedResult = result.concat(\n req.values\n ? includedValues.filter((v) => {\n const key = extractPrimKey(v);\n if (existingKeys.hasKey(key)) return false;\n existingKeys.addKey(key);\n return true;\n })\n : includedValues\n .map((v) => extractPrimKey(v))\n .filter((k) => {\n if (existingKeys.hasKey(k)) return false;\n existingKeys.addKey(k);\n return true;\n })\n );\n break;\n }\n case 'put': {\n const keySet = new RangeSet().addKeys(\n op.values.map((v) => extractPrimKey(v))\n );\n modifedResult = result\n .filter(\n // Remove all items that are being replaced\n (item) => !keySet.hasKey(req.values ? extractPrimKey(item) : item)\n )\n .concat(\n // Add all items that are being put (sorting will be done later)\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n }\n case 'delete':\n const keysToDelete = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter(\n (item) =>\n !keysToDelete.hasKey(req.values ? extractPrimKey(item) : item)\n );\n\n break;\n case 'deleteRange':\n const range = op.range;\n modifedResult = result.filter(\n (item) => !isWithinRange(extractPrimKey(item), range)\n );\n break;\n }\n return modifedResult;\n }, result);\n\n // If no changes were made, we can return the original result.\n if (finalResult === result) return result;\n\n // Sort the result on sortIndex:\n const sorter: (a: any, b: any) => number = (a, b) =>\n cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b));\n\n // If direction is 'prev' or 'prevunique', sort in descending order\n finalResult.sort(\n req.direction === 'prev' || req.direction === 'prevunique'\n ? (a, b) => sorter(b, a)\n : sorter\n );\n\n // If we have a limit we need to respect it:\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit; // Cut of any extras after sorting correctly.\n } else if (result.length === req.limit && finalResult.length < req.limit) {\n // We're missing some items because of the limit. We need to add them back.\n // The easiest way is to mark the cache entry as dirty, which will cause\n // it to be requeried after the write-transaction successfully completes.\n cacheEntry.dirty = true;\n }\n }\n return immutable ? (Object.freeze(finalResult) as any[]) : finalResult;\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function areRangesEqual(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen\n );\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function compareLowers(\n lower1: any,\n lower2: any,\n lowerOpen1: boolean,\n lowerOpen2: boolean\n) {\n if (lower1 === undefined) return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined) return 1; // since lower1 !== undefined\n const c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2) return 0;\n if (lowerOpen1) return 1;\n if (lowerOpen2) return -1;\n }\n return c;\n}\n\nexport function compareUppers(\n upper1: any,\n upper2: any,\n upperOpen1: boolean,\n upperOpen2: boolean\n) {\n if (upper1 === undefined) return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined) return -1; // since upper1 !== undefined\n const c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2) return 0;\n if (upperOpen1) return -1;\n if (upperOpen2) return 1;\n }\n return c;\n}\n\nexport function isSuperRange(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0\n );\n}\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreCountRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\nimport { areRangesEqual } from './are-ranges-equal';\nimport { cache } from './cache';\nimport { isSuperRange } from './is-super-range';\n\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query',\n req: DBCoreQueryRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'count',\n req: DBCoreCountRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query' | 'count',\n req: Partial<DBCoreQueryRequest> & Partial<DBCoreCountRequest>\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]] {\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return [];\n const queries = tblCache.queries[type];\n if (!queries) return [null, false, tblCache, null];\n const indexName = req.query ? req.query.index.name : null;\n const entries = queries[indexName || ''];\n if (!entries) return [null, false, tblCache, null];\n\n switch (type) {\n case 'query':\n // Normalize direction to improve cache hit rate for forward queries\n // (undefined and 'next' are equivalent)\n const reqDirection = req.direction ?? 'next';\n const equalEntry = entries.find(\n (entry) =>\n (entry.req as DBCoreQueryRequest).limit === req.limit &&\n (entry.req as DBCoreQueryRequest).values === req.values &&\n ((entry.req as DBCoreQueryRequest).direction ?? 'next') ===\n reqDirection &&\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n if (equalEntry)\n return [\n equalEntry,\n true, // exact match\n tblCache,\n entries,\n ];\n const superEntry = entries.find((entry) => {\n const limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (\n limit >= req.limit &&\n ((entry.req as DBCoreQueryRequest).direction ?? 'next') ===\n reqDirection &&\n (req.values ? (entry.req as DBCoreQueryRequest).values : true) &&\n isSuperRange(entry.req.query.range, req.query.range)\n );\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n const countQuery = entries.find((entry) =>\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n return [countQuery, !!countQuery, tblCache, entries];\n }\n}\n","import { delArrayItem } from '../../functions/utils';\nimport { CacheEntry } from '../../public/types/cache';\n\nexport function subscribeToCacheEntry(\n cacheEntry: CacheEntry,\n container: CacheEntry[],\n requery: () => void,\n signal: AbortSignal\n) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener('abort', () => {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n}\n\nfunction enqueForDeletion(cacheEntry: CacheEntry, container: CacheEntry[]) {\n setTimeout(() => {\n if (cacheEntry.subscribers.size === 0) {\n // Still empty (no new subscribers readded after grace time)\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n}\n","import { LiveQueryContext } from '..';\nimport type { Transaction } from '../../classes/transaction';\nimport { getEffectiveKeys } from '../../dbcore/get-effective-keys';\nimport { deepClone, delArrayItem, setByKeyPath } from '../../functions/utils';\nimport DexiePromise, { PSD } from '../../helpers/promise';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport {\n DBCore,\n DBCoreMutateRequest,\n DBCoreMutateResponse,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n} from '../../public/types/dbcore';\nimport { Middleware } from '../../public/types/middleware';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { adjustOptimisticFromFailures } from './adjust-optimistic-request-from-failures';\nimport { applyOptimisticOps } from './apply-optimistic-ops';\nimport { cache } from './cache';\nimport { findCompatibleQuery } from './find-compatible-query';\nimport { isCachableContext } from './is-cachable-context';\nimport { isCachableRequest } from './is-cachable-request';\nimport { signalSubscribersLazily } from './signalSubscribers';\nimport { subscribeToCacheEntry } from './subscribe-cachentry';\n\nexport const cacheMiddleware: Middleware<DBCore> = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: (core) => {\n const dbName = core.schema.name;\n const coreMW: DBCore = {\n ...core,\n transaction: (stores, mode, options) => {\n const idbtrans = core.transaction(\n stores,\n mode,\n options\n ) as IDBTransaction & {\n mutatedParts?: ObservabilitySet;\n _explicit?: boolean;\n };\n // Maintain TblQueryCache.ops array when transactions commit or abort\n if (mode === 'readwrite') {\n const ac = new AbortController();\n const { signal } = ac;\n const endTransaction = (wasCommitted: boolean) => () => {\n ac.abort();\n if (mode === 'readwrite') {\n // Collect which subscribers to notify:\n const affectedSubscribers = new Set<() => void>();\n\n // Go through all tables in transaction and check if they have any optimistic updates\n for (const storeName of stores) {\n const tblCache = cache[`idb://${dbName}/${storeName}`];\n if (tblCache) {\n const table = core.table(storeName);\n // Pick optimistic ops that are part of this transaction\n const ops = tblCache.optimisticOps.filter(\n (op) => op.trans === idbtrans\n );\n // Transaction was marked as _explicit in enterTransactionScope(), transaction-helpers.ts.\n if (\n idbtrans._explicit &&\n wasCommitted &&\n idbtrans.mutatedParts\n ) {\n // Invalidate all queries that overlap with the mutated parts and signal their subscribers\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)\n ) {\n delArrayItem(entries, entry); // Remove the entry from the cache so it can be refreshed\n entry.subscribers.forEach((requery) =>\n affectedSubscribers.add(requery)\n );\n }\n }\n }\n } else if (ops.length > 0) {\n // Remove them from the optimisticOps array\n tblCache.optimisticOps = tblCache.optimisticOps.filter(\n (op) => op.trans !== idbtrans\n );\n // Commit or abort the optimistic updates\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n entry.res != null && // if entry.promise but not entry.res, we're fine. Query will resume now and get the result.\n idbtrans.mutatedParts /* &&\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)*/\n ) {\n if (wasCommitted && !entry.dirty) {\n const freezeResults = Object.isFrozen(entry.res);\n const modRes = applyOptimisticOps(\n entry.res as any[],\n entry.req,\n ops,\n table,\n entry,\n freezeResults\n );\n if (entry.dirty) {\n // Found out at this point that the entry is dirty - not to rely on!\n delArrayItem(entries, entry);\n entry.subscribers.forEach((requery) =>\n affectedSubscribers.add(requery)\n );\n } else if (modRes !== entry.res) {\n entry.res = modRes;\n // Update promise\n entry.promise = DexiePromise.resolve({\n result: modRes,\n } satisfies DBCoreQueryResponse);\n\n // No need to notify subscribers. They already have this value.\n // We have just updated the value of the cache without having to\n // requery the database - because we know the result for this\n // query based on computing the operations and applying them\n // to the previous result.\n }\n } else {\n if (entry.dirty) {\n // If the entry is dirty we need to get rid of it so that\n // a new entry will be created when the query is run again.\n delArrayItem(entries, entry);\n }\n // If we're not committing, we need to notify subscribers that the\n // optimistic updates are no longer valid.\n entry.subscribers.forEach((requery) =>\n affectedSubscribers.add(requery)\n );\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers.forEach((requery) => requery());\n }\n };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal,\n });\n }\n return idbtrans;\n },\n table(tableName: string) {\n const downTable = core.table(tableName);\n const primKey = downTable.schema.primaryKey;\n const tableMW = {\n ...downTable,\n mutate(req: DBCoreMutateRequest): Promise<DBCoreMutateResponse> {\n const trans = PSD.trans as Transaction;\n if (\n primKey.outbound || // Non-inbound tables are harded to apply optimistic updates on because we can't know primary key of results\n trans.db._options.cache === 'disabled' || // User has opted-out from caching\n trans.explicit || // It's an explicit write transaction being made. Don't affect cache until transaction commits.\n trans.idbtrans.mode !== 'readwrite' // We only handle 'readwrite' in our transaction override. 'versionchange' transactions don't use cache (from populate or upgraders).\n ) {\n // Just forward the request to the core.\n return downTable.mutate(req);\n }\n // Find the TblQueryCache for this table:\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return downTable.mutate(req);\n\n const promise = downTable.mutate(req);\n if (\n (req.type === 'add' || req.type === 'put') &&\n (req.values.length >= 50 ||\n getEffectiveKeys(primKey, req).some((key) => key == null))\n ) {\n // There are some autoIncremented keys not set yet. Need to wait for completion before we can reliably enqueue the operation.\n // (or there are too many objects so we lazy out to avoid performance bottleneck for large bulk inserts)\n promise.then((res) => {\n // We need to extract result keys and generate cloned values with the keys set (so that applyOptimisticOps can work)\n // But we have a problem! The req.mutatedParts is still not complete so we have to actively add the keys to the unsignaledParts set manually.\n const reqWithResolvedKeys = {\n ...req,\n values: req.values.map((value, i) => {\n if (res.failures[i]) return value; // No need to rewrite a failing value\n const valueWithKey = primKey.keyPath?.includes('.')\n ? deepClone(value)\n : {\n ...value,\n };\n setByKeyPath(\n valueWithKey,\n primKey.keyPath,\n res.results![i]\n );\n return valueWithKey;\n }),\n };\n const adjustedReq = adjustOptimisticFromFailures(\n tblCache,\n reqWithResolvedKeys,\n res\n );\n tblCache.optimisticOps.push(adjustedReq);\n // Signal subscribers after the observability middleware has complemented req.mutatedParts with the new keys.\n // We must queue the task so that we get the req.mutatedParts updated by observability middleware first.\n // If we refactor the dependency between observability middleware and this middleware we might not need to queue the task.\n queueMicrotask(\n () =>\n req.mutatedParts &&\n signalSubscribersLazily(req.mutatedParts)\n ); // Reason for double laziness: in user awaits put and then does another put, signal once.\n });\n } else {\n // Enque the operation immediately\n tblCache.optimisticOps.push(req);\n // Signal subscribers that there are mutated parts\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts);\n promise.then((res) => {\n if (res.numFailures > 0) {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n const adjustedReq = adjustOptimisticFromFailures(\n tblCache,\n req,\n res\n );\n if (adjustedReq) {\n tblCache.optimisticOps.push(adjustedReq);\n }\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n }\n });\n promise.catch(() => {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n });\n }\n return promise;\n },\n query(req: DBCoreQueryRequest): Promise<DBCoreQueryResponse> {\n if (\n !isCachableContext(PSD, downTable) ||\n !isCachableRequest('query', req)\n )\n return downTable.query(req);\n const freezeResults =\n (PSD as LiveQueryContext).trans?.db._options.cache ===\n 'immutable';\n const { requery, signal } = PSD as LiveQueryContext;\n let [cacheEntry, exactMatch, tblCache, container] =\n findCompatibleQuery(dbName, tableName, 'query', req);\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet!; // So that optimistic result is monitored.\n // How? - because observability-middleware will track result where optimistic\n // mutations are applied and record it in the cacheEntry.\n // TODO: CHANGE THIS! The difference is resultKeys only.\n // Wanted behavior:\n // * cacheEntry obsSet should represent the obsSet without optimistic updates (so it can be checked when merging ops in tx commit)\n // * cacheEntry optimisticObsSet should represent the obsSet with current optimistic updates. It should be updated when adding an op\n // by adding the primary keys of the put/add/delete operation to the set.\n // * observability-middleware should stop recording req.obsSet when a cache entry exact match is found because it won't be used anyway.\n // I'm thinking of merging observability-middleware with cache-middleware into one single middleware because the dependencies are too\n // tight between them.\n } else {\n // --> TODO here: If not exact match, check if we have a superset to extract\n // the data from.\n\n // No cached result found. We need to query the database and cache the result.\n const promise = downTable\n .query(req)\n .then((res) => {\n // Freeze or clone results\n const result = res.result;\n if (cacheEntry) cacheEntry.res = result;\n if (freezeResults) {\n // For performance reasons don't deep freeze.\n // Only freeze the top-level array and its items.\n // This is good enough to teach users that the result must be treated as immutable\n // without enforcing it recursively on the entire result (which is not even possible\n // for things like Date objects and typed arrays)\n for (let i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n }\n // If not frozen (cache: 'cloned'), we do NOT clone here.\n // Since every cache read (including the initial one) will go through\n // the downstream .then() handler and perform a deepClone on read,\n // the original query results in the cache remain perfectly isolated\n // and we avoid a redundant double deepClone on the first query.\n return res;\n })\n .catch((error) => {\n // In case the query operation failed, we need to remove it from the cache\n // so that subsequent calls does not get the same error but re-evaluate\n // the query.\n if (container && cacheEntry)\n delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet!,\n promise,\n subscribers: new Set(),\n type: 'query',\n req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n } else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[`idb://${dbName}/${tableName}`] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {},\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container!, requery, signal);\n return cacheEntry.promise.then((res: DBCoreQueryResponse) => {\n const result = applyOptimisticOps(\n res.result,\n req,\n tblCache?.optimisticOps,\n downTable,\n cacheEntry!,\n freezeResults\n ) as any[]; // readonly any[]\n return {\n result: freezeResults ? result : deepClone(result),\n };\n });\n },\n };\n return tableMW;\n },\n };\n return coreMW;\n },\n};\n","import { type Dexie } from '../classes/dexie';\nimport { type Table } from '../classes/table';\nimport { type Transaction } from '../classes/transaction';\n\nexport function vipify<T extends Table | Transaction>(\n target: T,\n vipDb: Dexie\n): T {\n return new Proxy(target, {\n get(target, prop, receiver) {\n // The \"db\" prop of the table or transaction is the only one we need to\n // override. The rest of the props can be accessed from the original\n // object.\n if (prop === 'db') return vipDb;\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n","// Import types from the public API\nimport { Dexie as IDexie } from '../../public/types/dexie';\nimport {\n DexieOptions,\n DexieConstructor,\n} from '../../public/types/dexie-constructor';\nimport { DbEvents, DbEventFns } from '../../public/types/db-events';\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from '../table';\nimport {\n Collection,\n CollectionConstructor,\n createCollectionConstructor,\n} from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport {\n WhereClauseConstructor,\n createWhereClauseConstructor,\n} from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport {\n TransactionConstructor,\n createTransactionConstructor,\n} from '../transaction/transaction-constructor';\nimport { Version } from '../version/version';\nimport {\n VersionConstructor,\n createVersionConstructor,\n} from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD, globalPSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport {\n maxString,\n READONLY,\n READWRITE,\n DEFAULT_MAX_CONNECTIONS,\n} from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { _onDatabaseDeleted } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport {\n extractTransactionArgs,\n enterTransactionScope,\n} from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\nimport { cacheMiddleware } from '../../live-query/cache/cache-middleware';\nimport { vipify } from '../../helpers/vipify';\nimport { connections } from '../../globals/connections';\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise<any>;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise<any> & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n PR1398_maxLoop?: number;\n autoOpen?: boolean;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table };\n _createTransaction: (\n this: Dexie,\n mode: IDBTransactionMode,\n storeNames: ArrayLike<string>,\n dbschema: { [tableName: string]: TableSchema },\n parentTransaction?: Transaction\n ) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {\n [StackName in keyof DexieStacks]?: Middleware<DexieStacks[StackName]>[];\n } = {};\n _vip?: boolean;\n _novip: Dexie; // db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\n on: DbEvents;\n once: DbEventFns;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n static disableBfCache?: boolean;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n cache: 'cloned', // Default to cloned for backward compatibility. For best performance and least memory consumption use 'immutable'.\n maxConnections: DEFAULT_MAX_CONNECTIONS, // Default max connections\n ...options,\n };\n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange,\n };\n const { addons } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true,\n PR1398_maxLoop: 3,\n autoOpen: options.autoOpen,\n };\n state.dbReadyPromise = new Promise((resolve) => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, 'populate', 'blocked', 'versionchange', 'close', {\n ready: [promisableChain, nop],\n }) as DbEvents;\n this.once = (event: any, callback: any) => {\n const fn = (...args: any[]) => {\n this.on(event).unsubscribe(fn);\n callback.apply(this, args);\n };\n return this.on(event as any, fn);\n };\n this.on.ready.subscribe = override(this.on.ready.subscribe, (subscribe) => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen)\n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n const db = this;\n if (!bSticky)\n subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n\n // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n this.on('versionchange', (ev) => {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(\n `Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`\n );\n else\n console.warn(\n `Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`\n );\n this.close({ disableAutoOpen: false });\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n this.on('blocked', (ev) => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(\n `Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`\n );\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction\n ) =>\n new this.Transaction(\n mode,\n storeNames,\n dbschema,\n this._options.chromeTransactionDurability,\n parentTransaction\n );\n\n this._fireOnBlocked = (ev) => {\n this.on('blocked').fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n // TODO: Should be safe to remove this workaround below! Do it in another PR.\n connections\n .toArray()\n .filter((c) => c.name === this.name && c !== this && !c._state.vcFired)\n .map((c) => c.on('versionchange').fire(ev));\n };\n\n // Default middlewares:\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n const vipDB = new Proxy(this, {\n get: (_, prop, receiver) => {\n if (prop === '_vip') return true;\n if (prop === 'table')\n return (tableName: string) => vipify(this.table(tableName), vipDB);\n const rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table) return vipify(rv, vipDB);\n if (prop === 'tables')\n return (rv as Table[]).map((t) => vipify(t, vipDB));\n if (prop === '_createTransaction')\n return function () {\n const tx: Transaction = (\n rv as typeof this._createTransaction\n ).apply(this, arguments);\n return vipify(tx, vipDB);\n };\n return rv;\n },\n });\n this.vip = vipDB;\n\n // Call each addon:\n addons.forEach((addon) => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1)\n throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema('Cannot add version when database is open');\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n (v) => v._cfg.version === versionNumber\n )[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady<T>(fn: () => Promise<T>): Promise<T> {\n return this.idbdb &&\n (this._state.openComplete || PSD.letThrough || this._vip)\n ? fn()\n : new Promise<T>((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(\n new exceptions.DatabaseClosed(this._state.dbOpenError)\n );\n }\n if (!this._state.isBeingOpened) {\n if (!this._state.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({ stack, create, level, name }: Middleware<DBCore>): this {\n if (name) this.unuse({ stack, name }); // Be able to replace existing middleware.\n const middlewares =\n this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({\n stack,\n create,\n level: level == null ? 10 : level,\n name,\n });\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({ stack, create }: Middleware<{ stack: keyof DexieStacks }>): this;\n unuse({ stack, name }: { stack: keyof DexieStacks; name: string }): this;\n unuse({\n stack,\n name,\n create,\n }: {\n stack: keyof DexieStacks;\n name?: string;\n create?: Function;\n }) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter((mw) =>\n create\n ? mw.create !== create // Given middleware has a create method. Match that exactly.\n : name\n ? mw.name !== name // Given middleware spec\n : false\n );\n }\n return this;\n }\n\n open() {\n return usePSD(\n globalPSD, // Enforce global scope here since db.open() can be part of a live query or transaction scope\n () => dexieOpen(this)\n );\n }\n\n _close(): void {\n this.on.close.fire(new CustomEvent('close'));\n const state = this._state;\n connections.remove(this);\n if (this.idbdb) {\n try {\n this.idbdb.close();\n } catch (e) {}\n this.idbdb = null;\n }\n // Reset dbReadyPromise promise:\n if (!state.isBeingOpened) {\n // Only if not being opened, reset these promises.\n // Otherwise, keep them so existing promise consumers will resolve when db\n // db is reopened later on, in case closing for purpose reopening, using {disableAutoOpen: false}.\n state.dbReadyPromise = new Promise((resolve) => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n }\n\n close({ disableAutoOpen } = { disableAutoOpen: true }): void {\n const state = this._state;\n if (disableAutoOpen) {\n if (state.isBeingOpened) {\n // cancel before the call to this._close() because this._close() will recreate dbReadyPromise and openCanceller.\n state.cancelOpen(new exceptions.DatabaseClosed());\n }\n this._close();\n state.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n } else {\n this._close();\n state.autoOpen = this._options.autoOpen || state.isBeingOpened; // If an open call is ongoing, that same promise will resolve when db is reopend.\n state.openComplete = false;\n state.dbOpenError = null;\n }\n }\n\n delete(closeOptions = { disableAutoOpen: true }): Promise<void> {\n // Prevent accidentially doing db.delete(1) when intention was to do db.[table].delete(1).\n const hasInvalidArguments =\n arguments.length > 0 && typeof arguments[0] !== 'object';\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close(closeOptions);\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n };\n // Prevent accidentially doing db.delete(1) when intention was to do db.[table].delete(1).\n if (hasInvalidArguments)\n throw new exceptions.InvalidArgument(\n 'Invalid closeOptions argument to db.delete()'\n );\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && dbOpenError.name === 'DatabaseClosed';\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables() {\n return keys(this._allTables).map((name) => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(\n mode: TransactionMode,\n tables: Array<ITable | string>,\n scopeFunc: Function\n ) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (\n !parentTransaction ||\n parentTransaction.db !== this ||\n mode.indexOf('!') !== -1\n )\n parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode, storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map((table) => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string')\n throw new TypeError(\n 'Invalid table argument to Dexie.transaction(). Only Table or String are allowed'\n );\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == 'r' || mode === READONLY) idbMode = READONLY;\n else if (mode == 'rw' || mode == READWRITE) idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\n 'Invalid transaction mode: ' + mode\n );\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else\n throw new exceptions.SubTransaction(\n 'Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY'\n );\n }\n if (parentTransaction) {\n storeNames.forEach((storeName) => {\n if (\n parentTransaction &&\n parentTransaction.storeNames.indexOf(storeName) === -1\n ) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else\n throw new exceptions.SubTransaction(\n 'Table ' + storeName + ' not included in parent transaction.'\n );\n }\n });\n }\n if (\n onlyIfCompatible &&\n parentTransaction &&\n !parentTransaction.active\n ) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction\n ? parentTransaction._promise(null, (_, reject) => {\n reject(e);\n })\n : rejection(e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(\n null,\n this,\n idbMode,\n storeNames,\n parentTransaction,\n scopeFunc\n );\n return parentTransaction\n ? parentTransaction._promise(idbMode, enterTransaction, 'lock')\n : PSD.trans\n ? // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, () => this._whenReady(enterTransaction))\n : this._whenReady(enterTransaction);\n }\n\n table(tableName: string): Table;\n table<T, TKey extends IndexableType = IndexableType>(\n tableName: string\n ): ITable<T, TKey>;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`);\n }\n return this._allTables[tableName];\n }\n}\n","import {\n Observable as IObservable,\n Observer,\n Subscription,\n} from '../../public/types/observable';\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== 'undefined' && 'observable' in Symbol\n ? Symbol.observable\n : ('@@observable' as any);\n\nexport class Observable<T> implements IObservable<T> {\n private _subscribe: (observer: Observer<T>) => Subscription;\n hasValue?: () => boolean;\n getValue?: () => T;\n\n constructor(subscribe: (observer: Observer<T>) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer<T> | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === 'function' ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies;\n\ntry {\n domDeps = {\n // Required:\n indexedDB:\n _global.indexedDB ||\n _global.mozIndexedDB ||\n _global.webkitIndexedDB ||\n _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange,\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import {\n _global,\n isAsyncFunction,\n keys,\n objectIsEmpty,\n} from '../functions/utils';\nimport {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport {\n beginMicroTickScope,\n decrementExpectedAwaits,\n endMicroTickScope,\n execInGlobalContext,\n incrementExpectedAwaits,\n NativePromise,\n newScope,\n PSD,\n usePSD,\n} from '../helpers/promise';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n Observable as IObservable,\n Subscription,\n} from '../public/types/observable';\nimport { Observable } from '../classes/observable/observable';\nimport { extendObservabilitySet } from './extend-observability-set';\nimport { rangesOverlap } from '../helpers/rangeset';\nimport { domDeps } from '../classes/dexie/dexie-dom-dependencies';\nimport { Transaction } from '../classes/transaction';\nimport { obsSetsOverlap } from './obs-sets-overlap';\n\nexport interface LiveQueryContext {\n subscr: ObservabilitySet;\n signal: AbortSignal;\n requery: () => void;\n trans: null | Transaction;\n querier: Function; // For debugging purposes and Error messages\n}\n\nexport function liveQuery<T>(querier: () => T | Promise<T>): IObservable<T> {\n let hasValue = false;\n let currentValue: T;\n const observable = new Observable<T>((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx: LiveQueryContext) {\n const wasRootExec = beginMicroTickScope(); // Performance: Avoid starting a new microtick scope within the async context.\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n let rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n // Make sure to set rv = rv.finally in order to wait to after decrementExpectedAwaits() has been called.\n // This fixes zone leaking issue that the liveQuery zone can leak to observer's next microtask.\n rv = (rv as Promise<any>).finally(decrementExpectedAwaits);\n }\n return rv;\n } finally {\n wasRootExec && endMicroTickScope(); // Given that we created the microtick scope, we must also end it.\n }\n }\n\n let closed = false;\n let abortController: AbortController;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n if (closed) return;\n closed = true;\n if (abortController) abortController.abort();\n if (startedListening)\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let startedListening = false;\n\n const doQuery = () => execInGlobalContext(_doQuery);\n\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const _doQuery = () => {\n if (\n closed || // closed - don't run!\n !domDeps.indexedDB\n ) // SSR in sveltekit, nextjs etc\n {\n return;\n }\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n // Abort signal fill three purposes:\n // 1. Abort the query if the observable is unsubscribed.\n // 2. Abort the query if a new query is made before the previous one has completed.\n // 3. For cached queries to know if they should remain in memory or could be enqued for being freed up.\n // (they will remain in memory for a short time and if noone needs them again, they will eventually be freed up)\n if (abortController) abortController.abort(); // Cancel previous query. Last query will be cancelled on unsubscribe().\n abortController = new AbortController();\n\n const ctx: LiveQueryContext = {\n subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier,\n trans: null, // Make the scope transactionless (don't reuse transaction from outer scope of the caller of subscribe())\n };\n const ret = execute(ctx);\n\n // Register mutation listener before the async gap so that storagemutated\n // events that fire while the query is blocked (e.g. by a long rw transaction)\n // are captured in accumMuts. shouldNotify() is safe to call with empty\n // currentObs — it will return false, just accumulating mutations until the\n // query completes and populates currentObs.\n if (!startedListening) {\n globalEvents.storagemutated.subscribe(mutationListener);\n startedListening = true;\n }\n\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n // closed - no subscriber anymore.\n // signal.aborted - new query was made before this one completed and\n // the querier might have catched AbortError and return successful result.\n // If so, we should not rely in that result because we know we have aborted\n // this run, which means there's another run going on that will handle accumMuts\n // and we must not base currentObs on the half-baked subscr.\n return;\n }\n // Check if mutations arrived during the query that overlap with the\n // OLD observation set. If so, re-query immediately.\n if (shouldNotify()) {\n doQuery();\n } else {\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n // Re-check with the NEW observation set — mutations that arrived during\n // the query might overlap with tables we now care about but didn't before.\n if (shouldNotify()) {\n doQuery();\n } else {\n accumMuts = {};\n execInGlobalContext(\n () => !closed && observer.next && observer.next(result)\n );\n }\n }\n },\n (err) => {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err?.name)) {\n if (!closed)\n execInGlobalContext(() => {\n if (closed) return;\n observer.error && observer.error(err);\n });\n }\n }\n );\n };\n\n // Use setTimeot here to guarantee execution in a private macro task before and\n // after. The helper executeInGlobalContext(_doQuery) is not enough here because\n // caller of `subscribe()` could be anything, such as a frontend framework that will\n // continue in the same tick after subscribe() is called and call other\n // eftects, that could involve dexie operations such as writing to the DB.\n // If that happens, the private zone echoes from a live query tast started here\n // could still be ongoing when the other operations start and make them inherit\n // the async context from a live query.\n setTimeout(doQuery, 0);\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport {\n props,\n derive,\n extend,\n override,\n getByKeyPath,\n setByKeyPath,\n delByKeyPath,\n shallowClone,\n deepClone,\n asap,\n} from '../../functions/utils';\nimport { getObjectDiff } from '../../functions/get-object-diff';\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } from '../../helpers/database-enumerator';\nimport { PSD, globalPSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport {\n dexieStackFrameFilter,\n minKey,\n DEXIE_VERSION,\n} from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\nimport { cache } from '../../live-query/cache/cache';\nimport { connections } from '../../globals/connections';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n//\nprops(Dexie, {\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName, { addons: [] });\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] })\n .open()\n .then((db) => {\n db.close();\n return true;\n })\n .catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans\n ? usePSD(PSD.transless || globalPSD, scopeFunc) // Use the closest parent that was non-transactional.\n : scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null,\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function'\n ? Dexie.ignoreTransaction(promiseOrFunction)\n : promiseOrFunction\n ).timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required.\n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ? PSD.trans.waitFor(promise) : promise;\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: (value) => {\n Debug.setDebug(\n value,\n value === 'dexie' ? () => true : dexieStackFrameFilter\n );\n },\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap,\n //maxKey: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: {\n get: connections.toArray,\n },\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: domDeps,\n cache,\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map((n) => parseInt(n))\n .reduce((p, c, i) => p + c / Math.pow(10, i * 2)),\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n // default: Dexie, // Commented because solved in index-umd.ts instead.\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n // Dexie: Dexie // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n} from '../globals/global-events';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport { signalSubscribersNow } from './cache/signalSubscribers';\n\nif (\n typeof dispatchEvent !== 'undefined' &&\n typeof addEventListener !== 'undefined'\n) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (updatedParts) => {\n if (!propagatingLocally) {\n let event: CustomEvent<ObservabilitySet>;\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts,\n });\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n ({ detail }: CustomEvent<ObservabilitySet>) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n }\n );\n}\n\n/** Called from listeners to BroadcastChannel and DOM event to\n * propagate the event locally into dexie's storagemutated event\n * and invalidate cached queries.\n *\n * This function is only called when the event is not originating\n * from this same Dexie module - either from another redundant dexie import\n * or from a foreign tab or worker. That's why we need to invalidate\n * the cache when this happens.\n */\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n // Fire the \"storagemutated\" event.\n globalEvents.storagemutated.fire(updateParts);\n // Invalidate cached queries and signal subscribers to requery.\n signalSubscribersNow(updateParts, true);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nexport let bc: BroadcastChannel;\n\nexport let createBC = () => {};\n\nif (typeof BroadcastChannel !== 'undefined') {\n createBC = () => {\n bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n bc.onmessage = (ev) => ev.data && propagateLocally(ev.data);\n };\n createBC();\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n }\n\n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n}\n","import { Dexie } from './classes/dexie';\nimport { connections } from './globals/connections';\nimport { debug } from './helpers/debug';\nimport { RangeSet } from './helpers/rangeset';\nimport { bc, createBC } from './live-query/enable-broadcast';\nimport { propagateLocally } from './live-query/propagate-locally';\n\nif (typeof addEventListener !== 'undefined') {\n addEventListener('pagehide', (event) => {\n if (!Dexie.disableBfCache && event.persisted) {\n if (debug) console.debug('Dexie: handling persisted pagehide');\n bc?.close();\n for (const db of connections.toArray()) {\n db.close({ disableAutoOpen: false });\n }\n }\n });\n addEventListener('pageshow', (event) => {\n if (!Dexie.disableBfCache && event.persisted) {\n if (debug) console.debug('Dexie: handling persisted pageshow');\n createBC();\n propagateLocally({ all: new RangeSet(-Infinity, [[]]) }); // Trigger all queries to requery\n }\n });\n}\n","import { PropModification } from '../../helpers/prop-modification';\n\nexport function add(value: number | bigint | Array<string | number>) {\n return new PropModification({ add: value });\n}\n","import { PropModification } from '../../helpers/prop-modification';\n\nexport function remove(value: number | bigint | Array<string | number>) {\n return new PropModification({ remove: value });\n}\n","import { PropModification } from '../../helpers/prop-modification';\n\nexport function replacePrefix(a: string, b: string) {\n return new PropModification({ replacePrefix: [a, b] });\n}\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport {\n dexieStackFrameFilter,\n DEFAULT_MAX_CONNECTIONS,\n} from './globals/constants';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport './support-bfcache';\nimport { liveQuery } from './live-query/live-query';\nimport { Entity } from './classes/entity/Entity';\nimport { cmp } from './functions/cmp';\nimport { PropModification } from './helpers/prop-modification';\nimport { replacePrefix, add, remove } from './functions/propmods';\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport { RangeSet, mergeRanges, rangesOverlap } from './helpers/rangeset';\nexport { Dexie, liveQuery, DEFAULT_MAX_CONNECTIONS }; // Comply with public/index.d.ts.\nexport { Entity };\nexport { cmp };\nexport { PropModification, replacePrefix, add, remove };\nexport default Dexie;\n","// Issue #1127. Need another index.ts for the UMD module with only a default export\n// like it was before.\n// In practice though, the UMD export will also export the named export in\n// https://github.com/dfahlander/Dexie.js/blob/c9187ae60c0d7a424f85bab3af179fbbc9901c8e/src/classes/dexie/dexie-static-props.ts#L223-L228\nimport Dexie from './index';\nimport * as namedExports from './index';\nimport { __assign } from 'tslib';\n__assign(Dexie, namedExports, { default: Dexie });\nexport default Dexie;\n","// settings & const\nconst PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nconst supportsRequestInitExt = () => {\n return (\n typeof process === \"object\" &&\n Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&\n process.versions.undici\n );\n};\n\n/**\n * Returns a cheap, non-cryptographically-secure random ID\n * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)\n */\nexport function randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\n\n/**\n * Create an openapi-fetch client.\n * @type {import(\"./index.js\").default}\n */\nexport default function createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = undefined,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n\n /**\n * Per-request fetch (keeps settings created in createClient()\n * @param {T} url\n * @param {import('./index.js').FetchOptions<T>} fetchOptions\n */\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n\n let querySerializer =\n typeof globalQuerySerializer === \"function\"\n ? globalQuerySerializer\n : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer =\n typeof requestQuerySerializer === \"function\"\n ? requestQuerySerializer\n : createQuerySerializer({\n ...(typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {}),\n ...requestQuerySerializer,\n });\n }\n\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n\n const serializedBody =\n body === undefined\n ? undefined\n : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header),\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === undefined ||\n // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData\n ? {}\n : {\n \"Content-Type\": \"application/json\",\n },\n baseHeaders,\n headers,\n params.header,\n );\n\n // Client level middleware take priority over request-level middleware\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders,\n };\n\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit,\n );\n let response;\n\n /** Add custom parameters to Request object */\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n\n if (finalMiddlewares.length) {\n id = randomID();\n\n // middleware (request)\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer,\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n\n if (!response) {\n // fetch!\n try {\n response = await fetch(request, requestInitExt);\n } catch (error) {\n let errorAfterMiddleware = error;\n // middleware (error)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n // if error is handled by returning a response, skip remaining middleware\n if (result instanceof Response) {\n errorAfterMiddleware = undefined;\n response = result;\n break;\n }\n\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n\n // rethrow error if not handled by middleware\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n\n // middleware (response)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n\n const contentLength = response.headers.get(\"Content-Length\");\n // handle empty content\n if (\n response.status === 204 ||\n request.method === \"HEAD\" ||\n (contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\"))\n ) {\n return response.ok ? { data: undefined, response } : { error: undefined, response };\n }\n\n // parse response (falling back to .text() when necessary)\n if (response.ok) {\n const getResponseData = async () => {\n // if \"stream\", skip parsing entirely\n if (parseAs === \"stream\") {\n return response.body;\n }\n\n if (parseAs === \"json\" && !contentLength) {\n // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)\n const raw = await response.text();\n return raw ? JSON.parse(raw) : undefined;\n }\n\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n\n // handle errors\n let error = await response.text();\n try {\n error = JSON.parse(error); // attempt to parse as JSON\n } catch {\n // noop\n }\n return { error, response };\n }\n\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n },\n };\n}\n\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\n\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\n\n/**\n * Wrap openapi-fetch client to support a path based API.\n * @type {import(\"./index.js\").wrapAsPathBasedClient}\n */\nexport function wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n\n // Put the proxy on the prototype chain of the actual client.\n // This means if we do not have a memoized PathCallForwarder,\n // we fall back to the proxy to synthesize it.\n // However, the proxy itself is not on the hot-path (if we fetch the same\n // endpoint multiple times, only the first call will hit the proxy).\n function Client() {}\n Client.prototype = proxy;\n\n const client = new Client();\n\n // Feed the client back to the proxy handler so it can store the generated\n // PathCallForwarder.\n handler.client = client;\n\n return client;\n}\n\n/**\n * Convenience method to an openapi-fetch path based client.\n * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.\n * @type {import(\"./index.js\").createPathBasedClient}\n */\nexport function createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\n\n// utils\n\n/**\n * Serialize primitive param values\n * @type {import(\"./index.js\").serializePrimitiveParam}\n */\nexport function serializePrimitiveParam(name, value, options) {\n if (value === undefined || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.\",\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\n\n/**\n * Serialize object param (shallow only)\n * @type {import(\"./index.js\").serializeObjectParam}\n */\nexport function serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner =\n {\n simple: \",\",\n label: \".\",\n matrix: \";\",\n }[options.style] || \"&\";\n\n // explode: false\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final = values.join(\",\"); // note: values are always joined by comma in explode: false (but joiner can prefix)\n switch (options.style) {\n case \"form\": {\n return `${name}=${final}`;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n default: {\n return final;\n }\n }\n }\n\n // explode: true\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\n\n/**\n * Serialize array param (shallow only)\n * @type {import(\"./index.js\").serializeArrayParam}\n */\nexport function serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n\n // explode: false\n if (options.explode === false) {\n const joiner = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\"; // note: for arrays, joiners vary wildly based on style + explode behavior\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n\n // explode: true\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\"\n ? `${joiner}${values.join(joiner)}`\n : values.join(joiner);\n}\n\n/**\n * Serialize query params to string\n * @type {import(\"./index.js\").createQuerySerializer}\n */\nexport function createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\n\n/**\n * Handle different OpenAPI 3.x serialization styles\n * @type {import(\"./index.js\").defaultPathSerializer}\n * @see https://swagger.io/docs/specification/serialization/#path\n */\nexport function defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\n\n/**\n * Serialize body object to string\n * @type {import(\"./index.js\").defaultBodySerializer}\n */\nexport function defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType =\n headers.get instanceof Function\n ? (headers.get(\"Content-Type\") ?? headers.get(\"content-type\"))\n : (headers[\"Content-Type\"] ?? headers[\"content-type\"]);\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\n\n/**\n * Construct URL string from baseUrl and handle path and query params\n * @type {import(\"./index.js\").createFinalURL}\n */\nexport function createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\n\n/**\n * Merge headers a and b, with b taking priority\n * @type {import(\"./index.js\").mergeHeaders}\n */\nexport function mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== undefined) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\n\n/**\n * Remove trailing slash from url\n * @type {import(\"./index.js\").removeTrailingSlash}\n */\nexport function removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n","import createClient from \"openapi-fetch\";\nimport type { components, paths } from \"../generated/api.js\";\nimport { PROTOCOL_HEADERS } from \"../protocol.js\";\nimport { CLIENT_AGENT } from \"../version.js\";\n\nexport type ApiClient = ReturnType<typeof createClient<paths>>;\n\nexport type { paths, components };\n\n// Re-export commonly used types for convenience\nexport type TokenId = components[\"schemas\"][\"TokenId\"];\nexport type TokenInfo = components[\"schemas\"][\"TokenInfo\"];\nexport type TokenInfos = components[\"schemas\"][\"TokenInfos\"];\nexport type SwapStatus = components[\"schemas\"][\"SwapStatus\"];\nexport type ServiceStatus = components[\"schemas\"][\"ServiceStatus\"];\nexport type StatusResponse = components[\"schemas\"][\"StatusResponse\"];\nexport type GetSwapResponse = components[\"schemas\"][\"GetSwapResponse\"];\nexport type BulkStatusRequest = components[\"schemas\"][\"BulkStatusRequest\"];\nexport type BulkStatusResponse = components[\"schemas\"][\"BulkStatusResponse\"];\nexport type SwapStatusEntry = components[\"schemas\"][\"SwapStatusEntry\"];\nexport type BtcToArkadeSwapResponse =\n components[\"schemas\"][\"BtcToArkadeSwapResponse\"];\nexport type EvmToArkadeSwapResponse =\n components[\"schemas\"][\"EvmToArkadeSwapResponse\"];\n\n// Gasless claim types\nexport type ClaimGaslessRequest = components[\"schemas\"][\"ClaimGaslessRequest\"];\nexport type ClaimGaslessResponse =\n components[\"schemas\"][\"ClaimGaslessResponse\"];\nexport type RedeemAndSwapResponse =\n components[\"schemas\"][\"RedeemAndSwapResponse\"];\n\n// Arkade-to-EVM (generic endpoint) types\nexport type ArkadeToEvmSwapRequest =\n components[\"schemas\"][\"ArkadeToEvmSwapRequest\"];\nexport type ArkadeToEvmSwapResponse =\n components[\"schemas\"][\"ArkadeToEvmSwapResponse\"];\nexport type DexCallData = components[\"schemas\"][\"DexCallData\"];\n\n// Bitcoin-to-EVM (generic endpoint) types\nexport type BitcoinToEvmSwapRequest =\n components[\"schemas\"][\"BitcoinToEvmSwapRequest\"];\nexport type BitcoinToEvmSwapResponse =\n components[\"schemas\"][\"BitcoinToEvmSwapResponse\"];\n\n// EVM-to-Arkade (generic endpoint) types\nexport type EvmToArkadeGenericSwapRequest =\n components[\"schemas\"][\"EvmToArkadeGenericSwapRequest\"];\n\n// EVM-to-Lightning types\nexport type EvmToLightningSwapRequest =\n components[\"schemas\"][\"EvmToLightningSwapRequest\"];\nexport type EvmToLightningSwapResponse =\n components[\"schemas\"][\"EvmToLightningSwapResponse\"];\n\n// EVM-to-Bitcoin (generic endpoint) types\nexport type EvmToBitcoinSwapRequest =\n components[\"schemas\"][\"EvmToBitcoinSwapRequest\"];\nexport type EvmToBitcoinSwapResponse =\n components[\"schemas\"][\"EvmToBitcoinSwapResponse\"];\n\n// Lightning-to-Arkade types\nexport type LightningToArkadeSwapResponse =\n components[\"schemas\"][\"LightningToArkadeSwapResponse\"];\nexport type LightningToEvmSwapResponse =\n components[\"schemas\"][\"LightningToEvmSwapResponse\"];\n\n// Arkade-to-Lightning types\nexport type ArkadeToLightningSwapResponse =\n components[\"schemas\"][\"ArkadeToLightningSwapResponse\"];\n\n// Bitcoin-to-Lightning types\nexport type BitcoinToLightningSwapResponse =\n components[\"schemas\"][\"BitcoinToLightningSwapResponse\"];\n\n// Lightning-to-Bitcoin types\nexport type LightningToBitcoinSwapResponse =\n components[\"schemas\"][\"LightningToBitcoinSwapResponse\"];\n\n// `SwapPairInfo`, `SwapPairsResponse`, `QuoteResponse`, `Chain`,\n// `Token`, `TokenAmount`, `DexQuote*`, and `NetworkFee*` are now\n// hand-written in `../types/`. Don't re-export them here — the SDK's\n// public type surface is the hand-written module, not the OpenAPI\n// codegen.\n\nexport interface ApiClientOptions {\n baseUrl: string;\n defaultHeaders?: Record<string, string>;\n}\n\nexport function createApiClient(options: ApiClientOptions): ApiClient {\n const headers: Record<string, string> = {\n \"X-Lendaswap-Client\": CLIENT_AGENT,\n ...PROTOCOL_HEADERS,\n ...(options.defaultHeaders ?? {}),\n };\n\n return createClient<paths>({\n baseUrl: options.baseUrl,\n headers,\n });\n}\n","/**\n * Arkade VHTLC query utilities.\n *\n * Provides functions for querying VHTLC state from the Arkade indexer.\n */\n\nimport {\n ArkAddress,\n type IndexerProvider,\n RestIndexerProvider,\n} from \"@arkade-os/sdk\";\nimport { hex } from \"@scure/base\";\n\nimport { resolveArkadeServerUrl } from \"./arkade-network.js\";\n\n/** Overall VTXO lifecycle status */\nexport type VtxoStatus =\n | \"not_funded\"\n | \"spendable\"\n | \"recoverable\"\n | \"spent\"\n | \"mixed\";\n\n/** VHTLC amounts breakdown */\nexport interface VhtlcAmounts {\n /** Amount that can be spent (in satoshis) */\n spendable: number;\n /** Amount already spent (in satoshis) */\n spent: number;\n /** Amount that can be recovered via refund (in satoshis) */\n recoverable: number;\n /** Overall status derived from VTXO states */\n vtxoStatus: VtxoStatus;\n}\n\n/** Parameters for querying VHTLC amounts */\nexport interface GetVhtlcAmountsParams {\n /** The Arkade VHTLC address */\n vhtlcAddress: string;\n /** The Bitcoin network (e.g. \"bitcoin\", \"signet\") */\n network: string;\n /** Optional Arkade server URL override. Falls back to network-based defaults. */\n arkadeServerUrl?: string;\n}\n\n/**\n * Queries the Arkade indexer for spendable, spent, and recoverable balances\n * at a VHTLC address.\n *\n * @param params - The VHTLC address and network to query.\n * @returns The VHTLC amounts in satoshis.\n */\nexport async function getVhtlcAmounts(\n params: GetVhtlcAmountsParams,\n): Promise<VhtlcAmounts> {\n const { vhtlcAddress, network, arkadeServerUrl } = params;\n\n // Decode the Arkade address to get the pkScript for indexer queries\n const decoded = ArkAddress.decode(vhtlcAddress);\n const pkScript = hex.encode(decoded.pkScript);\n\n // Determine Arkade server URL: explicit override > network default\n const serverUrl = resolveArkadeServerUrl(network, arkadeServerUrl);\n\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n\n // Query each category separately\n const [spendableResult, spentResult, recoverableResult] = await Promise.all([\n indexerProvider.getVtxos({ scripts: [pkScript], spendableOnly: true }),\n indexerProvider.getVtxos({ scripts: [pkScript], spentOnly: true }),\n indexerProvider.getVtxos({ scripts: [pkScript], recoverableOnly: true }),\n ]);\n\n const sum = (vtxos: { value: number }[]) =>\n vtxos.reduce((acc, v) => acc + v.value, 0);\n\n // The indexer's spendableOnly filter doesn't account for expired batches.\n // A preconfirmed VTXO with batchExpiry in the past is effectively expired\n // and can only be spent via delegated settlement, not offchain spend.\n // Reclassify such VTXOs from spendable to recoverable.\n const now = Date.now();\n let actualSpendable = 0;\n let expiredSpendable = 0;\n for (const v of spendableResult.vtxos) {\n const expiry = v.expiresAt?.getTime();\n // A zero/NaN expiry means \"no expiry\", not \"expired at epoch 0\".\n if (expiry !== undefined && expiry > 0 && expiry <= now) {\n expiredSpendable += v.value;\n } else {\n actualSpendable += v.value;\n }\n }\n\n const spendable = actualSpendable;\n const spent = sum(spentResult.vtxos);\n const recoverable = sum(recoverableResult.vtxos) + expiredSpendable;\n\n const vtxoStatus: VtxoStatus =\n spendable === 0 && spent === 0 && recoverable === 0\n ? \"not_funded\"\n : spendable > 0 && recoverable > 0\n ? \"mixed\"\n : spendable > 0\n ? \"spendable\"\n : recoverable > 0\n ? \"recoverable\"\n : \"spent\";\n\n return { spendable, spent, recoverable, vtxoStatus };\n}\n","/**\n * Arkade address parsing and validation.\n *\n * Used to reject malformed destination addresses before a swap is created,\n * mirroring the server-side check.\n */\n\nimport { ArkAddress } from \"@arkade-os/sdk\";\nimport { getNetworkHrp, getNetworkName } from \"./arkade-network.js\";\n\n/** Bech32m prefixes for Arkade addresses: `ark` (mainnet) and `tark` (test networks). */\nconst ARKADE_HRPS = [\"ark\", \"tark\"];\n\n/**\n * Parses an Arkade address, throwing a descriptive error if it is not a\n * well-formed bech32m Ark address (`ark1...` / `tark1...`).\n *\n * @param address - The Arkade address to parse.\n * @param network - Optional network name (e.g. \"bitcoin\", \"signet\",\n * \"mutinynet\"). When provided, the address prefix must match the network;\n * otherwise any known Arkade prefix is accepted.\n * @returns The decoded {@link ArkAddress}.\n * @throws Error if the address is malformed or on the wrong network.\n */\nexport function parseArkadeAddress(\n address: string,\n network?: string,\n): ArkAddress {\n let decoded: ArkAddress;\n try {\n decoded = ArkAddress.decode(address);\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e);\n throw new Error(`Invalid Arkade address: ${reason}`);\n }\n\n if (network !== undefined) {\n const expectedHrp = getNetworkHrp(getNetworkName(network));\n if (decoded.hrp !== expectedHrp) {\n throw new Error(\n `Arkade address has wrong network: expected \"${expectedHrp}1...\" prefix, got \"${decoded.hrp}1...\"`,\n );\n }\n } else if (!ARKADE_HRPS.includes(decoded.hrp)) {\n throw new Error(`Invalid Arkade address: unknown prefix \"${decoded.hrp}1\"`);\n }\n\n return decoded;\n}\n\n/**\n * Returns whether the given string is a well-formed Arkade address.\n *\n * @param address - The Arkade address to validate.\n * @param network - Optional network name; when provided the prefix must match.\n */\nexport function isValidArkadeAddress(\n address: string,\n network?: string,\n): boolean {\n try {\n parseArkadeAddress(address, network);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * The little of BOLT 11 the SDK needs: an invoice's payment hash, read from\n * the `p` tagged field. Amount, expiry and routing stay the server's job.\n *\n * The signature is not checked: the party being checked is the server, which\n * signs whatever invoice it issues, and the paying wallet verifies the\n * signature itself. What matters is the hash that wallet commits to.\n */\n\nimport { bech32 } from \"@scure/base\";\n\nconst TAG_PAYMENT_HASH = 1;\nconst TIMESTAMP_WORDS = 7;\nconst SIGNATURE_WORDS = 104;\nconst PAYMENT_HASH_WORDS = 52;\n\n/**\n * The payment hash of a BOLT 11 invoice as 0x-prefixed lowercase hex.\n *\n * Read the way LDK reads it, which is what the swap server parses with: a `p`\n * field of any length other than 52 words is skipped, a second 52-word `p`\n * field is refused (LND would pay the first, LDK refuses the invoice, so the\n * two could disagree on the hash), and the 52 words give 260 bits of which\n * the first 256 are the hash.\n *\n * Accepts a `lightning:` prefix and mixed case. Throws when the string is\n * not a bech32 Lightning invoice, a tagged field runs past the signature, or\n * there is not exactly one payment hash.\n */\nexport function invoicePaymentHash(invoice: string): string {\n const value = invoice\n .trim()\n .replace(/^lightning:/i, \"\")\n .toLowerCase();\n if (!/^ln[a-z0-9]+1[02-9ac-hj-np-z]+$/.test(value)) {\n throw new Error(\"Not a Lightning invoice\");\n }\n let words: number[];\n try {\n ({ words } = bech32.decode(value as `${string}1${string}`, false));\n } catch (e) {\n throw new Error(`Not a Lightning invoice: ${(e as Error).message}`);\n }\n if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS) {\n throw new Error(\"Lightning invoice is too short\");\n }\n // Timestamp, then tagged fields `type(1) length(2) data(length)`, then\n // the signature.\n const fields = words.slice(TIMESTAMP_WORDS, words.length - SIGNATURE_WORDS);\n let paymentHash: string | undefined;\n let i = 0;\n while (i < fields.length) {\n if (i + 3 > fields.length) {\n throw new Error(\"Lightning invoice has a truncated tagged field\");\n }\n const tag = fields[i];\n const length = (fields[i + 1] << 5) | fields[i + 2];\n const start = i + 3;\n if (start + length > fields.length) {\n throw new Error(\"Lightning invoice has a truncated tagged field\");\n }\n if (tag === TAG_PAYMENT_HASH && length === PAYMENT_HASH_WORDS) {\n if (paymentHash !== undefined) {\n throw new Error(\"Lightning invoice carries more than one payment hash\");\n }\n paymentHash = first32Bytes(fields.slice(start, start + length));\n }\n i = start + length;\n }\n if (paymentHash === undefined) {\n throw new Error(\"Lightning invoice carries no payment hash\");\n }\n return `0x${paymentHash}`;\n}\n\n/** The first 32 bytes packed from 5-bit words, as hex; the rest is dropped. */\nfunction first32Bytes(words: number[]): string {\n const bytes: number[] = [];\n let acc = 0;\n let bits = 0;\n for (const word of words) {\n acc = (acc << 5) | word;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n if (bytes.length < 32) bytes.push((acc >> bits) & 0xff);\n }\n acc &= (1 << bits) - 1;\n }\n return bytes.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * The amount a BOLT 11 invoice asks for, in millisatoshis, read from its\n * human-readable part; undefined for an invoice without an amount.\n */\nexport function invoiceAmountMsat(invoice: string): bigint | undefined {\n const value = invoice\n .trim()\n .replace(/^lightning:/i, \"\")\n .toLowerCase();\n const separator = value.lastIndexOf(\"1\");\n const match = /^ln(?:bcrt|tbs|bc|tb|sb)(\\d*)([munp]?)$/.exec(\n value.slice(0, separator),\n );\n if (!match) throw new Error(\"Not a Lightning invoice\");\n const [, digits, multiplier] = match;\n if (digits === \"\") return undefined;\n // 1 BTC = 10^11 msat; each multiplier divides it further.\n const amount = BigInt(digits);\n switch (multiplier) {\n case \"\":\n return amount * 100_000_000_000n;\n case \"m\":\n return amount * 100_000_000n;\n case \"u\":\n return amount * 100_000n;\n case \"n\":\n return amount * 100n;\n case \"p\":\n if (amount % 10n !== 0n) {\n throw new Error(\"Invoice amount is not a whole millisatoshi\");\n }\n return amount / 10n;\n }\n throw new Error(\"Not a Lightning invoice\");\n}\n","/**\n * CCTP v2 fast-transfer fee query against Circle's IRIS API.\n *\n * The fast-transfer fee (`minimumFee`, in basis points × 100) is deducted\n * from the minted amount on the destination chain whenever the burn's\n * `minFinalityThreshold ≤ 1000`. We need to query it to know precisely\n * how much USDC will arrive so the Permit2 signature pulls the right\n * amount and the Multicall doesn't underflow.\n *\n * Mirrors the Rust backend's `swap/src/cctp.rs::compute_max_fee`.\n */\nimport { FINALITY_FAST, IRIS_API_MAINNET } from \"./constants.js\";\n\n/** Fee tiers returned by the IRIS API (low/med/high gas estimates for the forwarder). */\nexport interface IrisForwardFeeTiers {\n low: number;\n med: number;\n high: number;\n}\n\n/** Raw entry from `GET /v2/burn/USDC/fees/{sourceDomain}/{destDomain}`. */\nexport interface IrisFeeEntry {\n finalityThreshold: number;\n /** CCTPv2 fast-transfer fee in basis points (e.g. `1.3` = 0.013%). */\n minimumFee: number;\n /** Forward-service relayer fees (absolute USDC smallest-units). */\n forwardFee: IrisForwardFeeTiers;\n}\n\nexport interface FetchCctpFeeOptions {\n /** CCTP source domain ID (e.g. 2 = Optimism, 6 = Base). */\n sourceDomain: number;\n /** CCTP destination domain ID (3 = Arbitrum). */\n destinationDomain: number;\n /** Finality threshold to query — defaults to `FINALITY_FAST` (1000). */\n finalityThreshold?: number;\n /** IRIS API base URL. Defaults to mainnet. */\n irisApiUrl?: string;\n /** Optional abort signal. */\n signal?: AbortSignal;\n}\n\n/**\n * Fetch the fee entry for the given source → destination pair and\n * finality threshold. Returns the raw IRIS shape — callers that want\n * an applied maxFee should pass this to {@link computeCctpFastFee}.\n */\nexport async function fetchCctpFee(\n options: FetchCctpFeeOptions,\n): Promise<IrisFeeEntry> {\n const {\n sourceDomain,\n destinationDomain,\n finalityThreshold = FINALITY_FAST,\n irisApiUrl = IRIS_API_MAINNET,\n signal,\n } = options;\n\n const url = `${irisApiUrl}/v2/burn/USDC/fees/${sourceDomain}/${destinationDomain}?forward=true`;\n const response = await fetch(url, { signal });\n if (!response.ok) {\n throw new Error(\n `IRIS fee lookup failed: ${response.status} ${response.statusText}`,\n );\n }\n const entries = (await response.json()) as IrisFeeEntry[];\n const entry =\n entries.find((e) => e.finalityThreshold === finalityThreshold) ??\n entries[0];\n if (!entry) {\n throw new Error(\n `IRIS returned no fee entries for ${sourceDomain}→${destinationDomain}`,\n );\n }\n return entry;\n}\n\n/**\n * Tiny TTL cache for CCTP fee lookups. The IRIS fee is effectively\n * constant per-pair minute-to-minute — re-fetching on every quote\n * keystroke would bomb IRIS for no gain. 60s TTL is ample.\n */\nconst feeCache = new Map<string, { entry: IrisFeeEntry; expiresAt: number }>();\nconst FEE_CACHE_TTL_MS = 60_000;\n\n/**\n * Cached variant of {@link fetchCctpFee}. Multiple callers within a\n * 60-second window share a single IRIS round-trip per source→dest pair.\n */\nexport async function getCachedCctpFee(\n options: FetchCctpFeeOptions,\n): Promise<IrisFeeEntry> {\n const {\n sourceDomain,\n destinationDomain,\n finalityThreshold = FINALITY_FAST,\n irisApiUrl = IRIS_API_MAINNET,\n } = options;\n const key = `${sourceDomain}-${destinationDomain}-${finalityThreshold}-${irisApiUrl}`;\n const cached = feeCache.get(key);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.entry;\n }\n const entry = await fetchCctpFee(options);\n feeCache.set(key, { entry, expiresAt: Date.now() + FEE_CACHE_TTL_MS });\n return entry;\n}\n\n/**\n * Apply IRIS's `minimumFee` (basis points) to an amount in USDC smallest\n * units, matching the Rust backend's formula:\n * protocolFee = amount × round(minimumFee × 100) ÷ 1_000_000\n *\n * Adds a conservative 20% buffer to absorb rounding drift between quote\n * time and burn time. Return value is the fee in USDC smallest units,\n * suitable for `maxFee` in `depositForBurn` and as the subtracted amount\n * when sizing the Permit2 permit.\n */\nexport function computeCctpFastFee(\n entry: IrisFeeEntry,\n amountUsdcUnits: bigint,\n): bigint {\n const bpsScaled = Math.round(entry.minimumFee * 100);\n const protocolFee = (amountUsdcUnits * BigInt(bpsScaled)) / 1_000_000n;\n return (protocolFee * 120n) / 100n;\n}\n","/**\n * CCTP utility functions.\n */\n\nimport { base58 } from \"@scure/base\";\nimport { CCTP_DOMAINS, type CctpChainName } from \"./constants.js\";\n\n/**\n * Convert an EVM address to CCTP's bytes32 format (left-padded with zeros).\n * @param address - 0x-prefixed hex address (20 bytes)\n * @returns 0x-prefixed bytes32 hex string (32 bytes)\n */\nexport function addressToBytes32(address: string): string {\n const clean = address.toLowerCase().replace(\"0x\", \"\");\n if (clean.length !== 40) {\n throw new Error(\n `Invalid address length: expected 40 hex chars, got ${clean.length}`,\n );\n }\n return `0x${clean.padStart(64, \"0\")}`;\n}\n\n/**\n * Convert a CCTP bytes32 back to an EVM address.\n * @param bytes32 - 0x-prefixed bytes32 hex string\n * @returns 0x-prefixed checksummed address\n */\nexport function bytes32ToAddress(bytes32: string): string {\n const clean = bytes32.replace(\"0x\", \"\");\n if (clean.length !== 64) {\n throw new Error(\n `Invalid bytes32 length: expected 64 hex chars, got ${clean.length}`,\n );\n }\n return `0x${clean.slice(24)}`;\n}\n\n/**\n * Get the CCTP domain ID for a chain name.\n * @param chainName - Chain name (e.g. \"Ethereum\", \"Polygon\", \"Arbitrum\")\n * @returns The CCTP domain ID, or undefined if not supported.\n */\nexport function getDomain(chainName: string): number | undefined {\n return CCTP_DOMAINS[chainName as CctpChainName];\n}\n\n/**\n * Check if two chains require CCTP bridging (i.e., they're different chains).\n * @param sourceChain - Source chain name\n * @param targetChain - Target chain name\n * @returns true if CCTP bridging is needed\n */\nexport function needsBridge(sourceChain: string, targetChain: string): boolean {\n if (sourceChain === targetChain) return false;\n const sourceDomain = getDomain(sourceChain);\n const targetDomain = getDomain(targetChain);\n return sourceDomain !== undefined && targetDomain !== undefined;\n}\n\n/**\n * Validate a Solana address. Solana pubkeys are base58-encoded 32-byte\n * values, typically 32-44 base58 characters. Cheap structural check —\n * does not verify on-curve / system-program semantics.\n */\nexport function isValidSolanaAddress(address: string): boolean {\n if (!address) return false;\n if (address.length < 32 || address.length > 44) return false;\n // Disallow base58-illegal characters early so we don't rely on the\n // decode throwing for obvious junk.\n if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(address)) return false;\n try {\n return base58.decode(address).length === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * Decode a base58-encoded Solana pubkey into CCTP's 32-byte recipient\n * format. Solana pubkeys are natively 32 bytes — no padding needed.\n *\n * Returns a `0x`-prefixed 64-character hex string (the bytes32 form\n * accepted by Circle's TokenMessenger `mintRecipient` field), so the\n * shape matches `addressToBytes32` for EVM addresses.\n */\nexport function solanaAddressToBytes32(address: string): string {\n const decoded = base58.decode(address);\n if (decoded.length !== 32) {\n throw new Error(\n `Solana pubkey must decode to 32 bytes, got ${decoded.length} for ${address}`,\n );\n }\n let hex = \"0x\";\n for (const byte of decoded) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n","/**\n * Source-chain USDC approve + burn for the CCTP-inbound flow.\n *\n * Handles the full source-chain leg in one call:\n * 1. Read current allowance via `EvmSigner.call`. If < `amount`,\n * send an `approve` and wait for its receipt.\n * 2. Call `TokenMessenger.depositForBurn(...)` with `mintRecipient`\n * and `destinationCaller` both pinned to the caller's\n * smart-account address.\n * 3. Return the tx hashes.\n *\n * Takes the SDK's `EvmSigner` so the same signer used for direct\n * Permit2 swaps (wagmi, Privy, raw key via the `evm/wallet` adapter)\n * also powers the CCTP flow.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, erc20Abi, parseAbi } from \"viem\";\nimport { FINALITY_FAST, TOKEN_MESSENGER_V2 } from \"../cctp/constants.js\";\nimport { addressToBytes32 } from \"../cctp/utils.js\";\nimport type { EvmSigner } from \"../evm/wallet.js\";\n\nconst TOKEN_MESSENGER_ABI = parseAbi([\n \"function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold) external returns (uint64)\",\n]);\n\nexport interface ApproveAndBurnParams {\n /** SDK signer bound to the source chain. */\n signer: EvmSigner;\n /** USDC amount in smallest units (6 decimals). */\n amount: bigint;\n /** USDC contract address on the source chain. */\n usdcAddress: Address;\n /** CCTP destination domain id (3 = Arbitrum mainnet). */\n destinationDomain: number;\n /**\n * The address that will both (a) receive the minted USDC on the\n * destination chain and (b) be the sole caller allowed to submit\n * `receiveMessage`. For the CCTP-inbound settlement flow this is\n * the caller's Kernel smart-account address.\n */\n smartAccountAddress: Address;\n /**\n * Max CCTPv2 fast-transfer fee in USDC units, from the IRIS fee API.\n * The caller is responsible for fetching this — typical value is\n * ~1/10000 of the amount.\n */\n maxFee: bigint;\n /**\n * CCTP finality threshold. Defaults to fast transfer (1000).\n * Use 2000 for standard (cheaper, ~13 minutes) transfers.\n */\n minFinalityThreshold?: number;\n /**\n * Override the TokenMessenger contract address. Defaults to the\n * canonical CCTPv2 deployment shared across all EVM chains.\n */\n tokenMessengerAddress?: Address;\n /**\n * When `true`, always send `approve` even if existing allowance is\n * sufficient. Defaults to `false` to avoid unnecessary txs.\n */\n forceApprove?: boolean;\n}\n\nexport interface ApproveAndBurnResult {\n /** Tx hash of the USDC approval; omitted when the existing allowance was sufficient. */\n approveTxHash?: Hex;\n /** Tx hash of the `depositForBurn` call. */\n burnTxHash: Hex;\n}\n\n/**\n * Approve USDC to the TokenMessenger (if needed) then burn it for the\n * cross-chain transfer. Returns the tx hashes. Does NOT wait for the\n * burn receipt — the caller pairs this with `waitForAttestation`.\n */\nexport async function approveAndBurn(\n params: ApproveAndBurnParams,\n): Promise<ApproveAndBurnResult> {\n const {\n signer,\n amount,\n usdcAddress,\n destinationDomain,\n smartAccountAddress,\n maxFee,\n minFinalityThreshold = FINALITY_FAST,\n tokenMessengerAddress = TOKEN_MESSENGER_V2 as Address,\n forceApprove = false,\n } = params;\n\n // 1. Allowance check — skip `approve` if the user already granted\n // enough USDC to the TokenMessenger. Saves a tx + signature\n // prompt on repeat swaps.\n let approveTxHash: Hex | undefined;\n const needsApprove =\n forceApprove ||\n !(await hasEnoughAllowance({\n signer,\n usdcAddress,\n spender: tokenMessengerAddress,\n minAmount: amount,\n }));\n\n if (needsApprove) {\n approveTxHash = (await signer.sendTransaction({\n to: usdcAddress,\n data: encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [tokenMessengerAddress, amount],\n }),\n })) as Hex;\n // Wait for the approve to mine — otherwise depositForBurn sees a\n // stale allowance and reverts.\n const receipt = await signer.waitForReceipt(approveTxHash);\n if (receipt.status !== \"success\") {\n throw new Error(`USDC approve reverted: tx ${approveTxHash}`);\n }\n }\n\n // 2. Burn. `mintRecipient` and `destinationCaller` both pinned to\n // the smart-account address:\n // - Destination USDC mints into the smart account (not the EOA).\n // - Only that account can call `receiveMessage` on the\n // destination chain → blocks front-runners from drawing gas\n // from our paymaster via a racing UserOp.\n const recipientBytes32 = addressToBytes32(smartAccountAddress) as Hex;\n const burnTxHash = (await signer.sendTransaction({\n to: tokenMessengerAddress,\n data: encodeFunctionData({\n abi: TOKEN_MESSENGER_ABI,\n functionName: \"depositForBurn\",\n args: [\n amount,\n destinationDomain,\n recipientBytes32,\n usdcAddress,\n recipientBytes32,\n maxFee,\n minFinalityThreshold,\n ],\n }),\n })) as Hex;\n\n return { approveTxHash, burnTxHash };\n}\n\n/** ERC-20 `allowance(owner, spender)` read via `EvmSigner.call`. */\nasync function hasEnoughAllowance(args: {\n signer: EvmSigner;\n usdcAddress: Address;\n spender: Address;\n minAmount: bigint;\n}): Promise<boolean> {\n const { signer, usdcAddress, spender, minAmount } = args;\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [signer.address as Address, spender],\n });\n const result = await signer.call({ to: usdcAddress, data });\n // `allowance` returns uint256 — 32 bytes, big-endian hex.\n const hex = result.replace(/^0x/, \"\") || \"0\";\n const current = BigInt(`0x${hex}`);\n return current >= minAmount;\n}\n","/**\n * Source-chain burn calldata for the CCTP-inbound flow.\n *\n * Encodes `TokenMessenger.depositForBurn(...)` on CCTPv2. The user submits\n * this tx on the source chain (e.g. Optimism, Base); the resulting CCTP\n * message lets our backend's Multicall3 tx on Arbitrum call\n * `receiveMessage` to mint USDC to the SDK-derived Arbitrum address.\n *\n * Note: we intentionally use the plain `depositForBurn` (no hook), with\n * `destinationCaller = bytes32(0)` so anyone can call `receiveMessage`.\n * The HTLC-locking logic lives on the Arbitrum side inside the multicall,\n * not in a CCTP hook.\n */\n\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport { FINALITY_FAST } from \"../cctp/constants.js\";\nimport { addressToBytes32 } from \"../cctp/utils.js\";\n\n/** Parameters for `depositForBurn` on CCTPv2 TokenMessenger. */\nexport interface DepositForBurnParams {\n /** USDC amount in smallest units (6 decimals). */\n amount: bigint;\n /** CCTP destination domain ID (e.g. 3 = Arbitrum). */\n destinationDomain: number;\n /**\n * Destination address the USDC will be minted to. Accepts either a 20-byte\n * EVM address (will be left-padded to bytes32) or a pre-padded bytes32 hex.\n */\n mintRecipient: string;\n /** Source-chain USDC contract address. */\n burnToken: string;\n /**\n * Bytes32-encoded address allowed to call `receiveMessage` on destination.\n * Defaults to `bytes32(0)` — unrestricted, required for our backend-\n * submitted multicall flow.\n */\n destinationCaller?: string;\n /**\n * Maximum CCTPv2 fast-transfer fee in USDC units (from IRIS fee API).\n * Ignored if `minFinalityThreshold` is ≥ standard.\n */\n maxFee: bigint;\n /**\n * Finality threshold: `FINALITY_FAST` (1000) for fast transfers,\n * `FINALITY_STANDARD` (2000) for slow. Defaults to fast.\n */\n minFinalityThreshold?: number;\n}\n\n/**\n * Encodes the `depositForBurn` call data for CCTPv2 TokenMessenger.\n *\n * Returns a 0x-prefixed hex string ready to submit as a tx's `data` field\n * against the source chain's TokenMessenger address.\n */\nexport function encodeDepositForBurn(params: DepositForBurnParams): string {\n const destinationCaller =\n params.destinationCaller ??\n \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n const minFinalityThreshold = params.minFinalityThreshold ?? FINALITY_FAST;\n\n // depositForBurn(uint256,uint32,bytes32,address,bytes32,uint256,uint32)\n const selector = keccak256Hex(\n \"depositForBurn(uint256,uint32,bytes32,address,bytes32,uint256,uint32)\",\n ).slice(0, 10);\n\n const mintRecipientBytes32 = ensureBytes32(params.mintRecipient);\n const destinationCallerBytes32 = ensureBytes32(destinationCaller);\n\n const encoded =\n selector +\n encodeUint256(params.amount) +\n encodeUint256(BigInt(params.destinationDomain)) +\n stripHex(mintRecipientBytes32) +\n encodeAddress(params.burnToken) +\n stripHex(destinationCallerBytes32) +\n encodeUint256(params.maxFee) +\n encodeUint256(BigInt(minFinalityThreshold));\n\n return encoded;\n}\n\nfunction ensureBytes32(value: string): string {\n const clean = value.replace(/^0x/, \"\");\n if (clean.length === 64) {\n return `0x${clean.toLowerCase()}`;\n }\n if (clean.length === 40) {\n return addressToBytes32(value);\n }\n throw new Error(\n `Invalid mintRecipient/destinationCaller: expected 20-byte address or 32-byte hex, got ${clean.length / 2} bytes`,\n );\n}\n\nfunction keccak256Hex(input: string): string {\n return `0x${bytesToHex(keccak_256(new TextEncoder().encode(input)))}`;\n}\n\nfunction encodeUint256(value: bigint): string {\n if (value < 0n) throw new Error(\"uint256 cannot be negative\");\n return value.toString(16).padStart(64, \"0\");\n}\n\nfunction encodeAddress(address: string): string {\n return address.replace(/^0x/, \"\").toLowerCase().padStart(64, \"0\");\n}\n\nfunction stripHex(value: string): string {\n return value.replace(/^0x/, \"\").toLowerCase();\n}\n","/**\n * Map EVM chain IDs to CCTPv2 source-chain metadata (domain + USDC\n * address) for the consuming side of the CCTP-inbound flow.\n *\n * Callers pass `signer.chainId`; the SDK derives the CCTP domain +\n * the source-chain USDC address from that alone, so the public API\n * doesn't need a redundant \"sourceChain\" string.\n */\n\nimport type { Chain, Hex } from \"viem\";\nimport {\n arbitrum,\n avalanche,\n base,\n hyperEvm,\n ink,\n linea,\n mainnet,\n monad,\n optimism,\n polygon,\n sei,\n sonic,\n unichain,\n worldchain,\n xdc,\n} from \"viem/chains\";\nimport {\n CCTP_DOMAINS,\n type CctpChainName,\n FINALITY_FAST,\n FINALITY_STANDARD,\n USDC_ADDRESSES,\n} from \"../cctp/constants.js\";\n\n/** Canonical EVM chain id → CCTP chain name. */\nexport const CHAIN_ID_TO_CCTP_NAME: Record<number, CctpChainName> = {\n 1: \"Ethereum\",\n 10: \"Optimism\",\n 130: \"Unichain\",\n 137: \"Polygon\",\n 146: \"Sonic\",\n 1329: \"Sei\",\n 8453: \"Base\",\n 42161: \"Arbitrum\",\n 43114: \"Avalanche\",\n 59144: \"Linea\",\n 480: \"World Chain\",\n 57073: \"Ink\",\n 999: \"HyperEVM\",\n 143: \"Monad\",\n 50: \"XDC\",\n // Solana lands later (non-EVM, needs a different signer path).\n};\n\n/**\n * EVM chain ids the Lendaswap backend accepts directly as a swap\n * source via Permit2 — these chains are also CCTP-supported, but\n * we never route them through CCTP since a direct-Permit2 funding\n * is cheaper and faster.\n */\nexport const DIRECT_SOURCE_CHAIN_IDS: ReadonlySet<number> = new Set([\n 1, // Ethereum\n 137, // Polygon\n 42161, // Arbitrum\n]);\n\n/**\n * `true` when `chainId` is a CCTP-supported source that the backend\n * does NOT accept directly — i.e. funding a swap from this chain\n * requires a CCTP hop to Arbitrum before the HTLC is created.\n */\nexport function isCctpOnlySource(chainId: number): boolean {\n return (\n chainId in CHAIN_ID_TO_CCTP_NAME && !DIRECT_SOURCE_CHAIN_IDS.has(chainId)\n );\n}\n\n/**\n * CCTP source chains that do **not** support Fast Transfer (Circle's\n * supported-chains/finality docs mark \"Fast Transfer: N/A\"). Burns from\n * these chains must request Standard finality (2000); requesting fast\n * finality (1000) makes the fee/attestation assumptions wrong because no\n * fast-transfer fee tier exists for the route.\n */\nexport const CCTP_STANDARD_ONLY_CHAIN_IDS: ReadonlySet<number> = new Set([\n 50, // XDC\n]);\n\n/**\n * The CCTP `minFinalityThreshold` to request when burning *from* `chainId`:\n * `FINALITY_FAST` (1000) where Fast Transfer is supported, `FINALITY_STANDARD`\n * (2000) for chains in [`CCTP_STANDARD_ONLY_CHAIN_IDS`].\n *\n * Callers should also query the IRIS fee for the returned threshold so the\n * `maxFee` matches the tier the burn will actually settle at.\n */\nexport function finalityForChainId(chainId: number): number {\n return CCTP_STANDARD_ONLY_CHAIN_IDS.has(chainId)\n ? FINALITY_STANDARD\n : FINALITY_FAST;\n}\n\n/**\n * Look up CCTPv2 domain id + native USDC address for a given chain id.\n * Throws with a clear error if the chain is unsupported.\n */\nexport function cctpMetaForChainId(chainId: number): {\n name: CctpChainName;\n domain: number;\n usdc: Hex;\n} {\n const name = CHAIN_ID_TO_CCTP_NAME[chainId];\n if (!name) {\n throw new Error(\n `Chain id ${chainId} is not a supported CCTP source chain. Supported ids: ${Object.keys(CHAIN_ID_TO_CCTP_NAME).join(\", \")}.`,\n );\n }\n const usdc = USDC_ADDRESSES[name];\n if (!usdc) {\n throw new Error(\n `CCTP chain ${name} has no native USDC address in the SDK registry.`,\n );\n }\n return {\n name,\n domain: CCTP_DOMAINS[name],\n usdc: usdc as Hex,\n };\n}\n\n/**\n * Map of CCTP source chain id → viem `Chain` object. Mirrors\n * [`CHAIN_ID_TO_CCTP_NAME`] — keep them in lockstep when adding chains.\n *\n * Exposed so browser consumers (wagmi, viem clients) don't have to maintain\n * their own parallel mapping; tree-shakable so non-browser consumers don't\n * pay the bundle cost.\n */\nexport const CCTP_VIEM_CHAINS: Record<number, Chain> = {\n 1: mainnet,\n 10: optimism,\n 130: unichain,\n 137: polygon,\n 146: sonic,\n 1329: sei,\n 8453: base,\n 42161: arbitrum,\n 43114: avalanche,\n 59144: linea,\n 480: worldchain,\n 57073: ink,\n 999: hyperEvm,\n 143: monad,\n 50: xdc,\n};\n\n/** Look up the viem `Chain` for a CCTP source chain id, or `undefined`. */\nexport function getCctpViemChain(chainId: number): Chain | undefined {\n return CCTP_VIEM_CHAINS[chainId];\n}\n\n/** Look up the viem `Chain` for a CCTP source chain name, or `undefined`. */\nexport function getCctpViemChainByName(name: string): Chain | undefined {\n for (const [chainId, chainName] of Object.entries(CHAIN_ID_TO_CCTP_NAME)) {\n if (chainName === name) return CCTP_VIEM_CHAINS[Number(chainId)];\n }\n return undefined;\n}\n","/**\n * `cctpFundSwap` — one-shot CCTP-inbound settlement.\n *\n * Composes the three primitives into a single flow most consumers\n * can call directly:\n *\n * 1. `approveAndBurn` on the source chain.\n * 2. `waitForAttestation` against IRIS until the burn is attested.\n * 3. `submitUserOp` on the settlement chain via the caller's Kernel\n * smart account (paymaster-sponsored).\n *\n * `signer` sends the source-chain approve + burn. `ownerSigner` owns the\n * Kernel account that settles on Arbitrum; it defaults to `signer`, but a\n * browser wallet usually cannot sign an EIP-7702 authorization, so the\n * `Client` passes the SDK's own key there for swaps created gasless. The\n * smart-account address (the owner's address, under 7702) is derived once\n * up-front and pinned as `mintRecipient` / `destinationCaller` on the burn.\n */\n\nimport type { Chain, Hex } from \"viem\";\nimport { arbitrum } from \"viem/chains\";\nimport type { ApiClient } from \"../api/client.js\";\nimport { fetchAttestation } from \"../cctp/attestation.js\";\nimport { IRIS_API_MAINNET, TOKEN_MESSENGER_V2 } from \"../cctp/constants.js\";\nimport type { ExpectedFunding } from \"../evm/funding-pins.js\";\nimport type { EvmSigner } from \"../evm/wallet.js\";\nimport { approveAndBurn } from \"./approveAndBurn.js\";\nimport { cctpMetaForChainId, finalityForChainId } from \"./chainMap.js\";\nimport { createSwapSmartAccountClient } from \"./smartAccount.js\";\nimport { submitCctpInboundUserOp } from \"./submit.js\";\nimport type { AaConfig } from \"./types.js\";\n\n/**\n * High-level progress events emitted during a CCTP-inbound swap.\n * Consumers wire a single `onProgress` callback to drive UI updates\n * without coupling to the primitive-level mechanics.\n */\nexport type CctpProgressStep =\n | { phase: \"approving\" }\n | { phase: \"burning\"; burnTxHash: Hex }\n | { phase: \"attestation\" }\n | { phase: \"submitting\" }\n | { phase: \"settled\"; userOpHash: Hex; transactionHash?: Hex };\n\nexport interface CctpFundSwapParams {\n /**\n * What the funding must match: the hash lock this client fixed and the\n * terms it recorded at the swap's creation (`Client.getEvmFundingExpectation`),\n * plus optional pins. A payload naming another spender, hash, claimer,\n * timelock or token, taking more than the input, or with calls that\n * could move the deposit is refused before anything is signed, and the\n * batch is built from these terms, not from the payload.\n */\n expected: ExpectedFunding;\n /** Swap ID from `client.createSwap(...)`. */\n swapId: string;\n /**\n * SDK signer bound to the **source chain**: sends the approve + burn.\n * Also the Kernel-account owner unless `ownerSigner` is set, in which case\n * it needs `signMessage` and `signAuthorization`.\n */\n signer: EvmSigner;\n /**\n * Kernel-account owner on the settlement chain (needs `signMessage`,\n * `signTypedData` and `signAuthorization`). Defaults to `signer`. Its\n * address receives the minted USDC and is the only allowed caller of\n * `receiveMessage`, so it must match the swap's depositor.\n */\n ownerSigner?: EvmSigner;\n /**\n * A burn this swap already sent (e.g. recorded by a previous attempt that\n * was interrupted). Skips approve + burn and resumes at the attestation.\n */\n burnTxHash?: Hex;\n /**\n * Called as soon as the burn is broadcast, before its receipt. Persist the\n * hash here: from this point the USDC has left the source chain, and the\n * hash is what resuming or recovering the settlement needs.\n *\n * Called again once the burn has mined: with the replacement's hash if the\n * wallet sped it up, or with `undefined` if nothing was burned (the burn\n * reverted, or the wallet cancelled it) so the next attempt burns afresh.\n */\n onBurn?: (burnTxHash: Hex | undefined) => void | Promise<void>;\n /** USDC amount in smallest units (6 decimals). */\n amount: bigint;\n /**\n * Max fast-transfer fee in USDC units (from IRIS's\n * `/v2/burn/USDC/fees` endpoint). Typical: ~1/10000 of `amount`.\n */\n maxFee: bigint;\n /**\n * Settlement chain. Defaults to Arbitrum mainnet — the only\n * supported settlement chain today.\n */\n settlementChain?: Chain;\n /**\n * IRIS API base URL. Defaults to mainnet; override for testnet.\n */\n irisApiUrl?: string;\n /** Invoked as the flow advances through its phases. */\n onProgress?: (step: CctpProgressStep) => void;\n /** Abort signal for cancelling the attestation wait. */\n signal?: AbortSignal;\n}\n\nexport interface CctpFundSwapResult {\n /** Source-chain burn tx. */\n burnTxHash: Hex;\n /** Source-chain approve tx (omitted if allowance was already sufficient). */\n approveTxHash?: Hex;\n /** Settlement-chain UserOp hash. */\n userOpHash: Hex;\n /** Settlement-chain bundled tx hash (populated once the UserOp is mined). */\n transactionHash?: Hex;\n /** Deterministic Kernel smart-account address owning the HTLC deposit. */\n smartAccountAddress: Hex;\n}\n\n/** Context passed by `CctpInboundClient` when delegating to this function. */\nexport interface CctpFundSwapContext {\n apiClient: ApiClient;\n aa: AaConfig;\n}\n\n/**\n * Wait for the burn to mine and return the hash Circle attests it under.\n *\n * The receipt follows a replacement the wallet made, so the mined hash can\n * differ from the one sent: a speed-up burned under the new hash, a\n * cancellation (a self-send) burned nothing. Only a transaction to the\n * TokenMessenger burns, so that decides which. A burn that reverted or was\n * cancelled clears the recorded hash: nothing left the source chain, and the\n * next attempt must burn again rather than wait on an attestation that will\n * never come.\n */\nasync function confirmBurn(\n signer: EvmSigner,\n sentTxHash: Hex,\n onBurn: CctpFundSwapParams[\"onBurn\"],\n): Promise<Hex> {\n const receipt = await signer.waitForReceipt(sentTxHash);\n if (receipt.status !== \"success\") {\n await onBurn?.(undefined);\n throw new Error(`CCTP burn tx reverted: ${receipt.transactionHash}`);\n }\n const minedTxHash = (receipt.transactionHash ?? sentTxHash) as Hex;\n if (minedTxHash.toLowerCase() === sentTxHash.toLowerCase()) {\n return sentTxHash;\n }\n const mined = await signer.getTransaction(minedTxHash);\n if (mined?.to?.toLowerCase() !== TOKEN_MESSENGER_V2.toLowerCase()) {\n await onBurn?.(undefined);\n throw new Error(\n `The CCTP burn ${sentTxHash} was replaced by ${minedTxHash}, which did not burn (cancelled in the wallet?). No USDC left the source chain; try again.`,\n );\n }\n await onBurn?.(minedTxHash);\n return minedTxHash;\n}\n\n/**\n * Execute the full CCTP-inbound swap flow end to end. Most consumers\n * call this directly — the primitives (`approveAndBurn`,\n * `waitForAttestation`, `submitUserOp`) are available separately for\n * wizard-style UX that needs per-step control.\n */\nexport async function cctpFundSwap(\n context: CctpFundSwapContext,\n params: CctpFundSwapParams,\n): Promise<CctpFundSwapResult> {\n const {\n swapId,\n signer,\n ownerSigner = signer,\n burnTxHash: resumeBurnTxHash,\n onBurn,\n amount,\n maxFee,\n settlementChain = arbitrum,\n irisApiUrl = IRIS_API_MAINNET,\n onProgress,\n signal,\n } = params;\n\n // Derive CCTP source metadata from the signer's chain id. No need\n // for the caller to spell out \"Optimism\" or the numeric domain —\n // the signer already knows which chain it's on.\n const source = cctpMetaForChainId(signer.chainId);\n const destination = cctpMetaForChainId(settlementChain.id);\n\n // Sources without Fast Transfer (e.g. XDC) must burn at Standard\n // finality — requesting fast finality there charges the wrong fee tier\n // and the attestation never clears at the fast threshold.\n const minFinalityThreshold = finalityForChainId(signer.chainId);\n\n // Derive the Kernel smart-account address up front. Stable across\n // all three phases — we mint to it on settlement and gate the\n // `receiveMessage` call on it.\n const { accountAddress: smartAccountAddress } =\n await createSwapSmartAccountClient({\n signer: ownerSigner,\n aa: context.aa,\n chain: settlementChain,\n });\n\n // 1. Source-chain approve + burn, unless a previous attempt already burned.\n let approveTxHash: Hex | undefined;\n let burnTxHash: Hex;\n if (resumeBurnTxHash) {\n burnTxHash = resumeBurnTxHash;\n } else {\n onProgress?.({ phase: \"approving\" });\n const burn = await approveAndBurn({\n signer,\n amount,\n usdcAddress: source.usdc,\n destinationDomain: destination.domain,\n smartAccountAddress,\n maxFee,\n minFinalityThreshold,\n });\n approveTxHash = burn.approveTxHash;\n burnTxHash = burn.burnTxHash;\n // `approveAndBurn` returns as soon as the burn is broadcast.\n await onBurn?.(burnTxHash);\n }\n onProgress?.({ phase: \"burning\", burnTxHash });\n burnTxHash = await confirmBurn(signer, burnTxHash, onBurn);\n\n // 2. Wait for the IRIS attestation to clear.\n onProgress?.({ phase: \"attestation\" });\n const { message, attestation } = await fetchAttestation({\n sourceChain: source.name,\n txHash: burnTxHash,\n irisApiUrl,\n signal,\n });\n\n // 3. Submit the settlement UserOp and wait for the on-chain receipt.\n onProgress?.({ phase: \"submitting\" });\n const submit = await submitCctpInboundUserOp(context, {\n swapId,\n expected: params.expected,\n signer: ownerSigner,\n cctpMessage: message as Hex,\n cctpAttestation: attestation as Hex,\n chain: settlementChain,\n });\n onProgress?.({\n phase: \"settled\",\n userOpHash: submit.userOpHash,\n transactionHash: submit.transactionHash,\n });\n\n return {\n approveTxHash,\n burnTxHash,\n userOpHash: submit.userOpHash,\n transactionHash: submit.transactionHash,\n smartAccountAddress: smartAccountAddress as Hex,\n };\n}\n","/**\n * `CctpInboundClient` — the `client.cctpInbound` namespace on the main\n * `Client`. Holds the AA (bundler + paymaster) config and will expose\n * the step-by-step primitives for the CCTP-inbound flow:\n *\n * - `approveAndBurn` (source-chain burn)\n * - `waitForAttestation` (IRIS polling)\n * - `submitUserOp` (settlement-chain UserOp via Kernel smart account)\n * - `createSmartAccountClient` (low-level Kernel account factory)\n *\n * The one-shot `Client.fundSwap(...)` is implemented on top of these\n * primitives — consumers wanting custom progress UX drop down to the\n * primitives directly; simple integrations just call `fundSwap`.\n *\n * Scaffolding only in this commit; primitives land in follow-up steps.\n */\n\nimport type { Chain } from \"viem\";\nimport type { ApiClient } from \"../api/client.js\";\nimport {\n type AttestationResult,\n type FetchAttestationOptions,\n fetchAttestation,\n} from \"../cctp/attestation.js\";\nimport type { EvmSigner } from \"../evm/wallet.js\";\nimport type { Logger, LogLevel } from \"../logging.js\";\nimport {\n type ApproveAndBurnParams,\n type ApproveAndBurnResult,\n approveAndBurn,\n} from \"./approveAndBurn.js\";\nimport {\n type CctpFundSwapParams,\n type CctpFundSwapResult,\n cctpFundSwap,\n} from \"./fundSwap.js\";\nimport {\n type CreateSwapSmartAccountClientParams,\n createSwapSmartAccountClient,\n} from \"./smartAccount.js\";\nimport {\n type SubmitBalanceUserOpParams,\n type SubmitUserOpParams,\n type SubmitUserOpResult,\n submitCctpInboundBalanceUserOp,\n submitCctpInboundUserOp,\n} from \"./submit.js\";\nimport type { AaConfig } from \"./types.js\";\nimport {\n type BuildCctpInboundBatchParams,\n type BuiltBatch,\n buildCctpInboundBatch,\n} from \"./userOp.js\";\n\nexport interface CctpInboundClientConfig {\n apiClient: ApiClient;\n aa: AaConfig;\n /** Optional logger sink. Silent by default. */\n logger?: Logger;\n /** Minimum log level to emit. Defaults to `silent`. */\n logLevel?: LogLevel;\n}\n\nexport class CctpInboundClient {\n readonly #apiClient: ApiClient;\n readonly #aa: AaConfig;\n readonly #logger?: Logger;\n readonly #logLevel?: LogLevel;\n\n constructor(config: CctpInboundClientConfig) {\n this.#apiClient = config.apiClient;\n this.#aa = config.aa;\n this.#logger = config.logger;\n this.#logLevel = config.logLevel;\n }\n\n /** The AA config this client was built with. */\n get aa(): AaConfig {\n return this.#aa;\n }\n\n /** The underlying typed API client. */\n get api(): ApiClient {\n return this.#apiClient;\n }\n\n /**\n * Build a Kernel smart-account client owned by `owner`.\n *\n * Low-level primitive — most consumers will use `submitUserOp` or\n * the one-shot `client.fundSwap` instead of constructing the AA\n * client themselves.\n */\n createSmartAccountClient(args: { signer: EvmSigner; chain?: Chain }) {\n const params: CreateSwapSmartAccountClientParams = {\n signer: args.signer,\n aa: this.#aa,\n chain: args.chain,\n };\n return createSwapSmartAccountClient(params);\n }\n\n /**\n * Compose the 3-call UserOp batch (receiveMessage + USDC.approve +\n * executeAndCreateWithPermit2) that the smart account will execute\n * atomically. Produces the Permit2 signature via the caller-supplied\n * `signTypedData` — typically `kernelAccount.signTypedData`.\n *\n * Low-level primitive — most consumers call `submitUserOp` instead,\n * which composes batch + send + wait-for-receipt.\n */\n buildUserOpBatch(params: BuildCctpInboundBatchParams): Promise<BuiltBatch> {\n return buildCctpInboundBatch(params);\n }\n\n /**\n * End-to-end settlement UserOp: fetch calldata, build Kernel client,\n * compose the batch, submit via the bundler, and (by default) wait\n * for the on-chain receipt.\n *\n * This is the main high-level entry point for the CCTP-inbound\n * settlement step. Pass the IRIS message + attestation (from\n * `waitForAttestation`, landing in a follow-up step) and the\n * caller's signer.\n */\n submitUserOp(params: SubmitUserOpParams): Promise<SubmitUserOpResult> {\n return submitCctpInboundUserOp(\n { apiClient: this.#apiClient, aa: this.#aa },\n {\n ...params,\n logger: params.logger ?? this.#logger,\n logLevel: params.logLevel ?? this.#logLevel,\n },\n );\n }\n\n /**\n * Fund an Arbitrum-settled EVM-sourced swap from USDC/tBTC/WBTC that is\n * already sitting in the Kernel smart account. This is the retry/recovery\n * variant of the CCTP-inbound settlement path: it skips `receiveMessage` and\n * submits only `approve(Permit2) + executeAndCreateWithPermit2` as a\n * paymaster-sponsored UserOp.\n */\n submitBalanceUserOp(\n params: SubmitBalanceUserOpParams,\n ): Promise<SubmitUserOpResult> {\n return submitCctpInboundBalanceUserOp(\n { apiClient: this.#apiClient, aa: this.#aa },\n {\n ...params,\n logger: params.logger ?? this.#logger,\n logLevel: params.logLevel ?? this.#logLevel,\n },\n );\n }\n\n /**\n * Source-chain USDC approve (if needed) + `depositForBurn`. The\n * minted USDC on the destination chain is pinned to\n * `smartAccountAddress`, and `destinationCaller` is pinned to the\n * same address — only that account can settle the message.\n *\n * Does not wait for CCTP attestation; returns as soon as both txs\n * are broadcast. The caller pairs this with `waitForAttestation`\n * (landing in the next step) and `submitUserOp`.\n */\n approveAndBurn(params: ApproveAndBurnParams): Promise<ApproveAndBurnResult> {\n return approveAndBurn(params);\n }\n\n /**\n * Poll Circle's IRIS V2 API until the CCTP attestation for a burn\n * tx is `complete`, then return the `message` + `attestation` bytes\n * ready to feed into `submitUserOp`.\n *\n * Typical wait: ~15 seconds for fast transfers, a few minutes for\n * standard. Defaults to a 15-minute timeout; callers can pass\n * `signal` (AbortSignal) to cancel early.\n */\n waitForAttestation(\n options: FetchAttestationOptions,\n ): Promise<AttestationResult> {\n return fetchAttestation(options);\n }\n\n /**\n * One-shot CCTP-inbound swap: approve + burn on the source chain,\n * poll IRIS for the attestation, then submit the settlement UserOp\n * via the Kernel smart account. Paymaster sponsors the settlement\n * so the user needs no ETH on the destination chain.\n *\n * `signer` sends the source-chain txs; `ownerSigner` (default:\n * `signer`) owns the Kernel account that submits the settlement\n * UserOp, and its address anchors the smart-account address.\n */\n fundSwap(params: CctpFundSwapParams): Promise<CctpFundSwapResult> {\n return cctpFundSwap({ apiClient: this.#apiClient, aa: this.#aa }, params);\n }\n}\n","/**\n * EIP-2612 permit signing for USDC → Permit2 approval using the SDK's\n * HD-derived EVM key.\n *\n * On a brand-new SDK-derived Arbitrum address, USDC's allowance for Permit2\n * is zero. Rather than doing an on-chain `approve` (which requires ETH the\n * user doesn't have), we sign an EIP-2612 `permit` off-chain; the backend's\n * multicall on Arbitrum includes `USDC.permit(...)` to establish the\n * allowance atomically before `executeAndCreateWithPermit2` pulls via Permit2.\n */\n\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport {\n buildEip2612PermitDigest,\n type Eip2612PermitParams,\n PERMIT2_ADDRESS,\n} from \"../evm/coordinator.js\";\nimport { signEvmDigest } from \"../evm/signing.js\";\n\n/** Parameters for signing an EIP-2612 permit against a specific token. */\nexport interface SignEip2612Params {\n /** Signer's secp256k1 private key (from the SDK HD signer). */\n secretKey: Uint8Array | string;\n /** The token's EIP-712 DOMAIN_SEPARATOR (0x-prefixed, from `token.DOMAIN_SEPARATOR()`). */\n domainSeparator: string;\n /** Token owner address (= `deriveEvmAddress(secretKey)`). */\n owner: string;\n /**\n * Spender. Defaults to Permit2 (the usual target — this is what enables\n * `executeAndCreateWithPermit2` to pull via Permit2 in the same multicall).\n */\n spender?: string;\n /** Approval amount. Pass `MAX_UINT256` to remove the need for future permits. */\n value: bigint;\n /** Current EIP-2612 nonce for `owner` on the token (from `token.nonces(owner)`). */\n nonce: number;\n /** Signature deadline (unix seconds). */\n deadline: bigint;\n}\n\n/** Signed EIP-2612 permit ready to submit on-chain. */\nexport interface SignedEip2612Permit {\n /** v, r, s components — v is 27 or 28. */\n v: number;\n r: string;\n s: string;\n /** Approval amount (as stringified decimal for API transport). */\n value: string;\n /** Signature deadline (unix seconds). */\n deadline: number;\n}\n\n/** uint256 max — sign once, never need another permit. */\nexport const MAX_UINT256 = (1n << 256n) - 1n;\n\n/**\n * Signs an EIP-2612 permit using the SDK's derived key, returning the\n * split signature + value/deadline in a shape the backend's gasless\n * endpoint accepts directly.\n */\nexport function signEip2612Permit(\n params: SignEip2612Params,\n): SignedEip2612Permit {\n const spender = params.spender ?? PERMIT2_ADDRESS;\n\n const digestParams: Eip2612PermitParams = {\n domainSeparator: params.domainSeparator,\n owner: params.owner,\n spender,\n value: params.value,\n nonce: params.nonce,\n deadline: params.deadline,\n };\n const digest = buildEip2612PermitDigest(digestParams);\n const sig = signEvmDigest(params.secretKey, digest);\n\n return {\n v: sig.v,\n r: sig.r,\n s: sig.s,\n value: params.value.toString(),\n deadline: Number(params.deadline),\n };\n}\n\n// ── Domain separator helper ──────────────────────────────────────────────────\n\n/**\n * Builds an EIP-712 domain separator from the standard 4-field domain.\n *\n * Use when you know the token's on-chain `name` and `version` and want to\n * avoid an RPC call to `token.DOMAIN_SEPARATOR()`. For USDC deployments,\n * both vary slightly — see {@link USDC_DOMAIN_FIELDS}.\n */\nexport function buildDomainSeparator(params: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: string;\n}): string {\n const TYPEHASH = keccak256Hex(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\",\n );\n const encoded =\n strip(TYPEHASH) +\n strip(keccak256Hex(params.name)) +\n strip(keccak256Hex(params.version)) +\n uint256Hex(BigInt(params.chainId)) +\n addressHex(params.verifyingContract);\n\n return keccak256HexBytes(encoded);\n}\n\n/**\n * Known EIP-712 domain fields for native USDC on each CCTPv2-supported EVM\n * chain. Populate as needed — verify on-chain via `DOMAIN_SEPARATOR()` before\n * relying on these in production.\n *\n * Arbitrum native USDC (`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`) reports\n * `name = \"USD Coin\"`, `version = \"2\"`. Most Circle-issued native USDC uses\n * the same; bridged USDC.e variants differ.\n */\nexport const USDC_DOMAIN_FIELDS: Record<\n number,\n { name: string; version: string; address: string }\n> = {\n 42161: {\n name: \"USD Coin\",\n version: \"2\",\n address: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n },\n};\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction keccak256Hex(input: string): string {\n return `0x${bytesToHex(keccak_256(new TextEncoder().encode(input)))}`;\n}\n\nfunction keccak256HexBytes(hexInput: string): string {\n const bytes = new Uint8Array(hexInput.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hexInput.slice(i * 2, i * 2 + 2), 16);\n }\n return `0x${bytesToHex(keccak_256(bytes))}`;\n}\n\nfunction strip(hex: string): string {\n return hex.replace(/^0x/, \"\").toLowerCase();\n}\n\nfunction uint256Hex(value: bigint): string {\n return value.toString(16).padStart(64, \"0\");\n}\n\nfunction addressHex(address: string): string {\n return address.replace(/^0x/, \"\").toLowerCase().padStart(64, \"0\");\n}\n","/**\n * EVM key derivation and signing utilities.\n *\n * Derives EVM addresses and signs EIP-712 digests using secp256k1 keys\n * from the SDK's HD wallet — no external wallet or signer required.\n */\n\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\n\n/**\n * Derives an EVM address from a secp256k1 private key.\n *\n * The address is computed as the last 20 bytes of keccak256(uncompressed_pubkey).\n *\n * @param secretKey - 32-byte private key (Uint8Array or hex string)\n * @returns EVM address as a checksummed hex string with 0x prefix\n */\nexport function deriveEvmAddress(secretKey: Uint8Array | string): string {\n const keyBytes =\n typeof secretKey === \"string\"\n ? hexToBytes(secretKey.replace(/^0x/, \"\"))\n : secretKey;\n\n // Get uncompressed public key (65 bytes: 0x04 || x || y)\n const uncompressedPubkey = secp256k1.getPublicKey(keyBytes, false);\n\n // Keccak256 of the 64-byte public key (drop the 0x04 prefix)\n const hash = keccak_256(uncompressedPubkey.slice(1));\n\n // Take last 20 bytes as address\n const addressBytes = hash.slice(12);\n const addressHex = bytesToHex(addressBytes);\n\n return toChecksumAddress(addressHex);\n}\n\n/**\n * Signs an EIP-712 digest with a secp256k1 private key.\n *\n * Returns the signature components (v, r, s) needed for EVM contract calls.\n *\n * @param secretKey - 32-byte private key (Uint8Array or hex string)\n * @param digest - 32-byte digest hex string (with or without 0x prefix)\n * @returns Signature components { v, r, s }\n */\nexport function signEvmDigest(\n secretKey: Uint8Array | string,\n digest: string,\n): { v: number; r: string; s: string } {\n const keyBytes =\n typeof secretKey === \"string\"\n ? hexToBytes(secretKey.replace(/^0x/, \"\"))\n : secretKey;\n\n const digestBytes = hexToBytes(digest.replace(/^0x/, \"\"));\n\n // @noble/curves v2 returns raw Uint8Array from sign().\n // Use format: 'recovered' to get 65 bytes: [recovery_byte, r(32), s(32)].\n const sig = secp256k1.sign(digestBytes, keyBytes, {\n prehash: false,\n format: \"recovered\",\n });\n\n const recovery = sig[0];\n const r = bytesToHex(sig.slice(1, 33));\n const s = bytesToHex(sig.slice(33, 65));\n const v = (recovery ?? 0) + 27;\n\n return { v, r: `0x${r}`, s: `0x${s}` };\n}\n\n/**\n * Signs a message the EIP-191 way (`personal_sign`): the signature is over\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message)`.\n *\n * @param secretKey - 32-byte private key (Uint8Array or hex string)\n * @param message - The message as text (UTF-8) or raw bytes\n * @returns The 65-byte `r ‖ s ‖ v` signature as 0x-prefixed hex, `v` 27 or 28\n */\nexport function signEvmMessage(\n secretKey: Uint8Array | string,\n message: string | Uint8Array,\n): string {\n const { v, r, s } = signEvmDigest(secretKey, eip191Digest(message));\n return `${r}${s.slice(2)}${v.toString(16).padStart(2, \"0\")}`;\n}\n\n/** `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message)`. */\nexport function eip191Digest(message: string | Uint8Array): string {\n const body =\n typeof message === \"string\" ? new TextEncoder().encode(message) : message;\n const prefix = new TextEncoder().encode(\n `\\x19Ethereum Signed Message:\\n${body.length}`,\n );\n const whole = new Uint8Array(prefix.length + body.length);\n whole.set(prefix, 0);\n whole.set(body, prefix.length);\n return `0x${bytesToHex(keccak_256(whole))}`;\n}\n\n/**\n * Converts an address to EIP-55 checksummed format.\n */\nfunction toChecksumAddress(address: string): string {\n const clean = address.replace(/^0x/, \"\").toLowerCase();\n const hash = bytesToHex(keccak_256(new TextEncoder().encode(clean)));\n\n let checksummed = \"0x\";\n for (let i = 0; i < 40; i++) {\n checksummed +=\n parseInt(hash[i], 16) >= 8 ? clean[i].toUpperCase() : clean[i];\n }\n return checksummed;\n}\n","/**\n * Permit2 signing for `executeAndCreateWithPermit2` using the SDK's\n * HD-derived EVM key.\n *\n * Wraps the existing `buildPermit2FundingDigest` + `signEvmDigest` and\n * returns the compact 65-byte signature format (`r ‖ s ‖ v`) that\n * `HTLCCoordinator.executeAndCreateWithPermit2` expects, ready to POST\n * to the backend's gasless-funding endpoint.\n */\n\nimport {\n buildPermit2FundingDigest,\n type Permit2FundingParams,\n} from \"../evm/coordinator.js\";\nimport { signEvmDigest } from \"../evm/signing.js\";\n\n/** Parameters for signing a Permit2 witness with the SDK's HD key. */\nexport interface SignPermit2Params {\n /** Signer's secp256k1 private key. */\n secretKey: Uint8Array | string;\n /** All fields of the Permit2 witness + TokenPermissions. */\n funding: Permit2FundingParams;\n}\n\n/** Signed Permit2 witness in the shape the backend's gasless endpoint expects. */\nexport interface SignedPermit2Witness {\n /** Random Permit2 nonce (stringified for API transport). */\n nonce: string;\n /** Signature deadline (unix seconds). */\n deadline: number;\n /** Compact signature: `0x` + r(32) + s(32) + v(1), 65 bytes. */\n signature: string;\n}\n\n/**\n * Signs the Permit2 EIP-712 digest using the SDK's derived key and packs\n * the signature in the compact `r ‖ s ‖ v` form the backend submitter\n * forwards to Permit2 on-chain.\n */\nexport function signPermit2Witness(\n params: SignPermit2Params,\n): SignedPermit2Witness {\n const digest = buildPermit2FundingDigest(params.funding);\n const sig = signEvmDigest(params.secretKey, digest);\n\n const r = sig.r.replace(/^0x/, \"\");\n const s = sig.s.replace(/^0x/, \"\");\n const v = sig.v.toString(16).padStart(2, \"0\");\n if (r.length !== 64 || s.length !== 64) {\n throw new Error(\n `Malformed signature scalars: r=${r.length}, s=${s.length}`,\n );\n }\n\n return {\n nonce: params.funding.nonce.toString(),\n deadline: Number(params.funding.deadline),\n signature: `0x${r}${s}${v}`,\n };\n}\n","/**\n * `recoverCctpInbound` — sweep USDC stranded in the user's smart account\n * after a CCTP burn whose HTLC settlement never completed.\n *\n * Two failure modes are handled:\n * - User burned on the source chain but never called `receiveMessage`\n * on Arbitrum (smart account holds 0 USDC; the message is unconsumed).\n * - User called `receiveMessage` but the HTLC fund step reverted\n * (smart account already holds the minted USDC).\n *\n * Strategy: at most two paymaster-sponsored UserOps.\n * 1. If `MessageTransmitter.usedNonces(nonce) == 0`: send a UserOp that\n * calls `receiveMessage(message, attestation)`. The smart account\n * remains the `destinationCaller`, so only it can submit.\n * 2. Read the smart account's USDC balance, then send a UserOp that\n * calls `USDC.transfer(recipient, balance)`.\n *\n * The two-UserOp split avoids decoding the CCTP message body to predict\n * the post-mint balance — `balanceOf` between the calls is authoritative.\n */\n\nimport type { Address, Chain, Hex } from \"viem\";\nimport {\n createPublicClient,\n encodeFunctionData,\n erc20Abi,\n http,\n parseAbi,\n} from \"viem\";\nimport { arbitrum } from \"viem/chains\";\nimport { fetchAttestation } from \"../cctp/attestation.js\";\nimport {\n type CctpChainName,\n IRIS_API_MAINNET,\n MESSAGE_TRANSMITTER_V2,\n USDC_ADDRESSES,\n} from \"../cctp/constants.js\";\nimport type { EvmSigner } from \"../evm/wallet.js\";\nimport { createSwapSmartAccountClient } from \"./smartAccount.js\";\nimport type { AaConfig } from \"./types.js\";\n\nconst MESSAGE_TRANSMITTER_ABI = parseAbi([\n \"function receiveMessage(bytes message, bytes attestation) external returns (bool)\",\n]);\n\nconst USED_NONCES_ABI = [\n {\n type: \"function\",\n name: \"usedNonces\",\n stateMutability: \"view\",\n inputs: [{ name: \"nonce\", type: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\n/**\n * CCTPv2 message header layout: the per-burn nonce sits at bytes 12..44.\n * As a 0x-prefixed hex string, that's chars [26, 90).\n */\nfunction extractNonce(cctpMessage: Hex): Hex {\n return `0x${cctpMessage.slice(26, 26 + 64)}` as Hex;\n}\n\n/**\n * CCTPv2 message header: the `destinationCaller` is a bytes32 field at\n * offset 108..140. The address occupies the trailing 20 bytes (left-\n * padded with zeros). In hex-string coordinates that's chars [242, 282).\n *\n * `receiveMessage` reverts with `Invalid caller for message` when\n * `msg.sender` doesn't match this field, so we check it client-side\n * before burning a UserOp + paymaster gas on a guaranteed failure.\n */\nfunction extractDestinationCaller(cctpMessage: Hex): Address {\n return `0x${cctpMessage.slice(242, 282)}` as Address;\n}\n\n/**\n * A UserOp can be included on-chain yet revert during execution;\n * `waitForUserOperationReceipt` then resolves with `success: false` instead of\n * throwing (see submit.ts). A reverted recovery step moved nothing, so it must\n * fail rather than report funds as recovered. Both steps are safe to retry.\n */\nfunction assertExecuted(\n receipt: { success: boolean; reason?: string },\n step: string,\n userOpHash: Hex,\n): void {\n if (!receipt.success) {\n throw new Error(\n `CCTP-inbound recovery ${step} UserOp ${userOpHash} reverted on-chain${\n receipt.reason ? `: ${receipt.reason}` : \"\"\n }`,\n );\n }\n}\n\nexport type RecoveryProgress =\n | { phase: \"attestation\" }\n | { phase: \"receiving\"; userOpHash: Hex }\n | { phase: \"sweeping\"; userOpHash: Hex; amount: bigint }\n | {\n phase: \"done\";\n receiveUserOpHash?: Hex;\n sweepUserOpHash: Hex;\n sweepTxHash?: Hex;\n recoveredAmount: bigint;\n };\n\nexport interface RecoverCctpInboundParams {\n /** Kernel-account owner; must match the original burn's `destinationCaller`. */\n signer: EvmSigner;\n /**\n * Source-chain `depositForBurn` tx hash (for Solana, the base58 transaction\n * signature).\n */\n burnTxHash: string;\n /** SDK chain name the burn originated on (e.g. \"HyperEVM\"). */\n sourceChain: CctpChainName;\n /** EVM address that should receive the recovered USDC on the settlement chain. */\n recipient: Address;\n /** Settlement chain. Defaults to Arbitrum. */\n chain?: Chain;\n /** IRIS API base URL. Defaults to mainnet. */\n irisApiUrl?: string;\n /**\n * Pre-fetched attestation, if available. Skips the IRIS poll when\n * provided — useful when the caller has the burn cached from an\n * earlier session.\n */\n attestation?: { message: Hex; attestation: Hex };\n /** Progress callback for UI updates. */\n onProgress?: (step: RecoveryProgress) => void;\n /** Abort signal — propagates to the attestation poll. */\n signal?: AbortSignal;\n}\n\nexport interface RecoverCctpInboundResult {\n /** UserOp that called `receiveMessage`; omitted when it was already consumed. */\n receiveUserOpHash?: Hex;\n /** UserOp that swept USDC to `recipient`. */\n sweepUserOpHash: Hex;\n /** On-chain tx hash of the sweep UserOp's bundle. */\n sweepTxHash?: Hex;\n /** Smart-account address the funds were swept from. */\n smartAccountAddress: Address;\n /** USDC amount transferred to `recipient`, in smallest units (6 decimals). */\n recoveredAmount: bigint;\n}\n\nexport interface RecoverCctpInboundContext {\n aa: AaConfig;\n}\n\n/**\n * Recover USDC from a stalled CCTP-inbound flow by sweeping the smart\n * account's balance to a user-provided address. Paymaster-sponsored,\n * so the smart account needs no ETH.\n */\nexport async function recoverCctpInbound(\n context: RecoverCctpInboundContext,\n params: RecoverCctpInboundParams,\n): Promise<RecoverCctpInboundResult> {\n const {\n signer,\n burnTxHash,\n sourceChain,\n recipient,\n chain = arbitrum,\n irisApiUrl = IRIS_API_MAINNET,\n onProgress,\n signal,\n } = params;\n\n const { client: aaClient, accountAddress } =\n await createSwapSmartAccountClient({ signer, aa: context.aa, chain });\n\n const publicClient = createPublicClient({\n chain,\n transport: http(context.aa.rpcUrl ?? context.aa.bundlerUrl),\n });\n\n // 1. Make sure we have the attestation. If the receiveMessage call was\n // already made by someone (incl. the user themselves), we can skip\n // the IRIS poll entirely.\n let cctpMessage: Hex | undefined = params.attestation?.message;\n let cctpAttestation: Hex | undefined = params.attestation?.attestation;\n let receiveUserOpHash: Hex | undefined;\n\n // Only Arbitrum is a supported settlement chain today.\n const usdcAddress = USDC_ADDRESSES.Arbitrum;\n\n if (!cctpMessage || !cctpAttestation) {\n onProgress?.({ phase: \"attestation\" });\n const fetched = await fetchAttestation({\n sourceChain,\n txHash: burnTxHash,\n irisApiUrl,\n signal,\n });\n cctpMessage = fetched.message as Hex;\n cctpAttestation = fetched.attestation as Hex;\n }\n\n // 2. Decide whether to include receiveMessage. Use `usedNonces` — the\n // authoritative signal (matches the logic in submit.ts).\n const nonce = extractNonce(cctpMessage);\n const usedNonce = (await publicClient.readContract({\n address: MESSAGE_TRANSMITTER_V2 as Address,\n abi: USED_NONCES_ABI,\n functionName: \"usedNonces\",\n args: [nonce],\n })) as bigint;\n const skipReceiveMessage = usedNonce !== 0n;\n\n // 3. Submit receiveMessage UserOp if the burn hasn't been claimed yet.\n if (!skipReceiveMessage) {\n // Guard: only `destinationCaller` can call receiveMessage. If the\n // current owner key derives a different account, the on-chain\n // revert (\"Invalid caller for message\") is opaque — surface the\n // mismatch with an actionable message instead.\n const destinationCaller = extractDestinationCaller(cctpMessage);\n if (\n destinationCaller.toLowerCase() !==\n (accountAddress as string).toLowerCase()\n ) {\n throw new Error(\n `Recovery wallet mismatch: this CCTP burn was sent to ${destinationCaller}, ` +\n `but your current wallet's smart-account address is ${accountAddress}. ` +\n `You must recover with the same mnemonic that created the original swap.`,\n );\n }\n\n const receiveData = encodeFunctionData({\n abi: MESSAGE_TRANSMITTER_ABI,\n functionName: \"receiveMessage\",\n args: [cctpMessage, cctpAttestation],\n });\n receiveUserOpHash = await aaClient.sendUserOperation({\n calls: [\n {\n to: MESSAGE_TRANSMITTER_V2 as Address,\n data: receiveData,\n value: 0n,\n },\n ],\n });\n onProgress?.({ phase: \"receiving\", userOpHash: receiveUserOpHash });\n assertExecuted(\n await aaClient.waitForUserOperationReceipt({ hash: receiveUserOpHash }),\n \"receiveMessage\",\n receiveUserOpHash,\n );\n }\n\n // 4. Read the smart account's USDC balance — this is the recoverable amount.\n const balance = (await publicClient.readContract({\n address: usdcAddress as Address,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [accountAddress],\n })) as bigint;\n\n if (balance === 0n) {\n throw new Error(\n `No USDC at smart account ${accountAddress} after receiveMessage. Nothing to recover.`,\n );\n }\n\n // 5. Sweep the balance to `recipient`.\n const transferData = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [recipient, balance],\n });\n const sweepUserOpHash = await aaClient.sendUserOperation({\n calls: [\n {\n to: usdcAddress as Address,\n data: transferData,\n value: 0n,\n },\n ],\n });\n onProgress?.({\n phase: \"sweeping\",\n userOpHash: sweepUserOpHash,\n amount: balance,\n });\n\n const sweepReceipt = await aaClient.waitForUserOperationReceipt({\n hash: sweepUserOpHash,\n });\n assertExecuted(sweepReceipt, \"sweep\", sweepUserOpHash);\n const sweepTxHash = sweepReceipt.receipt?.transactionHash as Hex | undefined;\n\n onProgress?.({\n phase: \"done\",\n receiveUserOpHash,\n sweepUserOpHash,\n sweepTxHash,\n recoveredAmount: balance,\n });\n\n return {\n receiveUserOpHash,\n sweepUserOpHash,\n sweepTxHash,\n smartAccountAddress: accountAddress as Address,\n recoveredAmount: balance,\n };\n}\n","/**\n * USDT0 bridge constants.\n *\n * USDT0 uses LayerZero's OFT (Omnichain Fungible Token) standard for\n * cross-chain transfers. On L2s the token contract IS the OFT — it has\n * send() and quoteSend() built in. Transfers burn on source, mint on\n * destination via LayerZero messaging.\n *\n * See: https://docs.usdt0.to/\n */\n\n// ============================================================================\n// LayerZero V2 Endpoint IDs (EIDs)\n// See: https://docs.layerzero.network/v2/developers/evm/technical-reference/deployed-contracts\n// ============================================================================\n\n/**\n * LayerZero V2 Endpoint IDs for all chains with USDT0 deployments.\n * See: https://docs.usdt0.to/technical-documentation/deployments\n */\nexport const LZ_EIDS = {\n Ethereum: 30101,\n Polygon: 30109,\n Arbitrum: 30110,\n Optimism: 30111,\n Mantle: 30181,\n \"Conflux eSpace\": 30212,\n XLayer: 30274,\n Sei: 30280,\n Flare: 30295,\n Hedera: 30316,\n Unichain: 30320,\n Morph: 30322,\n Corn: 30331,\n Rootstock: 30333,\n Ink: 30339,\n Berachain: 30362,\n HyperEVM: 30367,\n Plasma: 30383,\n Monad: 30390,\n Stable: 30396,\n MegaETH: 30398,\n Tempo: 30410,\n Tron: 30420,\n} as const;\n\nexport type Usdt0ChainName = keyof typeof LZ_EIDS;\n\n// ============================================================================\n// USDT0 token addresses per chain\n// See: https://docs.usdt0.to/technical-documentation/deployments\n// ============================================================================\n\nexport const USDT0_ADDRESSES: Record<string, string> = {\n Tron: \"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t\",\n Ethereum: \"0xdAC17F958D2ee523a2206206994597C13D831ec7\",\n Arbitrum: \"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9\",\n Polygon: \"0xc2132D05D31c914a87C6611C10748AEb04B58e8F\",\n Optimism: \"0x01bFF41798a0BcF287b996046Ca68b395DbC1071\",\n Berachain: \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\",\n \"Conflux eSpace\": \"0xaf37E8B6C9ED7f6318979f56Fc287d76c30847ff\",\n Corn: \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\",\n Flare: \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\",\n HyperEVM: \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\",\n Hedera: \"0x00000000000000000000000000000000009Ce723\",\n Ink: \"0x0200C29006150606B650577BBE7B6248F58470c1\",\n Mantle: \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\",\n MegaETH: \"0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb\",\n Monad: \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\",\n Morph: \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\",\n Plasma: \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\",\n Rootstock: \"0x779dED0C9e1022225F8e0630b35A9B54Be713736\",\n Sei: \"0x9151434b16b9763660705744891fA906F660EcC5\",\n Stable: \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\",\n Tempo: \"0x20C00000000000000000000014f22CA97301EB73\",\n Unichain: \"0x9151434b16b9763660705744891fA906F660EcC5\",\n XLayer: \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\",\n};\n","/**\n * LayerZero message tracking for USDT0 cross-chain transfers.\n *\n * Polls the LayerZero Scan API until the cross-chain message is delivered.\n * Similar pattern to CCTP attestation polling.\n *\n * API: https://scan.layerzero-api.com/v1/messages/tx/{txHash}\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** LayerZero message delivery status. */\nexport type LayerZeroMessageStatus =\n | \"INFLIGHT\"\n | \"CONFIRMING\"\n | \"DELIVERED\"\n | \"FAILED\"\n | \"BLOCKED\"\n | \"PAYLOAD_STORED\";\n\n/** Summary of a tracked LayerZero cross-chain message. */\nexport interface LayerZeroMessageResult {\n /** Unique cross-chain message identifier. */\n guid: string;\n /** Current delivery status. */\n status: LayerZeroMessageStatus;\n /** Source chain transaction hash. */\n srcTxHash: string;\n /** Destination chain transaction hash (available once delivered). */\n dstTxHash?: string;\n /** Source chain name (e.g. \"arbitrum\"). */\n srcChain: string;\n /** Destination chain name (e.g. \"optimism\"). */\n dstChain: string;\n /** Source LayerZero endpoint ID. */\n srcEid: number;\n /** Destination LayerZero endpoint ID. */\n dstEid: number;\n}\n\n/** Raw response from the LayerZero Scan API. */\ninterface ScanApiResponse {\n data: Array<{\n pathway: {\n srcEid: number;\n dstEid: number;\n sender: { chain: string };\n receiver: { chain: string };\n };\n source: {\n status: string;\n tx: { txHash: string };\n };\n destination: {\n status: string;\n tx?: { txHash: string };\n };\n status: {\n name: LayerZeroMessageStatus;\n message: string;\n };\n guid: string;\n }>;\n}\n\n// ============================================================================\n// Tracking\n// ============================================================================\n\nexport interface TrackMessageOptions {\n /** Transaction hash of the OFT send on the source chain. */\n txHash: string;\n /** Select the destination message when a transaction emits several messages. */\n destinationEid?: number;\n /** LayerZero Scan API base URL. Defaults to mainnet. */\n apiUrl?: string;\n /** Polling interval in ms. Defaults to 5000 (5s). */\n pollIntervalMs?: number;\n /** Maximum time to wait in ms. Defaults to 300000 (5min). */\n timeoutMs?: number;\n /** Optional abort signal. */\n signal?: AbortSignal;\n /** Optional callback invoked on each poll with the current status. */\n onStatusChange?: (status: LayerZeroMessageStatus) => void;\n}\n\nconst LZ_SCAN_API = \"https://scan.layerzero-api.com\";\n\n/**\n * Poll the LayerZero Scan API until the cross-chain message is delivered.\n *\n * @returns The message result with delivery details.\n * @throws If the message is not delivered within the timeout, or status is FAILED.\n */\nexport async function trackMessage(\n options: TrackMessageOptions,\n): Promise<LayerZeroMessageResult> {\n const {\n txHash,\n destinationEid,\n apiUrl = LZ_SCAN_API,\n pollIntervalMs = 5_000,\n timeoutMs = 300_000,\n signal,\n onStatusChange,\n } = options;\n\n const url = `${apiUrl}/v1/messages/tx/${txHash}`;\n const startTime = Date.now();\n let lastStatus: LayerZeroMessageStatus | undefined;\n\n while (Date.now() - startTime < timeoutMs) {\n signal?.throwIfAborted();\n\n try {\n const response = await fetch(url);\n\n if (response.status === 404 || response.status === 429) {\n // Not yet indexed or rate-limited, keep polling\n await sleep(pollIntervalMs, signal);\n continue;\n }\n\n if (!response.ok) {\n throw new Error(\n `LayerZero Scan API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data: ScanApiResponse = await response.json();\n\n if (data.data.length === 0) {\n // Not yet indexed\n await sleep(pollIntervalMs, signal);\n continue;\n }\n\n const msg =\n destinationEid === undefined\n ? data.data[0]\n : data.data.find(\n (message) => message.pathway.dstEid === destinationEid,\n );\n if (!msg) {\n await sleep(pollIntervalMs, signal);\n continue;\n }\n const status = msg.status.name;\n\n if (status !== lastStatus) {\n lastStatus = status;\n onStatusChange?.(status);\n }\n\n if (status === \"FAILED\" || status === \"BLOCKED\") {\n throw new Error(\n `LayerZero message ${status}: ${msg.status.message} (guid: ${msg.guid})`,\n );\n }\n\n if (status === \"DELIVERED\") {\n return {\n guid: msg.guid,\n status,\n srcTxHash: msg.source.tx.txHash,\n dstTxHash: msg.destination.tx?.txHash,\n srcChain: msg.pathway.sender.chain,\n dstChain: msg.pathway.receiver.chain,\n srcEid: msg.pathway.srcEid,\n dstEid: msg.pathway.dstEid,\n };\n }\n\n // INFLIGHT / CONFIRMING — keep polling\n await sleep(pollIntervalMs, signal);\n } catch (err) {\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw err;\n }\n if (\n err instanceof Error &&\n (err.message.includes(\"FAILED\") || err.message.includes(\"BLOCKED\"))\n ) {\n throw err;\n }\n // Network errors — retry after delay\n await sleep(pollIntervalMs, signal);\n }\n }\n\n throw new Error(\n `LayerZero message not delivered after ${timeoutMs / 1000}s for tx ${txHash}`,\n );\n}\n\n/**\n * Get the current status of a LayerZero cross-chain message without polling.\n *\n * @returns The message result, or null if not yet indexed.\n */\nexport async function getMessageStatus(\n txHash: string,\n apiUrl: string = LZ_SCAN_API,\n destinationEid?: number,\n): Promise<LayerZeroMessageResult | null> {\n const url = `${apiUrl}/v1/messages/tx/${txHash}`;\n const response = await fetch(url);\n\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new Error(\n `LayerZero Scan API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data: ScanApiResponse = await response.json();\n if (data.data.length === 0) return null;\n\n const msg =\n destinationEid === undefined\n ? data.data[0]\n : data.data.find((message) => message.pathway.dstEid === destinationEid);\n if (!msg) return null;\n return {\n guid: msg.guid,\n status: msg.status.name,\n srcTxHash: msg.source.tx.txHash,\n dstTxHash: msg.destination.tx?.txHash,\n srcChain: msg.pathway.sender.chain,\n dstChain: msg.pathway.receiver.chain,\n srcEid: msg.pathway.srcEid,\n dstEid: msg.pathway.dstEid,\n };\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Get the LayerZero Scan explorer URL for a transaction.\n */\nexport function getExplorerUrl(txHash: string): string {\n return `https://layerzeroscan.com/tx/${txHash}`;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n },\n { once: true },\n );\n });\n}\n","/**\n * USDT0 bridge utility functions.\n */\n\nimport { LZ_EIDS, type Usdt0ChainName } from \"./constants.js\";\n\n/**\n * Convert an EVM address to OFT's bytes32 format (left-padded with zeros).\n * @param address - 0x-prefixed hex address (20 bytes)\n * @returns 0x-prefixed bytes32 hex string (32 bytes)\n */\nexport function addressToBytes32(address: string): string {\n const clean = address.toLowerCase().replace(\"0x\", \"\");\n if (clean.length !== 40) {\n throw new Error(\n `Invalid address length: expected 40 hex chars, got ${clean.length}`,\n );\n }\n return `0x${clean.padStart(64, \"0\")}`;\n}\n\n/**\n * Convert an OFT bytes32 back to an EVM address.\n * @param bytes32 - 0x-prefixed bytes32 hex string\n * @returns 0x-prefixed address\n */\nexport function bytes32ToAddress(bytes32: string): string {\n const clean = bytes32.replace(\"0x\", \"\");\n if (clean.length !== 64) {\n throw new Error(\n `Invalid bytes32 length: expected 64 hex chars, got ${clean.length}`,\n );\n }\n return `0x${clean.slice(24)}`;\n}\n\n/**\n * Get the LayerZero endpoint ID for a chain name.\n * @param chainName - Chain name (e.g. \"Ethereum\", \"Arbitrum\", \"Base\")\n * @returns The LayerZero EID, or undefined if not supported.\n */\nexport function getEid(chainName: string): number | undefined {\n return LZ_EIDS[chainName as Usdt0ChainName];\n}\n\n/**\n * Check if two chains require USDT0 OFT bridging (i.e., they're different\n * and both supported by USDT0).\n * @param sourceChain - Source chain name\n * @param targetChain - Target chain name\n * @returns true if USDT0 bridging is needed\n */\nexport function needsBridge(sourceChain: string, targetChain: string): boolean {\n if (sourceChain === targetChain) return false;\n const sourceEid = getEid(sourceChain);\n const targetEid = getEid(targetChain);\n return sourceEid !== undefined && targetEid !== undefined;\n}\n","import type { TokenId, TokenInfo } from \"./api/client.js\";\nimport { CCTP_DOMAINS, USDC_ADDRESSES } from \"./cctp/index.js\";\nimport type { Chain } from \"./types/chain.js\";\nimport { LZ_EIDS, USDT0_ADDRESSES } from \"./usdt0-bridge/index.js\";\n\n/** A token identifier: either a plain string TokenId or a TokenInfo object. */\nexport type TokenInput = TokenId;\n\n// ── Asset ────────────────────────────────────────────────────────────────────\n\n/**\n * Minimal asset identifier — just a chain and token ID.\n *\n * Use the predefined constants in {@link Asset} for common tokens,\n * or construct your own for any token the API supports:\n *\n * ```ts\n * // Predefined\n * Asset.BTC_ARKADE\n * Asset.USDC_POLYGON\n *\n * // Custom (any ERC-20 by contract address)\n * { chain: \"137\", tokenId: \"0x...\" }\n * ```\n */\nexport interface Asset {\n /** Chain identifier — e.g. \"Lightning\", \"Arkade\", \"Bitcoin\", \"137\", \"1\", \"42161\" */\n chain: Chain | (string & {});\n /** Token ID — \"btc\" for Bitcoin, or the ERC-20 contract address for EVM tokens */\n tokenId: string;\n}\n\n// Well-known USDC contract addresses\nconst USDC_POLYGON = \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\";\nconst USDC_ARBITRUM = \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\";\nconst USDC_ETHEREUM = \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\";\n\n// Well-known USDT contract addresses\nconst USDT_POLYGON = \"0xc2132D05D31c914a87C6611C10748AEb04B58e8F\";\nconst USDT_ARBITRUM = \"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9\";\nconst USDT_ETHEREUM = \"0xdAC17F958D2ee523a2206206994597C13D831ec7\";\n\n// Well-known WBTC contract addresses\nconst WBTC_POLYGON = \"0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6\";\nconst WBTC_ETHEREUM = \"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599\";\n\n// Circle Wrapped Bitcoin on Ethereum\nconst CIRBTC_ETHEREUM = \"0x72DFB2E44f59C5AD2bAFE84314E5b99a7cd5075E\";\n\n// Well-known tBTC contract addresses\nconst TBTC_ETHEREUM = \"0x18084fbA666a33d37592fA2633fD49a74DD93a88\";\nconst TBTC_ARBITRUM = \"0x6c84a8f1c29108F47a79964b5Fe888D4f4D0dE40\";\n\n/**\n * Predefined asset constants for common tokens.\n *\n * ```ts\n * import { Asset } from \"@lendasat/lendaswap-sdk-pure\";\n *\n * await client.createSwap({\n * source: Asset.BTC_ARKADE,\n * target: Asset.USDC_POLYGON,\n * sourceAmount: 100_000,\n * targetAddress: \"0x...\",\n * });\n * ```\n */\nexport const Asset = {\n // Bitcoin\n BTC_LIGHTNING: { chain: \"Lightning\", tokenId: \"btc\" } as Asset,\n BTC_ARKADE: { chain: \"Arkade\", tokenId: \"btc\" } as Asset,\n BTC_ONCHAIN: { chain: \"Bitcoin\", tokenId: \"btc\" } as Asset,\n\n // USDC\n USDC_POLYGON: { chain: \"137\", tokenId: USDC_POLYGON } as Asset,\n USDC_ARBITRUM: { chain: \"42161\", tokenId: USDC_ARBITRUM } as Asset,\n USDC_ETHEREUM: { chain: \"1\", tokenId: USDC_ETHEREUM } as Asset,\n\n // USDT\n USDT_POLYGON: { chain: \"137\", tokenId: USDT_POLYGON } as Asset,\n USDT_ARBITRUM: { chain: \"42161\", tokenId: USDT_ARBITRUM } as Asset,\n USDT_ETHEREUM: { chain: \"1\", tokenId: USDT_ETHEREUM } as Asset,\n USDT_TRON: { chain: \"Tron\", tokenId: USDT0_ADDRESSES.Tron } as Asset,\n\n // WBTC\n WBTC_POLYGON: { chain: \"137\", tokenId: WBTC_POLYGON } as Asset,\n WBTC_ETHEREUM: { chain: \"1\", tokenId: WBTC_ETHEREUM } as Asset,\n\n // Circle Wrapped Bitcoin\n CIRBTC_ETHEREUM: { chain: \"1\", tokenId: CIRBTC_ETHEREUM } as Asset,\n\n // tBTC\n TBTC_ETHEREUM: { chain: \"1\", tokenId: TBTC_ETHEREUM } as Asset,\n TBTC_ARBITRUM: { chain: \"42161\", tokenId: TBTC_ARBITRUM } as Asset,\n} as const;\n\n// ── Legacy constants (kept for backward compatibility) ───────────────────────\n\n// Well-known token ID constants\nexport const BTC_LIGHTNING: TokenId = \"btc\";\nexport const BTC_ARKADE: TokenId = \"btc\";\nexport const BTC_ONCHAIN: TokenId = \"btc\";\n\n// Well-known TokenInfo constants\nexport const BTC_LIGHTNING_INFO: TokenInfo = {\n token_id: BTC_LIGHTNING,\n symbol: \"BTC\",\n name: \"Bitcoin (Lightning)\",\n decimals: 8,\n chain: \"Lightning\",\n};\n\nexport const BTC_ARKADE_INFO: TokenInfo = {\n token_id: BTC_ARKADE,\n symbol: \"BTC\",\n name: \"Bitcoin (Arkade)\",\n decimals: 8,\n chain: \"Arkade\",\n};\n\nexport const BTC_ONCHAIN_INFO: TokenInfo = {\n token_id: BTC_ONCHAIN,\n symbol: \"BTC\",\n name: \"Bitcoin (On-chain)\",\n decimals: 8,\n chain: \"Bitcoin\",\n};\n\n// ============================================================================\n// EVM Chain IDs\n// ============================================================================\n\n/** Source chains where HTLCs and DEX swaps run. */\nconst SOURCE_EVM_CHAINS = [\"1\", \"137\", \"42161\"] as const;\n\n/** All EVM chain IDs including CCTP and USDT0 bridge-only destinations. */\nexport const ALL_EVM_CHAIN_IDS: Record<string, string> = {\n Ethereum: \"1\",\n Polygon: \"137\",\n Arbitrum: \"42161\",\n Optimism: \"10\",\n Base: \"8453\",\n Avalanche: \"43114\",\n Linea: \"59144\",\n Unichain: \"130\",\n Sonic: \"146\",\n \"World Chain\": \"480\",\n Ink: \"57073\",\n Sei: \"1329\",\n HyperEVM: \"999\",\n Monad: \"143\",\n XDC: \"50\",\n // USDT0-only chains\n Berachain: \"80094\",\n \"Conflux eSpace\": \"1030\",\n Corn: \"21000000\",\n Flare: \"14\",\n Hedera: \"295\",\n Mantle: \"5000\",\n MegaETH: \"4326\",\n Morph: \"2818\",\n Plasma: \"9745\",\n Rootstock: \"30\",\n Stable: \"988\",\n Tempo: \"4217\",\n XLayer: \"196\",\n};\n\n/** Reverse lookup: chain ID → chain name. */\nconst CHAIN_ID_TO_NAME: Record<string, string> = Object.fromEntries(\n Object.entries(ALL_EVM_CHAIN_IDS).map(([name, id]) => [id, name]),\n);\n\n// ============================================================================\n// Chain detection helpers\n// ============================================================================\n\n/** Returns true if the token is Bitcoin on Lightning. */\nexport function isLightning(token: { chain: string }): boolean {\n return token.chain.toLowerCase() === \"lightning\";\n}\n\n/** Returns true if the token is Bitcoin on Arkade. */\nexport function isArkade(token: { chain: string }): boolean {\n return token.chain.toLowerCase() === \"arkade\";\n}\n\n/** Returns true if the token is Bitcoin on-chain (L1). */\nexport function isBtcOnchain(token: { chain: string }): boolean {\n return token.chain.toLowerCase() === \"bitcoin\";\n}\n\n/** Returns true if the token is any form of Bitcoin (Lightning, Arkade, or on-chain). */\nexport function isBtc(token: { chain: string }): boolean {\n return isLightning(token) || isArkade(token) || isBtcOnchain(token);\n}\n\n/**\n * Returns true if the token is a BTC-pegged EVM asset (WBTC, cirBTC, tBTC, or RBTC,\n * Rootstock's coin). These should be displayed like BTC (sats/BTC, 8 decimal\n * precision) even though tBTC and RBTC have 18 on-chain decimals.\n */\nexport function isBtcPegged(token: { chain: string; symbol: string }): boolean {\n const sym = token.symbol.toLowerCase();\n return (\n (sym === \"wbtc\" || sym === \"cirbtc\" || sym === \"tbtc\" || sym === \"rbtc\") &&\n isEvmToken(token.chain)\n );\n}\n\n/** Returns true if the chain is any EVM chain (source or bridge destination). */\nexport function isEvmToken(chain: string): boolean {\n return (\n SOURCE_EVM_CHAINS.includes(chain as (typeof SOURCE_EVM_CHAINS)[number]) ||\n Object.values(ALL_EVM_CHAIN_IDS).includes(chain) ||\n isNativeLockChain(chain)\n );\n}\n\n/** Returns true if the chain is a source EVM chain (has HTLC contracts). */\nexport function isSourceEvmChain(chain: string): boolean {\n return SOURCE_EVM_CHAINS.includes(\n chain as (typeof SOURCE_EVM_CHAINS)[number],\n );\n}\n\n/** Returns true if the chain is a bridge-only destination (no HTLC contracts). */\nexport function isBridgeOnlyChain(chain: string): boolean {\n if (isSolanaToken(chain) || isTronToken(chain)) return true;\n return isEvmToken(chain) && !isSourceEvmChain(chain);\n}\n\n/**\n * Returns true for a chain that locks its own coin in its own HTLC: Rootstock,\n * under its mainnet id (\"30\"), its testnet id (\"31\" — what a testnet daemon\n * reports it as) or by name.\n */\nexport function isNativeLockChain(chain: string): boolean {\n const c = chain.toLowerCase();\n return c === \"30\" || c === \"31\" || c === \"rootstock\";\n}\n\n/**\n * Returns true for the native coin of a chain that locks it in its own HTLC\n * (RBTC on Rootstock, token id = the zero address). Rootstock is also a USDT0\n * bridge destination, so the chain alone does not say whether a target is\n * bridged; its coin is a first-class target settled on Rootstock itself, never\n * remapped to the Arbitrum hub.\n */\nexport function isNativeLockTarget(chain: string, token: string): boolean {\n return isNativeLockChain(chain) && /^0x0{40}$/i.test(token);\n}\n\n/**\n * Returns true when `token` on `chain` can be the source of an EVM-sourced\n * swap: any asset on a chain with the ERC20 HTLC contracts, or the native\n * coin of a native-lock chain (RBTC on Rootstock). Rootstock is not a source\n * chain in general, since its USDT0 bridge deposits are targets only.\n */\nexport function isEvmSwapSource(chain: string, token: string): boolean {\n return isSourceEvmChain(chain) || isNativeLockTarget(chain, token);\n}\n\n/** Native USDT on Tron is a send-only Legacy Mesh destination. */\nexport function isTronToken(chain: string): boolean {\n return chain.toLowerCase() === \"tron\";\n}\n\n/**\n * Kill switch for paying out USDC on Ethereum and Polygon over CCTP from\n * Arbitrum. With `false`, those payouts run on the chain directly again.\n * Keep in sync with `CCTP_ROUTED_USDC_ENABLED` in the Rust SDK.\n */\nexport const CCTP_ROUTED_USDC_ENABLED = true;\n\n/** Hub chains whose native USDC is paid out over CCTP from Arbitrum. */\nconst CCTP_ROUTED_USDC_CHAINS: Record<string, string> = {\n \"1\": \"Ethereum\",\n \"137\": \"Polygon\",\n};\n\n/**\n * Returns true for native USDC on Ethereum or Polygon as a swap *target*.\n * Both chains have HTLCs, but USDC payouts to them settle on Arbitrum and\n * bridge over CCTP, which keeps the BTC-pegged liquidity on one chain.\n * Sources are unaffected: USDC on these chains still funds a swap directly.\n */\nexport function isCctpRoutedUsdcTarget(chain: string, token: string): boolean {\n if (!CCTP_ROUTED_USDC_ENABLED) return false;\n const name = CCTP_ROUTED_USDC_CHAINS[toChain(chain)];\n return (\n name != null && USDC_ADDRESSES[name]?.toLowerCase() === token.toLowerCase()\n );\n}\n\n/**\n * Returns true when a swap paying out `token` on `chain` settles on Arbitrum\n * and bridges to `chain`: any token on a bridge-only chain (except a native\n * lock target such as RBTC), plus USDC on Ethereum and Polygon.\n */\nexport function isBridgedTarget(chain: string, token: string): boolean {\n if (isNativeLockTarget(chain, token)) return false;\n return isBridgeOnlyChain(chain) || isCctpRoutedUsdcTarget(chain, token);\n}\n\n/**\n * Returns true if the chain is Solana. Solana is a CCTP-only destination —\n * funds reach it via Circle's Forwarding Service after an Arbitrum-side\n * burn, never as a swap source/target chain in its own right.\n */\nexport function isSolanaToken(chain: string): boolean {\n return chain.toLowerCase() === \"solana\";\n}\n\n/**\n * Returns true if the token is USDC on a CCTPv2-supported chain.\n *\n * Used to decide whether a token can act as the *source* of a swap via\n * bridge-kit (any CCTP chain → Arbitrum → BTC): we bridge the user's USDC\n * into Arbitrum first, then run the existing Arbitrum USDC → BTC swap.\n */\nexport function isCctpUsdc(token: {\n chain: string;\n symbol: string;\n token_id?: string;\n}): boolean {\n if (token.symbol.toUpperCase() !== \"USDC\") return false;\n const tokenChainLower = token.chain.toLowerCase();\n for (const chainName of Object.keys(CCTP_DOMAINS)) {\n if (tokenChainLower === chainName.toLowerCase()) return true;\n const chainId = ALL_EVM_CHAIN_IDS[chainName];\n if (chainId && token.chain === chainId) return true;\n }\n return false;\n}\n\n/** Returns true if the chain is Ethereum. */\nexport function isEthereumToken(c: string): boolean {\n return c.toLowerCase() === \"ethereum\" || c === \"1\";\n}\n\n/** Returns true if the chain is Polygon. */\nexport function isPolygonToken(c: string): boolean {\n return c.toLowerCase() === \"polygon\" || c === \"137\";\n}\n\n/** Returns true if the chain is Arbitrum. */\nexport function isArbitrumToken(chain: string): boolean {\n return chain.toLowerCase() === \"arbitrum\" || chain === \"42161\";\n}\n\nexport function isBaseToken(chain: string): boolean {\n return chain.toLowerCase() === \"base\" || chain === \"8453\";\n}\n\nexport function isOptimismToken(chain: string): boolean {\n return chain.toLowerCase() === \"optimism\" || chain === \"10\";\n}\n\nexport function isAvalancheToken(chain: string): boolean {\n return chain.toLowerCase() === \"avalanche\" || chain === \"43114\";\n}\n\nexport function isLineaToken(chain: string): boolean {\n return chain.toLowerCase() === \"linea\" || chain === \"59144\";\n}\n\nexport function isSonicToken(chain: string): boolean {\n return chain.toLowerCase() === \"sonic\" || chain === \"146\";\n}\n\n/** Normalizes any chain string to its canonical Chain value. */\nexport function toChain(str: string): Chain {\n const c = str.toLowerCase();\n if (c === \"ethereum\" || c === \"1\") return \"1\";\n if (c === \"polygon\" || c === \"137\") return \"137\";\n if (c === \"arbitrum\" || c === \"42161\") return \"42161\";\n if (c === \"rootstock\" || c === \"30\") return \"30\";\n // Rootstock testnet keeps its own id: a testnet daemon's chain \"31\" must\n // not collapse into mainnet's \"30\".\n if (c === \"31\") return \"31\";\n if (c === \"lightning\") return \"Lightning\";\n if (c === \"arkade\") return \"Arkade\";\n if (c === \"bitcoin\") return \"Bitcoin\";\n // Solana is a CCTP destination only — not a first-class Chain in the\n // backend's union, so we cast through. Frontends use the literal \"Solana\"\n // string for icons / dropdown filters.\n if (c === \"solana\") return \"Solana\" as Chain;\n if (c === \"tron\") return \"Tron\";\n // Check new chains by name\n for (const [name, id] of Object.entries(ALL_EVM_CHAIN_IDS)) {\n if (c === name.toLowerCase() || c === id) return id as Chain;\n }\n return \"Bitcoin\";\n}\n\nexport function toChainName(chain: Chain): string {\n if (isTronToken(chain)) return \"Tron\";\n return CHAIN_ID_TO_NAME[chain] ?? chain.toString();\n}\n\n/**\n * Get the CCTP bridge target chain name for a token, if bridging is needed.\n * Returns undefined if the token is on a source chain (no bridge needed)\n * or is not an EVM token.\n */\nexport function getBridgeTargetChain(token: TokenInfo): string | undefined {\n if (isBridgedTarget(token.chain, String(token.token_id))) {\n return CHAIN_ID_TO_NAME[token.chain] ?? toChainName(token.chain as Chain);\n }\n return undefined;\n}\n\n// ============================================================================\n// CCTP USDC bridge tokens (target-only)\n// ============================================================================\n\n/**\n * Generate TokenInfo objects for USDC on all CCTP-supported chains.\n * These are \"bridge-only\" target tokens — the swap runs on a source chain\n * (Polygon/Ethereum/Arbitrum) and USDC is bridged to the destination via CCTP.\n *\n * Excludes source chains (those already have USDC tokens from the backend).\n */\n/**\n * A {@link TokenInfo} for an SDK-composed bridge target. Identical shape to\n * `TokenInfo` except `chain` is the wide public {@link Chain} — these tokens\n * live on CCTP/OFT bridge chains (Base, Optimism, Solana, …) that the narrow\n * wire `TokenInfo[\"chain\"]` can't represent.\n */\nexport type BridgeTokenInfo = Omit<TokenInfo, \"chain\"> & { chain: Chain };\n\nexport function getCctpBridgeTokens(): BridgeTokenInfo[] {\n const sourceChainNames = new Set([\"Ethereum\", \"Polygon\", \"Arbitrum\"]);\n const tokens: BridgeTokenInfo[] = [];\n\n for (const chainName of Object.keys(CCTP_DOMAINS)) {\n // Skip source chains (backend already provides their USDC tokens)\n if (sourceChainNames.has(chainName)) continue;\n\n const usdcAddress = USDC_ADDRESSES[chainName];\n if (!usdcAddress) continue;\n\n // Solana has no EVM chain id — use the literal \"Solana\" string as the\n // chain identifier (matches the backend's `bridge_target_chain` value).\n const chainIdentifier =\n chainName === \"Solana\" ? \"Solana\" : ALL_EVM_CHAIN_IDS[chainName];\n if (!chainIdentifier) continue;\n\n tokens.push({\n token_id: usdcAddress as TokenId,\n symbol: \"USDC\",\n name: `USD Coin (${chainName})`,\n decimals: 6,\n chain: chainIdentifier as Chain,\n });\n }\n\n return tokens;\n}\n\n// ============================================================================\n// USDT0 OFT bridge tokens (target-only)\n// ============================================================================\n\n/**\n * Generate TokenInfo objects for USDT0 on all LayerZero OFT-supported chains.\n * These are \"bridge-only\" target tokens — the swap runs on Arbitrum and USDT0\n * is bridged to the destination via LayerZero OFT send().\n *\n * Excludes source chains (those already have USDT0 tokens from the backend).\n */\nexport function getUsdt0BridgeTokens(): BridgeTokenInfo[] {\n const sourceChainNames = new Set([\"Ethereum\", \"Polygon\", \"Arbitrum\"]);\n const tokens: BridgeTokenInfo[] = [];\n\n for (const chainName of Object.keys(LZ_EIDS)) {\n // Skip source chains (backend already provides their USDT tokens)\n if (sourceChainNames.has(chainName)) continue;\n\n const usdt0Address = USDT0_ADDRESSES[chainName];\n const chainId =\n chainName === \"Tron\" ? \"Tron\" : ALL_EVM_CHAIN_IDS[chainName];\n if (!usdt0Address || !chainId) continue;\n\n tokens.push({\n token_id: usdt0Address as TokenId,\n symbol: \"USDT\",\n name: `Tether USD (${chainName})`,\n decimals: 6,\n chain: chainId as Chain,\n });\n }\n\n return tokens;\n}\n","/**\n * `composeQuote` — build an end-to-end `QuoteResponse` from the three\n * server primitives:\n *\n * - `/swap-pairs` — static rates and limits per pair.\n * - `/network-fees` — current gas/mining sats per pair.\n * - `/dex-quote` — live DEX-leg pricing on the settlement hub.\n *\n * The output is the *same* `QuoteResponse` shape as `getQuote()` so the\n * two are substitutable. An E2E parity harness keeps them numerically\n * aligned; once parity holds across all supported pairs, the legacy\n * `getQuote()` body gets replaced with a call to this and the names\n * swap.\n *\n * # Supported pairs\n *\n * - A BTC-denominated side (`source_token`/`target_token` = `\"btc\"`) on\n * Bitcoin, Arkade, or Lightning, paired with an EVM token on any chain\n * present in `/chain-config` (Arbitrum, Polygon, …).\n * - Either direction (BTC-side → EVM, or EVM → BTC-side).\n * - Either `sourceAmount` or `targetAmount` pinned.\n * - Direct BTC↔pegged-pivot targets (tBTC / WBTC) skip the DEX; other\n * targets route through `/dex-quote`.\n *\n * Foreign-target EVM↔EVM (neither side BTC) is not supported and throws\n * `UnsupportedComposeQuotePath`.\n */\n\nimport { isCctpRoutedUsdcTarget } from \"./tokens.js\";\nimport type {\n Chain,\n ChainConfigResponse,\n DexQuoteResponse,\n NetworkFeesResponse,\n QuoteResponse,\n SwapPairsResponse,\n Token,\n} from \"./types/index.js\";\n\n/**\n * Look up the BTC-pegged pivot token for an EVM chain.\n *\n * The truth lives on the server (`config.wbtc_address(chain)` + the\n * token list for decimals/symbol) and ships in `/chain-config`. Pulling\n * it from the response — rather than hardcoding a per-chain map in the\n * SDK — means new chains light up the moment the server's config does.\n *\n * Both `composeBtcToEvm` and `composeEvmToBtc` compute the scale as\n * `10^(decimals - 8)`, so any chain whose `btc_pegged_token` is in the\n * range [8, 18] decimals works without further changes.\n */\ninterface Pivot {\n address: string;\n decimals: number;\n /** Pegged-token units per 1 BTC (`\"1\"` for tBTC, WBTC/BTC rate for WBTC). */\n pegRate: string;\n}\n\nfunction pivotForChain(\n chainConfig: ChainConfigResponse,\n chain: Chain,\n): Pivot | undefined {\n const entry = chainConfig.chains.find((c) => c.chain === chain);\n if (!entry) return undefined;\n return {\n address: entry.btc_pegged_token.address,\n decimals: entry.btc_pegged_token.decimals,\n pegRate: entry.btc_peg_rate,\n };\n}\n\n/** Arbitrum — the settlement hub every bridge pivots through. */\nconst ARBITRUM_CHAIN = \"42161\" as Chain;\nconst ARBITRUM_CHAIN_ID = 42161;\n\n/** How the EVM leg reaches a given chain — directly on a hub, or bridged. */\ninterface EvmRouting {\n /** Pivot token on the settlement chain: the EVM chain itself if it's a hub,\n * otherwise Arbitrum's tBTC. */\n btcPegged: Pivot;\n /** Chain id the pivot + HTLC live on (the DEX pivot side). */\n pivotChainId: number;\n /** Chain used for swap-pair / network-fee lookups (the settlement hub). */\n hubChain: Chain;\n /** Chain id of the user's EVM token (same as `pivotChainId` when direct,\n * the remote chain when bridged). */\n tokenChainId: number;\n /** True when the route bridges through Arbitrum. */\n bridged: boolean;\n}\n\n/**\n * Decide how the EVM leg reaches `evmChain`:\n *\n * - **hub** (a chain with a BTC-pegged pivot in `/chain-config` — today\n * Arbitrum, Polygon, Ethereum) → swap there directly; pivot/HTLC and the\n * user's token share the chain, no bridge.\n * - **anything else** (Optimism, Base, Solana, USDT0-only chains, …) → bridge\n * through Arbitrum: the HTLC settles in tBTC on Arbitrum, the DEX leg crosses\n * Arbitrum↔`evmChain`, and the swap-pair / network-fee legs key off Arbitrum.\n * The bridge protocol (CCTP vs OFT) and its fee are resolved server-side from\n * the token, and `/dex-quote` already folds the fee into the amounts.\n *\n * `viaArbitrum` forces the bridged route for a hub chain. Payouts in USDC on\n * Ethereum or Polygon use it: they settle on Arbitrum and bridge over CCTP\n * (see `isCctpRoutedUsdcTarget`). Sources on those chains stay direct.\n */\nfunction resolveEvmRouting(\n chainConfig: ChainConfigResponse,\n evmChain: Chain,\n viaArbitrum = false,\n): EvmRouting {\n const tokenChainId = Number.parseInt(evmChain, 10);\n if (Number.isNaN(tokenChainId)) {\n throw new UnsupportedComposeQuotePath(\n `composeQuote: EVM chain ${evmChain} is not numeric`,\n );\n }\n const direct = viaArbitrum ? undefined : pivotForChain(chainConfig, evmChain);\n if (direct) {\n return {\n btcPegged: direct,\n pivotChainId: tokenChainId,\n hubChain: evmChain,\n tokenChainId,\n bridged: false,\n };\n }\n const arb = pivotForChain(chainConfig, ARBITRUM_CHAIN);\n if (!arb) {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: Arbitrum pivot missing from chain-config; cannot bridge\",\n );\n }\n return {\n btcPegged: arb,\n pivotChainId: ARBITRUM_CHAIN_ID,\n hubChain: ARBITRUM_CHAIN,\n tokenChainId,\n bridged: true,\n };\n}\n\n/** Solana — a CCTP-only, non-EVM destination carried as a base58 SPL token. */\nconst SOLANA_CHAIN = \"Solana\" as Chain;\n\n/** The routing + the actual `to` token a BTC→EVM/Solana quote delivers to. */\ninterface TargetRouting {\n btcPegged: Pivot;\n pivotChainId: number;\n hubChain: Chain;\n /** The remote token the DEX delivers — EVM (hub or bridged) or Solana. */\n toToken: Token;\n}\n\n/**\n * Resolve the target side, including non-EVM Solana. Solana is CCTP-only, so it\n * bridges through Arbitrum (like a non-hub EVM chain) but its `to` token is a\n * `{ kind: \"solana\" }` base58 SPL address rather than an EVM hex address.\n */\nfunction resolveTargetRouting(\n chainConfig: ChainConfigResponse,\n targetChain: Chain,\n targetToken: string,\n): TargetRouting {\n if (targetChain === SOLANA_CHAIN) {\n const arb = pivotForChain(chainConfig, ARBITRUM_CHAIN);\n if (!arb) {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: Arbitrum pivot missing from chain-config; cannot bridge to Solana\",\n );\n }\n return {\n btcPegged: arb,\n pivotChainId: ARBITRUM_CHAIN_ID,\n hubChain: ARBITRUM_CHAIN,\n toToken: { kind: \"solana\", address: targetToken },\n };\n }\n const r = resolveEvmRouting(\n chainConfig,\n targetChain,\n isCctpRoutedUsdcTarget(targetChain, targetToken),\n );\n return {\n btcPegged: r.btcPegged,\n pivotChainId: r.pivotChainId,\n hubChain: r.hubChain,\n toToken: {\n kind: \"evm\",\n chain_id: r.tokenChainId,\n address: targetToken.toLowerCase(),\n },\n };\n}\n\n/**\n * Parse a decimal rate string (\"1\", \"0.99790000\") into an exact\n * numerator/denominator so the BTC↔pegged conversion is integer-exact\n * and matches the server's `rust_decimal` arithmetic to the unit.\n */\nfunction parseRate(rate: string): { num: bigint; den: bigint } {\n const [intPart, fracPart = \"\"] = rate.split(\".\");\n const num = BigInt(`${intPart}${fracPart}` || \"0\");\n const den = 10n ** BigInt(fracPart.length);\n return { num, den };\n}\n\n// Direct BTC↔pegged conversions, applying the pivot's `btc_peg_rate` as a\n// *consistent* exchange rate: `pegged = sats × rate` forward,\n// `sats = pegged / rate` inverse — a true inverse, so a round trip is\n// lossless. The server currently reports `btc_peg_rate = \"1\"` for every\n// chain (BTC pegs treated 1:1), so these reduce to pure decimal scaling;\n// the rate is plumbed through for the day a chain's peg isn't 1:1. (Note:\n// this deliberately does NOT reproduce legacy `calculate_wbtc_amounts`'s\n// symmetric ×rate haircut on WBTC — see the composed-only WBTC tests.)\n\n/** Pegged base units = round(btcSats × rate) × pivotScale. */\nfunction satsToPeggedBase(\n btcSats: bigint,\n pegRate: string,\n pivotScale: bigint,\n): bigint {\n const { num, den } = parseRate(pegRate);\n // round(btcSats × num / den), half away from zero (positive amounts).\n const peggedSats = (btcSats * num + den / 2n) / den;\n return peggedSats * pivotScale;\n}\n\n/** BTC sats = trunc((peggedBase / pivotScale) / rate). */\nfunction peggedBaseToSats(\n peggedBase: bigint,\n pegRate: string,\n pivotScale: bigint,\n): bigint {\n const { num, den } = parseRate(pegRate);\n // trunc((peggedBase / pivotScale) / (num / den)) = peggedBase × den / (pivotScale × num)\n return (peggedBase * den) / (pivotScale * num);\n}\n\n/** True if `token` is the chain's BTC-pegged pivot (case-insensitive). */\nfunction isPivotToken(token: string, btcPegged: { address: string }): boolean {\n return token.toLowerCase() === btcPegged.address.toLowerCase();\n}\n\n/**\n * Direct BTC → pegged-token pivot, no DEX leg — the target token *is* the\n * pivot (e.g. BTC → tBTC). The BTC↔pegged conversion uses the pivot's\n * `pegRate` from `/chain-config`: exact 1:1 for tBTC, the live WBTC/BTC\n * rate for WBTC. Matches the server's `calculate_wbtc_amounts` to the\n * unit (round-half-up forward, truncating inverse).\n */\nfunction directBtcToPeggedPivot(\n params: ComposeQuoteParams,\n pivot: Pivot,\n pivotScale: bigint,\n): BtcEvmPivot {\n let btcSats: bigint;\n let evmSmallest: bigint;\n if (params.sourceAmount != null) {\n // Source-pinned: BTC sats in, pegged base units out.\n btcSats = BigInt(params.sourceAmount);\n evmSmallest = satsToPeggedBase(btcSats, pivot.pegRate, pivotScale);\n } else if (params.targetAmount != null) {\n // Target-pinned: pegged base units in, BTC sats out.\n evmSmallest = BigInt(params.targetAmount);\n btcSats = peggedBaseToSats(evmSmallest, pivot.pegRate, pivotScale);\n } else {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: no amount pinned (unreachable)\",\n );\n }\n return {\n btcSats,\n evmSmallest,\n evmDecimals: pivot.decimals,\n bridgeFee: 0n,\n bridgeNativeFeeSats: 0,\n };\n}\n\n/**\n * Direct pegged-token → BTC pivot, no DEX leg — the source token *is* the\n * pivot (e.g. tBTC → BTC). Mirror of {@link directBtcToPeggedPivot}.\n */\nfunction directPeggedToBtcPivot(\n params: ComposeQuoteParams,\n pivot: Pivot,\n pivotScale: bigint,\n): EvmBtcPivot {\n let btcSats: bigint;\n let evmSmallest: bigint;\n if (params.sourceAmount != null) {\n // Source-pinned: pegged base units in, BTC sats out.\n evmSmallest = BigInt(params.sourceAmount);\n btcSats = peggedBaseToSats(evmSmallest, pivot.pegRate, pivotScale);\n } else if (params.targetAmount != null) {\n // Target-pinned: BTC sats in, pegged base units out.\n btcSats = BigInt(params.targetAmount);\n evmSmallest = satsToPeggedBase(btcSats, pivot.pegRate, pivotScale);\n } else {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: no amount pinned (unreachable)\",\n );\n }\n return { btcSats, evmSmallest, evmDecimals: pivot.decimals, bridgeFee: 0n };\n}\n\nexport class UnsupportedComposeQuotePath extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedComposeQuotePath\";\n }\n}\n\ntype BaseUnitAmount = bigint;\ntype AmountInput = number | BaseUnitAmount;\n\nexport interface ComposeQuoteParams {\n sourceChain: Chain;\n sourceToken: string;\n targetChain: Chain;\n targetToken: string;\n sourceAmount?: AmountInput;\n targetAmount?: AmountInput;\n slippageBps?: number;\n /** Referral code — resolved to an extra-fee rate via `/referral-fee`. */\n referralCode?: string;\n /** Per-swap extra-fee surcharge (bps), capped per referral key. */\n extraFees?: number;\n /**\n * `true` when a Solana CCTP recipient has no USDC ATA yet — folds the higher\n * ATA-setup bridge fee. Only meaningful for Solana targets.\n */\n bridgeRecipientSetup?: boolean;\n}\n\n/**\n * Inputs `composeQuote` needs from the rest of the SDK. Passed in as a\n * dependency object rather than baked into the function so callers can\n * cache `/swap-pairs` and `/network-fees` across many quote attempts.\n *\n * In the SDK's `Client.composeQuote()` wrapper these are fetched fresh\n * each call; in tighter UI loops a caller can pre-fetch them and reuse.\n */\nexport interface ComposeQuoteDeps {\n swapPairs: SwapPairsResponse;\n networkFees: NetworkFeesResponse;\n chainConfig: ChainConfigResponse;\n\n /**\n * Referral/extra-fee rate (decimal fraction) from `/referral-fee`, added on\n * top of the per-pair `fee_percentage`. `0`/omitted for non-referral quotes.\n */\n referralExtraFeeRate?: number;\n\n /**\n * Negotiated base fee (decimal fraction) from `/referral-fee`. When set it\n * replaces the per-pair `fee_percentage` before `referralExtraFeeRate` is\n * added. Omitted for keys without a partner rate.\n */\n referralBaseFeeRate?: number;\n\n /**\n * DEX-leg quote primitive — `Client.getDexQuote` once bound to the\n * underlying HTTP client.\n */\n getDexQuote(params: {\n from: Token;\n to: Token;\n amount: { kind: \"exact_in\" | \"exact_out\"; value: string };\n slippageBps: number;\n recipientSetup?: boolean;\n }): Promise<{\n expected_amount_in: { raw: string; decimals: number };\n estimated_amount_out: { raw: string; decimals: number };\n /** Bridge fee deducted (bridged-token smallest units); absent if no bridge. */\n bridge_fee?: string;\n /** Bridge fee model; a `layerzero` leg carries a sats fee for the network fee. */\n bridge_rate?: DexQuoteResponse[\"bridge_rate\"];\n }>;\n}\n\nexport async function composeQuote(\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n): Promise<QuoteResponse> {\n const sourceIsBtc = params.sourceToken.toLowerCase() === \"btc\";\n const targetIsBtc = params.targetToken.toLowerCase() === \"btc\";\n\n if (sourceIsBtc === targetIsBtc) {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote currently requires exactly one BTC side; foreign-target EVM↔EVM not implemented yet\",\n );\n }\n const sourcePinned = params.sourceAmount != null;\n const targetPinned = params.targetAmount != null;\n if (sourcePinned === targetPinned) {\n throw new UnsupportedComposeQuotePath(\n \"specify exactly one of sourceAmount or targetAmount\",\n );\n }\n\n if (sourceIsBtc) {\n return composeBtcToEvm(params, deps);\n }\n return composeEvmToBtc(params, deps);\n}\n\n/**\n * Source-pinned BTC→EVM net target (what the user receives after all fees).\n *\n * `deliveredEvm` is already net of the bridge fee. Apply the BTC-side fee ratio\n * (`effectiveSats / btcSats`) to the *gross* DEX output, then subtract the\n * bridge fee at full value — scaling `deliveredEvm` directly would discount the\n * (largely flat) CCTP fee by the same ratio and overstate delivery. Exported\n * for unit testing.\n */\nexport function netTargetSourcePinned(\n btcSats: bigint,\n effectiveSats: bigint,\n deliveredEvm: bigint,\n bridgeFee: bigint,\n): bigint {\n if (btcSats === 0n || effectiveSats < 0n) return 0n;\n const scaledGross = (effectiveSats * (deliveredEvm + bridgeFee)) / btcSats;\n return scaledGross > bridgeFee ? scaledGross - bridgeFee : 0n;\n}\n\nasync function composeBtcToEvm(\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n): Promise<QuoteResponse> {\n // Direct on a hub chain, or bridged through Arbitrum for everything else\n // (incl. non-EVM Solana, whose `to` token is base58).\n const { btcPegged, pivotChainId, hubChain, toToken } = resolveTargetRouting(\n deps.chainConfig,\n params.targetChain,\n params.targetToken,\n );\n\n // The BTC↔pivot leg (rate, fee, limits) keys off the settlement hub —\n // Arbitrum for a bridged target, the target chain itself when direct.\n const pair = lookupPair(deps.swapPairs, params.sourceChain, hubChain);\n const feeEntry = lookupFeeEntry(\n deps.networkFees,\n params.sourceChain,\n hubChain,\n );\n const baseNetworkFeeSats =\n feeEntry.fees.source_sats +\n feeEntry.fees.target_sats +\n pair.network_fee_sats;\n // `gasless_network_fee` is always 0: the gasless settlement cost is folded\n // into `network_fee` upstream (the `/network-fees` values already include it\n // on chains that pass settlement gas through). The field is kept on the\n // QuoteResponse for wire compatibility with `getQuote()`.\n const gaslessNetworkFee = 0;\n\n // Pivot scale: BTC sats (8-dec) ↔ tBTC/WBTC base units. Direction-agnostic\n // — same factor used to inflate (source-pinned) or deflate (target-pinned).\n const pivotScale = 10n ** BigInt(btcPegged.decimals - 8);\n\n // Run the DEX leg in whichever direction the caller pinned. Both paths\n // produce the same shape: (btc_sats, evm_smallest), with the DEX quote\n // carrying the precise opposite side. The entry-point guarantees exactly\n // one side is pinned; the trailing throw is unreachable but keeps the\n // amount typed as a non-null `bigint` for each branch.\n let pivot: BtcEvmPivot;\n if (isPivotToken(params.targetToken, btcPegged)) {\n // Direct BTC → pegged token (e.g. BTC → tBTC): the pegged token *is*\n // the pivot, so there's no DEX hop — just the 1:1 BTC peg. See\n // directBtcToPeggedPivot for the tBTC-exact / WBTC caveat.\n pivot = directBtcToPeggedPivot(params, btcPegged, pivotScale);\n } else if (params.sourceAmount != null) {\n pivot = await dexSourcePinned(\n BigInt(params.sourceAmount),\n params,\n deps,\n btcPegged,\n pivotChainId,\n toToken,\n pivotScale,\n );\n } else if (params.targetAmount != null) {\n pivot = await dexTargetPinned(\n BigInt(params.targetAmount),\n params,\n deps,\n btcPegged,\n pivotChainId,\n toToken,\n pivotScale,\n );\n } else {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: no amount pinned (unreachable)\",\n );\n }\n\n const { btcSats, evmSmallest, evmDecimals, bridgeFee } = pivot;\n const networkFeeSats = baseNetworkFeeSats + pivot.bridgeNativeFeeSats;\n\n // Protocol fee in sats: floor(btc_sats × fee_percentage). The server\n // uses `rust_decimal` arithmetic on a `Decimal`; we use `BigInt`\n // multiplication after scaling the percentage by 1e18 to dodge\n // floating-point drift.\n // Effective rate = base + referral/extra-fee delta (0 if none), mirroring\n // the server's `effective_fee_pct = base + org_extra`, where a partner's\n // negotiated base replaces the per-pair fee.\n const effectiveFeePct =\n (deps.referralBaseFeeRate ?? pair.fee_percentage) +\n (deps.referralExtraFeeRate ?? 0);\n const FEE_SCALE = 10n ** 18n;\n const feePctScaled = BigInt(Math.round(effectiveFeePct * Number(FEE_SCALE)));\n const protocolFee = Number((btcSats * feePctScaled) / FEE_SCALE);\n const totalFeeSats = networkFeeSats + gaslessNetworkFee + protocolFee;\n\n // Net amounts mirror quote_calculator::compute_net_amounts for the BTC→EVM\n // arms. Source-pinned: net_target = sats_to_evm(btc_sats − fees).\n // Target-pinned: net_source = btc_sats + fees, target echoes pinned.\n let netSource: bigint;\n let netTarget: bigint;\n if (params.sourceAmount != null) {\n const effectiveSats = btcSats - BigInt(totalFeeSats);\n netSource = btcSats;\n netTarget = netTargetSourcePinned(\n btcSats,\n effectiveSats,\n evmSmallest,\n bridgeFee,\n );\n } else {\n netSource = btcSats + BigInt(totalFeeSats);\n netTarget = evmSmallest;\n }\n\n return {\n exchange_rate: calculateExchangeRate(btcSats, evmSmallest, evmDecimals),\n network_fee: networkFeeSats,\n gasless_network_fee: gaslessNetworkFee,\n protocol_fee: protocolFee,\n protocol_fee_rate: effectiveFeePct,\n min_amount: pair.min_sats,\n max_amount: pair.max_sats,\n source_amount: btcSats.toString(),\n // Source-pinned: `evmSmallest` is the delivered (fee-netted) DEX output, so\n // gross it back up by the bridge fee — `target_amount` is the gross output\n // (`target_amount − bridge_fee = delivered`). Target-pinned: the user pinned\n // the *delivered* amount, so `target_amount` must echo it (and equal\n // `net_target_amount` above); the server already covers the fee on the input\n // side (`expected_amount_in`), so adding it here would overshoot the pin.\n // Keyed on the same predicate as `net_target` above.\n target_amount: (params.sourceAmount != null\n ? evmSmallest + bridgeFee\n : evmSmallest\n ).toString(),\n net_source_amount: netSource.toString(),\n net_target_amount: netTarget.toString(),\n bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : undefined,\n };\n}\n\ninterface BtcEvmPivot {\n btcSats: bigint;\n evmSmallest: bigint;\n evmDecimals: number;\n /** Bridge fee deducted (target-token smallest units); `0n` if no bridge. */\n bridgeFee: bigint;\n /**\n * Bridge cost the server pays in native gas and charges in sats (the\n * LayerZero messaging fee for USDT0); `0` if none.\n */\n bridgeNativeFeeSats: number;\n}\n\n/**\n * BTC→EVM, source-pinned: user pins BTC sats; DEX runs exact-input\n * (tBTC pivot → target token) and returns the receivable target amount.\n */\nasync function dexSourcePinned(\n btcSats: bigint,\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n btcPegged: { address: string; decimals: number },\n pivotChainId: number,\n toToken: Token,\n pivotScale: bigint,\n): Promise<BtcEvmPivot> {\n const pivotInBase = btcSats * pivotScale;\n // `from` (pivot) and `to` (target token) share a chain when direct, and\n // straddle Arbitrum↔dest when bridged — the server bridges and folds the fee.\n const dexQuote = await deps.getDexQuote({\n from: { kind: \"evm\", chain_id: pivotChainId, address: btcPegged.address },\n to: toToken,\n amount: { kind: \"exact_in\", value: pivotInBase.toString() },\n slippageBps: params.slippageBps ?? 100,\n recipientSetup: params.bridgeRecipientSetup,\n });\n return {\n btcSats,\n evmSmallest: BigInt(dexQuote.estimated_amount_out.raw),\n evmDecimals: dexQuote.estimated_amount_out.decimals,\n bridgeFee: BigInt(dexQuote.bridge_fee ?? \"0\"),\n bridgeNativeFeeSats: bridgeNativeFeeSats(dexQuote),\n };\n}\n\n/**\n * BTC→EVM, target-pinned: user pins target token amount; DEX runs\n * exact-output (tBTC pivot → target token) and returns the required\n * pivot amount. We divide that back into BTC sats for the fee math.\n *\n * Integer-floors the sats conversion to match server-side\n * `token_units_to_sats`. The DEX result is the precise tBTC needed; any\n * sub-sat dust is absorbed.\n */\nasync function dexTargetPinned(\n evmSmallest: bigint,\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n btcPegged: { address: string; decimals: number },\n pivotChainId: number,\n toToken: Token,\n pivotScale: bigint,\n): Promise<BtcEvmPivot> {\n // Bridged exact-out: the server grosses the DEX output up by the bridge fee\n // so `expected_amount_in` (the pivot needed) already covers it.\n const dexQuote = await deps.getDexQuote({\n from: { kind: \"evm\", chain_id: pivotChainId, address: btcPegged.address },\n to: toToken,\n amount: { kind: \"exact_out\", value: evmSmallest.toString() },\n slippageBps: params.slippageBps ?? 100,\n recipientSetup: params.bridgeRecipientSetup,\n });\n const pivotInBase = BigInt(dexQuote.expected_amount_in.raw);\n return {\n btcSats: pivotInBase / pivotScale,\n evmSmallest,\n evmDecimals: dexQuote.estimated_amount_out.decimals,\n bridgeFee: BigInt(dexQuote.bridge_fee ?? \"0\"),\n bridgeNativeFeeSats: bridgeNativeFeeSats(dexQuote),\n };\n}\n\n/**\n * Sats the server charges for a bridge it pays in native gas: the LayerZero\n * messaging fee on a USDT0 bridge leg. `0` for CCTP (whose fee comes off the\n * bridged USDC) and for unbridged legs.\n */\nfunction bridgeNativeFeeSats(dexQuote: {\n bridge_rate?: DexQuoteResponse[\"bridge_rate\"];\n}): number {\n return dexQuote.bridge_rate?.router === \"layerzero\"\n ? Number(dexQuote.bridge_rate.native_fee_sats)\n : 0;\n}\n\nfunction lookupPair(\n swapPairs: SwapPairsResponse,\n source: Chain,\n target: Chain,\n) {\n const pair = swapPairs.pairs.find(\n (p) => p.source === source && p.target === target,\n );\n if (!pair) {\n throw new UnsupportedComposeQuotePath(\n `composeQuote: no swap-pair entry for ${source}→${target}`,\n );\n }\n return pair;\n}\n\nfunction lookupFeeEntry(\n networkFees: NetworkFeesResponse,\n source: Chain,\n target: Chain,\n) {\n const entry = networkFees.pairs.find(\n (p) => p.source === source && p.target === target,\n );\n if (!entry) {\n throw new UnsupportedComposeQuotePath(\n `composeQuote: no network-fee entry for ${source}→${target}`,\n );\n }\n return entry;\n}\n\nasync function composeEvmToBtc(\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n): Promise<QuoteResponse> {\n // Direct on a hub chain, or bridged in through Arbitrum for everything else.\n const { btcPegged, pivotChainId, hubChain, tokenChainId } = resolveEvmRouting(\n deps.chainConfig,\n params.sourceChain,\n );\n\n // The pivot↔BTC leg keys off the settlement hub — Arbitrum for a bridged\n // source, the source chain itself when direct.\n const pair = lookupPair(deps.swapPairs, hubChain, params.targetChain);\n const feeEntry = lookupFeeEntry(\n deps.networkFees,\n hubChain,\n params.targetChain,\n );\n const networkFeeSats =\n feeEntry.fees.source_sats +\n feeEntry.fees.target_sats +\n pair.network_fee_sats;\n const gaslessNetworkFee = 0;\n\n // Pivot scale: BTC sats (8-dec) ↔ tBTC/WBTC base units. Same direction-\n // agnostic factor used by composeBtcToEvm.\n const pivotScale = 10n ** BigInt(btcPegged.decimals - 8);\n\n // Entry-point guarantees exactly one side is pinned; the trailing throw\n // is unreachable but keeps the amount typed as a non-null `bigint`.\n let pivot: EvmBtcPivot;\n if (isPivotToken(params.sourceToken, btcPegged)) {\n // Direct pegged token → BTC (e.g. tBTC → BTC): the source *is* the\n // pivot, no DEX hop — just the 1:1 BTC peg.\n pivot = directPeggedToBtcPivot(params, btcPegged, pivotScale);\n } else if (params.sourceAmount != null) {\n pivot = await dexEvmToBtcSourcePinned(\n BigInt(params.sourceAmount),\n params,\n deps,\n btcPegged,\n pivotChainId,\n tokenChainId,\n pivotScale,\n );\n } else if (params.targetAmount != null) {\n pivot = await dexEvmToBtcTargetPinned(\n BigInt(params.targetAmount),\n params,\n deps,\n btcPegged,\n pivotChainId,\n tokenChainId,\n pivotScale,\n );\n } else {\n throw new UnsupportedComposeQuotePath(\n \"composeQuote: no amount pinned (unreachable)\",\n );\n }\n\n const { btcSats, evmSmallest, evmDecimals, bridgeFee } = pivot;\n\n // Protocol fee in sats: floor(btc_sats × fee_percentage). Same fixed-\n // point trick as composeBtcToEvm; effective rate = base + referral delta,\n // with a partner's negotiated base replacing the per-pair fee.\n const effectiveFeePct =\n (deps.referralBaseFeeRate ?? pair.fee_percentage) +\n (deps.referralExtraFeeRate ?? 0);\n const FEE_SCALE = 10n ** 18n;\n const feePctScaled = BigInt(Math.round(effectiveFeePct * Number(FEE_SCALE)));\n const protocolFee = Number((btcSats * feePctScaled) / FEE_SCALE);\n const totalFeeSats = networkFeeSats + gaslessNetworkFee + protocolFee;\n\n // Net amounts mirror quote_calculator::compute_net_amounts for the\n // EVM→BTC arms.\n // - Source-pinned: source echoes pinned, net_target = btc_sats − fees.\n // - Target-pinned: target echoes pinned, net_source = sats_to_evm(btc_sats + fees).\n // `sats_to_evm(s) = s × evm_smallest / btc_sats`, the implicit\n // per-sat-to-evm ratio carried by the DEX quote.\n let netSource: bigint;\n let netTarget: bigint;\n if (params.sourceAmount != null) {\n netSource = evmSmallest;\n netTarget =\n btcSats > BigInt(totalFeeSats) ? btcSats - BigInt(totalFeeSats) : 0n;\n } else {\n const grossSats = btcSats + BigInt(totalFeeSats);\n netSource = btcSats === 0n ? 0n : (grossSats * evmSmallest) / btcSats;\n netTarget = btcSats;\n }\n\n return {\n exchange_rate: calculateExchangeRate(btcSats, evmSmallest, evmDecimals),\n network_fee: networkFeeSats,\n gasless_network_fee: gaslessNetworkFee,\n protocol_fee: protocolFee,\n protocol_fee_rate: effectiveFeePct,\n min_amount: pair.min_sats,\n max_amount: pair.max_sats,\n // EVM→BTC: the EVM source is the bridged side. The dex-quote already\n // reports `evmSmallest` as the gross the user supplies (the inbound fee was\n // folded onto it), so `source_amount` needs no adjustment — just surface\n // the fee.\n source_amount: evmSmallest.toString(),\n target_amount: btcSats.toString(),\n net_source_amount: netSource.toString(),\n net_target_amount: netTarget.toString(),\n bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : undefined,\n };\n}\n\ninterface EvmBtcPivot {\n btcSats: bigint;\n evmSmallest: bigint;\n evmDecimals: number;\n /** Bridge fee deducted (source-token smallest units); `0n` if no bridge. */\n bridgeFee: bigint;\n}\n\n/**\n * EVM→BTC, source-pinned: user pins source token; DEX runs\n * exact-input (source → tBTC pivot) and returns the receivable pivot\n * amount, which divides back into BTC sats.\n */\nasync function dexEvmToBtcSourcePinned(\n evmSmallest: bigint,\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n btcPegged: { address: string; decimals: number },\n pivotChainId: number,\n tokenChainId: number,\n pivotScale: bigint,\n): Promise<EvmBtcPivot> {\n // `from` (source token) and `to` (pivot) share a chain when direct, and\n // straddle dest↔Arbitrum when bridged in — the server bridges the source USDC\n // to the hub and folds the inbound fee.\n const dexQuote = await deps.getDexQuote({\n from: {\n kind: \"evm\",\n chain_id: tokenChainId,\n address: params.sourceToken.toLowerCase(),\n },\n to: { kind: \"evm\", chain_id: pivotChainId, address: btcPegged.address },\n amount: { kind: \"exact_in\", value: evmSmallest.toString() },\n slippageBps: params.slippageBps ?? 100,\n });\n const pivotBase = BigInt(dexQuote.estimated_amount_out.raw);\n return {\n btcSats: pivotBase / pivotScale,\n evmSmallest,\n evmDecimals: dexQuote.expected_amount_in.decimals,\n bridgeFee: BigInt(dexQuote.bridge_fee ?? \"0\"),\n };\n}\n\n/**\n * EVM→BTC, target-pinned: user pins target BTC sats; DEX runs\n * exact-output (source → tBTC pivot) and returns the required source\n * amount. We inflate the pinned sats into pivot base units, ask the\n * DEX for the input cost, and use that as the pre-fee `evm_smallest`.\n *\n * Net source then re-scales `btc_sats + fees` through the same\n * implicit ratio (`evm_smallest / btc_sats`) the legacy server's\n * `sats_to_evm` helper uses, so source-side fee inflation matches.\n */\nasync function dexEvmToBtcTargetPinned(\n btcSats: bigint,\n params: ComposeQuoteParams,\n deps: ComposeQuoteDeps,\n btcPegged: { address: string; decimals: number },\n pivotChainId: number,\n tokenChainId: number,\n pivotScale: bigint,\n): Promise<EvmBtcPivot> {\n const pivotInBase = btcSats * pivotScale;\n // Bridged-in exact-out: the server grosses the source USDC burn up by the\n // inbound fee, so `expected_amount_in` is what the user must supply on the\n // remote chain.\n const dexQuote = await deps.getDexQuote({\n from: {\n kind: \"evm\",\n chain_id: tokenChainId,\n address: params.sourceToken.toLowerCase(),\n },\n to: { kind: \"evm\", chain_id: pivotChainId, address: btcPegged.address },\n amount: { kind: \"exact_out\", value: pivotInBase.toString() },\n slippageBps: params.slippageBps ?? 100,\n });\n return {\n btcSats,\n evmSmallest: BigInt(dexQuote.expected_amount_in.raw),\n evmDecimals: dexQuote.expected_amount_in.decimals,\n bridgeFee: BigInt(dexQuote.bridge_fee ?? \"0\"),\n };\n}\n\n/**\n * Format the BTC→EVM exchange rate as a decimal string.\n *\n * Rate semantics: \"how much of the EVM token you get per 1 BTC.\"\n * Concretely: `(evm_smallest / 10^evm_decimals) / (btc_sats / 10^8)`.\n *\n * Implementation does the division at high precision via `BigInt`\n * scaling, then formats with up to 12 fractional digits trimmed of\n * trailing zeros. The legacy server formats this with `rust_decimal`,\n * which preserves its own precision rules — a parity test should parse\n * both sides as numbers and compare with tolerance, not compare strings.\n */\nfunction calculateExchangeRate(\n btcSats: bigint,\n evmSmallest: bigint,\n evmDecimals: number,\n): string {\n if (btcSats === 0n) return \"0\";\n const PRECISION = 12;\n const scale = 10n ** BigInt(PRECISION);\n const numerator = evmSmallest * 10n ** 8n * scale;\n const denominator = btcSats * 10n ** BigInt(evmDecimals);\n const scaled = numerator / denominator;\n const intPart = scaled / scale;\n const fracPart = scaled % scale;\n let frac = fracPart.toString().padStart(PRECISION, \"0\");\n frac = frac.replace(/0+$/, \"\");\n return frac.length === 0 ? intPart.toString() : `${intPart}.${frac}`;\n}\n","/**\n * Signer module for HD wallet key derivation.\n *\n * This module provides BIP39/BIP32 key derivation for Lendaswap swaps,\n * mirroring the Rust implementation in `client-sdk/core/src/hd_wallet.rs`.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport { HDKey } from \"@scure/bip32\";\nimport * as bip39 from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/** BIP-85 prefix for signing keys. */\nconst SIGNING_PREFIX = 83696968;\n/** Prefix for identity key derivation. */\nconst ID_PREFIX = 9419;\n/** Lendaswap identifier (\"LSW\" encoded). */\nconst LSW_IDENTIFIER = 121923;\n/** Tag for BIP340-style tagged hash preimage generation. */\nconst PREIMAGE_TAG = \"lendaswap/preimage\";\n/** BIP44 coin type for Nostr (NIP-06). */\nconst NOSTR_COIN_TYPE = 1237;\n\n/**\n * Parameters derived for a single swap.\n */\nexport interface SwapParams {\n /** The secret key (32 bytes) for signing. */\n secretKey: Uint8Array;\n /** The compressed public key (33 bytes). */\n publicKey: Uint8Array;\n /** The preimage (32 bytes) for the HTLC. */\n preimage: Uint8Array;\n /** The SHA256 hash of the preimage (32 bytes). */\n preimageHash: Uint8Array;\n /** The user ID public key (33 bytes) for swap recovery. */\n userId: Uint8Array;\n /** The key index used for derivation. */\n keyIndex: number;\n}\n\n/**\n * BIP340-style tagged hash function for domain separation.\n *\n * Computes: sha256(sha256(tag) || sha256(tag) || data).\n *\n * @param tag - The domain separation tag.\n * @param data - The data to hash.\n * @returns The tagged hash (32 bytes).\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagHash = sha256(new TextEncoder().encode(tag));\n const combined = new Uint8Array(tagHash.length * 2 + data.length);\n combined.set(tagHash, 0);\n combined.set(tagHash, tagHash.length);\n combined.set(data, tagHash.length * 2);\n return sha256(combined);\n}\n\n/**\n * HD Wallet Signer for Lendaswap key derivation.\n *\n * Provides BIP39/BIP32 key derivation matching the Rust `HdWallet` implementation.\n * Can be constructed from either a BIP39 mnemonic or a BIP32 extended private key\n * (xprv). When constructed from an xprv, the `mnemonic` getter returns `undefined`.\n *\n * @example\n * ```ts\n * // Generate a new signer with a random mnemonic\n * const signer = Signer.generate();\n *\n * // Or restore from an existing mnemonic\n * const signer = Signer.fromMnemonic(\"your twelve word mnemonic phrase here ...\");\n *\n * // Or restore from a BIP32 extended private key (xprv)\n * const signer = Signer.fromXprv(\"xprv9s21ZrQH143K...\");\n *\n * // Derive swap parameters at a specific index\n * const params = signer.deriveSwapParams(0);\n * ```\n */\nexport class Signer {\n readonly #mnemonic: string | undefined;\n readonly #master: HDKey;\n\n private constructor(master: HDKey, mnemonic?: string) {\n this.#master = master;\n this.#mnemonic = mnemonic;\n }\n\n /**\n * Generate a new Signer with a random mnemonic.\n *\n * @param wordCount - Number of words (12, 15, 18, 21, or 24). Defaults to 12.\n * @returns A new Signer instance.\n * @throws Error if the word count is invalid.\n */\n static generate(wordCount: 12 | 15 | 18 | 21 | 24 = 12): Signer {\n const strength = (wordCount / 3) * 32; // 128, 160, 192, 224, or 256 bits\n const mnemonic = bip39.generateMnemonic(wordlist, strength);\n return Signer.fromMnemonic(mnemonic);\n }\n\n /**\n * Create a Signer from an existing mnemonic phrase.\n *\n * @param phrase - The BIP39 mnemonic phrase (12, 15, 18, 21, or 24 words).\n * @returns A new Signer instance.\n * @throws Error if the mnemonic is invalid.\n */\n static fromMnemonic(phrase: string): Signer {\n const normalized = phrase.trim().toLowerCase();\n if (!bip39.validateMnemonic(normalized, wordlist)) {\n throw new Error(\"Invalid mnemonic phrase\");\n }\n const seed = bip39.mnemonicToSeedSync(normalized, \"\");\n const master = HDKey.fromMasterSeed(seed);\n return new Signer(master, normalized);\n }\n\n /**\n * Create a Signer from a BIP32 extended private key (xprv).\n *\n * The xprv is treated as the master key for all subsequent derivations,\n * so it must be the root key (depth 0) for derivation paths to match those\n * produced from a mnemonic. Signers created this way have no mnemonic\n * available — `mnemonic` returns `undefined`.\n *\n * @param xprv - The base58check-encoded extended private key.\n * @returns A new Signer instance.\n * @throws Error if the key is not a valid xprv or is a public-only extended key.\n */\n static fromXprv(xprv: string): Signer {\n let master: HDKey;\n try {\n master = HDKey.fromExtendedKey(xprv.trim());\n } catch (err) {\n throw new Error(`Invalid xprv: ${(err as Error).message}`);\n }\n if (!master.privateKey) {\n throw new Error(\n \"Extended key has no private key (xprv required, not xpub)\",\n );\n }\n return new Signer(master);\n }\n\n /**\n * Get the mnemonic phrase, if this signer was created from one.\n *\n * Returns `undefined` for signers created via `fromXprv()`.\n *\n * @returns The BIP39 mnemonic phrase, or `undefined`.\n */\n get mnemonic(): string | undefined {\n return this.#mnemonic;\n }\n\n /**\n * Derive swap parameters at the given index.\n *\n * Derivation path: `m/{SIGNING_PREFIX}'/{LSW_IDENTIFIER}'/{index}'`\n *\n * @param index - The key index to derive.\n * @returns The derived swap parameters.\n */\n deriveSwapParams(index: number): SwapParams {\n // Derive signing key: m/{SIGNING_PREFIX}'/{LSW_IDENTIFIER}'/{index}'\n const signingPath = `m/${SIGNING_PREFIX}'/${LSW_IDENTIFIER}'/${index}'`;\n const derived = this.#master.derive(signingPath);\n\n if (!derived.privateKey || !derived.publicKey) {\n throw new Error(\"Failed to derive key\");\n }\n\n const secretKey = derived.privateKey;\n const publicKey = derived.publicKey;\n\n // Generate preimage using tagged hash (BIP340-style)\n const preimage = taggedHash(PREIMAGE_TAG, secretKey);\n\n // preimageHash = SHA256(preimage)\n const preimageHash = sha256(preimage);\n\n // Derive user ID\n const userId = this.deriveUserId(index);\n\n return {\n secretKey,\n publicKey,\n preimage,\n preimageHash,\n userId,\n keyIndex: index,\n };\n }\n\n /**\n * Derive a user ID at the specified index.\n *\n * User IDs are derived using a non-hardened path, so that the corresponding\n * Xpub can be shared with the server for efficient recovery of swap data.\n *\n * @param index - The key index.\n * @returns The user ID public key (33 bytes).\n */\n private deriveUserId(index: number): Uint8Array {\n const xpub = this.deriveUserIdXpub();\n\n // Build non-hardened derivation path from the xpub\n const path = `m/${ID_PREFIX}/${LSW_IDENTIFIER}/${index}`;\n const derived = xpub.derive(path);\n\n if (!derived.publicKey) {\n throw new Error(\"Failed to derive user ID\");\n }\n\n return derived.publicKey;\n }\n\n /**\n * Derive the Xpub used for user ID derivation.\n *\n * This Xpub is derived using a hardened path from the master key,\n * ensuring parent key safety even if individual derived keys are leaked.\n *\n * This Xpub can be shared with the server for wallet recovery.\n *\n * @returns The HDKey representing the user ID Xpub.\n */\n deriveUserIdXpub(): HDKey {\n // Build hardened derivation path\n const path = `m/${ID_PREFIX}'/${LSW_IDENTIFIER}'/0'`;\n const derived = this.#master.derive(path);\n\n // Return neutered key (Xpub only, no private key)\n return derived.wipePrivateData();\n }\n\n /**\n * Get the serialized user ID Xpub string.\n *\n * @returns The base58check-encoded extended public key (xpub...).\n */\n getUserIdXpubString(): string {\n const xpub = this.deriveUserIdXpub();\n // HDKey.publicExtendedKey returns the base58check-encoded xpub\n return xpub.publicExtendedKey;\n }\n\n /**\n * Derive a deterministic EVM signing key from the mnemonic.\n *\n * Unlike per-swap keys, this key is fixed for a given mnemonic,\n * allowing a single Permit2 approval to be reused across all swaps.\n * Uses the standard BIP-44 Ethereum path so the key is recoverable\n * with any standard wallet in emergency scenarios.\n *\n * Derivation path: `m/44'/60'/0'/0/0`\n *\n * @returns The 32-byte secret key for EVM signing.\n */\n deriveEvmKey(): { secretKey: Uint8Array } {\n const path = \"m/44'/60'/0'/0/0\";\n const derived = this.#master.derive(path);\n\n if (!derived.privateKey) {\n throw new Error(\"Failed to derive EVM key\");\n }\n\n return { secretKey: derived.privateKey };\n }\n\n /**\n * Derive a deterministic Nostr private key from the mnemonic.\n *\n * Uses the NIP-06 derivation path: `m/44'/1237'/account'/0/0`\n * The same mnemonic always produces the same Nostr identity.\n *\n * @param account - The account index (default 0).\n * @returns The 32-byte private key as a hex string.\n */\n deriveNostrKeyHex(account = 0): string {\n const path = `m/44'/${NOSTR_COIN_TYPE}'/${account}'/0/0`;\n const derived = this.#master.derive(path);\n\n if (!derived.privateKey) {\n throw new Error(\"Failed to derive Nostr key\");\n }\n\n return bytesToHex(derived.privateKey);\n }\n}\n\n// Re-export utility functions\nexport { bytesToHex, hexToBytes };\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, kdfInputToBytes,\n type CHash,\n type Hash,\n type KDFInput\n} from './utils.ts';\n\n/**\n * PBKDF2 options:\n * * c: iterations, should probably be higher than 100_000\n * * dkLen: desired length of derived key in bytes\n * * asyncTick: max time in ms for which async function can block execution\n */\nexport type Pbkdf2Opt = {\n c: number;\n dkLen?: number;\n asyncTick?: number;\n};\n// Common start and end for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1) throw new Error('iterations (c) must be >= 1');\n const password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output<T extends Hash<T>>(\n PRF: Hash<T>,\n PRFSalt: Hash<T>,\n DK: Uint8Array,\n prfW: Hash<T>,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise<Uint8Array> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new Error('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedWebcrypto(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","/**\n * Checks that what the server says about a swap binds to what this client\n * holds, before the client stores it, shows it or pays into it.\n */\n\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { hex } from \"@scure/base\";\nimport type {\n ArkadeToEvmSwapResponse,\n ArkadeToLightningSwapResponse,\n BitcoinToEvmSwapResponse,\n BitcoinToLightningSwapResponse,\n BtcToArkadeSwapResponse,\n GetSwapResponse,\n} from \"./api/client.js\";\nimport { getNetworkHrp, getNetworkName } from \"./arkade-network.js\";\nimport { invoiceAmountMsat, invoicePaymentHash } from \"./bolt11.js\";\nimport { parseXOnlyPubKey, refundableVhtlc } from \"./refund/arkade.js\";\nimport { type BitcoinNetwork, verifyHtlcAddress } from \"./refund/onchain.js\";\nimport { bytesToHex, type SwapParams } from \"./signer/index.js\";\nimport type { LightningPaymentHash, StoredSwap } from \"./storage/types.js\";\nimport {\n ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n BTC_HTLC_SCRIPT_VERSION_STRICT,\n} from \"./strict-vhtlc.js\";\n\n/**\n * The server's terms for a swap do not bind to what this client holds: a\n * Lightning invoice that does not pay the swap's hash lock, a lock that does\n * not open with it, or terms that changed after the swap was created. Do not\n * pay or fund the swap.\n */\nexport class SwapVerificationError extends Error {\n /** The response field that failed the check, e.g. `bolt11_invoice`. */\n readonly field: string;\n /** What this client expected the field to commit to. */\n readonly expected: string;\n /** What the server's field commits to. */\n readonly received: string;\n readonly swapId?: string;\n\n constructor(\n message: string,\n details: {\n field: string;\n expected: string;\n received: string;\n swapId?: string;\n },\n ) {\n super(message);\n this.name = \"SwapVerificationError\";\n this.field = details.field;\n this.expected = details.expected;\n this.received = details.received;\n this.swapId = details.swapId;\n }\n}\n\n/** A hex hash without `0x`, lowercase. */\nexport function normalizeHash(hash: string): string {\n return hash.toLowerCase().replace(/^0x/, \"\");\n}\n\n/** An invoice's payment hash as lowercase hex without `0x`, like {@link normalizeHash}. */\nfunction paymentHashOf(invoice: string): string {\n return normalizeHash(invoicePaymentHash(invoice));\n}\n\n/**\n * Checks that the invoice the payer will pay locks to `hashLock`, this\n * client's own preimage hash. A Lightning to X swap's server could otherwise\n * settle the payment with a preimage it chose and never fund the other side.\n */\nexport function assertInvoicePays(invoice: string, hashLock: string): void {\n const paymentHash = paymentHashOf(invoice);\n const expected = normalizeHash(hashLock);\n if (paymentHash !== expected) {\n throw new SwapVerificationError(\n `The swap's Lightning invoice pays hash ${paymentHash}, not this swap's hash lock ${expected}; do not pay it`,\n { field: \"bolt11_invoice\", expected, received: paymentHash },\n );\n }\n}\n\n/**\n * The payment hash an X to Lightning swap's lock must use, checked against\n * the server's answer. From an invoice the caller supplied it is read off\n * that invoice, and the server must pay that invoice and lock to its hash.\n * For a Lightning address or LNURL the server resolves the invoice, so the\n * hash is read off the invoice it returned, which must carry its `hash_lock`\n * and the payout it quoted (and the payout asked for, if one was): what\n * remains trusted is that the server resolved the address honestly, which\n * the client cannot check without resolving it itself.\n *\n * @throws {SwapVerificationError} if any of that fails; do not fund the swap.\n */\nexport function checkedLightningPaymentHash(\n options: { lightningInvoice?: string; targetAmountSats?: number },\n data: {\n hash_lock: string;\n client_lightning_invoice?: string | null;\n target_amount?: string | number | null;\n },\n): LightningPaymentHash {\n const lock = normalizeHash(data.hash_lock);\n const invoice = data.client_lightning_invoice || undefined;\n if (options.lightningInvoice !== undefined) {\n const hash = paymentHashOf(options.lightningInvoice);\n const returned = invoice === undefined ? hash : paymentHashOf(invoice);\n if (returned !== hash) {\n throw new SwapVerificationError(\n `The server returned an invoice for hash ${returned}, not the supplied invoice's ${hash}; do not fund the swap`,\n {\n field: \"client_lightning_invoice\",\n expected: hash,\n received: returned,\n },\n );\n }\n if (lock !== hash) {\n throw new SwapVerificationError(\n `The server created the swap under hash ${lock}, not the invoice's payment hash ${hash}; do not fund it`,\n { field: \"hash_lock\", expected: hash, received: lock },\n );\n }\n return { hash: `0x${hash}`, source: \"invoice\" };\n }\n if (invoice === undefined) {\n throw new SwapVerificationError(\n \"The server returned no invoice for this Lightning address, so the swap's hash lock cannot be checked; do not fund it\",\n {\n field: \"client_lightning_invoice\",\n expected: \"an invoice\",\n received: \"\",\n },\n );\n }\n const returned = paymentHashOf(invoice);\n if (lock !== returned) {\n throw new SwapVerificationError(\n `The server created the swap under hash ${lock}, not the payment hash ${returned} of the invoice it resolved; do not fund it`,\n { field: \"hash_lock\", expected: returned, received: lock },\n );\n }\n const msat = invoiceAmountMsat(invoice);\n const asked = [data.target_amount, options.targetAmountSats].filter(\n (amount) => amount !== undefined && amount !== null,\n );\n for (const sats of asked) {\n if (\n msat === undefined ||\n msat !== BigInt(sats as string | number) * 1000n\n ) {\n throw new SwapVerificationError(\n `The invoice the server resolved asks for ${msat === undefined ? \"any amount\" : `${msat} msat`}, not the ${sats} sats payout; do not fund it`,\n {\n field: \"client_lightning_invoice\",\n expected: `${sats} sats`,\n received: msat === undefined ? \"any amount\" : `${msat} msat`,\n },\n );\n }\n }\n return { hash: `0x${returned}`, source: \"server-invoice\" };\n}\n\n/** The terms of a VHTLC the user funds and refunds as its sender. */\ninterface FundedVhtlcTerms {\n id: string;\n network: string;\n receiver_pk: string;\n arkade_server_pk: string;\n arkade_htlc_script_version: number;\n vhtlc_refund_locktime: number;\n unilateral_claim_delay: number;\n unilateral_refund_delay: number;\n unilateral_refund_without_receiver_delay: number;\n}\n\n/**\n * Rebuilds the VHTLC the user funds, as a refund rebuilds it, from `hash160`,\n * the user's refund key and the server's keys and timelocks, and refuses a\n * script version this client cannot refund or an `address` that differs.\n */\nfunction assertFundedVhtlc(\n response: FundedVhtlcTerms,\n addressField: string,\n address: string,\n hash160: Uint8Array,\n refundPublicKey: Uint8Array,\n lockDescription: string,\n): void {\n const swapId = response.id;\n if (\n response.arkade_htlc_script_version !== ARKADE_HTLC_SCRIPT_VERSION_STRICT\n ) {\n throw new SwapVerificationError(\n `Swap ${swapId} uses Arkade HTLC script version ${response.arkade_htlc_script_version}, which this client cannot refund; do not fund it`,\n {\n field: \"arkade_htlc_script_version\",\n expected: String(ARKADE_HTLC_SCRIPT_VERSION_STRICT),\n received: String(response.arkade_htlc_script_version),\n swapId,\n },\n );\n }\n const server = parseXOnlyPubKey(response.arkade_server_pk);\n const vhtlc = refundableVhtlc({\n senderPubKey: bytesToHex(refundPublicKey),\n receiverPubKey: response.receiver_pk,\n serverPubKey: response.arkade_server_pk,\n preimageHash: hash160,\n refundLocktime: response.vhtlc_refund_locktime,\n unilateralClaimDelay: response.unilateral_claim_delay,\n unilateralRefundDelay: response.unilateral_refund_delay,\n unilateralRefundWithoutReceiverDelay:\n response.unilateral_refund_without_receiver_delay,\n });\n const expected = vhtlc\n .address(getNetworkHrp(getNetworkName(response.network)), server)\n .encode();\n if (expected !== address) {\n throw new SwapVerificationError(\n `Swap ${swapId}'s VHTLC address ${address} does not lock to ${lockDescription} and this client's refund key (expected ${expected}); do not fund it`,\n { field: addressField, expected, received: address, swapId },\n );\n }\n}\n\n/**\n * Rebuilds the Arkade to Lightning VHTLC the user is asked to fund, as a\n * refund rebuilds it, from the invoice's payment hash and the swap's refund\n * key, and refuses a script version this client cannot refund. Consumers fund\n * `arkade_vhtlc_address` straight from the stored response, so it is checked\n * before the swap is first stored: at creation, or when recovery stores it.\n */\nexport function assertArkadeToLightningVhtlc(\n response: ArkadeToLightningSwapResponse,\n paymentHash: string,\n refundPublicKey: Uint8Array,\n): void {\n assertFundedVhtlc(\n response,\n \"arkade_vhtlc_address\",\n response.arkade_vhtlc_address,\n ripemd160(hex.decode(paymentHash)),\n refundPublicKey,\n \"the invoice's payment hash\",\n );\n}\n\n/**\n * Rebuilds the Arkade to EVM VHTLC the user is asked to fund from the swap's\n * own preimage hash and refund key, like {@link assertArkadeToLightningVhtlc}.\n * The refund rebuilds it from `hash_lock`, so that must be the swap's SHA-256\n * or HASH160 too.\n */\nexport function assertArkadeToEvmVhtlc(\n response: ArkadeToEvmSwapResponse,\n preimageHash: Uint8Array,\n refundPublicKey: Uint8Array,\n): void {\n const hash160 = ripemd160(preimageHash);\n assertHashLock(response.id, \"hash_lock\", response.hash_lock, [\n hex.encode(preimageHash),\n hex.encode(hash160),\n ]);\n assertFundedVhtlc(\n response,\n \"btc_vhtlc_address\",\n response.btc_vhtlc_address,\n hash160,\n refundPublicKey,\n \"the swap's preimage hash\",\n );\n}\n\n/** Refuses a hash lock that is none of `accepted` (lowercase hex). */\nfunction assertHashLock(\n swapId: string,\n field: string,\n hashLock: string,\n accepted: string[],\n): void {\n const received = normalizeHash(hashLock);\n if (!accepted.includes(received)) {\n throw new SwapVerificationError(\n `Swap ${swapId}'s ${field} ${received} is not this swap's hash lock ${accepted.join(\" or \")}; do not fund it`,\n { field, expected: accepted.join(\" or \"), received, swapId },\n );\n }\n}\n\n/** The terms of an on-chain HTLC the user funds and refunds. */\ninterface FundedHtlcTerms {\n id: string;\n network: string;\n btc_htlc_address: string;\n btc_htlc_script_version: number;\n btc_refund_locktime: number;\n}\n\n/**\n * Rebuilds the on-chain HTLC the user funds, as a refund rebuilds it, from\n * `hash160`, the server's claim key and the user's refund key. The refund\n * rebuilds it from the response's hash lock, so that must be `hash160` too,\n * or the HTLC could be funded and never refunded.\n */\nfunction assertFundedHtlc(\n response: FundedHtlcTerms,\n hashField: string,\n hashLock: string,\n serverPk: string,\n hash160: string,\n refundPublicKey: Uint8Array,\n lockDescription: string,\n): void {\n const swapId = response.id;\n if (response.btc_htlc_script_version !== BTC_HTLC_SCRIPT_VERSION_STRICT) {\n throw new SwapVerificationError(\n `Swap ${swapId} uses Bitcoin HTLC script version ${response.btc_htlc_script_version}, which this client cannot refund; do not fund it`,\n {\n field: \"btc_htlc_script_version\",\n expected: String(BTC_HTLC_SCRIPT_VERSION_STRICT),\n received: String(response.btc_htlc_script_version),\n swapId,\n },\n );\n }\n const serverHash160 = normalizeHash(hashLock);\n if (serverHash160 !== hash160) {\n throw new SwapVerificationError(\n `Swap ${swapId}'s HTLC hash ${serverHash160} is not the HASH160 ${hash160} of ${lockDescription}; do not fund it`,\n { field: hashField, expected: hash160, received: serverHash160, swapId },\n );\n }\n const name = getNetworkName(response.network);\n const network: BitcoinNetwork =\n name === \"bitcoin\" ? \"mainnet\" : name === \"mutinynet\" ? \"signet\" : name;\n const binds = verifyHtlcAddress(\n response.btc_htlc_address,\n hash160,\n bytesToHex(parseXOnlyPubKey(serverPk)),\n bytesToHex(parseXOnlyPubKey(bytesToHex(refundPublicKey))),\n response.btc_refund_locktime,\n network,\n response.btc_htlc_script_version,\n );\n if (!binds) {\n throw new SwapVerificationError(\n `Swap ${swapId}'s HTLC address ${response.btc_htlc_address} does not lock to ${lockDescription} and this client's refund key; do not fund it`,\n {\n field: \"btc_htlc_address\",\n expected: `an HTLC on ${lockDescription} and this client's refund key`,\n received: response.btc_htlc_address,\n swapId,\n },\n );\n }\n}\n\n/**\n * Rebuilds the Bitcoin to Lightning HTLC the user is asked to fund, as a\n * refund rebuilds it, from the invoice's payment hash and the swap's refund\n * key. `btc_hash_lock` must be the HASH160 of the invoice's payment hash.\n * Checked before the swap is first stored, like the Arkade to Lightning VHTLC.\n */\nexport function assertBitcoinToLightningHtlc(\n response: BitcoinToLightningSwapResponse,\n paymentHash: string,\n refundPublicKey: Uint8Array,\n): void {\n assertFundedHtlc(\n response,\n \"btc_hash_lock\",\n response.btc_hash_lock,\n response.btc_server_pk,\n hex.encode(ripemd160(hex.decode(paymentHash))),\n refundPublicKey,\n \"the invoice's payment hash\",\n );\n}\n\n/**\n * Rebuilds the Bitcoin to EVM HTLC the user is asked to fund from the swap's\n * own preimage hash and refund key, like {@link assertBitcoinToLightningHtlc}.\n */\nexport function assertBitcoinToEvmHtlc(\n response: BitcoinToEvmSwapResponse,\n preimageHash: Uint8Array,\n refundPublicKey: Uint8Array,\n): void {\n assertFundedHtlc(\n response,\n \"btc_hash_lock\",\n response.btc_hash_lock,\n response.btc_server_pk,\n hex.encode(ripemd160(preimageHash)),\n refundPublicKey,\n \"the swap's preimage hash\",\n );\n}\n\n/**\n * Rebuilds the Bitcoin to Arkade HTLC the user is asked to fund from the\n * swap's own preimage hash and refund key, like\n * {@link assertBitcoinToLightningHtlc}. This direction names the HTLC's hash\n * `hash_lock` and its server key `server_vhtlc_pk`.\n */\nexport function assertBitcoinToArkadeHtlc(\n response: BtcToArkadeSwapResponse,\n preimageHash: Uint8Array,\n refundPublicKey: Uint8Array,\n): void {\n assertFundedHtlc(\n response,\n \"hash_lock\",\n response.hash_lock,\n response.server_vhtlc_pk,\n hex.encode(ripemd160(preimageHash)),\n refundPublicKey,\n \"the swap's preimage hash\",\n );\n}\n\n/**\n * How the keys recovery derives at the server's `index` fail to match a\n * stored swap, if they do. The swap's locks were built on the stored keys and\n * preimage, so keys from another index must never replace them.\n */\nexport function recoveredKeysChange(\n stored: StoredSwap,\n index: number,\n derivedPreimageHash: string,\n): SwapVerificationError | undefined {\n if (\n normalizeHash(derivedPreimageHash) === normalizeHash(stored.preimageHash)\n ) {\n return undefined;\n }\n return new SwapVerificationError(\n `The server's index ${index} for swap ${stored.swapId} derives other keys than the stored index ${stored.keyIndex}; keeping the stored copy`,\n {\n field: \"index\",\n expected: String(stored.keyIndex),\n received: String(index),\n swapId: stored.swapId,\n },\n );\n}\n\n/**\n * How a server copy of a swap this client has not stored fails the checks\n * creation makes on the server's terms, if it does: a Lightning to X invoice\n * must pay the hash of the secret in `swapParams`, and an Arkade or Bitcoin\n * to Lightning hash lock must be the payment hash of an invoice for the\n * swap's payout, with a lock that rebuilds from that hash and the refund key\n * in `swapParams`. A Bitcoin to Arkade, Bitcoin to EVM or Arkade to EVM lock\n * the user funds must rebuild from the preimage hash and refund key in\n * `swapParams`. A field that is missing or does not decode fails too.\n */\nexport function unboundTerms(\n fresh: GetSwapResponse,\n swapParams: SwapParams,\n): Error | undefined {\n try {\n switch (fresh.direction) {\n case \"lightning_to_arkade\":\n case \"lightning_to_evm\":\n case \"lightning_to_bitcoin\":\n assertInvoicePays(\n fresh.bolt11_invoice,\n bytesToHex(swapParams.preimageHash),\n );\n break;\n // EVM-sourced swaps are left to the commitments their creation records.\n case \"arkade_to_lightning\":\n assertArkadeToLightningVhtlc(\n fresh,\n normalizeHash(checkedLightningPaymentHash({}, fresh).hash),\n swapParams.publicKey,\n );\n break;\n case \"bitcoin_to_lightning\":\n assertBitcoinToLightningHtlc(\n fresh,\n normalizeHash(checkedLightningPaymentHash({}, fresh).hash),\n swapParams.publicKey,\n );\n break;\n case \"btc_to_arkade\":\n assertBitcoinToArkadeHtlc(\n fresh,\n swapParams.preimageHash,\n swapParams.publicKey,\n );\n break;\n case \"bitcoin_to_evm\":\n assertBitcoinToEvmHtlc(\n fresh,\n swapParams.preimageHash,\n swapParams.publicKey,\n );\n break;\n case \"arkade_to_evm\":\n assertArkadeToEvmVhtlc(\n fresh,\n swapParams.preimageHash,\n swapParams.publicKey,\n );\n break;\n }\n } catch (error) {\n return error instanceof Error ? error : new Error(String(error));\n }\n return undefined;\n}\n\nconst EVM_SOURCED = new Set([\n \"evm_to_bitcoin\",\n \"evm_to_arkade\",\n \"evm_to_lightning\",\n]);\nconst HASH_FIELDS = [\"hash_lock\", \"evm_hash_lock\", \"btc_hash_lock\"];\nconst ADDRESS_FIELDS = [\n \"arkade_vhtlc_address\",\n \"btc_vhtlc_address\",\n \"btc_htlc_address\",\n \"evm_htlc_address\",\n];\nconst INVOICE_FIELDS = [\"bolt11_invoice\", \"client_lightning_invoice\"];\n/**\n * Where a swap pays out, and the EVM key its claim signs for. Fixed when the\n * swap is created, for every direction: an EVM-sourced rehash moves only\n * the hash lock and invoice.\n */\nconst PAYOUT_FIELDS = [\n \"target_evm_address\",\n \"target_btc_address\",\n \"target_arkade_address\",\n \"client_evm_address\",\n];\n\n/**\n * An address in the form two copies of it compare by: hex and bech32 ignore\n * case (the server checksums or lowercases them), base58 does not.\n */\nfunction addressKey(address: string): string {\n const lower = address.toLowerCase();\n const bech32 = /^(bc|tb|bcrt|ark|tark)1/.test(lower);\n return lower.startsWith(\"0x\") || bech32 ? lower : address;\n}\n\n/**\n * Whether two addresses are the same, by {@link addressKey}.\n */\nexport function sameAddress(a: string, b: string): boolean {\n return addressKey(a) === addressKey(b);\n}\n\n/** The response field a direction's claim pays out to. */\nconst PAYOUT_FIELD: Record<string, string> = {\n arkade_to_evm: \"target_evm_address\",\n bitcoin_to_evm: \"target_evm_address\",\n lightning_to_evm: \"target_evm_address\",\n evm_to_bitcoin: \"target_btc_address\",\n lightning_to_bitcoin: \"target_btc_address\",\n btc_to_arkade: \"target_arkade_address\",\n evm_to_arkade: \"target_arkade_address\",\n lightning_to_arkade: \"target_arkade_address\",\n};\n\n/**\n * Where a stored swap's claim pays out: the target this client sent at\n * creation, or for a swap without one (stored before it was pinned, or\n * recovered) the stored copy's field for its direction, which a refresh\n * cannot change. Only that field: one the stored copy lacks is not compared\n * on refresh, so a server could add it.\n */\nexport function storedPayoutTarget(stored: StoredSwap): string | undefined {\n if (stored.targetAddress) return stored.targetAddress;\n const field = PAYOUT_FIELD[stored.response.direction];\n if (!field) return undefined;\n const value = (stored.response as unknown as Record<string, unknown>)[field];\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Refuses a create response whose `field` is not the address this client\n * sent. The claim pays out to that field, so a server answering with an\n * address of its own would take the payout. With nothing requested, the\n * server must not name one either.\n */\nexport function assertAddressEchoed(\n response: Record<string, unknown>,\n field: string,\n requested: string | undefined,\n): void {\n const received = response[field];\n const named = typeof received === \"string\" && received !== \"\";\n const matches =\n requested === undefined || requested === \"\"\n ? !named\n : named && sameAddress(received, requested);\n if (!matches) {\n const swapId = typeof response.id === \"string\" ? response.id : undefined;\n throw new SwapVerificationError(\n `The server's ${field} for swap ${swapId ?? \"(new)\"} is ${String(received)}, expected ${requested ?? \"none\"}; not storing the swap`,\n {\n field,\n expected: requested ?? \"\",\n received: String(received),\n swapId,\n },\n );\n }\n}\n\n/**\n * An invoice compared by the hash it pays. One that does not decode is\n * compared as is, so a record stored before invoices were checked still\n * matches an unchanged copy.\n */\nfunction invoiceKey(invoice: string): string {\n try {\n return paymentHashOf(invoice);\n } catch {\n return invoice;\n }\n}\n\n/**\n * A fresh server copy of a stored swap that {@link swapTermsChange} refused,\n * with the stored copy's terms in place of the server's: its status and\n * progress are still current, and nothing that locks funds comes from the\n * refused copy. A term the stored copy lacks is kept from the server's copy,\n * as an accepted refresh would store it, unless it is what was refused.\n */\nexport function withStoredTerms(\n stored: StoredSwap,\n fresh: GetSwapResponse,\n refused: SwapVerificationError,\n): GetSwapResponse {\n // A hash lock refused against its invoice condemns the invoice too.\n const condemned =\n refused.field === \"hash_lock\"\n ? [\"hash_lock\", \"client_lightning_invoice\"]\n : [refused.field];\n const before = stored.response as unknown as Record<string, unknown>;\n const kept: Record<string, unknown> = { ...fresh };\n // An EVM-sourced rehash legitimately moves the hash lock and invoice.\n const terms = EVM_SOURCED.has(stored.response.direction)\n ? [\"direction\", \"bridge_target_chain\", ...PAYOUT_FIELDS]\n : [\n \"direction\",\n \"bridge_target_chain\",\n ...HASH_FIELDS,\n ...ADDRESS_FIELDS,\n ...INVOICE_FIELDS,\n ...PAYOUT_FIELDS,\n ];\n for (const field of terms) {\n if (field in before) kept[field] = before[field];\n else if (condemned.includes(field)) delete kept[field];\n }\n return kept as unknown as GetSwapResponse;\n}\n\n/**\n * How a fresh server copy of a stored swap fails to bind to it, if it does:\n * a direction, hash lock, lock address or invoice payment hash that differs\n * from the stored one, a Lightning to X invoice that does not pay this client's\n * preimage hash, or an X to Lightning hash lock that is not its invoice's\n * payment hash, or a payout address or claim key that differs from the\n * stored one. These never change once a swap exists, so a difference means\n * the copy must not replace the stored one.\n *\n * EVM-sourced swaps are checked only for their direction and payout: their\n * funding uses what creation recorded (`lightningPaymentHash`,\n * `evmFundingTerms`), never the server's copy, and a rehash legitimately\n * moves their hash lock and invoice.\n */\nexport function swapTermsChange(\n stored: StoredSwap,\n fresh: GetSwapResponse,\n): SwapVerificationError | undefined {\n const before = stored.response as unknown as Record<string, unknown>;\n const after = fresh as unknown as Record<string, unknown>;\n const swapId = stored.swapId;\n const changed = (field: string, expected: string, received: string) =>\n new SwapVerificationError(\n `The server's ${field} for swap ${swapId} commits to ${received}, expected ${expected}; keeping the stored copy`,\n { field, expected, received, swapId },\n );\n\n const compare = (fields: string[], key: (value: string) => string) => {\n for (const field of fields) {\n const was = before[field];\n if (typeof was !== \"string\" || was === \"\") continue;\n const now = after[field];\n const expected = key(was);\n const received = typeof now === \"string\" ? key(now) : String(now);\n if (received !== expected) return changed(field, expected, received);\n }\n return undefined;\n };\n const payout =\n compare([\"direction\", \"bridge_target_chain\"], (value) => value) ??\n compare(PAYOUT_FIELDS, addressKey);\n if (payout) return payout;\n if (EVM_SOURCED.has(stored.response.direction)) return undefined;\n\n const difference =\n compare(HASH_FIELDS, normalizeHash) ??\n compare(ADDRESS_FIELDS, (address) => address.toLowerCase()) ??\n compare(INVOICE_FIELDS, invoiceKey);\n if (difference) return difference;\n\n if (typeof after.bolt11_invoice === \"string\") {\n const expected = normalizeHash(stored.preimageHash);\n const received = invoiceKey(after.bolt11_invoice);\n if (received !== expected) {\n return changed(\"bolt11_invoice\", expected, received);\n }\n }\n if (\n typeof after.client_lightning_invoice === \"string\" &&\n typeof after.hash_lock === \"string\"\n ) {\n const expected = invoiceKey(after.client_lightning_invoice);\n const received = normalizeHash(after.hash_lock);\n if (received !== expected) return changed(\"hash_lock\", expected, received);\n }\n return undefined;\n}\n","/**\n * Arkade (off-chain) VHTLC refund implementation.\n *\n * This module provides VHTLC refund functionality for Arkade (btc_arkade) swaps.\n * When a swap times out, users can reclaim their funds using this refund logic.\n *\n * The VHTLC uses a Taproot output with multiple spending paths. For refunds\n * after the locktime, we use the `refundWithoutReceiver` script path.\n */\n\nimport {\n type ArkTxInput,\n buildOffchainTx,\n CSVMultisigTapscript,\n type IndexerProvider,\n type OperatorProvider,\n RestIndexerProvider,\n RestOperatorProvider,\n SingleKey,\n type VHTLC,\n} from \"@arkade-os/sdk\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { hex } from \"@scure/base\";\n\nimport {\n getNetworkHrp,\n getNetworkName,\n resolveArkadeServerUrlByName,\n} from \"../arkade-network.js\";\nimport { submitOffchainTxOneShot } from \"../arkade-submit.js\";\nimport { createSdkLogger, type Logger, type LogLevel } from \"../logging.js\";\nimport {\n ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n StrictVhtlcScript,\n} from \"../strict-vhtlc.js\";\n\n/** Parameters needed to build an Arkade refund */\nexport interface ArkadeRefundParams {\n /** User's secret key (32-byte hex) for signing */\n userSecretKey: string;\n /** User's x-only public key (32-byte hex) - this is the sender in the VHTLC */\n userPubKey: string;\n /** Lendaswap's public key (33-byte compressed hex or 32-byte x-only) - this is the receiver */\n lendaswapPubKey: string;\n /** Arkade server's x-only public key (32-byte hex) */\n arkadeServerPubKey: string;\n /** Hash lock (32-byte hex, SHA256 of preimage) - we'll compute RIPEMD160(hashLock) */\n hashLock: string;\n /** VHTLC address to refund from */\n vhtlcAddress: string;\n /** Refund locktime (unix timestamp) */\n refundLocktime: number;\n /** Unilateral claim delay in seconds */\n unilateralClaimDelay: number;\n /** Unilateral refund delay in seconds */\n unilateralRefundDelay: number;\n /** Unilateral refund without receiver delay in seconds */\n unilateralRefundWithoutReceiverDelay: number;\n /** Destination Arkade address to receive refunded funds */\n destinationAddress: string;\n /** Bitcoin network (mainnet, signet, etc.) */\n network: string;\n /** Arkade HTLC script version. Only strict version 1 is supported. */\n arkadeHtlcScriptVersion?: number;\n /** Arkade server URL (optional, uses default based on network) */\n arkadeServerUrl?: string;\n /** Optional logger sink. Silent by default. */\n logger?: Logger;\n /** Minimum log level to emit. Defaults to `silent`. */\n logLevel?: LogLevel;\n}\n\n/** Result of building an Arkade refund */\nexport interface ArkadeRefundResult {\n /** Virtual transaction ID */\n txId: string;\n /** Amount refunded in satoshis */\n refundAmount: bigint;\n}\n\n/**\n * Convert seconds to RelativeTimelock format.\n */\nfunction secondsToTimelock(\n seconds: number,\n): VHTLC.Options[\"unilateralClaimDelay\"] {\n // Arkade SDK expects blocks or seconds for timelocks.\n // The sequence encoding for seconds requires 512-second granularity.\n return {\n type: \"seconds\" as const,\n value: BigInt(seconds),\n };\n}\n\n/**\n * Parse public key, handling both compressed (33-byte) and x-only (32-byte) formats.\n * Returns x-only (32-byte) format.\n */\nexport function parseXOnlyPubKey(pubKeyHex: string): Uint8Array {\n const bytes = hex.decode(pubKeyHex);\n if (bytes.length === 33) {\n // Compressed pubkey, strip the prefix byte\n return bytes.slice(1);\n }\n if (bytes.length === 32) {\n // Already x-only\n return bytes;\n }\n throw new Error(\n `Invalid public key length: expected 32 or 33, got ${bytes.length}`,\n );\n}\n\n/**\n * The VHTLC an Arkade-sourced swap locks in, rebuilt from its terms as a\n * refund spends it. Creation checks build it here too, so a swap they accept\n * is one this refund can spend.\n */\nexport function refundableVhtlc(params: {\n senderPubKey: string;\n receiverPubKey: string;\n serverPubKey: string;\n /** HASH160 of the preimage. */\n preimageHash: Uint8Array;\n refundLocktime: number;\n unilateralClaimDelay: number;\n unilateralRefundDelay: number;\n unilateralRefundWithoutReceiverDelay: number;\n scriptVersion?: number;\n}): StrictVhtlcScript {\n if (\n params.scriptVersion !== undefined &&\n params.scriptVersion !== ARKADE_HTLC_SCRIPT_VERSION_STRICT\n ) {\n throw new Error(\n `Unsupported Arkade HTLC script version: ${params.scriptVersion}`,\n );\n }\n return new StrictVhtlcScript({\n sender: parseXOnlyPubKey(params.senderPubKey),\n receiver: parseXOnlyPubKey(params.receiverPubKey),\n server: parseXOnlyPubKey(params.serverPubKey),\n preimageHash: params.preimageHash,\n refundLocktime: BigInt(params.refundLocktime),\n unilateralClaimDelay: secondsToTimelock(params.unilateralClaimDelay),\n unilateralRefundDelay: secondsToTimelock(params.unilateralRefundDelay),\n unilateralRefundWithoutReceiverDelay: secondsToTimelock(\n params.unilateralRefundWithoutReceiverDelay,\n ),\n });\n}\n\n/**\n * Refund a VHTLC swap after the locktime expires.\n *\n * This function:\n * 1. Constructs the VHTLC with the same parameters as the original swap\n * 2. Connects to the Arkade server\n * 3. Fetches spendable VTXOs at the VHTLC address\n * 4. Builds an offchain transaction using the refundWithoutReceiver script path\n * 5. Signs and submits the transaction\n * 6. Finalizes the transaction\n *\n * @param params - The refund parameters\n * @returns The refund result with transaction ID and amount\n * @throws Error if the refund fails\n */\nexport async function buildArkadeRefund(\n params: ArkadeRefundParams,\n): Promise<ArkadeRefundResult> {\n const {\n userSecretKey,\n userPubKey,\n lendaswapPubKey,\n arkadeServerPubKey,\n hashLock,\n vhtlcAddress,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n destinationAddress,\n network,\n arkadeHtlcScriptVersion,\n arkadeServerUrl,\n } = params;\n\n const logger = createSdkLogger(params).child({\n module: \"refund/arkade\",\n operation: \"arkade.refund\",\n data: { vhtlcAddress, network, destinationAddress },\n });\n\n logger.info({\n event: \"arkade.refund.start\",\n message: \"Starting Arkade refund\",\n });\n\n const serverPkBytes = parseXOnlyPubKey(arkadeServerPubKey);\n\n // Compute preimage hash for VHTLC\n // The API sends us the SHA256 hash (32 bytes) or HASH160 (20 bytes)\n const hashLockBytes = hex.decode(hashLock);\n let preimageHashBytes: Uint8Array;\n if (hashLockBytes.length === 32) {\n // the preimage is a SHA256 hash, we need to compute RIPEMD160 of it\n preimageHashBytes = ripemd160(hashLockBytes);\n } else if (hashLockBytes.length === 20) {\n // Already HASH160\n preimageHashBytes = hashLockBytes;\n } else {\n throw new Error(\n `Invalid hash lock length: expected 20 or 32, got ${hashLockBytes.length}`,\n );\n }\n\n // Determine Arkade server URL\n const networkName = getNetworkName(network);\n const serverUrl = resolveArkadeServerUrlByName(networkName, arkadeServerUrl);\n\n // Create Arkade providers\n const arkProvider: OperatorProvider = new RestOperatorProvider(serverUrl);\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n // Get server info\n const serverInfo = await arkProvider.getInfo();\n\n // For a refund the user is the VHTLC's sender, Lendaswap its receiver.\n const vhtlc = refundableVhtlc({\n senderPubKey: userPubKey,\n receiverPubKey: lendaswapPubKey,\n serverPubKey: arkadeServerPubKey,\n preimageHash: preimageHashBytes,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n scriptVersion: arkadeHtlcScriptVersion,\n });\n\n // Get network HRP and verify computed VHTLC address\n const hrp = getNetworkHrp(networkName);\n const computedAddress = vhtlc.address(hrp, serverPkBytes);\n const computedAddressStr = computedAddress.encode();\n\n // Verify address matches expected\n if (computedAddressStr !== vhtlcAddress) {\n throw new Error(\n `Computed VHTLC address (${computedAddressStr}) does not match expected (${vhtlcAddress})`,\n );\n }\n\n // Fetch VTXOs at the VHTLC address\n // We need the pk script to query the indexer\n const vhtlcPkScript = hex.encode(vhtlc.pkScript);\n\n const { vtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n spendableOnly: true,\n });\n\n if (vtxos.length === 0) {\n const { vtxos: updated } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n });\n logger.debug({\n event: \"arkade.refund.no_spendable_vtxos\",\n message: \"No spendable VTXOs found at VHTLC address\",\n data: { vtxos: updated },\n });\n throw new Error(\"No spendable VTXOs found at the VHTLC address\");\n }\n\n // Calculate total amount (vtxos have value as number)\n const totalAmount = vtxos.reduce((acc, v) => acc + BigInt(v.value), 0n);\n if (totalAmount === 0n) {\n throw new Error(\"Total VTXO amount is zero\");\n }\n\n // Get the refundWithoutReceiver TapLeafScript\n const refundLeafScript = vhtlc.refundWithoutReceiver();\n\n // Encode the VHTLC tap tree\n const tapTree = vhtlc.encode();\n\n // Decode the server's checkpoint tapscript from the server info\n const checkpointTapscript = CSVMultisigTapscript.decode(\n hex.decode(serverInfo.checkpointTapscript),\n );\n\n // Build inputs for offchain transaction\n const inputs: ArkTxInput[] = vtxos.map((v) => ({\n txid: v.txid,\n vout: v.vout,\n value: v.value,\n tapTree: tapTree,\n tapLeafScript: refundLeafScript,\n }));\n\n // Parse destination address to get the output script\n // The destination should be an Arkade address that we can decode\n const { ArkAddress } = await import(\"@arkade-os/sdk\");\n const destAddr = ArkAddress.decode(destinationAddress);\n const destPkScript = destAddr.pkScript;\n\n // Build outputs\n const outputs = [\n {\n script: destPkScript,\n amount: totalAmount,\n },\n ];\n\n const destinationAddressPPkScript = hex.encode(destPkScript);\n logger.info({\n event: \"arkade.refund.vtxos_found\",\n message: \"Found spendable VTXOs for Arkade refund\",\n data: { totalAmount, vtxoCount: vtxos.length, destinationAddressPPkScript },\n });\n\n // Build the offchain transaction\n const { arkTx, checkpoints } = buildOffchainTx(\n inputs,\n outputs,\n checkpointTapscript,\n );\n\n // Create signer from user's secret key\n const signer = SingleKey.fromHex(userSecretKey);\n\n // Sign the ark transaction and, up front, every checkpoint (one-shot submit)\n const signedArkTx = await signer.sign(arkTx);\n const userSignedCheckpoints = await Promise.all(\n checkpoints.map((cp) => signer.sign(cp)),\n );\n\n const { arkTxid, mode } = await submitOffchainTxOneShot(\n arkProvider,\n signedArkTx,\n checkpoints,\n userSignedCheckpoints,\n );\n logger.info({\n event: \"arkade.refund.finalized\",\n message: \"Arkade refund finalized\",\n data: { arkTxid, mode },\n });\n\n return {\n txId: arkTxid,\n refundAmount: totalAmount,\n };\n}\n","/**\n * One-shot submission of an Arkade offchain transaction.\n *\n * The client signs its checkpoints up front and sends them with the ark tx.\n * An arkd that supports one-shot submit finalizes in that single `submitTx`\n * call and hands the checkpoints back still carrying our signatures. An older\n * arkd strips them, returns server-signed checkpoints, and waits for\n * `finalizeTx` — so in that case we merge our signatures back in and finalize.\n */\n\nimport {\n assertSubmittedArkTxid,\n ConditionWitness,\n combineTapscriptSigs,\n getArkPsbtFields,\n matchServerCheckpoints,\n type OperatorProvider,\n setArkPsbtField,\n type Transaction,\n} from \"@arkade-os/sdk\";\nimport { base64, hex } from \"@scure/base\";\n\n/** The two operator calls a submission needs. */\nexport type OffchainSubmitProvider = Pick<\n OperatorProvider,\n \"submitTx\" | \"finalizeTx\"\n>;\n\nexport interface OneShotSubmitResult {\n arkTxid: string;\n /**\n * `\"one-shot\"` when arkd finalized on submit; `\"two-step\"` when it was an\n * older arkd and we had to call `finalizeTx`.\n */\n mode: \"one-shot\" | \"two-step\";\n}\n\n/**\n * Submit a signed ark tx with fully user-signed checkpoints, finalizing\n * through `finalizeTx` only if arkd did not already finalize.\n *\n * @param provider operator provider\n * @param signedArkTx ark tx carrying every user-side signature it needs\n * @param checkpoints checkpoints as built (used to match arkd's response)\n * @param userSignedCheckpoints the same checkpoints, same order, carrying every\n * user-side signature (and condition witness) they need\n */\nexport async function submitOffchainTxOneShot(\n provider: OffchainSubmitProvider,\n signedArkTx: Transaction,\n checkpoints: Transaction[],\n userSignedCheckpoints: Transaction[],\n): Promise<OneShotSubmitResult> {\n if (userSignedCheckpoints.length !== checkpoints.length) {\n throw new Error(\n `expected ${checkpoints.length} user-signed checkpoints, got ${userSignedCheckpoints.length}`,\n );\n }\n const userByTxid = new Map(\n checkpoints.map((c, i) => [c.id, userSignedCheckpoints[i]] as const),\n );\n\n const response = await provider.submitTx(\n base64.encode(signedArkTx.toPSBT()),\n userSignedCheckpoints.map((c) => base64.encode(c.toPSBT())),\n );\n assertSubmittedArkTxid(response, signedArkTx, \"submitTx\");\n const { arkTxid } = response;\n const matched = matchServerCheckpoints(\n response.signedCheckpointTxs,\n checkpoints,\n \"submitTx\",\n );\n\n const userSignedFor = (local: Transaction): Transaction => {\n const user = userByTxid.get(local.id);\n if (!user) throw new Error(`no user-signed checkpoint for ${local.id}`);\n return user;\n };\n\n if (\n matched.every(({ server, local }) =>\n carriesTapscriptSigs(server, userSignedFor(local)),\n )\n ) {\n return { arkTxid, mode: \"one-shot\" };\n }\n\n const finalCheckpoints = matched.map(({ server, local }) => {\n const user = userSignedFor(local);\n combineTapscriptSigs(user, server);\n carryConditionWitness(user, server);\n return base64.encode(server.toPSBT());\n });\n await provider.finalizeTx(arkTxid, finalCheckpoints);\n return { arkTxid, mode: \"two-step\" };\n}\n\n/** Whether `server` already carries every tapscript sig `user` has on input 0. */\nfunction carriesTapscriptSigs(server: Transaction, user: Transaction): boolean {\n const entries = (tx: Transaction) =>\n (tx.getInput(0).tapScriptSig ?? []).map(\n ([{ pubKey, leafHash }, sig]) =>\n hex.encode(pubKey) + hex.encode(leafHash) + hex.encode(sig),\n );\n const have = new Set(entries(server));\n const want = entries(user);\n return want.length > 0 && want.every((e) => have.has(e));\n}\n\n/** Copy our condition witness onto arkd's checkpoint if arkd dropped it. */\nfunction carryConditionWitness(user: Transaction, server: Transaction): void {\n if (getArkPsbtFields(server, 0, ConditionWitness).length > 0) return;\n const [witness] = getArkPsbtFields(user, 0, ConditionWitness);\n if (witness) setArkPsbtField(server, 0, ConditionWitness, witness);\n}\n","/**\n * On-chain Bitcoin HTLC refund implementation.\n *\n * This module provides Taproot HTLC refund transaction building for BTC → EVM swaps\n * where users lock on-chain Bitcoin. If the swap times out, users can reclaim\n * their funds using this refund logic.\n *\n * The HTLC uses a Taproot output with:\n * - Unspendable key spend (NUMS internal key)\n * - Hashlock script path: server claims with preimage\n * - Timelock script path: user refunds after locktime\n */\n\nimport { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { hex } from \"@scure/base\";\nimport * as btc from \"@scure/btc-signer\";\n\n/** Bitcoin network type */\nexport type BitcoinNetwork = \"mainnet\" | \"testnet\" | \"signet\" | \"regtest\";\n\n/** Parameters needed to build a claim transaction for an on-chain Taproot HTLC */\nexport interface OnchainClaimParams {\n /** The funding transaction ID (hex, no 0x prefix) */\n fundingTxId: string;\n /** The output index in the funding transaction */\n fundingVout: number;\n /** Amount locked in the HTLC in satoshis */\n htlcAmount: bigint;\n /** Hash lock (20-byte hex, RIPEMD160(SHA256(secret))) */\n hashLock: string;\n /** User's x-only public key (32-byte hex) — the claimer */\n userClaimPubKey: string;\n /** Server's x-only public key (32-byte hex) — the refunder */\n serverRefundPubKey: string;\n /** User's secret key (32-byte hex) for signing */\n userSecretKey: string;\n /** The preimage (32-byte hex) that hashes to the hash lock */\n preimage: string;\n /** Refund locktime (unix timestamp) — needed to reconstruct the HTLC */\n refundLocktime: number;\n /** Destination address to receive claimed funds */\n destinationAddress: string;\n /** Fee rate in satoshis per virtual byte */\n feeRateSatPerVb: number;\n /** Bitcoin network */\n network: BitcoinNetwork;\n /** Bitcoin HTLC script version. Only strict version 1 is supported. */\n btcHtlcScriptVersion?: number;\n}\n\n/** Result of building a claim transaction */\nexport interface OnchainClaimResult {\n /** The signed transaction hex (ready to broadcast) */\n txHex: string;\n /** Transaction ID (hash) */\n txId: string;\n /** Amount being claimed (after fees) */\n claimAmount: bigint;\n /** Fee paid in satoshis */\n fee: bigint;\n /** The HTLC address that funds are being claimed from */\n htlcAddress: string;\n}\n\n/** Parameters needed to build a refund transaction */\nexport interface OnchainRefundParams {\n /** The funding transaction ID (hex, no 0x prefix) */\n fundingTxId: string;\n /** The output index in the funding transaction (usually 0) */\n fundingVout: number;\n /** Amount locked in the HTLC in satoshis */\n htlcAmount: bigint;\n /** Hash lock (20-byte hex, RIPEMD160(SHA256(secret))) */\n hashLock: string;\n /** Server's x-only public key (32-byte hex) */\n serverPubKey: string;\n /** User's x-only public key (32-byte hex) */\n userPubKey: string;\n /** User's secret key (32-byte hex) for signing */\n userSecretKey: string;\n /** Refund locktime (unix timestamp) */\n refundLocktime: number;\n /** Destination address to receive refunded funds */\n destinationAddress: string;\n /** Fee rate in satoshis per virtual byte */\n feeRateSatPerVb: number;\n /** Bitcoin network */\n network: BitcoinNetwork;\n /** Bitcoin HTLC script version. Only strict version 1 is supported. */\n btcHtlcScriptVersion?: number;\n}\n\n/** Result of building a refund transaction */\nexport interface OnchainRefundResult {\n /** The signed transaction hex (ready to broadcast) */\n txHex: string;\n /** Transaction ID (hash) */\n txId: string;\n /** Amount being refunded (after fees) */\n refundAmount: bigint;\n /** Fee paid in satoshis */\n fee: bigint;\n /** The HTLC address that funds are being refunded from */\n htlcAddress: string;\n}\n\n/**\n * NUMS (Nothing Up My Sleeve) point - provably unspendable public key.\n * This is the standard BIP-341 NUMS point used as the internal key\n * for script-only Taproot outputs.\n */\nconst NUMS_POINT = hex.decode(\n \"0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0\",\n);\n\n/**\n * Regtest network configuration.\n * btc-signer only provides NETWORK (mainnet) and TEST_NETWORK (testnet/signet),\n * but regtest uses a different bech32 prefix ('bcrt' instead of 'tb').\n */\nconst REGTEST_NETWORK = {\n bech32: \"bcrt\",\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n} as const;\n\n/**\n * Get the btc-signer network configuration.\n */\nfunction getNetwork(\n network: BitcoinNetwork,\n): typeof btc.NETWORK | typeof REGTEST_NETWORK {\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 default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Build the hashlock tapscript for server claim.\n *\n * Script: `<server_pk> OP_CHECKSIGVERIFY OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 <hash_lock> OP_EQUAL`\n *\n * The server must provide a valid Schnorr signature AND a 32-byte preimage.\n */\nfunction buildHashlockScript(\n hashLock: Uint8Array,\n serverPubKey: Uint8Array,\n btcHtlcScriptVersion = 1,\n): Uint8Array {\n if (btcHtlcScriptVersion !== 1) {\n throw new Error(\n `Unsupported BTC HTLC script version: ${btcHtlcScriptVersion}`,\n );\n }\n const script = [\n serverPubKey,\n \"CHECKSIGVERIFY\",\n \"SIZE\",\n 32,\n \"EQUALVERIFY\",\n \"HASH160\",\n hashLock,\n \"EQUAL\",\n ] as Parameters<typeof btc.Script.encode>[0];\n return btc.Script.encode(script);\n}\n\n/**\n * Build the timelock tapscript for user refund.\n *\n * Script: `<locktime> OP_CLTV OP_DROP <user_pk> OP_CHECKSIG`\n *\n * The user can spend after the locktime has passed.\n */\nfunction buildTimelockScript(\n userPubKey: Uint8Array,\n refundLocktime: number,\n): Uint8Array {\n return btc.Script.encode([\n refundLocktime,\n \"CHECKLOCKTIMEVERIFY\",\n \"DROP\",\n userPubKey,\n \"CHECKSIG\",\n ]);\n}\n\n/**\n * Compute HASH160 (RIPEMD160(SHA256(data))).\n */\nexport function computeHash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data));\n}\n\n/**\n * Build a Taproot HTLC spending info.\n *\n * Creates the P2TR structure with:\n * - Unspendable internal key (NUMS point)\n * - Left leaf: hashlock script (server claim)\n * - Right leaf: timelock script (user refund)\n */\nfunction buildHtlcTaprootInfo(\n hashLock: Uint8Array,\n serverPubKey: Uint8Array,\n userPubKey: Uint8Array,\n refundLocktime: number,\n btcHtlcScriptVersion = 1,\n): {\n hashlockScript: Uint8Array;\n timelockScript: Uint8Array;\n p2tr: ReturnType<typeof btc.p2tr>;\n} {\n const hashlockScript = buildHashlockScript(\n hashLock,\n serverPubKey,\n btcHtlcScriptVersion,\n );\n const timelockScript = buildTimelockScript(userPubKey, refundLocktime);\n\n // Build the taproot tree with two leaves\n // Using NUMS point as internal key (script-path only)\n const p2tr = btc.p2tr(\n NUMS_POINT.slice(1), // Remove the 02/03 prefix for x-only\n [{ script: hashlockScript }, { script: timelockScript }],\n undefined,\n true, // allowUnknownOutputs\n );\n\n return { hashlockScript, timelockScript, p2tr };\n}\n\n/**\n * Estimate the virtual size of a Taproot script-path refund transaction.\n *\n * Components:\n * - Version: 4 bytes\n * - Marker + Flag: 2 bytes (for witness)\n * - Input count: 1 byte\n * - Input: 32 (txid) + 4 (vout) + 1 (script len) + 4 (sequence) = 41 bytes\n * - Output count: 1 byte\n * - Output: 8 (value) + 1 (script len) + 34 (P2TR output) = 43 bytes\n * - Witness: ~130 bytes (sig + script + control block)\n * - Locktime: 4 bytes\n *\n * Total base: ~96 bytes, witness: ~130 bytes\n * vBytes = base + witness/4 ≈ 96 + 33 = 129 vBytes\n *\n * Using a conservative estimate of 130 vBytes.\n */\nconst REFUND_TX_VBYTES = 130n;\n\n/**\n * Estimate vBytes for a claim transaction.\n * Similar to refund but includes the preimage in the witness (~32 bytes extra).\n * Conservative estimate: 150 vBytes.\n */\nconst CLAIM_TX_VBYTES = 150n;\n\n/**\n * Build and sign a claim transaction for an on-chain Bitcoin Taproot HTLC.\n *\n * This creates a transaction that spends from the HTLC using the hashlock\n * script path by providing the preimage and a valid signature.\n *\n * Used for EVM-to-Bitcoin swaps where the user claims BTC after the server\n * has funded the on-chain HTLC.\n *\n * @param params - The claim parameters\n * @returns The signed transaction and related info\n * @throws Error if the transaction cannot be built\n */\nexport function buildOnchainClaimTransaction(\n params: OnchainClaimParams,\n): OnchainClaimResult {\n const {\n fundingTxId,\n fundingVout,\n htlcAmount,\n hashLock,\n userClaimPubKey,\n serverRefundPubKey,\n userSecretKey,\n preimage,\n refundLocktime,\n destinationAddress,\n feeRateSatPerVb,\n network,\n } = params;\n\n // Parse hex inputs\n const hashLockBytes = hex.decode(hashLock);\n const userClaimPkBytes = hex.decode(userClaimPubKey);\n const serverRefundPkBytes = hex.decode(serverRefundPubKey);\n const userSkBytes = hex.decode(userSecretKey);\n const preimageBytes = hex.decode(preimage);\n\n if (hashLockBytes.length !== 20) {\n throw new Error(\n `Invalid hash lock length: expected 20, got ${hashLockBytes.length}`,\n );\n }\n if (userClaimPkBytes.length !== 32) {\n throw new Error(\n `Invalid user claim pubkey length: expected 32, got ${userClaimPkBytes.length}`,\n );\n }\n if (serverRefundPkBytes.length !== 32) {\n throw new Error(\n `Invalid server refund pubkey length: expected 32, got ${serverRefundPkBytes.length}`,\n );\n }\n if (userSkBytes.length !== 32) {\n throw new Error(\n `Invalid user secret key length: expected 32, got ${userSkBytes.length}`,\n );\n }\n if (preimageBytes.length !== 32) {\n throw new Error(\n `Invalid preimage length: expected 32, got ${preimageBytes.length}`,\n );\n }\n\n // Verify preimage matches hash lock\n const computedHashLock = computeHash160(preimageBytes);\n if (hex.encode(computedHashLock) !== hex.encode(hashLockBytes)) {\n throw new Error(\n \"Preimage does not match hash lock: HASH160(preimage) != hashLock\",\n );\n }\n\n // Build the HTLC Taproot structure\n // For evm_to_bitcoin: user is claimer (hashlock), server is refunder (timelock)\n // buildHtlcTaprootInfo(hashLock, claimerPk, refunderPk, locktime)\n const { p2tr } = buildHtlcTaprootInfo(\n hashLockBytes,\n userClaimPkBytes,\n serverRefundPkBytes,\n refundLocktime,\n params.btcHtlcScriptVersion,\n );\n\n // Calculate fee\n const fee = CLAIM_TX_VBYTES * BigInt(Math.ceil(feeRateSatPerVb));\n if (fee >= htlcAmount) {\n throw new Error(\n `Fee (${fee} sats) exceeds HTLC amount (${htlcAmount} sats)`,\n );\n }\n const claimAmount = htlcAmount - fee;\n\n // Get network config\n const networkConfig = getNetwork(network);\n\n // Find the tapLeafScript for the hashlock script (index 0 in our tree)\n const tapLeafScript = p2tr.tapLeafScript;\n if (!tapLeafScript || tapLeafScript.length < 1) {\n throw new Error(\"Failed to build tapLeafScript for hashlock\");\n }\n\n // The hashlock script is at index 0 in our tree\n const hashlockLeaf = tapLeafScript[0];\n\n // Build the transaction\n const tx = new btc.Transaction({\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n });\n\n // Add input (the HTLC output we're spending)\n tx.addInput({\n txid: fundingTxId,\n index: fundingVout,\n witnessUtxo: {\n script: p2tr.script,\n amount: htlcAmount,\n },\n tapLeafScript: [hashlockLeaf],\n sequence: 0xffffffff,\n });\n\n // Add output (destination)\n tx.addOutputAddress(destinationAddress, claimAmount, networkConfig);\n\n // Manually compute sighash, sign, and build the full witness.\n // We can't use tx.signIdx() because finalize() only produces [signature]\n // but the hashlock script requires [preimage, signature] in the witness.\n // After signIdx, btc-signer locks the transaction and won't let us modify\n // the witness fields. So we do everything manually.\n\n const [controlBlockInfo, leafScriptWithVersion] = hashlockLeaf;\n\n // tapLeafScript entries have the leaf version byte appended to the script.\n // Strip it for sighash computation and the witness.\n const leafScript = leafScriptWithVersion.slice(0, -1);\n const leafVersion = leafScriptWithVersion[leafScriptWithVersion.length - 1];\n\n // Compute the Taproot script-path sighash (BIP 342)\n // preimageWitnessV1 returns the final tagged hash, not a preimage to be hashed again.\n const sighash = tx.preimageWitnessV1(\n 0,\n [p2tr.script],\n btc.SigHash.DEFAULT,\n [htlcAmount],\n undefined,\n leafScript,\n leafVersion,\n );\n\n // Sign the sighash with Schnorr (BIP 340)\n const sig = schnorr.sign(sighash, userSkBytes);\n\n // Encode the control block struct to raw bytes:\n // [version(1)] [internalKey(32)] [merklePath(32*n)]\n const cbInfo = controlBlockInfo as {\n version: number;\n internalKey: Uint8Array;\n merklePath: Uint8Array[];\n };\n const encodedControlBlock = new Uint8Array(\n 1 + 32 + 32 * cbInfo.merklePath.length,\n );\n encodedControlBlock[0] = cbInfo.version;\n encodedControlBlock.set(cbInfo.internalKey, 1);\n for (let i = 0; i < cbInfo.merklePath.length; i++) {\n encodedControlBlock.set(cbInfo.merklePath[i], 33 + 32 * i);\n }\n\n // Set the final witness directly (no signIdx needed):\n // [preimage, signature, script, control_block]\n tx.updateInput(0, {\n finalScriptWitness: [preimageBytes, sig, leafScript, encodedControlBlock],\n });\n\n // Extract the signed transaction\n const txHex = hex.encode(tx.extract());\n const txId = tx.id;\n\n // Compute the HTLC address\n const htlcAddress = btc.Address(networkConfig).encode({\n type: \"tr\",\n pubkey: p2tr.tweakedPubkey,\n });\n\n return {\n txHex,\n txId,\n claimAmount,\n fee,\n htlcAddress,\n };\n}\n\n/**\n * Build and sign a refund transaction for an on-chain Bitcoin HTLC.\n *\n * This creates a transaction that spends from the HTLC using the timelock\n * script path after the refund locktime has passed.\n *\n * @param params - The refund parameters\n * @returns The signed transaction and related info\n * @throws Error if the transaction cannot be built\n */\nexport function buildOnchainRefundTransaction(\n params: OnchainRefundParams,\n): OnchainRefundResult {\n const {\n fundingTxId,\n fundingVout,\n htlcAmount,\n hashLock,\n serverPubKey,\n userPubKey,\n userSecretKey,\n refundLocktime,\n destinationAddress,\n feeRateSatPerVb,\n network,\n } = params;\n\n // Parse hex inputs\n const hashLockBytes = hex.decode(hashLock);\n const serverPkBytes = hex.decode(serverPubKey);\n const userPkBytes = hex.decode(userPubKey);\n const userSkBytes = hex.decode(userSecretKey);\n\n if (hashLockBytes.length !== 20) {\n throw new Error(\n `Invalid hash lock length: expected 20, got ${hashLockBytes.length}`,\n );\n }\n if (serverPkBytes.length !== 32) {\n throw new Error(\n `Invalid server pubkey length: expected 32, got ${serverPkBytes.length}`,\n );\n }\n if (userPkBytes.length !== 32) {\n throw new Error(\n `Invalid user pubkey length: expected 32, got ${userPkBytes.length}`,\n );\n }\n if (userSkBytes.length !== 32) {\n throw new Error(\n `Invalid user secret key length: expected 32, got ${userSkBytes.length}`,\n );\n }\n\n // Build the HTLC Taproot structure\n const { p2tr } = buildHtlcTaprootInfo(\n hashLockBytes,\n serverPkBytes,\n userPkBytes,\n refundLocktime,\n params.btcHtlcScriptVersion,\n );\n\n // Calculate fee\n const fee = REFUND_TX_VBYTES * BigInt(Math.ceil(feeRateSatPerVb));\n if (fee >= htlcAmount) {\n throw new Error(\n `Fee (${fee} sats) exceeds HTLC amount (${htlcAmount} sats)`,\n );\n }\n const refundAmount = htlcAmount - fee;\n\n // Get network config\n const networkConfig = getNetwork(network);\n\n // Find the tapLeafScript for the timelock script (index 1 in our tree)\n // p2tr.tapLeafScript is an array of [controlBlockInfo, script] tuples\n const tapLeafScript = p2tr.tapLeafScript;\n if (!tapLeafScript || tapLeafScript.length < 2) {\n throw new Error(\"Failed to build tapLeafScript for timelock\");\n }\n\n // The timelock script is at index 1 in our tree\n const timelockLeaf = tapLeafScript[1];\n\n // Build the transaction with lockTime in constructor\n const tx = new btc.Transaction({\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n lockTime: refundLocktime,\n });\n\n // Add input (the HTLC output we're spending)\n tx.addInput({\n txid: fundingTxId,\n index: fundingVout,\n witnessUtxo: {\n script: p2tr.script,\n amount: htlcAmount,\n },\n tapLeafScript: [timelockLeaf],\n sequence: 0xfffffffe, // Enable locktime (< 0xffffffff)\n });\n\n // Add output (destination)\n tx.addOutputAddress(destinationAddress, refundAmount, networkConfig);\n\n // Sign the input\n tx.signIdx(userSkBytes, 0);\n\n // Finalize\n tx.finalize();\n\n // Extract the signed transaction\n const txHex = hex.encode(tx.extract());\n const txId = tx.id;\n\n // Compute the HTLC address\n const htlcAddress = btc.Address(networkConfig).encode({\n type: \"tr\",\n pubkey: p2tr.tweakedPubkey,\n });\n\n return {\n txHex,\n txId,\n refundAmount,\n fee,\n htlcAddress,\n };\n}\n\n/**\n * Verify that a Taproot address matches the expected HTLC parameters.\n *\n * This is useful to confirm the HTLC address returned by the server\n * matches what we expect based on the swap parameters.\n *\n * @param expectedAddress - The address to verify\n * @param hashLock - Hash lock (20-byte hex)\n * @param serverPubKey - Server's x-only public key (32-byte hex)\n * @param userPubKey - User's x-only public key (32-byte hex)\n * @param refundLocktime - Refund locktime (unix timestamp)\n * @param network - Bitcoin network\n * @param btcHtlcScriptVersion - Bitcoin HTLC script version. Only strict version 1 is supported.\n * @returns true if the address matches, false otherwise\n */\nexport function verifyHtlcAddress(\n expectedAddress: string,\n hashLock: string,\n serverPubKey: string,\n userPubKey: string,\n refundLocktime: number,\n network: BitcoinNetwork,\n btcHtlcScriptVersion = 1,\n): boolean {\n return (\n htlcAddress(\n hashLock,\n serverPubKey,\n userPubKey,\n refundLocktime,\n network,\n btcHtlcScriptVersion,\n ) === expectedAddress\n );\n}\n\n/**\n * The Taproot address of the HTLC on these terms, with the same arguments as\n * {@link verifyHtlcAddress}.\n */\nexport function htlcAddress(\n hashLock: string,\n serverPubKey: string,\n userPubKey: string,\n refundLocktime: number,\n network: BitcoinNetwork,\n btcHtlcScriptVersion = 1,\n): string {\n const hashLockBytes = hex.decode(hashLock);\n const serverPkBytes = hex.decode(serverPubKey);\n const userPkBytes = hex.decode(userPubKey);\n\n const { p2tr } = buildHtlcTaprootInfo(\n hashLockBytes,\n serverPkBytes,\n userPkBytes,\n refundLocktime,\n btcHtlcScriptVersion,\n );\n\n return btc.Address(getNetwork(network)).encode({\n type: \"tr\",\n pubkey: p2tr.tweakedPubkey,\n });\n}\n","/**\n * Retry helper for swap creation when the server rejects a duplicate hash lock,\n * and error types for non-retryable duplicate conditions.\n */\n\nimport { createSdkLogger } from \"../logging.js\";\nimport type { CreateSwapContext } from \"./types.js\";\n\nconst MAX_RETRIES = 10;\nconst SKIP_COUNT = 10;\n\n/**\n * Thrown when the server rejects a submarine swap because the Lightning\n * invoice has already been used in another swap. This cannot be retried\n * automatically — the caller must provide a different invoice.\n */\nexport class DuplicateInvoiceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DuplicateInvoiceError\";\n }\n}\n\n/**\n * Returns true if the error indicates a hash lock collision (409 Conflict\n * from the server, or a rejection for a reused preimage hash).\n */\nfunction isHashCollisionError(message: string): boolean {\n return message.includes(\"a swap with this preimage hash exists already\");\n}\n\n/**\n * Returns true if the error indicates a duplicate Lightning invoice.\n */\nexport function isDuplicateInvoiceError(message: string): boolean {\n return message.includes(\"a swap with this invoice exists already\");\n}\n\n/**\n * Wraps a swap creation attempt with automatic retry on hash lock collisions.\n *\n * When the server returns 409 (duplicate hash lock) or rejects the\n * preimage, this skips the key index forward and retries with fresh params.\n *\n * @param ctx - The swap creation context (must include skipKeyIndices).\n * @param attempt - A function that derives params and creates the swap.\n * Called once per attempt; must call ctx.deriveSwapParams() internally.\n */\nexport async function retryOnHashCollision<T>(\n ctx: CreateSwapContext,\n attempt: () => Promise<T>,\n): Promise<T> {\n let lastError: Error | undefined;\n const logger = createSdkLogger(ctx).child({\n module: \"create/retry\",\n operation: \"create.retry_on_hash_collision\",\n });\n\n for (let i = 0; i < MAX_RETRIES; i++) {\n try {\n return await attempt();\n } catch (e) {\n logger.debug({\n event: \"create.retry.attempt_failed\",\n message: \"Swap creation attempt failed\",\n data: { attempt: i + 1 },\n error: e,\n });\n\n if (e instanceof Error && isHashCollisionError(e.message)) {\n lastError = e;\n if (ctx.skipKeyIndices) {\n await ctx.skipKeyIndices(SKIP_COUNT);\n }\n continue;\n }\n throw e;\n }\n }\n\n throw lastError;\n}\n","/**\n * Arkade to EVM swap creation.\n */\n\nimport { deriveEvmAddress } from \"../evm/signing.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { ARKADE_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertAddressEchoed,\n assertArkadeToEvmVhtlc,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n ArkadeToEvmSwapOptions,\n ArkadeToEvmSwapResult,\n CreateSwapContext,\n} from \"./types.js\";\n\n/**\n * Creates a new Arkade-to-EVM swap via the generic endpoint.\n *\n * Uses the chain-agnostic `/swap/arkade/evm` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation. The response includes\n * `evm_coordinator_address` and optional `dex_call_data` for the\n * redeem-and-swap flow.\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createArkadeToEvmSwapGeneric(\n * {\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Fund:\", result.response.btc_vhtlc_address);\n * console.log(\"Coordinator:\", result.response.evm_coordinator_address);\n * ```\n */\nexport async function createArkadeToEvmSwapGeneric(\n options: ArkadeToEvmSwapOptions,\n ctx: CreateSwapContext,\n /**\n * The lock's claim address when it is not this swap's own key: the\n * recipient's RIF Relay smart wallet on a chain that claims through RIF.\n */\n claimingAddressOverride?: string,\n): Promise<ArkadeToEvmSwapResult> {\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const refundPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n // The claiming address is this swap's own key, not the wallet-level\n // EVM address used for gasless deposits. A sponsored claim installs an\n // EIP-7702 delegation (Kernel) on the claiming address; keeping that\n // off the deposit address means Permit2 / EIP-2612 keep seeing a plain\n // EOA there. Recovery re-derives this key from the swap's index.\n const claimingAddress =\n claimingAddressOverride ?? deriveEvmAddress(swapParams.secretKey);\n\n // Target address is where tokens are swept after the claim (user's final destination).\n // This is required and stored on the server for use during redemption.\n\n const body = {\n hash_lock: hashLock,\n arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n refund_pk: refundPk,\n user_id: userId,\n claiming_address: claimingAddress,\n target_address: options.targetAddress,\n token_address: options.tokenAddress,\n evm_chain_id: options.evmChainId,\n amount_in: options.sourceAmount\n ? Number(options.sourceAmount)\n : undefined,\n amount_out: options.targetAmount?.toString(),\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? true,\n bridge_target_chain: options.bridgeParams?.targetChain,\n bridge_target_token_address: options.bridgeParams?.targetTokenAddress,\n bridge_recipient_setup: options.bridgeParams?.recipientSetup,\n };\n const { data, error } = await ctx.apiClient.POST(\"/swap/arkade/evm\", {\n body,\n });\n\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n // The user funds btc_vhtlc_address, so it must be a VHTLC this client\n // can refund before the swap is stored or returned.\n assertArkadeToEvmVhtlc(data, swapParams.preimageHash, swapParams.publicKey);\n\n // The claim pays the target and signs with the claiming key: both must\n // be the ones this client sent.\n assertAddressEchoed(data, \"target_evm_address\", options.targetAddress);\n assertAddressEchoed(data, \"client_evm_address\", claimingAddress);\n\n // Store the swap if storage is configured; pin the bridge claim\n // recipient (Solana ATA) so a bare claim can route the CCTP burn.\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"arkade_to_evm\",\n },\n options.targetAddress,\n {\n recipient: options.bridgeParams?.recipient,\n recipientWallet: options.bridgeParams?.recipientWallet,\n },\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * Arkade to Lightning swap creation.\n *\n * The user locks Arkade VTXOs in a VHTLC; the server pays the user's\n * Lightning invoice and claims the VHTLC with the revealed preimage.\n */\n\nimport { invoicePaymentHash } from \"../bolt11.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { ARKADE_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertArkadeToLightningVhtlc,\n checkedLightningPaymentHash,\n normalizeHash,\n} from \"../swap-verification.js\";\nimport type {\n ArkadeToLightningSwapOptions,\n ArkadeToLightningSwapResult,\n CreateSwapContext,\n} from \"./types.js\";\n\n/**\n * Creates a new Arkade to Lightning swap.\n *\n * Flow:\n * 1. User funds the returned Arkade VHTLC (`arkade_vhtlc_address`) with `source_amount` sats\n * 2. Server pays the Lightning invoice; the settled payment reveals the preimage\n * 3. Server claims the VHTLC with the preimage\n *\n * The destination is **one of** `lightningInvoice` (its amount pins the\n * payout), or `lightningAddress`/`lnurl` with one of `sourceAmountSats`\n * (send-max: fees deducted from the payout) or `targetAmountSats` (exact\n * payout: fees added on top).\n *\n * Unlike the other directions, the swap's hash lock is the invoice's\n * payment hash — the derived swap key is only used for the refund path\n * (`refund_pk`), so a duplicate-hash 409 is not retried with a new key:\n * it means this exact invoice already has a swap.\n *\n * Before the swap is stored or returned, `hash_lock` is checked to be the\n * payment hash of `client_lightning_invoice`, and that invoice to pay the\n * same hash as `lightningInvoice` when one was given. A lock on any other\n * hash would let the server claim the VHTLC without paying the invoice. With\n * `lightningAddress` or `lnurl` the server resolves the invoice, which must\n * then also ask for the payout the server quoted. `arkade_vhtlc_address` is\n * then rebuilt from the hash, this swap's refund key and the server's keys and\n * timelocks, and must match.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's hash lock, invoice or VHTLC\n * address does not match. Nothing is stored; do not fund the VHTLC.\n * @throws Error if `lightningInvoice` is not a BOLT11 invoice (before any\n * request is made), or if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await createArkadeToLightningSwap(\n * { lightningInvoice: \"lnbc...\" },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Fund:\", result.response.arkade_vhtlc_address);\n * console.log(\"Lock amount:\", result.response.source_amount);\n * ```\n */\nexport async function createArkadeToLightningSwap(\n options: ArkadeToLightningSwapOptions,\n ctx: CreateSwapContext,\n): Promise<ArkadeToLightningSwapResult> {\n const destinations = [\n options.lightningInvoice,\n options.lightningAddress,\n options.lnurl,\n ].filter((d) => d !== undefined);\n if (destinations.length !== 1) {\n throw new Error(\n \"Provide exactly one of lightningInvoice, lightningAddress or lnurl\",\n );\n }\n if (\n options.lightningInvoice === undefined &&\n (options.sourceAmountSats === undefined) ===\n (options.targetAmountSats === undefined)\n ) {\n throw new Error(\n \"Provide exactly one of sourceAmountSats or targetAmountSats\",\n );\n }\n // A malformed invoice is refused before a key is derived or the server asked.\n if (options.lightningInvoice !== undefined) {\n invoicePaymentHash(options.lightningInvoice);\n }\n\n const swapParams = await ctx.deriveSwapParams();\n const refundPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const body = {\n lightning_invoice: options.lightningInvoice,\n lightning_address: options.lightningAddress,\n lnurl: options.lnurl,\n source_amount_sats: options.sourceAmountSats,\n target_amount_sats: options.targetAmountSats,\n refund_pk: refundPk,\n user_id: userId,\n arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n };\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/arkade/lightning\", {\n body,\n });\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n const { hash } = checkedLightningPaymentHash(options, data);\n assertArkadeToLightningVhtlc(data, normalizeHash(hash), swapParams.publicKey);\n\n // Store the swap if storage is configured — the derived key is what\n // signs a collaborative/unilateral refund of the VHTLC.\n await ctx.storeSwap(data.id, swapParams, {\n ...data,\n direction: \"arkade_to_lightning\",\n });\n\n return { response: data, swapParams };\n}\n","/**\n * Bitcoin (on-chain) to EVM swap creation via the generic endpoint.\n */\n\nimport { deriveEvmAddress } from \"../evm/signing.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { BTC_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertAddressEchoed,\n assertBitcoinToEvmHtlc,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n BitcoinToEvmSwapOptions,\n BitcoinToEvmSwapResult,\n CreateSwapContext,\n} from \"./types.js\";\n\n/**\n * Creates a new Bitcoin (on-chain) to EVM swap.\n *\n * Uses the chain-agnostic `/swap/bitcoin/evm` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation.\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createBitcoinToEvmSwap(\n * {\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * ```\n */\nexport async function createBitcoinToEvmSwap(\n options: BitcoinToEvmSwapOptions,\n ctx: CreateSwapContext,\n /**\n * The lock's claim address when it is not this swap's own key: the\n * recipient's RIF Relay smart wallet on a chain that claims through RIF.\n */\n claimingAddressOverride?: string,\n): Promise<BitcoinToEvmSwapResult> {\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const refundPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n // The claiming address is this swap's own key, not the wallet-level\n // EVM address used for gasless deposits. A sponsored claim installs an\n // EIP-7702 delegation (Kernel) on the claiming address; keeping that\n // off the deposit address means Permit2 / EIP-2612 keep seeing a plain\n // EOA there. Recovery re-derives this key from the swap's index.\n const claimingAddress =\n claimingAddressOverride ?? deriveEvmAddress(swapParams.secretKey);\n\n const body = {\n hash_lock: hashLock,\n btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,\n refund_pk: refundPk,\n user_id: userId,\n claiming_address: claimingAddress,\n target_address: options.targetAddress,\n token_address: options.tokenAddress,\n evm_chain_id: options.evmChainId,\n amount_in: options.sourceAmount,\n amount_out: options.targetAmount?.toString(),\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? true,\n bridge_target_chain: options.bridgeParams?.targetChain,\n bridge_target_token_address: options.bridgeParams?.targetTokenAddress,\n bridge_recipient_setup: options.bridgeParams?.recipientSetup,\n };\n const { data, error } = await ctx.apiClient.POST(\"/swap/bitcoin/evm\", {\n body,\n });\n\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n // The user funds btc_htlc_address, so it must be an HTLC this client\n // can refund before the swap is stored or returned.\n assertBitcoinToEvmHtlc(data, swapParams.preimageHash, swapParams.publicKey);\n\n // The claim pays the target and signs with the claiming key: both must\n // be the ones this client sent.\n assertAddressEchoed(data, \"target_evm_address\", options.targetAddress);\n assertAddressEchoed(data, \"client_evm_address\", claimingAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"bitcoin_to_evm\",\n },\n options.targetAddress,\n {\n recipient: options.bridgeParams?.recipient,\n recipientWallet: options.bridgeParams?.recipientWallet,\n },\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * Bitcoin (on-chain) to Arkade swap creation.\n *\n * The user sends on-chain BTC to a Taproot HTLC address and receives\n * Arkade VTXOs after the server funds the Arkade VHTLC.\n */\n\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { parseArkadeAddress } from \"../arkade-address.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport {\n ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n BTC_HTLC_SCRIPT_VERSION_STRICT,\n} from \"../strict-vhtlc.js\";\nimport {\n assertAddressEchoed,\n assertBitcoinToArkadeHtlc,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n BitcoinToArkadeSwapOptions,\n BitcoinToArkadeSwapResult,\n CreateSwapContext,\n} from \"./types.js\";\n\n/**\n * Creates a new Bitcoin (on-chain) to Arkade swap.\n *\n * Flow:\n * 1. User sends BTC to the Taproot HTLC address returned\n * 2. After 1 confirmation, server creates Arkade VHTLC for user\n * 3. User claims Arkade VHTLC with secret, revealing it\n * 4. Server claims on-chain BTC with the revealed secret\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createBitcoinToArkadeSwap(\n * {\n * satsReceive: 100000, // 100k sats to receive on Arkade\n * targetAddress: \"ark1q...\", // Arkade address\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * console.log(\"Amount to send:\", result.response.source_amount, \"sats\");\n * ```\n */\nexport async function createBitcoinToArkadeSwap(\n options: BitcoinToArkadeSwapOptions,\n ctx: CreateSwapContext,\n): Promise<BitcoinToArkadeSwapResult> {\n parseArkadeAddress(options.targetAddress);\n\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n\n // Bitcoin-to-Arkade uses HASH160 (RIPEMD160(SHA256(preimage))) not SHA256\n const hash160 = ripemd160(swapParams.preimageHash);\n const hashLock = bytesToHex(hash160);\n\n // Both claim_pk (for Arkade VHTLC) and refund_pk (for on-chain HTLC)\n // use the same derived public key\n const publicKey = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const body = {\n hash_lock: hashLock,\n claim_pk: publicKey,\n refund_pk: publicKey,\n user_id: userId,\n sats_receive: options.satsReceive,\n target_arkade_address: options.targetAddress,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,\n arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n };\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/bitcoin/arkade\", {\n body,\n });\n if (error)\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n if (!data) throw new Error(\"No swap data returned\");\n\n const response = data;\n // The user funds btc_htlc_address, so it must be an HTLC this client\n // can refund before the swap is stored or returned.\n assertBitcoinToArkadeHtlc(\n response,\n swapParams.preimageHash,\n swapParams.publicKey,\n );\n\n // The claim pays this address, so it must be the one this client sent.\n assertAddressEchoed(data, \"target_arkade_address\", options.targetAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n response.id,\n swapParams,\n { ...response, direction: \"btc_to_arkade\" },\n options.targetAddress,\n );\n\n return { response, swapParams };\n });\n}\n","/**\n * Bitcoin (on-chain) to Lightning swap creation.\n *\n * The user locks BTC in an on-chain Taproot HTLC; the server pays the user's\n * Lightning invoice and claims the HTLC with the revealed preimage.\n */\nimport { invoicePaymentHash } from \"../bolt11.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { BTC_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertBitcoinToLightningHtlc,\n checkedLightningPaymentHash,\n normalizeHash,\n} from \"../swap-verification.js\";\nimport type {\n BitcoinToLightningSwapOptions,\n BitcoinToLightningSwapResult,\n CreateSwapContext,\n} from \"./types.js\";\n\n/**\n * Creates a new Bitcoin (on-chain) to Lightning swap.\n *\n * Flow:\n * 1. User sends `source_amount` sats to the returned HTLC address (`btc_htlc_address`)\n * 2. After one confirmation the server pays the Lightning invoice; the settled\n * payment reveals the preimage\n * 3. Server claims the HTLC with the preimage\n *\n * The destination is **one of** `lightningInvoice` (its amount pins the\n * payout), or `lightningAddress`/`lnurl` with one of `sourceAmountSats`\n * (send-max: fees deducted from the payout) or `targetAmountSats` (exact\n * payout: fees added on top).\n *\n * As for Arkade → Lightning, the swap's hash lock is the invoice's payment\n * hash; the derived swap key is only the HTLC's refund key, so a\n * duplicate-hash 409 is not retried with a new key: it means this exact\n * invoice already has a swap.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await createBitcoinToLightningSwap(\n * { lightningInvoice: \"lnbc...\" },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * console.log(\"Amount to send:\", result.response.source_amount, \"sats\");\n * ```\n */\nexport async function createBitcoinToLightningSwap(\n options: BitcoinToLightningSwapOptions,\n ctx: CreateSwapContext,\n): Promise<BitcoinToLightningSwapResult> {\n const destinations = [\n options.lightningInvoice,\n options.lightningAddress,\n options.lnurl,\n ].filter((d) => d !== undefined);\n if (destinations.length !== 1) {\n throw new Error(\n \"Provide exactly one of lightningInvoice, lightningAddress or lnurl\",\n );\n }\n if (\n options.lightningInvoice === undefined &&\n (options.sourceAmountSats === undefined) ===\n (options.targetAmountSats === undefined)\n ) {\n throw new Error(\n \"Provide exactly one of sourceAmountSats or targetAmountSats\",\n );\n }\n // A malformed invoice is refused before a key is derived or the server asked.\n if (options.lightningInvoice !== undefined) {\n invoicePaymentHash(options.lightningInvoice);\n }\n\n const swapParams = await ctx.deriveSwapParams();\n const refundPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const body = {\n lightning_invoice: options.lightningInvoice,\n lightning_address: options.lightningAddress,\n lnurl: options.lnurl,\n source_amount_sats: options.sourceAmountSats,\n target_amount_sats: options.targetAmountSats,\n refund_pk: refundPk,\n user_id: userId,\n btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n };\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/bitcoin/lightning\", {\n body,\n });\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n const { hash } = checkedLightningPaymentHash(options, data);\n assertBitcoinToLightningHtlc(data, normalizeHash(hash), swapParams.publicKey);\n\n // The derived key is what signs a refund of the HTLC after its locktime.\n await ctx.storeSwap(data.id, swapParams, {\n ...data,\n direction: \"bitcoin_to_lightning\",\n });\n\n return { response: data, swapParams };\n}\n","import type { EvmFundingTerms } from \"../evm/funding-pins.js\";\n\n/**\n * The funding terms of an EVM-sourced swap, read from its creation\n * response: the coordinator the server named then is the only Permit2\n * spender this client will sign for, and the HTLC, claimer, timelock,\n * tokens and input are what every later funding payload must match.\n */\nexport function fundingTermsOf(data: {\n evm_chain_id?: number | null;\n evm_coordinator_address?: string | null;\n evm_htlc_address?: string | null;\n evm_htlc_kind?: string | null;\n evm_htlc_version?: number | null;\n server_evm_address?: string | null;\n evm_refund_locktime?: number | null;\n source_amount?: string | number | null;\n source_token?: { token_id?: string | null } | null;\n evm_htlc_token?: string | null;\n}): EvmFundingTerms | undefined {\n // A response without them records nothing: funding then fails closed.\n if (\n !data.evm_chain_id ||\n !data.evm_coordinator_address ||\n !data.evm_htlc_address ||\n !data.server_evm_address ||\n !data.evm_refund_locktime ||\n data.source_amount === undefined ||\n data.source_amount === null ||\n !data.source_token?.token_id\n ) {\n return undefined;\n }\n return {\n chainId: data.evm_chain_id,\n coordinator: data.evm_coordinator_address.toLowerCase(),\n htlcAddress: data.evm_htlc_address.toLowerCase(),\n htlcKind: data.evm_htlc_kind ?? undefined,\n htlcVersion: data.evm_htlc_version ?? undefined,\n claimAddress: data.server_evm_address.toLowerCase(),\n timelock: data.evm_refund_locktime,\n sourceToken: data.source_token.token_id.toLowerCase(),\n sourceAmount: String(data.source_amount),\n lockToken: data.evm_htlc_token?.toLowerCase(),\n };\n}\n","/**\n * EVM to Arkade swap creation.\n *\n * Supports swapping tokens from Polygon, Arbitrum, or Ethereum to BTC on Arkade.\n */\n\nimport { parseArkadeAddress } from \"../arkade-address.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { ARKADE_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport { assertAddressEchoed } from \"../swap-verification.js\";\nimport { fundingTermsOf } from \"./funding-terms.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n CreateSwapContext,\n EvmToArkadeSwapGenericOptions,\n EvmToArkadeSwapGenericResult,\n} from \"./types.js\";\n\n/**\n * Creates a new EVM-to-Arkade swap via the generic endpoint.\n *\n * Uses the chain-agnostic `/swap/evm/arkade` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation.\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createEvmToArkadeSwapGeneric(\n * {\n * targetAddress: \"ark1q...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * userAddress: \"0x1234...\",\n * sourceAmount: 100000000, // 100 USDC (6 decimals)\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"HTLC:\", result.response.evm_htlc_address);\n * ```\n */\nexport async function createEvmToArkadeSwapGeneric(\n options: EvmToArkadeSwapGenericOptions,\n ctx: CreateSwapContext,\n): Promise<EvmToArkadeSwapGenericResult> {\n parseArkadeAddress(options.targetAddress);\n\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const receiverPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/evm/arkade\", {\n body: {\n hash_lock: hashLock,\n receiver_pk: receiverPk,\n user_id: userId,\n target_address: options.targetAddress,\n token_address: options.tokenAddress,\n evm_chain_id: options.evmChainId,\n user_address: userAddress,\n amount_in: options.sourceAmount\n ? options.sourceAmount.toString()\n : undefined,\n amount_out: options.targetAmount\n ? Number(options.targetAmount)\n : undefined,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? false,\n arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n bridge_source_chain: options.inboundBridgeParams?.sourceChain,\n bridge_source_token_address:\n options.inboundBridgeParams?.sourceTokenAddress,\n },\n });\n\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n // The claim pays this address, so it must be the one this client sent.\n assertAddressEchoed(data, \"target_arkade_address\", options.targetAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"evm_to_arkade\",\n },\n options.targetAddress,\n undefined,\n { evmFundingTerms: fundingTermsOf(data) },\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * EVM to Bitcoin (on-chain) swap creation.\n *\n * Supports swapping tokens from Polygon, Arbitrum, or Ethereum to BTC on-chain\n * via Taproot HTLC.\n */\n\nimport { bytesToHex } from \"../signer/index.js\";\nimport { BTC_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport { assertAddressEchoed } from \"../swap-verification.js\";\nimport { fundingTermsOf } from \"./funding-terms.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n CreateSwapContext,\n EvmToBitcoinSwapOptions,\n EvmToBitcoinSwapResult,\n} from \"./types.js\";\n\n/**\n * Creates a new EVM-to-Bitcoin swap via the generic endpoint.\n *\n * Uses the chain-agnostic `/swap/evm/bitcoin` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation.\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createEvmToBitcoinSwap(\n * {\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * userAddress: \"0x1234...\",\n * sourceAmount: 100000000n, // 100 USDC (6 decimals)\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"EVM HTLC:\", result.response.evm_htlc_address);\n * console.log(\"BTC HTLC:\", result.response.btc_htlc_address);\n * ```\n */\nexport async function createEvmToBitcoinSwap(\n options: EvmToBitcoinSwapOptions,\n ctx: CreateSwapContext,\n): Promise<EvmToBitcoinSwapResult> {\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n // For BTC on-chain claim, the user needs their public key (compressed, 33 bytes)\n const claimPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/evm/bitcoin\", {\n body: {\n hash_lock: hashLock,\n btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,\n claim_pk: claimPk,\n user_id: userId,\n token_address: options.tokenAddress,\n evm_chain_id: options.evmChainId,\n user_address: userAddress,\n target_address: options.targetAddress,\n amount_in: options.sourceAmount\n ? options.sourceAmount.toString()\n : undefined,\n amount_out: options.targetAmount\n ? Number(options.targetAmount)\n : undefined,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? false,\n bridge_source_chain: options.inboundBridgeParams?.sourceChain,\n bridge_source_token_address:\n options.inboundBridgeParams?.sourceTokenAddress,\n },\n });\n\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n // The claim pays this address, so it must be the one this client sent.\n assertAddressEchoed(data, \"target_btc_address\", options.targetAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"evm_to_bitcoin\",\n },\n options.targetAddress,\n undefined,\n { evmFundingTerms: fundingTermsOf(data) },\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * EVM to Lightning swap creation.\n *\n * The user locks an ERC-20 token on an EVM chain in an HTLCErc20 (via the\n * coordinator) whose hash lock is the payment hash of the Lightning\n * invoice they want paid; the server pays the invoice and claims the HTLC\n * with the revealed preimage.\n */\n\nimport { bytesToHex } from \"../signer/index.js\";\nimport { checkedLightningPaymentHash } from \"../swap-verification.js\";\nimport { fundingTermsOf } from \"./funding-terms.js\";\nimport type {\n CreateSwapContext,\n EvmToLightningSwapOptions,\n EvmToLightningSwapResult,\n} from \"./types.js\";\n\n/**\n * Creates a new EVM to Lightning swap.\n *\n * Flow:\n * 1. User funds the HTLCErc20 (`fundSwap` / `fundSwapGasless`) with `source_amount` token units\n * 2. Once the funding is final the server pays the Lightning invoice; the settled payment reveals\n * the preimage\n * 3. Server claims the HTLC with the preimage\n *\n * The destination is **one of** `lightningInvoice` (its amount pins the\n * payout), or `lightningAddress`/`lnurl` with one of `sourceAmount`\n * (send-max: fees deducted from the payout) or `targetAmountSats` (exact\n * payout: fees added on top).\n *\n * Like Arkade → Lightning, the swap's hash lock is the invoice's payment\n * hash — the derived swap key is the EVM depositor for gasless funding and\n * the refund signer, so a duplicate-hash 409 is not retried with a new\n * key: it means this exact invoice already has a swap.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n */\nexport async function createEvmToLightningSwap(\n options: EvmToLightningSwapOptions,\n ctx: CreateSwapContext,\n): Promise<EvmToLightningSwapResult> {\n const destinations = [\n options.lightningInvoice,\n options.lightningAddress,\n options.lnurl,\n ].filter((d) => d !== undefined);\n if (destinations.length !== 1) {\n throw new Error(\n \"Provide exactly one of lightningInvoice, lightningAddress or lnurl\",\n );\n }\n if (\n options.lightningInvoice === undefined &&\n (options.sourceAmount === undefined) ===\n (options.targetAmountSats === undefined)\n ) {\n throw new Error(\"Provide exactly one of sourceAmount or targetAmountSats\");\n }\n if (!options.gasless && !options.userAddress) {\n throw new Error(\"userAddress is required unless the swap is gasless\");\n }\n\n const swapParams = await ctx.deriveSwapParams();\n const userId = bytesToHex(swapParams.userId);\n const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/evm/lightning\", {\n body: {\n lightning_invoice: options.lightningInvoice,\n lightning_address: options.lightningAddress,\n lnurl: options.lnurl,\n evm_chain_id: options.evmChainId,\n token_address: options.tokenAddress,\n amount_in:\n options.sourceAmount === undefined\n ? undefined\n : options.sourceAmount.toString(),\n target_amount_sats: options.targetAmountSats,\n user_address: userAddress ?? \"\",\n user_id: userId,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? false,\n bridge_source_chain: options.inboundBridgeParams?.sourceChain,\n bridge_source_token_address:\n options.inboundBridgeParams?.sourceTokenAddress,\n },\n });\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n // The lock's hash decides who can claim it: one the server knows the\n // preimage of lets it claim without paying. It must be the invoice's.\n const lightningPaymentHash = checkedLightningPaymentHash(options, data);\n\n // Store the swap if storage is configured — the derived key is the\n // gasless depositor and what signs a collaborative refund of the HTLC.\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"evm_to_lightning\",\n },\n undefined,\n undefined,\n { lightningPaymentHash, evmFundingTerms: fundingTermsOf(data) },\n );\n\n return { response: data, swapParams };\n}\n","/**\n * Lightning to Arkade swap creation.\n *\n * The user pays a Lightning hold invoice and receives Arkade VTXOs after\n * the server funds the Arkade VHTLC.\n */\n\nimport { parseArkadeAddress } from \"../arkade-address.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport { ARKADE_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertAddressEchoed,\n assertInvoicePays,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n CreateSwapContext,\n LightningToArkadeSwapOptions,\n LightningToArkadeSwapResult,\n} from \"./types.js\";\n\n/**\n * Creates a new Lightning to Arkade swap.\n *\n * Flow:\n * 1. User pays the Lightning hold invoice returned\n * 2. The payment is held; the server funds the Arkade VHTLC\n * 3. User claims the Arkade VHTLC with the secret, revealing it\n * 4. Server settles the hold invoice with the revealed secret\n *\n * The returned invoice is decoded and its payment hash checked against the\n * hash of this swap's own secret before the swap is stored or returned. An\n * invoice on any other hash would let the server settle the payment without\n * ever funding the VHTLC.\n *\n * Provide **one of** `sourceAmountSats` (invoice amount, fees come out of\n * it) or `targetAmountSats` (exact sats to receive on Arkade).\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's invoice does not pay this\n * swap's hash lock. Nothing is stored; do not pay that invoice.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createLightningToArkadeSwap(\n * {\n * targetAmountSats: 100000, // 100k sats to receive on Arkade\n * targetAddress: \"ark1q...\", // Arkade address\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\nexport async function createLightningToArkadeSwap(\n options: LightningToArkadeSwapOptions,\n ctx: CreateSwapContext,\n): Promise<LightningToArkadeSwapResult> {\n parseArkadeAddress(options.targetAddress);\n\n if (\n (options.sourceAmountSats === undefined) ===\n (options.targetAmountSats === undefined)\n ) {\n throw new Error(\n \"Provide exactly one of sourceAmountSats or targetAmountSats\",\n );\n }\n\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const publicKey = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const body = {\n hash_lock: hashLock,\n claim_pk: publicKey,\n user_id: userId,\n source_amount_sats: options.sourceAmountSats,\n target_amount_sats: options.targetAmountSats,\n target_arkade_address: options.targetAddress,\n arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n // `undefined` is omitted from the JSON body so the server applies its\n // default; an explicit \"\" is sent to blank the invoice description.\n invoice_description: options.invoiceDescription,\n };\n\n const { data, error } = await ctx.apiClient.POST(\"/swap/lightning/arkade\", {\n body,\n });\n if (error)\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n if (!data) throw new Error(\"No swap data returned\");\n\n assertInvoicePays(data.bolt11_invoice, hashLock);\n // The claim pays this address, so it must be the one this client sent.\n assertAddressEchoed(data, \"target_arkade_address\", options.targetAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n data.id,\n swapParams,\n { ...data, direction: \"lightning_to_arkade\" },\n options.targetAddress,\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * Lightning to Bitcoin (on-chain) swap creation.\n *\n * The user pays a hold invoice locked to the SDK's hash; the server funds an\n * on-chain Taproot HTLC the user claims with the preimage, and the revealed\n * preimage settles the hold invoice.\n */\nimport { bytesToHex } from \"../signer/index.js\";\nimport { BTC_HTLC_SCRIPT_VERSION_STRICT } from \"../strict-vhtlc.js\";\nimport {\n assertAddressEchoed,\n assertInvoicePays,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n CreateSwapContext,\n LightningToBitcoinSwapOptions,\n LightningToBitcoinSwapResult,\n} from \"./types.js\";\n\n/**\n * Creates a new Lightning to Bitcoin (on-chain) swap.\n *\n * Flow:\n * 1. User pays the returned hold invoice (`bolt11_invoice`)\n * 2. Server funds the on-chain HTLC (`btc_htlc_address`)\n * 3. User claims the HTLC with the preimage (`claim()`), which settles the\n * hold invoice\n *\n * Provide exactly one of `sourceAmountSats` (invoice amount, fees deducted\n * from the payout) or `targetAmountSats` (exact on-chain payout, fees added\n * on top). `targetAddress` is the Bitcoin address the claim pays out to.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await createLightningToBitcoinSwap(\n * { targetAmountSats: 100000, targetAddress: \"bc1q...\" },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\nexport async function createLightningToBitcoinSwap(\n options: LightningToBitcoinSwapOptions,\n ctx: CreateSwapContext,\n): Promise<LightningToBitcoinSwapResult> {\n if (\n (options.sourceAmountSats === undefined) ===\n (options.targetAmountSats === undefined)\n ) {\n throw new Error(\n \"Provide exactly one of sourceAmountSats or targetAmountSats\",\n );\n }\n\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const claimPk = bytesToHex(swapParams.publicKey);\n const userId = bytesToHex(swapParams.userId);\n\n const body = {\n hash_lock: hashLock,\n claim_pk: claimPk,\n user_id: userId,\n source_amount_sats: options.sourceAmountSats,\n target_amount_sats: options.targetAmountSats,\n target_address: options.targetAddress,\n btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n invoice_description: options.invoiceDescription,\n };\n\n const { data, error } = await ctx.apiClient.POST(\n \"/swap/lightning/bitcoin\",\n { body },\n );\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n assertInvoicePays(data.bolt11_invoice, hashLock);\n // The claim pays this address, so it must be the one this client sent.\n assertAddressEchoed(data, \"target_btc_address\", options.targetAddress);\n\n // The derived key claims the HTLC; the preimage settles the invoice.\n await ctx.storeSwap(\n data.id,\n swapParams,\n { ...data, direction: \"lightning_to_bitcoin\" },\n options.targetAddress,\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * Lightning to EVM swap creation via the generic endpoint.\n *\n * The user pays a hold invoice locked to the SDK-derived preimage hash;\n * the server funds an HTLCErc20 with the same lock, and the user's claim\n * (gasless via the coordinator) reveals the preimage that settles the\n * held payment. If anything fails before the claim, the held payment is\n * automatically returned to the payer when the hold expires — there is\n * no client-side refund action on this route.\n */\n\nimport { deriveEvmAddress } from \"../evm/signing.js\";\nimport { bytesToHex } from \"../signer/index.js\";\nimport {\n assertAddressEchoed,\n assertInvoicePays,\n} from \"../swap-verification.js\";\nimport { retryOnHashCollision } from \"./retry.js\";\nimport type {\n CreateSwapContext,\n LightningToEvmSwapOptions,\n LightningToEvmSwapResult,\n} from \"./types.js\";\n\n/**\n * Creates a new Lightning to EVM swap.\n *\n * Uses the chain-agnostic `/swap/lightning/evm` endpoint which supports\n * any ERC-20 token reachable through 1inch aggregation, plus CCTP/USDT0\n * bridge destinations.\n *\n * If the server rejects the hash lock (duplicate or collision), the\n * function automatically retries with a new key index.\n *\n * The returned invoice is decoded and its payment hash checked against the\n * hash of this swap's own secret before the swap is stored or returned. An\n * invoice on any other hash would let the server settle the payment without\n * ever funding the HTLC.\n *\n * @param options - The swap options.\n * @param ctx - The context containing API client and helper functions.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's invoice does not pay this\n * swap's hash lock. Nothing is stored; do not pay that invoice.\n * @throws Error if the swap creation fails after all retries.\n *\n * @example\n * ```ts\n * const result = await createLightningToEvmSwap(\n * {\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats over Lightning\n * },\n * { apiClient, deriveSwapParams, storeSwap }\n * );\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\nexport async function createLightningToEvmSwap(\n options: LightningToEvmSwapOptions,\n ctx: CreateSwapContext,\n /**\n * The lock's claim address when it is not this swap's own key: the\n * recipient's RIF Relay smart wallet on a chain that claims through RIF.\n */\n claimingAddressOverride?: string,\n): Promise<LightningToEvmSwapResult> {\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\"Provide exactly one of sourceAmount or targetAmount\");\n }\n\n return retryOnHashCollision(ctx, async () => {\n const swapParams = await ctx.deriveSwapParams();\n const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;\n const userId = bytesToHex(swapParams.userId);\n\n // The claiming address is this swap's own key, not the wallet-level\n // EVM address used for gasless deposits. A sponsored claim installs an\n // EIP-7702 delegation (Kernel) on the claiming address; keeping that\n // off the deposit address means Permit2 / EIP-2612 keep seeing a plain\n // EOA there. Recovery re-derives this key from the swap's index.\n const claimingAddress =\n claimingAddressOverride ?? deriveEvmAddress(swapParams.secretKey);\n\n const body = {\n hash_lock: hashLock,\n user_id: userId,\n claiming_address: claimingAddress,\n target_address: options.targetAddress,\n token_address: options.tokenAddress,\n evm_chain_id: options.evmChainId,\n amount_in: options.sourceAmount,\n amount_out: options.targetAmount?.toString(),\n invoice_description: options.invoiceDescription,\n referral_code: options.referralCode,\n extra_fees: options.extraFees,\n gasless: options.gasless ?? true,\n bridge_target_chain: options.bridgeParams?.targetChain,\n bridge_target_token_address: options.bridgeParams?.targetTokenAddress,\n bridge_recipient_setup: options.bridgeParams?.recipientSetup,\n };\n const { data, error } = await ctx.apiClient.POST(\"/swap/lightning/evm\", {\n body,\n });\n\n if (error) {\n throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n assertInvoicePays(data.bolt11_invoice, hashLock);\n // The claim pays the target and signs with the claiming key: both must\n // be the ones this client sent.\n assertAddressEchoed(data, \"target_evm_address\", options.targetAddress);\n assertAddressEchoed(data, \"client_evm_address\", claimingAddress);\n\n // Store the swap if storage is configured\n await ctx.storeSwap(\n data.id,\n swapParams,\n {\n ...data,\n direction: \"lightning_to_evm\",\n },\n options.targetAddress,\n {\n recipient: options.bridgeParams?.recipient,\n recipientWallet: options.bridgeParams?.recipientWallet,\n },\n );\n\n return { response: data, swapParams };\n });\n}\n","/**\n * Electrum protocol client over WebSocket (Fulcrum-compatible).\n *\n * Fulcrum serves the same JSON-RPC protocol on its `ws`/`wss` ports as on\n * TCP/SSL, so a browser (which cannot open raw TCP sockets) can talk to it\n * directly. This gives the SDK two things Esplora polling cannot:\n *\n * - Lookups against our own infrastructure instead of rate-limited public\n * explorers.\n * - `blockchain.scripthash.subscribe` push notifications, so waiting for an\n * HTLC funding output resolves the moment the server sees the tx instead\n * of on the next poll tick.\n *\n * The client is lazy: no socket is opened until the first request. While\n * subscriptions are active it reconnects with capped backoff and re-issues\n * the subscriptions; with no subscriptions a dropped socket simply\n * reconnects on the next request.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport * as btc from \"@scure/btc-signer\";\n\n/** Networks the SDK deals in (mirrors `refund/onchain.ts`). */\nexport type ElectrumNetwork = \"mainnet\" | \"testnet\" | \"signet\" | \"regtest\";\n\n/** One entry of `blockchain.scripthash.listunspent`. */\nexport interface ElectrumUnspent {\n tx_hash: string;\n tx_pos: number;\n /** Block height; 0 for mempool, -1 for mempool with unconfirmed parents. */\n height: number;\n /** Value in satoshis. */\n value: number;\n}\n\n/** Minimal logging hook so the SDK's logger can observe this module. */\nexport type ElectrumLogHook = (\n level: \"debug\" | \"warn\",\n event: string,\n message: string,\n data?: Record<string, unknown>,\n) => void;\n\nconst REQUEST_TIMEOUT_MS = 5_000;\nconst BROADCAST_TIMEOUT_MS = 10_000;\nconst CONNECT_TIMEOUT_MS = 8_000;\nconst PING_INTERVAL_MS = 60_000;\nconst MIN_RECONNECT_MS = 1_000;\nconst MAX_RECONNECT_MS = 30_000;\n/**\n * With no in-flight requests and no subscriptions the socket is closed after\n * this long, so a Node process (e2e script, CLI) isn't kept alive by an idle\n * connection. The next request reconnects transparently.\n */\nconst IDLE_CLOSE_MS = 30_000;\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: ElectrumNetwork) {\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 default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Electrum scripthash for an address: sha256 of the output script,\n * hex-encoded in reversed byte order.\n */\nexport function addressToScriptHash(\n address: string,\n network: ElectrumNetwork,\n): string {\n const net = toBtcSignerNetwork(network);\n const decoded = btc.Address(net).decode(address);\n if (!decoded) throw new Error(`Unrecognised Bitcoin address: ${address}`);\n const script = btc.OutScript.encode(decoded);\n return bytesToHex(sha256(script).reverse());\n}\n\ninterface PendingRequest {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\ntype ScriptHashHandler = (status: string | null) => void;\n\n/**\n * A single-socket Electrum JSON-RPC client over WebSocket.\n *\n * All calls are `id`-correlated; `blockchain.scripthash.subscribe`\n * notifications are dispatched to registered handlers.\n */\nexport class ElectrumWsClient {\n readonly #url: string;\n readonly #log: ElectrumLogHook;\n\n #socket: WebSocket | null = null;\n /** Resolves once the current socket is open and handshaken. */\n #connecting: Promise<void> | null = null;\n #nextId = 1;\n readonly #pending = new Map<number, PendingRequest>();\n readonly #scriptHashHandlers = new Map<string, Set<ScriptHashHandler>>();\n #pingTimer: ReturnType<typeof setInterval> | null = null;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n #idleTimer: ReturnType<typeof setTimeout> | null = null;\n #reconnectAttempt = 0;\n #closed = false;\n\n constructor(url: string, opts?: { onLog?: ElectrumLogHook }) {\n this.#url = url;\n this.#log = opts?.onLog ?? (() => {});\n }\n\n /**\n * Send a JSON-RPC request and await its response. Connects lazily.\n * Rejects on server error, timeout, or socket close.\n */\n async request<T>(\n method: string,\n params: unknown[],\n timeoutMs = REQUEST_TIMEOUT_MS,\n ): Promise<T> {\n await this.#ensureConnected();\n const socket = this.#socket;\n if (!socket || socket.readyState !== WebSocket.OPEN) {\n throw new Error(\"Electrum WebSocket is not connected\");\n }\n const id = this.#nextId++;\n const payload = JSON.stringify({ jsonrpc: \"2.0\", id, method, params });\n if (this.#idleTimer) {\n clearTimeout(this.#idleTimer);\n this.#idleTimer = null;\n }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.#pending.delete(id);\n this.#maybeScheduleIdleClose();\n reject(\n new Error(\n `Electrum request ${method} timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n this.#pending.set(id, {\n resolve: (result) => resolve(result as T),\n reject,\n timer,\n });\n socket.send(payload);\n });\n }\n\n /**\n * Subscribe to script hash status changes. Returns the current status\n * (null = never used). `onChange` fires on every subsequent change and,\n * after a reconnect, once with the then-current status.\n */\n async subscribeScriptHash(\n scripthash: string,\n onChange: ScriptHashHandler,\n ): Promise<string | null> {\n let handlers = this.#scriptHashHandlers.get(scripthash);\n if (!handlers) {\n handlers = new Set();\n this.#scriptHashHandlers.set(scripthash, handlers);\n }\n handlers.add(onChange);\n try {\n return await this.request<string | null>(\n \"blockchain.scripthash.subscribe\",\n [scripthash],\n );\n } catch (error) {\n // A server-rejected subscription (or a closed client) never recovers,\n // so drop the handler. A transport failure keeps it registered: the\n // reconnect loop re-issues every registered subscription once the\n // server is reachable again, so the push self-heals.\n const permanent =\n this.#closed ||\n (error instanceof Error && error.message.startsWith(\"Electrum error:\"));\n if (permanent) {\n handlers.delete(onChange);\n if (handlers.size === 0) this.#scriptHashHandlers.delete(scripthash);\n this.#maybeScheduleIdleClose();\n } else {\n this.#scheduleReconnect();\n }\n throw error;\n }\n }\n\n /** Remove a handler; unsubscribes on the wire when none remain. */\n unsubscribeScriptHash(scripthash: string, onChange: ScriptHashHandler): void {\n const handlers = this.#scriptHashHandlers.get(scripthash);\n if (!handlers) return;\n handlers.delete(onChange);\n if (handlers.size > 0) return;\n this.#scriptHashHandlers.delete(scripthash);\n if (this.#socket?.readyState === WebSocket.OPEN) {\n this.request(\"blockchain.scripthash.unsubscribe\", [scripthash]).catch(\n () => {\n // Best-effort: the server drops the subscription on disconnect anyway.\n },\n );\n }\n this.#maybeScheduleIdleClose();\n }\n\n /** Close the socket and reject all in-flight requests. */\n close(): void {\n this.#closed = true;\n if (this.#reconnectTimer) {\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n this.#teardownSocket(new Error(\"Electrum client closed\"));\n this.#scriptHashHandlers.clear();\n }\n\n async #ensureConnected(): Promise<void> {\n if (this.#closed) throw new Error(\"Electrum client closed\");\n if (this.#socket?.readyState === WebSocket.OPEN) return;\n this.#connecting ??= this.#connect().finally(() => {\n this.#connecting = null;\n });\n return this.#connecting;\n }\n\n #connect(): Promise<void> {\n if (typeof WebSocket === \"undefined\") {\n return Promise.reject(\n new Error(\"WebSocket is not available in this runtime\"),\n );\n }\n return new Promise<void>((resolve, reject) => {\n const socket = new WebSocket(this.#url);\n this.#socket = socket;\n const connectTimer = setTimeout(() => {\n reject(\n new Error(\n `Electrum WebSocket connect to ${this.#url} timed out after ${CONNECT_TIMEOUT_MS}ms`,\n ),\n );\n try {\n socket.close();\n } catch {\n // ignore\n }\n }, CONNECT_TIMEOUT_MS);\n\n socket.addEventListener(\"open\", () => {\n clearTimeout(connectTimer);\n this.#reconnectAttempt = 0;\n this.#startPing();\n this.#log(\"debug\", \"electrum.connected\", \"Electrum WebSocket open\", {\n url: this.#url,\n });\n // Handshake (some servers require it before other calls), then\n // re-issue any active subscriptions from before a reconnect.\n this.request(\"server.version\", [\"lendaswap-sdk\", \"1.4\"]).catch(() => {\n // Non-fatal: Fulcrum answers other methods regardless.\n });\n for (const scripthash of this.#scriptHashHandlers.keys()) {\n this.request<string | null>(\"blockchain.scripthash.subscribe\", [\n scripthash,\n ])\n .then((status) => this.#dispatchScriptHash(scripthash, status))\n .catch(() => {\n // The next reconnect (or caller-level safety re-check) covers this.\n });\n }\n resolve();\n });\n\n socket.addEventListener(\"message\", (evt) => {\n this.#onMessage(evt.data);\n });\n\n socket.addEventListener(\"error\", () => {\n clearTimeout(connectTimer);\n reject(\n new Error(`Electrum WebSocket error connecting to ${this.#url}`),\n );\n });\n\n socket.addEventListener(\"close\", () => {\n clearTimeout(connectTimer);\n reject(new Error(\"Electrum WebSocket closed during connect\"));\n this.#teardownSocket(new Error(\"Electrum WebSocket closed\"));\n if (!this.#closed && this.#scriptHashHandlers.size > 0) {\n this.#scheduleReconnect();\n }\n });\n });\n }\n\n #teardownSocket(error: Error): void {\n this.#stopPing();\n if (this.#idleTimer) {\n clearTimeout(this.#idleTimer);\n this.#idleTimer = null;\n }\n const socket = this.#socket;\n this.#socket = null;\n if (socket && socket.readyState !== WebSocket.CLOSED) {\n try {\n socket.close();\n } catch {\n // ignore\n }\n }\n for (const [id, pending] of this.#pending) {\n clearTimeout(pending.timer);\n pending.reject(error);\n this.#pending.delete(id);\n }\n }\n\n #scheduleReconnect(): void {\n if (this.#reconnectTimer) return;\n const delay = Math.min(\n MAX_RECONNECT_MS,\n MIN_RECONNECT_MS * 2 ** this.#reconnectAttempt,\n );\n this.#reconnectAttempt += 1;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n if (this.#closed || this.#scriptHashHandlers.size === 0) return;\n this.#ensureConnected().catch(() => this.#scheduleReconnect());\n }, delay);\n }\n\n /**\n * Close an idle socket after {@link IDLE_CLOSE_MS}. Subscriptions and\n * in-flight requests keep it open; the keepalive ping only runs while a\n * socket exists, so a closed idle socket costs nothing.\n */\n #maybeScheduleIdleClose(): void {\n if (this.#idleTimer || this.#closed) return;\n if (this.#pending.size > 0 || this.#scriptHashHandlers.size > 0) return;\n if (!this.#socket) return;\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null;\n if (this.#pending.size > 0 || this.#scriptHashHandlers.size > 0) return;\n this.#teardownSocket(new Error(\"Electrum connection idle-closed\"));\n }, IDLE_CLOSE_MS);\n }\n\n #startPing(): void {\n this.#stopPing();\n this.#pingTimer = setInterval(() => {\n if (this.#socket?.readyState !== WebSocket.OPEN) return;\n this.request(\"server.ping\", []).catch(() => {\n // A half-open socket (NAT/proxy blackhole after a network change) can\n // stay OPEN yet never answer — no close event ever fires. Tear it\n // down ourselves so the reconnect path runs instead of every later\n // request timing out against a dead socket.\n if (this.#socket && this.#socket.readyState === WebSocket.OPEN) {\n this.#teardownSocket(new Error(\"Electrum keepalive timed out\"));\n if (!this.#closed && this.#scriptHashHandlers.size > 0) {\n this.#scheduleReconnect();\n }\n }\n });\n }, PING_INTERVAL_MS);\n }\n\n #stopPing(): void {\n if (this.#pingTimer) {\n clearInterval(this.#pingTimer);\n this.#pingTimer = null;\n }\n }\n\n #onMessage(data: unknown): void {\n if (typeof data !== \"string\") return;\n // Fulcrum newline-terminates frames; be tolerant of batched lines.\n for (const line of data.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let parsed: {\n id?: number;\n result?: unknown;\n error?: { code?: number; message?: string } | null;\n method?: string;\n params?: unknown[];\n };\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (parsed.id !== undefined && parsed.id !== null) {\n const pending = this.#pending.get(parsed.id);\n if (!pending) continue;\n this.#pending.delete(parsed.id);\n clearTimeout(pending.timer);\n this.#maybeScheduleIdleClose();\n if (parsed.error) {\n pending.reject(\n new Error(\n `Electrum error: ${parsed.error.message ?? JSON.stringify(parsed.error)}`,\n ),\n );\n } else {\n pending.resolve(parsed.result);\n }\n } else if (parsed.method === \"blockchain.scripthash.subscribe\") {\n const [scripthash, status] = (parsed.params ?? []) as [\n string,\n string | null,\n ];\n this.#dispatchScriptHash(scripthash, status ?? null);\n }\n }\n }\n\n #dispatchScriptHash(scripthash: string, status: string | null): void {\n const handlers = this.#scriptHashHandlers.get(scripthash);\n if (!handlers) return;\n for (const handler of handlers) {\n try {\n handler(status);\n } catch (error) {\n this.#log(\"warn\", \"electrum.handlerError\", \"scripthash handler threw\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n}\n\n/**\n * Finds the largest unspent output at `address` via\n * `blockchain.scripthash.listunspent` (includes mempool entries).\n * Mirrors the shape of `esplora.findOutputByAddress` — largest rather than\n * first, because the HTLC address is public and a stray dust output must\n * not shadow the real deposit (a sub-fee UTXO would make every claim or\n * refund built against it fail).\n */\nexport async function electrumFindOutputByAddress(\n client: ElectrumWsClient,\n address: string,\n network: ElectrumNetwork,\n): Promise<{ txid: string; vout: number; amount: bigint } | null> {\n const scripthash = addressToScriptHash(address, network);\n const utxos = await client.request<ElectrumUnspent[]>(\n \"blockchain.scripthash.listunspent\",\n [scripthash],\n );\n if (!utxos || utxos.length === 0) return null;\n const utxo = utxos.reduce((best, candidate) =>\n candidate.value > best.value ? candidate : best,\n );\n return {\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n amount: BigInt(utxo.value),\n };\n}\n\n/**\n * Fetches a transaction's outputs via `blockchain.transaction.get` (raw hex,\n * parsed locally). Returns null when the server doesn't know the tx yet, so\n * callers can fall back or keep waiting — mirrors\n * `esplora.fetchTransactionOutputs`.\n */\nexport async function electrumFetchTransactionOutputs(\n client: ElectrumWsClient,\n txid: string,\n): Promise<{ vout: Array<{ value: number }> } | null> {\n let rawHex: string;\n try {\n rawHex = await client.request<string>(\"blockchain.transaction.get\", [txid]);\n } catch {\n return null;\n }\n try {\n const tx = btc.Transaction.fromRaw(hexToBytes(rawHex), {\n allowUnknownOutputs: true,\n allowUnknownInputs: true,\n disableScriptCheck: true,\n });\n const vout: Array<{ value: number }> = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n vout.push({ value: Number(tx.getOutput(i).amount ?? 0n) });\n }\n return { vout };\n } catch {\n return null;\n }\n}\n\n/**\n * Broadcasts a raw transaction via `blockchain.transaction.broadcast`.\n * Returns the txid; throws with the server's rejection message (kept\n * verbatim so `bad-txns-*` style errors remain classifiable as permanent).\n */\nexport async function electrumBroadcastTransaction(\n client: ElectrumWsClient,\n txHex: string,\n): Promise<string> {\n return client.request<string>(\n \"blockchain.transaction.broadcast\",\n [txHex],\n BROADCAST_TIMEOUT_MS,\n );\n}\n\n/**\n * Waits for an unspent output at `address`, driven by scripthash push\n * notifications instead of polling. Resolves null on timeout. A slow\n * safety re-check covers a missed notification; the initial check covers\n * an already-funded address.\n */\nexport async function electrumWaitForOutputByAddress(\n client: ElectrumWsClient,\n address: string,\n network: ElectrumNetwork,\n timeoutMs: number,\n opts?: { safetyRecheckMs?: number },\n): Promise<{ txid: string; vout: number; amount: bigint } | null> {\n const scripthash = addressToScriptHash(address, network);\n const safetyRecheckMs = opts?.safetyRecheckMs ?? 5_000;\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let deadlineTimer: ReturnType<typeof setTimeout> | null = null;\n let safetyTimer: ReturnType<typeof setInterval> | null = null;\n /** Serializes checks so a notification burst doesn't stack lookups. */\n let checking = false;\n\n const finish = (\n outcome:\n | { ok: { txid: string; vout: number; amount: bigint } | null }\n | { err: Error },\n ) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer) clearTimeout(deadlineTimer);\n if (safetyTimer) clearInterval(safetyTimer);\n client.unsubscribeScriptHash(scripthash, onChange);\n if (\"err\" in outcome) reject(outcome.err);\n else resolve(outcome.ok);\n };\n\n const check = async () => {\n if (settled || checking) return;\n checking = true;\n try {\n const output = await electrumFindOutputByAddress(\n client,\n address,\n network,\n );\n if (output) finish({ ok: output });\n } catch {\n // Transient lookup failure; the safety timer retries.\n } finally {\n checking = false;\n }\n };\n\n const onChange = () => {\n void check();\n };\n\n deadlineTimer = setTimeout(\n () => finish({ ok: null }),\n Math.max(0, timeoutMs),\n );\n safetyTimer = setInterval(() => void check(), safetyRecheckMs);\n\n client.subscribeScriptHash(scripthash, onChange).then(\n (status) => {\n // Non-null status means the script has history — check immediately.\n // Check on null too: cheap, and guards against a stale status.\n void status;\n void check();\n },\n (error) =>\n finish({\n err: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n });\n}\n","/**\n * Esplora API utilities for Bitcoin transaction lookups.\n *\n * All functions accept either a single Esplora base URL or a list of URLs.\n * With a list, each URL is tried in order and the first successful response\n * wins, so an outage of one explorer doesn't break\n * claims/refunds as long as a fallback instance is reachable.\n */\n\n/** One or more Esplora API base URLs, tried in order. */\nexport type EsploraUrls = string | string[];\n\n/**\n * Per-request timeouts. Without these a hanging explorer would sit on the\n * platform default (~300s in Node, browser-dependent otherwise), so the\n * fallback URL would never get a chance within the caller's polling\n * budget (e.g. the 30s funding wait in the claim path).\n *\n * Lookups normally return in well under a second, so they fail over\n * quickly; broadcasts get more headroom since the node has to validate\n * and accept the transaction.\n */\nconst LOOKUP_TIMEOUT_MS = 2_000;\nconst BROADCAST_TIMEOUT_MS = 10_000;\n\n/** Esplora UTXO response */\nexport interface EsploraUtxo {\n txid: string;\n vout: number;\n status: {\n confirmed: boolean;\n block_height?: number;\n block_hash?: string;\n block_time?: number;\n };\n value: number;\n}\n\n/** Result of finding an HTLC output */\nexport interface HtlcOutputResult {\n txid: string;\n vout: number;\n amount: bigint;\n}\n\n/**\n * `fetch` with a timeout built from `AbortController` + `setTimeout` instead\n * of `AbortSignal.timeout`, which is missing in some supported runtimes\n * (React Native/Hermes). If `AbortController` itself is absent, the request\n * is issued without a timeout rather than throwing before it starts.\n */\nexport async function fetchWithTimeout(\n url: string,\n timeoutMs: number,\n init?: RequestInit,\n): Promise<Response> {\n if (typeof AbortController === \"undefined\") {\n return fetch(url, init);\n }\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Normalizes to a trailing-slash-free URL list. */\nfunction toUrlList(esploraUrls: EsploraUrls): string[] {\n const urls = Array.isArray(esploraUrls) ? esploraUrls : [esploraUrls];\n return urls.map((url) => url.replace(/\\/+$/, \"\"));\n}\n\n/**\n * Runs `fn` against each URL in order, returning the first successful\n * result. Throws the last error if every URL fails.\n */\nasync function withFallback<T>(\n esploraUrls: EsploraUrls,\n fn: (url: string) => Promise<T>,\n): Promise<T> {\n const urls = toUrlList(esploraUrls);\n if (urls.length === 0) {\n throw new Error(\"No Esplora URL provided\");\n }\n let lastError: unknown;\n for (const url of urls) {\n try {\n return await fn(url);\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError instanceof Error ? lastError : new Error(String(lastError));\n}\n\n/**\n * Finds a UTXO at the given address.\n *\n * Queries the Esplora `/address/:address/utxo` endpoint to find\n * unspent outputs. Returns the largest UTXO: the HTLC address is public, so\n * anyone can send extra (dust) outputs to it, and picking by explorer order\n * would let such an output shadow the real deposit — a sub-fee UTXO makes\n * every claim/refund built against it fail. With several genuine deposits,\n * callers recover them largest-first across repeated runs.\n *\n * @param esploraUrls - Esplora API base URL(s), tried in order\n * @param address - The address to look up UTXOs for\n * @returns The txid, vout, and amount of the largest UTXO, or null if none found\n */\nexport async function findOutputByAddress(\n esploraUrls: EsploraUrls,\n address: string,\n): Promise<HtlcOutputResult | null> {\n return withFallback(esploraUrls, async (esploraUrl) => {\n const response = await fetchWithTimeout(\n `${esploraUrl}/address/${address}/utxo`,\n LOOKUP_TIMEOUT_MS,\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch UTXOs for address ${address}: ${response.status}`,\n );\n }\n\n const utxos = (await response.json()) as EsploraUtxo[];\n\n if (utxos.length === 0) {\n return null;\n }\n\n const utxo = utxos.reduce((best, candidate) =>\n candidate.value > best.value ? candidate : best,\n );\n return { txid: utxo.txid, vout: utxo.vout, amount: BigInt(utxo.value) };\n });\n}\n\n/**\n * Fetches a transaction's outputs via the Esplora `/tx/:txid` endpoint.\n *\n * Returns null when no explorer knows the transaction yet (or all\n * explorers are unreachable) so callers can fall back to an address\n * lookup or keep polling.\n *\n * @param esploraUrls - Esplora API base URL(s), tried in order\n * @param txid - The transaction ID to look up\n */\nexport async function fetchTransactionOutputs(\n esploraUrls: EsploraUrls,\n txid: string,\n): Promise<{ vout: Array<{ value: number }> } | null> {\n try {\n return await withFallback(esploraUrls, async (esploraUrl) => {\n const response = await fetchWithTimeout(\n `${esploraUrl}/tx/${txid}`,\n LOOKUP_TIMEOUT_MS,\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch tx ${txid}: ${response.status}`);\n }\n return (await response.json()) as { vout: Array<{ value: number }> };\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Fee rate (sat/vB) the explorer expects to confirm within `targetBlocks`,\n * from the Esplora `/fee-estimates` endpoint. Returns undefined when no\n * explorer answers or none has an estimate for that target (regtest\n * explorers have none).\n *\n * @param esploraUrls - Esplora API base URL(s), tried in order\n * @param targetBlocks - Confirmation target in blocks\n */\nexport async function fetchFeeRateEstimate(\n esploraUrls: EsploraUrls,\n targetBlocks: number,\n): Promise<number | undefined> {\n try {\n return await withFallback(esploraUrls, async (esploraUrl) => {\n const response = await fetchWithTimeout(\n `${esploraUrl}/fee-estimates`,\n LOOKUP_TIMEOUT_MS,\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch fee estimates: ${response.status}`);\n }\n const estimates = (await response.json()) as Record<string, unknown>;\n const rate = estimates[String(targetBlocks)];\n if (typeof rate !== \"number\" || !Number.isFinite(rate)) {\n throw new Error(`No ${targetBlocks}-block fee estimate`);\n }\n return rate;\n });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Broadcasts a raw transaction to the Bitcoin network via Esplora API.\n *\n * With multiple URLs, each is tried in order until one accepts the\n * transaction. If one explorer rejects it with a permanent validation\n * error (e.g. `bad-txns-*`), that error is preferred over transient\n * network errors from other explorers so retry logic doesn't spin on a\n * transaction that can never confirm.\n *\n * @param esploraUrls - Esplora API base URL(s), tried in order\n * @param txHex - The raw transaction hex to broadcast\n * @returns The transaction ID on success\n */\nexport async function broadcastTransaction(\n esploraUrls: EsploraUrls,\n txHex: string,\n): Promise<string> {\n const urls = toUrlList(esploraUrls);\n if (urls.length === 0) {\n throw new Error(\"No Esplora URL provided\");\n }\n const errors: unknown[] = [];\n for (const esploraUrl of urls) {\n try {\n const response = await fetchWithTimeout(\n `${esploraUrl}/tx`,\n BROADCAST_TIMEOUT_MS,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n body: txHex,\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Broadcast failed: ${response.status} - ${errorText}`);\n }\n\n return response.text();\n } catch (error) {\n errors.push(error);\n }\n }\n // Prefer a permanent (non-transient) rejection: it tells the caller the\n // tx itself is invalid, which no amount of retrying or failing over fixes.\n const permanent = errors.find((e) => !isTransientBroadcastError(e));\n const chosen = permanent ?? errors[errors.length - 1];\n throw chosen instanceof Error ? chosen : new Error(String(chosen));\n}\n\n/**\n * Heuristic: does this broadcast error look transient (worth retrying)?\n *\n * The common race is that the node we broadcast the claim to has not yet\n * seen the HTLC funding tx, so it rejects the claim's inputs as\n * missing/unknown. Those resolve once the funding tx propagates. Network\n * errors are also treated as transient.\n *\n * Inspects the whole error, not just `.message`: in Node/undici a rejected\n * `fetch` surfaces as `Error(\"fetch failed\")` with the real reason\n * (`ECONNREFUSED`, `ETIMEDOUT`, …) on `error.cause`, so a message-only check\n * would miss connection hiccups and fail fast.\n */\nfunction isTransientBroadcastError(error: unknown): boolean {\n const parts: string[] = [];\n if (error instanceof Error) {\n parts.push(error.message);\n if (error.cause != null) {\n const cause = error.cause;\n parts.push(\n cause instanceof Error\n ? `${cause.message} ${String(cause)}`\n : String(cause),\n );\n }\n } else {\n parts.push(String(error));\n }\n const m = parts.join(\" \").toLowerCase();\n return (\n m.includes(\"missingorspent\") ||\n m.includes(\"missing-inputs\") ||\n m.includes(\"bad-txns-inputs\") ||\n m.includes(\"txn-mempool-conflict\") ||\n m.includes(\"non-bip68-final\") ||\n m.includes(\"no such mempool\") ||\n m.includes(\"not found\") ||\n m.includes(\"failed to fetch\") ||\n m.includes(\"fetch failed\") ||\n m.includes(\"network\") ||\n m.includes(\"timeout\") ||\n // Timeout-abort rejections: our fetchWithTimeout reason (\"request timed\n // out after Nms\"), or a generic AbortError (\"the operation was aborted\")\n // in runtimes that ignore the abort reason.\n m.includes(\"timed out\") ||\n m.includes(\"aborted\") ||\n m.includes(\"econnrefused\") ||\n m.includes(\"econnreset\") ||\n m.includes(\"etimedout\") ||\n m.includes(\"eai_again\")\n );\n}\n\n/**\n * Broadcasts a raw transaction, retrying on transient failures.\n *\n * The funding tx may still be propagating to the broadcast node when the\n * client tries to claim, so the first attempt can fail with a\n * missing-inputs style error that clears within a few seconds. Retries use\n * a capped backoff (500ms → 2s). Each attempt fails over across all\n * configured Esplora URLs.\n *\n * @param esploraUrls - Esplora API base URL(s), tried in order\n * @param txHex - The raw transaction hex to broadcast\n * @param retries - Number of additional attempts after the first (default 5)\n * @returns The transaction ID on success\n */\nexport async function broadcastTransactionWithRetry(\n esploraUrls: EsploraUrls,\n txHex: string,\n retries = 5,\n): Promise<string> {\n let delayMs = 500;\n let lastError: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await broadcastTransaction(esploraUrls, txHex);\n } catch (error) {\n lastError = error;\n // Don't waste attempts on errors that won't clear on their own.\n if (attempt >= retries || !isTransientBroadcastError(error)) {\n throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n delayMs = Math.min(delayMs * 2, 2_000);\n }\n }\n // Unreachable, but satisfies the type checker.\n throw lastError instanceof Error ? lastError : new Error(String(lastError));\n}\n","/**\n * ZeroDev Kernel V3.3 ERC-1271 support for the SDK-controlled EVM key.\n *\n * The sponsored-UserOp claim path delegates the SDK's deterministic EVM\n * address to Kernel V3.3 via EIP-7702. From then on the address has code,\n * so Permit2 verifies signatures through `isValidSignature` on the Kernel\n * account instead of `ecrecover`. Kernel accepts only its own envelope:\n *\n * `0x00` (sudo-mode selector → 7702 root validator, i.e. the EOA's key)\n * `||` ECDSA over the EIP-712 digest of `Kernel(bytes32 hash)` with domain\n * `name=\"Kernel\"`, `version=\"0.3.3\"`, `chainId`, `verifyingContract` = the\n * account itself.\n *\n * Mirrors `rust-sdk/src/aa/kernel.rs` (`erc1271_wrapped_digest`,\n * `wrap_erc1271_signature`). Sources: Kernel v3.3\n * `src/core/ValidationManager.sol::_toWrappedHash`,\n * `src/utils/ValidationTypeLib.sol::decodeSignature`.\n */\n\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport {\n hexToBytes as nobleFromHex,\n bytesToHex as nobleToHex,\n} from \"@noble/hashes/utils.js\";\n\n/**\n * Kernel V3.3 implementation — the EIP-7702 delegation target. Same\n * address on every chain. Must match the backend's\n * `KERNEL_DELEGATION_TARGET_V3_3`.\n */\nexport const KERNEL_DELEGATION_TARGET =\n \"0xd6CEDDe84be40893d153Be9d467CD6aD37875b28\";\n\n/** EIP-712 domain `version` Kernel V3.3 uses in `isValidSignature`. */\nexport const KERNEL_VERSION = \"0.3.3\";\n\n/** EIP-7702 delegation designator prefix (`0xef0100 || address`). */\nconst EIP7702_PREFIX = \"ef0100\";\n\n/** Validator-selection prefix for the 7702 root-validator (\"sudo\") path. */\nconst ERC1271_SUDO_MODE_PREFIX = \"00\";\n\nconst EIP712_DOMAIN_TYPEHASH = keccak(\n utf8(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\",\n ),\n);\nconst KERNEL_WRAPPER_TYPEHASH = keccak(utf8(\"Kernel(bytes32 hash)\"));\n\n/**\n * Return the EIP-7702 delegation target encoded in `code`, or `null` if\n * the code is empty or not a delegation designator.\n */\nexport function parseEip7702Delegation(\n code: string | null | undefined,\n): string | null {\n const hex = (code ?? \"\").replace(/^0x/i, \"\").toLowerCase();\n if (hex.length !== 46 || !hex.startsWith(EIP7702_PREFIX)) {\n return null;\n }\n return `0x${hex.slice(6)}`;\n}\n\n/** True if `code` is an EIP-7702 delegation to Kernel V3.3. */\nexport function isKernelDelegation(code: string | null | undefined): boolean {\n const target = parseEip7702Delegation(code);\n return target !== null && target === KERNEL_DELEGATION_TARGET.toLowerCase();\n}\n\n/**\n * EIP-712 digest a Kernel-delegated EOA must sign so that\n * `isValidSignature(innerHash, …)` on the account passes.\n *\n * The result is a raw EIP-712 hash: sign it with plain ECDSA (no EIP-191\n * prefix), exactly like the inner Permit2 digest.\n */\nexport function kernelErc1271Digest(\n innerHash: string,\n account: string,\n chainId: number,\n): string {\n const domainSeparator = keccak(\n concat(\n EIP712_DOMAIN_TYPEHASH,\n keccak(utf8(\"Kernel\")),\n keccak(utf8(KERNEL_VERSION)),\n uint256(BigInt(chainId)),\n address(account),\n ),\n );\n const structHash = keccak(\n concat(KERNEL_WRAPPER_TYPEHASH, bytes32(innerHash)),\n );\n return `0x${nobleToHex(\n keccak_256(concat(nobleFromHex(\"1901\"), domainSeparator, structHash)),\n )}`;\n}\n\n/**\n * Wrap a 65-byte `r || s || v` signature for Kernel's `isValidSignature`:\n * prepends the `0x00` sudo-mode selector, routing verification to the\n * delegated EOA's own key.\n */\nexport function wrapKernelErc1271Signature(signature: string): string {\n const hex = signature.replace(/^0x/i, \"\");\n if (hex.length !== 130) {\n throw new Error(\n `wrapKernelErc1271Signature: expected a 65-byte signature, got ${hex.length / 2} bytes`,\n );\n }\n return `0x${ERC1271_SUDO_MODE_PREFIX}${hex}`;\n}\n\nfunction keccak(data: Uint8Array): Uint8Array {\n return keccak_256(data);\n}\n\nfunction utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nfunction uint256(value: bigint): Uint8Array {\n return nobleFromHex(value.toString(16).padStart(64, \"0\"));\n}\n\nfunction address(value: string): Uint8Array {\n const hex = value.replace(/^0x/i, \"\").toLowerCase();\n if (hex.length !== 40) {\n throw new Error(`kernelErc1271Digest: invalid address ${value}`);\n }\n return nobleFromHex(hex.padStart(64, \"0\"));\n}\n\nfunction bytes32(value: string): Uint8Array {\n const hex = value.replace(/^0x/i, \"\").toLowerCase();\n if (hex.length !== 64) {\n throw new Error(\n `kernelErc1271Digest: expected a 32-byte hash, got ${value}`,\n );\n }\n return nobleFromHex(hex);\n}\n","/**\n * An {@link EvmSigner} backed by one of the SDK's own derived keys, for the\n * paths where that key owns a sponsored Kernel account (EIP-7702) rather than\n * sending transactions itself: the UserOp claim, and the CCTP-inbound\n * settlement when the swap was created gasless.\n */\nimport { type Hex, toHex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { EvmSigner } from \"./wallet.js\";\n\n/**\n * Wrap a derived private key as the Kernel-owner {@link EvmSigner}:\n * `signMessage` (UserOp hash), `signTypedData` (Permit2 witness) and\n * `signAuthorization` (7702 tuple). The key never sends transactions on these\n * paths, so the transaction methods throw.\n */\nexport function keyToKernelOwnerSigner(\n secretKey: Uint8Array,\n chainId: number,\n): EvmSigner {\n const account = privateKeyToAccount(toHex(secretKey));\n const unsupported = (m: string) => async (): Promise<never> => {\n throw new Error(\n `keyToKernelOwnerSigner: ${m} is not supported on the sponsored UserOp path`,\n );\n };\n return {\n address: account.address,\n chainId,\n signMessage: ({ raw }) =>\n account.signMessage({ message: { raw: raw as Hex } }),\n signTypedData: (typedData) =>\n account.signTypedData(\n typedData as unknown as Parameters<typeof account.signTypedData>[0],\n ),\n signAuthorization: async (auth) => {\n const signed = await account.signAuthorization({\n chainId: auth.chainId,\n address: auth.contractAddress as Hex,\n nonce: auth.nonce,\n });\n return {\n r: signed.r,\n s: signed.s,\n v: signed.v === undefined ? undefined : Number(signed.v),\n yParity: signed.yParity ?? 0,\n chainId: auth.chainId,\n address: auth.contractAddress,\n nonce: auth.nonce,\n };\n },\n sendTransaction: unsupported(\"sendTransaction\"),\n waitForReceipt: unsupported(\"waitForReceipt\"),\n getTransaction: unsupported(\"getTransaction\"),\n call: unsupported(\"call\"),\n };\n}\n","/** Direct calls to the deployed native HTLC. No coordinator is involved. */\nimport { type Address, encodeFunctionData, type Hex, parseAbi } from \"viem\";\nimport {\n buildNativeRedeemDigest,\n computeCoordinatorCallsHash,\n NATIVE_TOKEN_ADDRESS,\n} from \"./coordinator.js\";\nimport { normalizeBytes32 } from \"./htlc.js\";\nimport { signEvmDigest } from \"./signing.js\";\n\nconst abi = parseAbi([\n \"function create(bytes32 preimageHash, address claimAddress, uint256 timelock) payable\",\n \"function redeemBySig(bytes32 preimage, uint256 amount, address sender, uint256 timelock, address destination, address sweepToken, uint256 minAmountOut, bytes32 callsHash, uint8 v, bytes32 r, bytes32 s) returns (address)\",\n]);\n\nexport function encodeNativeCreate(params: {\n htlcAddress: string;\n preimageHash: string;\n claimAddress: string;\n timelock: number;\n amount: bigint;\n}): { to: string; data: string; value: bigint } {\n return {\n to: params.htlcAddress,\n data: encodeFunctionData({\n abi,\n functionName: \"create\",\n args: [\n `0x${normalizeBytes32(params.preimageHash)}` as Hex,\n params.claimAddress as Address,\n BigInt(params.timelock),\n ],\n }),\n value: params.amount,\n };\n}\n\n/** The deployed HTLC pays msg.sender; caller MUST be the intended recipient. */\nexport function buildNativeClaimTx(params: {\n preimage: string;\n secretKey: Uint8Array;\n caller: string;\n destination: string;\n swap: {\n evm_htlc_address: string;\n evm_chain_id: number;\n evm_htlc_version: number;\n evm_expected_sats: string | number;\n server_evm_address: string;\n evm_refund_locktime: number;\n };\n}): { to: string; data: string } {\n const { swap, caller, destination, secretKey } = params;\n if (caller.toLowerCase() !== destination.toLowerCase()) {\n throw new Error(\n \"Connect the payout wallet to claim RBTC: the native HTLC pays the submitting wallet.\",\n );\n }\n const preimage = (\n params.preimage.startsWith(\"0x\") ? params.preimage : `0x${params.preimage}`\n ) as Hex;\n const amount = BigInt(swap.evm_expected_sats);\n const callsHash = computeCoordinatorCallsHash([]) as Hex;\n const signature = signEvmDigest(\n secretKey,\n buildNativeRedeemDigest({\n htlcAddress: swap.evm_htlc_address,\n chainId: swap.evm_chain_id,\n htlcVersion: swap.evm_htlc_version,\n preimage,\n amount,\n sender: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n caller,\n destination,\n sweepToken: NATIVE_TOKEN_ADDRESS,\n minAmountOut: amount,\n callsHash,\n }),\n );\n return {\n to: swap.evm_htlc_address,\n data: encodeFunctionData({\n abi,\n functionName: \"redeemBySig\",\n args: [\n preimage,\n amount,\n swap.server_evm_address as Address,\n BigInt(swap.evm_refund_locktime),\n destination as Address,\n NATIVE_TOKEN_ADDRESS,\n amount,\n callsHash,\n signature.v,\n signature.r as Hex,\n signature.s as Hex,\n ],\n }),\n };\n}\n","/**\n * The refund calls the server may hand out for an expired EVM lock, decoded\n * so the client can check them and re-encode them itself instead of sending\n * the server's bytes. Any other call is refused: `HTLCErc20` also has a\n * `refund` overload that pays an arbitrary destination, and the server must\n * not be able to pick it (or any other contract call).\n */\n\nimport {\n encodeNativeRefundTo,\n encodeRefundTo,\n keccak256,\n NATIVE_TOKEN_ADDRESS,\n} from \"./coordinator.js\";\nimport { encodeHtlcNativeRefundCallData, normalizeBytes32 } from \"./htlc.js\";\nimport { decodeUint256 } from \"./wallet.js\";\n\nconst selector = (signature: string) =>\n keccak256(new TextEncoder().encode(signature)).slice(0, 10);\n\nconst SHAPES = {\n // HTLCCoordinator.refundTo: the coordinator is the lock's sender (v6).\n refundTo: {\n selector: selector(\"refundTo(bytes32,uint256,address,address,uint256)\"),\n words: [\"hash\", \"amount\", \"token\", \"claim\", \"timelock\"],\n },\n // HTLCNativeCoordinator.refundTo (native v1).\n nativeRefundTo: {\n selector: selector(\"refundTo(bytes32,uint256,address,uint256)\"),\n words: [\"hash\", \"amount\", \"claim\", \"timelock\"],\n },\n // HTLCErc20.refundFor: pays the lock's sender, the depositor (v7).\n refundFor: {\n selector: selector(\n \"refundFor(bytes32,uint256,address,address,address,uint256)\",\n ),\n words: [\"hash\", \"amount\", \"token\", \"sender\", \"claim\", \"timelock\"],\n },\n // HTLCNative.refundFor (native v2).\n nativeRefundFor: {\n selector: selector(\"refundFor(bytes32,uint256,address,address,uint256)\"),\n words: [\"hash\", \"amount\", \"sender\", \"claim\", \"timelock\"],\n },\n // HTLCNative.refund: msg.sender's own lock, created directly on the HTLC.\n nativeRefund: {\n selector: selector(\"refund(bytes32,uint256,address,uint256)\"),\n words: [\"hash\", \"amount\", \"claim\", \"timelock\"],\n },\n} as const;\n\nexport type RefundCallKind = keyof typeof SHAPES;\n\n/** A server refund call, decoded. */\nexport interface DecodedRefundCall {\n kind: RefundCallKind;\n preimageHash: string;\n amount: bigint;\n /** Lowercase; the zero address for a native lock. */\n token: string;\n /** The lock's sender, for `refundFor`; lowercase. */\n sender?: string;\n claimAddress: string;\n timelock: number;\n}\n\n/**\n * Decodes one of the refund calls the server builds, or throws for anything\n * else: an unknown selector, a wrong length, or a dirty address word.\n */\nexport function decodeRefundCall(data: string): DecodedRefundCall {\n const clean = data.toLowerCase();\n const entry = Object.entries(SHAPES).find(\n ([, shape]) => clean.slice(0, 10) === shape.selector,\n );\n if (!entry) {\n throw new Error(\n `The server's refund call has selector ${clean.slice(0, 10)}, which is none of the refund calls this client accepts`,\n );\n }\n const [kind, shape] = entry as [\n RefundCallKind,\n (typeof SHAPES)[RefundCallKind],\n ];\n if (clean.length !== 10 + 64 * shape.words.length) {\n throw new Error(\n `The server's ${kind} call is ${(clean.length - 10) / 2} bytes of arguments, expected ${32 * shape.words.length}`,\n );\n }\n const values: Record<string, string> = {};\n shape.words.forEach((name, i) => {\n values[name] = clean.slice(10 + 64 * i, 10 + 64 * (i + 1));\n });\n const address = (name: string) => {\n const word = values[name];\n if (!/^0{24}/.test(word)) {\n throw new Error(`The server's ${kind} call has a malformed ${name}`);\n }\n return `0x${word.slice(24)}`;\n };\n const timelock = decodeUint256(values.timelock);\n if (timelock > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`The server's ${kind} call has a malformed timelock`);\n }\n return {\n kind,\n preimageHash: `0x${values.hash}`,\n amount: decodeUint256(values.amount),\n token:\n \"token\" in values ? address(\"token\") : NATIVE_TOKEN_ADDRESS.toLowerCase(),\n sender: \"sender\" in values ? address(\"sender\") : undefined,\n claimAddress: address(\"claim\"),\n timelock: Number(timelock),\n };\n}\n\n/** Encodes `call` on `to` with this client's own encoders. */\nexport function encodeRefundCall(\n to: string,\n call: DecodedRefundCall,\n): { to: string; data: string } {\n const word = (hex: string) => normalizeBytes32(hex);\n const uint = (value: bigint | number) =>\n BigInt(value).toString(16).padStart(64, \"0\");\n switch (call.kind) {\n case \"refundTo\":\n return { to, data: encodeRefundTo(to, call).data };\n case \"nativeRefundTo\":\n return { to, data: encodeNativeRefundTo(to, call).data };\n case \"nativeRefund\":\n return { to, data: encodeHtlcNativeRefundCallData(to, call).data };\n case \"refundFor\":\n case \"nativeRefundFor\": {\n if (call.sender === undefined) {\n throw new Error(\"refundFor needs the lock's sender\");\n }\n const words =\n call.kind === \"refundFor\"\n ? [\n word(call.preimageHash),\n uint(call.amount),\n word(call.token),\n word(call.sender),\n word(call.claimAddress),\n uint(call.timelock),\n ]\n : [\n word(call.preimageHash),\n uint(call.amount),\n word(call.sender),\n word(call.claimAddress),\n uint(call.timelock),\n ];\n return { to, data: [SHAPES[call.kind].selector, ...words].join(\"\") };\n }\n }\n}\n","/**\n * Gasless claim logic.\n *\n * Claims are submitted via the server's claim-gasless endpoint which\n * uses the HTLCCoordinator contract for gasless execution.\n */\n\nimport type { ArkadeToEvmSwapResponse } from \"../api/client.js\";\nimport {\n buildRedeemDigest,\n computeCoordinatorCallsHash,\n normalizeBytes32,\n signEvmDigest,\n} from \"../evm/index.js\";\nimport { PROTOCOL_HEADERS } from \"../protocol.js\";\nimport { CLIENT_AGENT } from \"../version.js\";\nimport type { ClaimGaslessResult } from \"./types.js\";\n\n/** Swap types that support gasless claiming */\nexport type GaslessSwapResponse = ArkadeToEvmSwapResponse;\n\n/** Parameters for a gasless claim */\nexport interface GaslessClaimParams {\n /** Base URL for the API (e.g. \"https://api.satora.io\") */\n baseUrl: string;\n /** The swap preimage/secret (hex, with or without 0x prefix) */\n preimage: string;\n /** The secret key for EVM signing (raw bytes) */\n secretKey: Uint8Array;\n /** The swap data from the server */\n swap: GaslessSwapResponse;\n /** The EVM address where tokens should be sent */\n destination: string;\n /** Pre-fetched DEX calldata (for non-WBTC targets) */\n dexCalldata?: { to: string; data: string; value: string };\n /** Minimum amount of sweepToken to receive, from the redeem-and-swap-calldata endpoint. */\n minAmountOut: bigint;\n /** keccak256(abi.encode(calls)) from the redeem-and-swap-calldata endpoint.\n * Required for non-WBTC targets (when dexCalldata is provided). */\n callsHash: string;\n /**\n * Optional non-EVM bridge recipient (e.g. a Solana base58 SPL pubkey).\n * Required when the swap's `bridge_target_chain` is non-EVM. Must\n * match the value passed to `redeem-and-swap-calldata` so the\n * rebuilt server-side `calls_hash` matches the EIP-712 signature.\n *\n * For Solana: this is the recipient's USDC ATA, not the wallet pubkey.\n */\n bridgeRecipient?: string;\n /**\n * Optional Solana wallet pubkey, supplied alongside `bridgeRecipient`\n * when the recipient's USDC ATA does not yet exist. Triggers the\n * extended 65-byte forwarding hookData. Must mirror what was passed\n * to the calldata-fetch endpoint so the rebuilt `calls_hash` matches.\n */\n bridgeRecipientWallet?: string;\n}\n\n/**\n * Claims an Arkade-to-EVM swap gaslessly via the server.\n *\n * Builds the EIP-712 digest, signs it with the provided secret key,\n * and sends the signature + secret to the server. The server submits\n * the `coordinator.redeemAndExecute` transaction.\n *\n * @param params - All data needed for the gasless claim.\n * @returns The gasless claim result with transaction hash.\n */\nexport async function claimViaGasless(\n params: GaslessClaimParams,\n): Promise<ClaimGaslessResult> {\n const {\n baseUrl,\n preimage,\n secretKey,\n swap,\n destination,\n dexCalldata,\n minAmountOut,\n callsHash,\n bridgeRecipient,\n bridgeRecipientWallet,\n } = params;\n\n const secretHex = preimage.startsWith(\"0x\") ? preimage : `0x${preimage}`;\n\n const wbtcAddress = swap.wbtc_address;\n const amount = BigInt(swap.evm_expected_sats);\n\n if (swap.evm_chain_id === 30 || swap.evm_chain_id === 31) {\n throw new Error(\n \"Rootstock RIF sponsorship is not configured. Call claimEvmWithSigner() with the payout wallet; the user pays claim gas.\",\n );\n }\n\n // target_token.token_id contains the ERC-20 contract address for the final token\n const targetTokenAddress = String(swap.target_token.token_id);\n\n // Check if target token differs from WBTC (meaning a DEX swap is needed)\n const needsDexSwap =\n targetTokenAddress.toLowerCase() !== wbtcAddress.toLowerCase();\n\n // sweepToken: if there's a DEX swap, sweep the target token; otherwise sweep WBTC\n const sweepToken = needsDexSwap ? targetTokenAddress : wbtcAddress;\n\n // A direct claim needs no coordinator calls, and any call could move the\n // locked amount elsewhere.\n if (\n !needsDexSwap &&\n normalizeBytes32(callsHash) !==\n normalizeBytes32(computeCoordinatorCallsHash([]))\n ) {\n throw new Error(\n \"Refusing the server's claim: server calls on a direct claim\",\n );\n }\n\n // Build EIP-712 digest\n const digest = buildRedeemDigest({\n htlcAddress: swap.evm_htlc_address,\n chainId: swap.evm_chain_id,\n preimage: secretHex,\n amount,\n token: wbtcAddress,\n sender: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n caller: swap.evm_coordinator_address,\n destination,\n sweepToken,\n minAmountOut,\n callsHash,\n htlcVersion: swap.evm_htlc_version,\n });\n\n // Sign with the swap's internally derived EVM key\n const sig = signEvmDigest(secretKey, digest);\n\n // Send to server with DEX calldata if applicable\n return postClaim(baseUrl, swap.id, {\n secret: secretHex,\n destination,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n dex_calldata: needsDexSwap ? dexCalldata : undefined,\n bridge_recipient: bridgeRecipient,\n bridge_recipient_wallet: bridgeRecipientWallet,\n });\n}\n\n/**\n * Whether the swap's lock is the native-coin HTLC family. The field is\n * reported on the responses of the directions that can lock native coin;\n * absent means the ERC-20 family.\n */\nexport function nativeHtlcKind(swap: GaslessSwapResponse): boolean {\n return (swap as { evm_htlc_kind?: string }).evm_htlc_kind === \"native\";\n}\n\n/**\n * The post-claim state named by the server's \"wrong state\" rejection, or\n * `client_redeeming` for its \"claim already in progress\" rejection (a relay\n * is in flight and will move the swap there); `undefined` when the rejection\n * is about something else.\n */\nexport function alreadyClaimedStatus(errorText: string): string | undefined {\n if (/gasless claim already in progress/.test(errorText)) {\n return \"client_redeeming\";\n }\n const match =\n /cannot claim a swap in (client_redeeming|client_redeemed|server_redeemed)/.exec(\n errorText,\n );\n return match?.[1];\n}\n\nasync function postClaim(\n baseUrl: string,\n swapId: string,\n body: Record<string, unknown>,\n): Promise<ClaimGaslessResult> {\n const response = await fetch(`${baseUrl}/swap/${swapId}/claim-gasless`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Lendaswap-Client\": CLIENT_AGENT,\n ...PROTOCOL_HEADERS,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // The server already relayed a claim for this swap (this call, or the\n // auto-claim worker's, or an earlier attempt), or is relaying one right\n // now: the claim is on its way from the client's side, not failed.\n // Retrying would only be refused again.\n const claimed = alreadyClaimedStatus(errorText);\n if (response.status === 400 && claimed) {\n return {\n id: swapId,\n status: claimed,\n txHash: \"\",\n message: `Swap already claimed (${claimed})`,\n };\n }\n throw new Error(`Gasless claim failed (${response.status}): ${errorText}`);\n }\n\n const result = await response.json();\n return {\n id: result.id,\n status: result.status,\n txHash: result.tx_hash,\n message: result.message,\n };\n}\n","/**\n * Ethereum claim logic with contract call data encoding.\n *\n * EVM claims use the HTLCErc20 contract's redeem() function which requires\n * all original swap parameters for verification.\n */\n\nimport type { GetSwapResponse } from \"../api/client.js\";\nimport type { ClaimResult } from \"./types.js\";\n\n/**\n * Builds the claim data for an EVM swap (Ethereum, Polygon, or Arbitrum).\n *\n * The HTLCErc20 contract requires all original swap parameters for verification:\n * - preimage: The secret whose SHA-256 hash matches the preimageHash\n * - amount: Token amount that was locked\n * - token: ERC20 token address that was locked\n * - sender: Address that created the swap (server)\n * - timelock: Unix timestamp after which sender can refund\n *\n * @param id - The UUID of the swap (not used in contract call, kept for reference).\n * @param secret - The preimage/secret (32-byte hex string, with or without 0x prefix).\n * @param swap - The swap response from the API.\n * @param chain - The target chain for the claim.\n * @returns A ClaimResult with the EVM claim data.\n */\nexport function buildEthereumClaimData(\n id: string,\n secret: string,\n swap: GetSwapResponse,\n chain: \"polygon\" | \"arbitrum\" | \"ethereum\",\n): ClaimResult {\n const contractAddress = getEvmHtlcAddress(swap);\n if (!contractAddress) {\n return {\n success: false,\n message: \"Could not find HTLC contract address in swap response.\",\n chain,\n };\n }\n\n // Extract swap parameters needed for redeem()\n const params = getRedeemParams(swap);\n if (!params) {\n return {\n success: false,\n message:\n \"Could not extract redeem parameters from swap response. Missing amount, token, sender, or timelock.\",\n chain,\n };\n }\n\n // Normalize the secret - strip any double 0x prefix first\n let normalizedSecret = secret;\n while (normalizedSecret.startsWith(\"0x0x\")) {\n normalizedSecret = normalizedSecret.slice(2);\n }\n normalizedSecret = normalizedSecret.startsWith(\"0x\")\n ? normalizedSecret\n : `0x${normalizedSecret}`;\n\n // Encode the call data for redeem(bytes32,uint256,address,address,uint256)\n const callData = encodeRedeemCallData(\n normalizedSecret,\n params.amount,\n params.token,\n params.sender,\n params.timelock,\n );\n\n return {\n success: true,\n message: `${chain.charAt(0).toUpperCase() + chain.slice(1)} claims require manual execution. Use the provided call data to submit the transaction.`,\n chain,\n ethereumClaimData: {\n contractAddress,\n callData,\n swapId: id, // Keep for reference (not used in contract)\n secret: normalizedSecret,\n functionSignature:\n \"redeem(bytes32 preimage, uint256 amount, address token, address sender, uint256 timelock)\",\n // Additional params for manual construction\n amount: params.amount,\n token: params.token,\n sender: params.sender,\n timelock: params.timelock,\n },\n };\n}\n\n/**\n * Extracts redeem parameters from a swap response.\n *\n * Note: Lightning-to-EVM and Arkade-to-EVM swaps use the gasless claim path\n * and don't go through this function.\n */\nfunction getRedeemParams(swap: GetSwapResponse):\n | {\n amount: bigint;\n token: string;\n sender: string;\n timelock: bigint;\n }\n | undefined {\n // BTC-to-EVM swaps (BtcToEvmSwapResponse) - legacy type\n if (\"htlc_address_evm\" in swap) {\n // These swaps use different field names - not supported for manual redeem\n return undefined;\n }\n\n // EVM swaps with the newer field structure\n // Check for the fields we need\n const evmSwap = swap as {\n evm_expected_sats?: number | string;\n wbtc_address?: string;\n server_evm_address?: string;\n evm_refund_locktime?: number;\n };\n\n if (\n evmSwap.evm_expected_sats !== undefined &&\n evmSwap.wbtc_address &&\n evmSwap.server_evm_address &&\n evmSwap.evm_refund_locktime !== undefined\n ) {\n return {\n amount: BigInt(evmSwap.evm_expected_sats),\n token: evmSwap.wbtc_address,\n sender: evmSwap.server_evm_address,\n timelock: BigInt(evmSwap.evm_refund_locktime),\n };\n }\n\n return undefined;\n}\n\n/**\n * Encodes call data for the redeem(bytes32,uint256,address,address,uint256) function.\n *\n * Function selector: keccak256(\"redeem(bytes32,uint256,address,address,uint256)\")[0:4]\n *\n * @param preimage - The preimage/secret as a bytes32 hex string\n * @param amount - The token amount\n * @param token - The ERC20 token address\n * @param sender - The swap sender (server) address\n * @param timelock - The refund timelock\n * @returns The encoded call data as a hex string with 0x prefix\n */\nexport function encodeRedeemCallData(\n preimage: string,\n amount: bigint,\n token: string,\n sender: string,\n timelock: bigint,\n): string {\n // Function selector for redeem(bytes32,uint256,address,address,uint256)\n // keccak256(\"redeem(bytes32,uint256,address,address,uint256)\") = 0xb31597ad\n const selector = \"0xb31597ad\";\n\n // Normalize preimage to 32 bytes (64 hex chars)\n const normalizedPreimage = normalizeBytes32(preimage);\n\n // Encode amount as uint256 (32 bytes, left-padded)\n const encodedAmount = amount.toString(16).padStart(64, \"0\");\n\n // Encode addresses as 32 bytes (left-padded with zeros)\n const encodedToken = normalizeAddress(token);\n const encodedSender = normalizeAddress(sender);\n\n // Encode timelock as uint256 (32 bytes, left-padded)\n const encodedTimelock = timelock.toString(16).padStart(64, \"0\");\n\n return `${selector}${normalizedPreimage}${encodedAmount}${encodedToken}${encodedSender}${encodedTimelock}`;\n}\n\n/**\n * Encodes call data for the legacy claimSwap(bytes32,bytes32) function.\n * @deprecated Use encodeRedeemCallData instead for HTLCErc20 v2 contracts.\n */\nexport function encodeClaimSwapCallData(\n swapId: string,\n secret: string,\n): string {\n // Function selector for claimSwap(bytes32,bytes32)\n // keccak256(\"claimSwap(bytes32,bytes32)\") = 0x84cc315b...\n const selector = \"0x84cc315b\";\n\n // Normalize inputs - remove 0x prefix if present and ensure 64 chars (32 bytes)\n const normalizedSwapId = normalizeBytes32(swapId);\n const normalizedSecret = normalizeBytes32(secret);\n\n return `${selector}${normalizedSwapId}${normalizedSecret}`;\n}\n\n/**\n * Normalizes a hex string to a 32-byte (64 character) representation.\n * Left-pads with zeros (for secrets/hashes).\n *\n * @param input - Hex string\n * @returns 64-character hex string (without 0x prefix)\n */\nfunction normalizeBytes32(input: string): string {\n // Remove 0x prefix if present\n let hex = input.startsWith(\"0x\") ? input.slice(2) : input;\n\n // Pad to 64 characters (32 bytes) if needed - left pad for hashes\n if (hex.length < 64) {\n hex = hex.padStart(64, \"0\");\n }\n\n // Truncate if longer (shouldn't happen for valid inputs)\n if (hex.length > 64) {\n hex = hex.slice(0, 64);\n }\n\n return hex.toLowerCase();\n}\n\n/**\n * Normalizes an Ethereum address to a 32-byte (64 character) representation.\n * Left-pads with zeros (addresses are 20 bytes, need 12 bytes of padding).\n *\n * @param address - Ethereum address (with or without 0x prefix)\n * @returns 64-character hex string (without 0x prefix)\n */\nfunction normalizeAddress(address: string): string {\n // Remove 0x prefix if present\n const hex = address.startsWith(\"0x\") ? address.slice(2) : address;\n\n // Addresses are 20 bytes (40 hex chars), pad to 32 bytes (64 hex chars)\n return hex.padStart(64, \"0\").toLowerCase();\n}\n\n/**\n * Converts a UUID to a bytes32 hex string.\n * Removes dashes and right-pads with zeros to make 32 bytes.\n *\n * @param uuid - UUID string (e.g., \"550e8400-e29b-41d4-a716-446655440000\")\n * @returns 64-character hex string (without 0x prefix)\n */\nexport function uuidToBytes32(uuid: string): string {\n // Remove dashes and 0x prefix if present\n let hex = uuid.replace(/-/g, \"\");\n if (hex.startsWith(\"0x\")) {\n hex = hex.slice(2);\n }\n\n // Right-pad to 64 characters (32 bytes)\n if (hex.length < 64) {\n hex = hex.padEnd(64, \"0\");\n }\n\n // Truncate if longer (shouldn't happen for valid UUIDs)\n if (hex.length > 64) {\n hex = hex.slice(0, 64);\n }\n\n return hex.toLowerCase();\n}\n\n/**\n * Gets the EVM HTLC contract address from a swap response.\n *\n * @param swap - The swap response\n * @returns The HTLC contract address or undefined if not found\n */\nfunction getEvmHtlcAddress(swap: GetSwapResponse): string | undefined {\n // Other EVM swap types use evm_htlc_address\n if (\"evm_htlc_address\" in swap) {\n return (swap as { evm_htlc_address: string }).evm_htlc_address;\n }\n return undefined;\n}\n","/**\n * Types for redeem/claim operations.\n */\n\nimport type { ApiClient, GetSwapResponse } from \"../api/client.js\";\n\n/** Supported chains for claiming */\nexport type ClaimChain = \"polygon\" | \"arbitrum\" | \"ethereum\" | \"arkade\";\n\n/** Data needed for manual Ethereum claims */\nexport interface EthereumClaimData {\n /** The HTLC contract address */\n contractAddress: string;\n /** The encoded call data for redeem() */\n callData: string;\n /** The swap ID (UUID, for reference only - not used in contract call) */\n swapId: string;\n /** The secret/preimage (bytes32) */\n secret: string;\n /** Human-readable function signature */\n functionSignature: string;\n /** Token amount locked in HTLC (for manual claim construction) */\n amount?: bigint;\n /** ERC20 token address (for manual claim construction) */\n token?: string;\n /** Sender address who created the HTLC (for manual claim construction) */\n sender?: string;\n /** Refund timelock timestamp (for manual claim construction) */\n timelock?: bigint;\n}\n\n/** Data needed for Arkade-to-EVM coordinator claims (redeemAndExecute) */\nexport interface CoordinatorClaimData {\n /** HTLCErc20 contract address (for EIP-712 domain) */\n htlcAddress: string;\n /** HTLCCoordinator contract address (target for redeemAndExecute) */\n coordinatorAddress: string;\n /** EVM chain ID */\n chainId: number;\n /** WBTC/tBTC amount locked in the HTLC (evm_expected_sats) */\n amount: number | string;\n /** WBTC/tBTC token address (derived from chain config or response) */\n wbtcAddress: string;\n /** HTLC sender (server's EVM address) */\n sender: string;\n /** EVM refund locktime (unix timestamp) */\n timelock: number;\n /** DEX swap calldata (null for WBTC-to-WBTC swaps) */\n dexCallData?: { to: string; data: string; value: string } | null;\n /** Target token address (for sweepToken) */\n targetTokenAddress: string;\n /** Bitcoin network */\n network: string;\n}\n\n/** Data needed for Arkade VHTLC claims */\nexport interface ArkadeClaimData {\n /** Lendaswap's public key (SENDER in the VHTLC) */\n lendaswapPubKey: string;\n /** Arkade server's public key */\n arkadeServerPubKey: string;\n /** VHTLC address to claim from */\n vhtlcAddress: string;\n /** Refund locktime (unix timestamp) */\n refundLocktime: number;\n /** Unilateral claim delay in seconds */\n unilateralClaimDelay: number;\n /** Unilateral refund delay in seconds */\n unilateralRefundDelay: number;\n /** Unilateral refund without receiver delay in seconds */\n unilateralRefundWithoutReceiverDelay: number;\n /** Bitcoin network */\n network: string;\n}\n\n/** Result of a claim operation */\nexport interface ClaimResult {\n /** Whether the claim was successful */\n success: boolean;\n /** Human-readable message about the claim status */\n message: string;\n /** The chain the swap targets */\n chain?: ClaimChain;\n /** Task ID (deprecated, kept for backwards compatibility) */\n taskId?: string;\n /** Transaction hash */\n txHash?: string;\n /** Data for manual Ethereum claims */\n ethereumClaimData?: EthereumClaimData;\n /** Data for Arkade VHTLC claims */\n arkadeClaimData?: ArkadeClaimData;\n /** Data for Arkade-to-EVM coordinator claims (redeemAndExecute) */\n coordinatorClaimData?: CoordinatorClaimData;\n}\n\n/** Result of a gasless claim via the server-side claim-gasless endpoint */\nexport interface ClaimGaslessResult {\n /** Swap ID */\n id: string;\n /** Current swap status */\n status: string;\n /** Transaction hash of the redeemAndExecute call */\n txHash: string;\n /** Success message */\n message: string;\n}\n\n/**\n * Context passed to redeem functions.\n */\nexport interface RedeemContext {\n /** The API client for making requests */\n apiClient: ApiClient;\n /** Function to get swap details */\n getSwap: (id: string) => Promise<GetSwapResponse>;\n}\n\n/**\n * Extracts the chain from a token ID.\n *\n * Token IDs follow the pattern: `{token}_{chain}` (e.g., \"usdc_pol\", \"usdt_eth\", \"usdc_arb\")\n *\n * @param tokenId - The token identifier\n * @returns The chain or undefined if not recognized\n */\nexport function getChainFromTokenId(tokenId: string): ClaimChain | undefined {\n if (tokenId.endsWith(\"_pol\")) return \"polygon\";\n if (tokenId.endsWith(\"_arb\")) return \"arbitrum\";\n if (tokenId.endsWith(\"_eth\")) return \"ethereum\";\n if (tokenId === \"btc_arkade\") return \"arkade\";\n return undefined;\n}\n\n/**\n * Maps an API Chain name (e.g. \"Polygon\") to a ClaimChain (e.g. \"polygon\").\n */\nexport function getClaimChainFromChainName(\n chain: string,\n): ClaimChain | undefined {\n const lower = chain.toLowerCase();\n if (\n lower === \"polygon\" ||\n lower === \"arbitrum\" ||\n lower === \"ethereum\" ||\n lower === \"arkade\"\n ) {\n return lower;\n }\n return undefined;\n}\n","/**\n * Arkade (off-chain) VHTLC claim implementation.\n *\n * This module provides VHTLC claim functionality for Arkade swaps.\n * When a swap is funded by the server (EVM-to-Arkade direction),\n * the user can claim their BTC by revealing the preimage.\n *\n * The VHTLC uses a Taproot output with multiple spending paths. For claims,\n * we use the `claim` script path which requires revealing the preimage.\n */\n\nimport {\n type ArkTxInput,\n buildOffchainTx,\n ConditionWitness,\n CSVMultisigTapscript,\n type IndexerProvider,\n type OperatorProvider,\n Proof,\n RestIndexerProvider,\n RestOperatorProvider,\n type SignedProof,\n SingleKey,\n setArkPsbtField,\n Transaction,\n type VHTLC,\n VtxoTaprootTree,\n} from \"@arkade-os/sdk\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { base64, hex } from \"@scure/base\";\nimport { SigHash } from \"@scure/btc-signer\";\nimport {\n getNetworkHrp,\n getNetworkName,\n resolveArkadeServerUrlByName,\n} from \"../arkade-network.js\";\nimport { submitOffchainTxOneShot } from \"../arkade-submit.js\";\nimport { createSdkLogger, type Logger, type LogLevel } from \"../logging.js\";\nimport {\n ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n StrictVhtlcScript,\n} from \"../strict-vhtlc.js\";\nimport {\n attachClaimConditionWitness,\n ensureConditionWitness,\n} from \"./arkade-condition.js\";\n\n/** Parameters needed to build an Arkade claim */\nexport interface ArkadeClaimParams {\n /** User's secret key (32-byte hex) for signing */\n userSecretKey: string;\n /** User's x-only public key (32-byte hex) - this is the RECEIVER in the VHTLC */\n userPubKey: string;\n /** Lendaswap's public key (33-byte compressed hex or 32-byte x-only) - this is the SENDER */\n lendaswapPubKey: string;\n /** Arkade server's x-only public key (32-byte hex) */\n arkadeServerPubKey: string;\n /** Preimage (32-byte hex) - reveals the secret to claim */\n preimage: string;\n /** Preimage Hash */\n preimageHash: string;\n /** VHTLC address to claim from */\n vhtlcAddress: string;\n /** Refund locktime (unix timestamp) */\n refundLocktime: number;\n /** Unilateral claim delay in seconds */\n unilateralClaimDelay: number;\n /** Unilateral refund delay in seconds */\n unilateralRefundDelay: number;\n /** Unilateral refund without receiver delay in seconds */\n unilateralRefundWithoutReceiverDelay: number;\n /** Destination Arkade address to receive claimed funds */\n destinationAddress: string;\n /** Bitcoin network (mainnet, signet, etc.) */\n network: string;\n /** Arkade HTLC script version. Only strict version 1 is supported. */\n arkadeHtlcScriptVersion?: number;\n /** Arkade server URL (optional, uses default based on network) */\n arkadeServerUrl?: string;\n /** Optional logger sink. Silent by default. */\n logger?: Logger;\n /** Minimum log level to emit. Defaults to `silent`. */\n logLevel?: LogLevel;\n}\n\n/** Result of building an Arkade claim */\nexport interface ArkadeClaimResult {\n /** Virtual transaction ID */\n txId: string;\n /** Amount claimed in satoshis */\n claimAmount: bigint;\n}\n\n/**\n * Convert seconds to RelativeTimelock format.\n */\nfunction secondsToTimelock(\n seconds: number,\n): VHTLC.Options[\"unilateralClaimDelay\"] {\n return {\n type: \"seconds\" as const,\n value: BigInt(seconds),\n };\n}\n\n/**\n * Parse public key, handling both compressed (33-byte) and x-only (32-byte) formats.\n * Returns x-only (32-byte) format.\n */\nfunction parseXOnlyPubKey(pubKeyHex: string): Uint8Array {\n const bytes = hex.decode(pubKeyHex);\n if (bytes.length === 33) {\n // Compressed pubkey, strip the prefix byte\n return bytes.slice(1);\n }\n if (bytes.length === 32) {\n // Already x-only\n return bytes;\n }\n throw new Error(\n `Invalid public key length: expected 32 or 33, got ${bytes.length}`,\n );\n}\n\nfunction isNoPendingClaimError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.startsWith(\n \"No pending transactions found at the VHTLC address\",\n )\n );\n}\n\n/**\n * Claim a VHTLC swap by revealing the preimage.\n *\n * This function:\n * 1. Constructs the VHTLC with the same parameters as the original swap\n * 2. Connects to the Arkade server\n * 3. Fetches spendable VTXOs at the VHTLC address\n * 4. Builds an offchain transaction using the claim script path\n * 5. Signs and submits the transaction (with preimage in witness)\n * 6. Finalizes the transaction\n *\n * @param params - The claim parameters\n * @returns The claim result with transaction ID and amount\n * @throws Error if the claim fails\n */\nexport async function buildArkadeClaim(\n params: ArkadeClaimParams,\n): Promise<ArkadeClaimResult> {\n const {\n userSecretKey,\n userPubKey,\n lendaswapPubKey,\n arkadeServerPubKey,\n preimage,\n preimageHash,\n vhtlcAddress,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n destinationAddress,\n network,\n arkadeHtlcScriptVersion,\n arkadeServerUrl,\n } = params;\n\n const logger = createSdkLogger(params).child({\n module: \"redeem/arkade\",\n operation: \"arkade.claim\",\n data: { vhtlcAddress, network, destinationAddress },\n });\n\n logger.info({\n event: \"arkade.claim.start\",\n message: \"Starting Arkade claim\",\n });\n\n // Arkade offchain spends are submit/finalize. If a previous attempt submitted\n // but failed before finalization, submitting again with the same VTXOs will\n // fail. First ask the server for an existing pending tx and finalize that.\n try {\n return await continueArkadeClaim(params);\n } catch (error) {\n if (!isNoPendingClaimError(error)) {\n throw error;\n }\n console.log(\"No pending Arkade claim found; submitting a new claim\");\n }\n\n // Parse keys\n // For claim: user is RECEIVER, lendaswap is SENDER\n const userPkBytes = parseXOnlyPubKey(userPubKey);\n const lendaswapPkBytes = parseXOnlyPubKey(lendaswapPubKey);\n const serverPkBytes = parseXOnlyPubKey(arkadeServerPubKey);\n\n // Parse preimage and compute hash\n const preimageBytes = hex.decode(preimage);\n if (preimageBytes.length !== 32) {\n throw new Error(\n `Invalid preimage length: expected 32, got ${preimageBytes.length}`,\n );\n }\n\n // Compute preimage hash: SHA256 -> RIPEMD160 (HASH160)\n const sha256Hash = sha256(preimageBytes);\n const preimageHashBytes = ripemd160(sha256Hash);\n\n const preimageHashBytesString = hex.encode(preimageHashBytes);\n if (\n preimageHashBytesString !== hex.encode(ripemd160(hex.decode(preimageHash)))\n ) {\n throw new Error(\n `Preimage hash are not equal. '${hex.encode(ripemd160(hex.decode(preimageHash)))}' vs ${preimageHashBytesString}'`,\n );\n }\n\n // Determine Arkade server URL\n const networkName = getNetworkName(network);\n const serverUrl = resolveArkadeServerUrlByName(networkName, arkadeServerUrl);\n\n // Create Arkade providers\n const arkProvider: OperatorProvider = new RestOperatorProvider(serverUrl);\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n\n // Get server info\n const serverInfo = await arkProvider.getInfo();\n\n // Construct VHTLC with the same parameters as the original swap\n // For claim: lendaswap is the SENDER, user is the RECEIVER\n const vhtlcOptions = {\n sender: lendaswapPkBytes,\n receiver: userPkBytes,\n server: serverPkBytes,\n preimageHash: preimageHashBytes,\n refundLocktime: BigInt(refundLocktime),\n unilateralClaimDelay: secondsToTimelock(unilateralClaimDelay),\n unilateralRefundDelay: secondsToTimelock(unilateralRefundDelay),\n unilateralRefundWithoutReceiverDelay: secondsToTimelock(\n unilateralRefundWithoutReceiverDelay,\n ),\n };\n if (\n arkadeHtlcScriptVersion !== undefined &&\n arkadeHtlcScriptVersion !== ARKADE_HTLC_SCRIPT_VERSION_STRICT\n ) {\n throw new Error(\n `Unsupported Arkade HTLC script version: ${arkadeHtlcScriptVersion}`,\n );\n }\n const vhtlc = new StrictVhtlcScript(vhtlcOptions);\n\n // Get network HRP and verify computed VHTLC address\n const hrp = getNetworkHrp(networkName);\n const computedAddress = vhtlc.address(hrp, serverPkBytes);\n const computedAddressStr = computedAddress.encode();\n\n // Verify address matches expected\n if (computedAddressStr !== vhtlcAddress) {\n throw new Error(\n `Computed VHTLC address (${computedAddressStr}) does not match expected (${vhtlcAddress})`,\n );\n }\n\n // Fetch VTXOs at the VHTLC address\n const vhtlcPkScript = hex.encode(vhtlc.pkScript);\n\n const { vtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n spendableOnly: true,\n });\n\n if (vtxos.length === 0) {\n const { vtxos: allVtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n });\n logger.debug({\n event: \"arkade.claim.no_spendable_vtxos\",\n message: \"No spendable VTXOs found at VHTLC address\",\n data: { vtxos: allVtxos },\n });\n throw new Error(\"No spendable VTXOs found at the VHTLC address\");\n }\n\n // Calculate total amount\n const totalAmount = vtxos.reduce((acc, v) => acc + BigInt(v.value), 0n);\n if (totalAmount === 0n) {\n throw new Error(\"Total VTXO amount is zero\");\n }\n\n // Get the claim TapLeafScript (this is the key difference from refund)\n const claimLeafScript = vhtlc.claim();\n\n // Encode the VHTLC tap tree\n const tapTree = vhtlc.encode();\n\n // Decode the server's checkpoint tapscript\n const checkpointTapscript = CSVMultisigTapscript.decode(\n hex.decode(serverInfo.checkpointTapscript),\n );\n\n // Build inputs for offchain transaction\n // Include the preimage in the witness data\n const inputs: ArkTxInput[] = vtxos.map((v) => ({\n txid: v.txid,\n vout: v.vout,\n value: v.value,\n tapTree: tapTree,\n tapLeafScript: claimLeafScript,\n // The preimage will be added to the witness during signing\n witnessData: preimageBytes,\n }));\n\n // Parse destination address\n const { ArkAddress } = await import(\"@arkade-os/sdk\");\n const destAddr = ArkAddress.decode(destinationAddress);\n const destPkScript = destAddr.pkScript;\n\n // Build outputs\n const outputs = [\n {\n script: destPkScript,\n amount: totalAmount,\n },\n ];\n\n logger.info({\n event: \"arkade.claim.vtxos_found\",\n message: \"Found spendable VTXOs for Arkade claim\",\n data: { totalAmount, vtxoCount: vtxos.length },\n });\n\n // Build the offchain transaction\n const { arkTx, checkpoints } = buildOffchainTx(\n inputs,\n outputs,\n checkpointTapscript,\n );\n\n // Create signer from user's secret key\n const signer = SingleKey.fromHex(userSecretKey);\n const computedPk = await signer.xOnlyPublicKey();\n if (hex.encode(userPkBytes) !== hex.encode(computedPk)) {\n throw new Error(\n `Signing with wrong key? ${hex.encode(userPkBytes)} vs ${hex.encode(computedPk)}`,\n );\n }\n\n attachClaimConditionWitness(arkTx, checkpoints, preimageBytes);\n\n // Sign the ark transaction and, up front, every checkpoint (one-shot submit)\n const signedArkTx = await signer.sign(arkTx);\n const userSignedCheckpoints = await Promise.all(\n checkpoints.map((cp) => signer.sign(cp, [0])),\n );\n\n let arkTxid: string;\n try {\n const result = await submitOffchainTxOneShot(\n arkProvider,\n signedArkTx,\n checkpoints,\n userSignedCheckpoints,\n );\n arkTxid = result.arkTxid;\n logger.info({\n event: \"arkade.claim.finalized\",\n message: \"Arkade claim finalized\",\n data: { arkTxid, mode: result.mode },\n });\n } catch (error) {\n logger.error({\n event: \"arkade.claim.finalize_failed\",\n message: \"Failed to submit or finalize Arkade claim\",\n error,\n });\n throw error;\n }\n\n return {\n txId: arkTxid,\n claimAmount: totalAmount,\n };\n}\n\nexport async function continueArkadeClaim(\n params: ArkadeClaimParams,\n): Promise<ArkadeClaimResult> {\n const {\n userSecretKey,\n userPubKey,\n lendaswapPubKey,\n arkadeServerPubKey,\n preimage,\n preimageHash,\n vhtlcAddress,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n // destinationAddress not needed — we continue an existing pending tx\n network,\n arkadeHtlcScriptVersion,\n arkadeServerUrl,\n } = params;\n\n const logger = createSdkLogger(params).child({\n module: \"redeem/arkade\",\n operation: \"arkade.claim.continue\",\n data: { vhtlcAddress, network },\n });\n\n logger.info({\n event: \"arkade.claim.continue_start\",\n message: \"Continuing Arkade claim\",\n });\n\n // Parse keys\n // For claim: user is RECEIVER, lendaswap is SENDER\n const userPkBytes = parseXOnlyPubKey(userPubKey);\n const lendaswapPkBytes = parseXOnlyPubKey(lendaswapPubKey);\n const serverPkBytes = parseXOnlyPubKey(arkadeServerPubKey);\n\n // Parse preimage and compute hash\n const preimageBytes = hex.decode(preimage);\n if (preimageBytes.length !== 32) {\n throw new Error(\n `Invalid preimage length: expected 32, got ${preimageBytes.length}`,\n );\n }\n\n // Compute preimage hash: SHA256 -> RIPEMD160 (HASH160)\n const sha256Hash = sha256(preimageBytes);\n const preimageHashBytes = ripemd160(sha256Hash);\n\n const preimageHashBytesString = hex.encode(preimageHashBytes);\n if (\n preimageHashBytesString !== hex.encode(ripemd160(hex.decode(preimageHash)))\n ) {\n throw new Error(\n `Preimage hash are not equal. '${hex.encode(ripemd160(hex.decode(preimageHash)))}' vs ${preimageHashBytesString}'`,\n );\n }\n\n // Determine Arkade server URL\n const networkName = getNetworkName(network);\n const serverUrl = resolveArkadeServerUrlByName(networkName, arkadeServerUrl);\n\n // Create Arkade providers\n const arkProvider: OperatorProvider = new RestOperatorProvider(serverUrl);\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n\n // Construct VHTLC with the same parameters as the original swap\n // For claim: lendaswap is the SENDER, user is the RECEIVER\n const vhtlcOptions = {\n sender: lendaswapPkBytes,\n receiver: userPkBytes,\n server: serverPkBytes,\n preimageHash: preimageHashBytes,\n refundLocktime: BigInt(refundLocktime),\n unilateralClaimDelay: secondsToTimelock(unilateralClaimDelay),\n unilateralRefundDelay: secondsToTimelock(unilateralRefundDelay),\n unilateralRefundWithoutReceiverDelay: secondsToTimelock(\n unilateralRefundWithoutReceiverDelay,\n ),\n };\n if (\n arkadeHtlcScriptVersion !== undefined &&\n arkadeHtlcScriptVersion !== ARKADE_HTLC_SCRIPT_VERSION_STRICT\n ) {\n throw new Error(\n `Unsupported Arkade HTLC script version: ${arkadeHtlcScriptVersion}`,\n );\n }\n const vhtlc = new StrictVhtlcScript(vhtlcOptions);\n\n // Get network HRP and verify computed VHTLC address\n const hrp = getNetworkHrp(networkName);\n const computedAddress = vhtlc.address(hrp, serverPkBytes);\n const computedAddressStr = computedAddress.encode();\n\n // Verify address matches expected\n if (computedAddressStr !== vhtlcAddress) {\n throw new Error(\n `Computed VHTLC address (${computedAddressStr}) does not match expected (${vhtlcAddress})`,\n );\n }\n\n // Fetch VTXOs at the VHTLC address\n const vhtlcPkScript = hex.encode(vhtlc.pkScript);\n\n const { vtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n });\n\n if (vtxos.length === 0) {\n const { vtxos: allVtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n });\n logger.debug({\n event: \"arkade.claim.no_spendable_vtxos\",\n message: \"No spendable VTXOs found at VHTLC address\",\n data: { vtxos: allVtxos },\n });\n throw new Error(\"No spendable VTXOs found at the VHTLC address\");\n }\n\n // Calculate total amount\n const totalAmount = vtxos.reduce((acc, v) => acc + BigInt(v.value), 0n);\n if (totalAmount === 0n) {\n throw new Error(\"Total VTXO amount is zero\");\n }\n\n // Get the claim TapLeafScript (needed for the GetPendingTx intent)\n const claimLeafScript = vhtlc.claim();\n const claimScriptByte = claimLeafScript[1];\n\n // Encode the VHTLC tap tree\n const tapTree = vhtlc.encode();\n\n logger.info({\n event: \"arkade.claim.continue_vtxos_found\",\n message: \"Found VTXOs for pending Arkade claim\",\n data: { totalAmount, vtxoCount: vtxos.length },\n });\n\n // Build a GetPendingTx intent to ask Arkade for pending transactions\n const now = Math.floor(Date.now() / 1000);\n const intentMessage: Proof.GetPendingTxMessage = {\n type: \"get-pending-tx\",\n expire_at: now + 120,\n };\n\n // Build intent inputs from VTXOs\n const pkScriptBytes = hex.decode(vhtlcPkScript);\n const intentInputs = vtxos.map((v) => ({\n txid: hex.decode(v.txid),\n index: v.vout,\n witnessUtxo: {\n script: pkScriptBytes,\n amount: BigInt(v.value),\n },\n tapLeafScript: [claimLeafScript],\n sighashType: SigHash.ALL,\n }));\n\n // Create the intent proof PSBT\n const intentProof = Proof.create(intentMessage, intentInputs);\n\n // Set VtxoTaprootTree on each real input (skip input 0 which is the toSpend ref)\n for (let i = 0; i < vtxos.length; i++) {\n setArkPsbtField(intentProof, i + 1, VtxoTaprootTree, tapTree);\n }\n\n // Set condition witness (preimage) on each real input\n for (let i = 0; i < vtxos.length; i++) {\n setArkPsbtField(intentProof, i + 1, ConditionWitness, [preimageBytes]);\n }\n\n // Create signer from user's secret key\n const signer = SingleKey.fromHex(userSecretKey);\n const computedPk = await signer.xOnlyPublicKey();\n if (hex.encode(userPkBytes) !== hex.encode(computedPk)) {\n throw new Error(\n `Signing with wrong key? ${hex.encode(userPkBytes)} vs ${hex.encode(computedPk)}`,\n );\n }\n\n // Sign the intent proof\n const signedIntentProof = await signer.sign(intentProof);\n const signedIntent: SignedProof<Proof.GetPendingTxMessage> = {\n proof: base64.encode(signedIntentProof.toPSBT()),\n message: intentMessage,\n };\n\n // Fetch pending transactions from Arkade\n const pendingTxs = await arkProvider.getPendingTxs(signedIntent);\n\n if (pendingTxs.length === 0) {\n throw new Error(\n \"No pending transactions found at the VHTLC address. The claim may have already been finalized or was never submitted.\",\n );\n }\n\n logger.info({\n event: \"arkade.claim.pending_txs_found\",\n message: \"Found pending Arkade claim transactions\",\n data: { pendingTxCount: pendingTxs.length },\n });\n\n // Finalize each pending transaction\n let lastResult: ArkadeClaimResult | undefined;\n\n for (const pendingTx of pendingTxs) {\n const { arkTxid, signedCheckpointTxs } = pendingTx;\n\n // Sign and finalize checkpoint transactions\n const finalCheckpoints = await Promise.all(\n signedCheckpointTxs.map(async (c) => {\n const checkpointTx = Transaction.fromPSBT(base64.decode(c));\n\n // Restore missing witness scripts from the ark tx\n checkpointTx.updateInput(0, {\n witnessScript: claimScriptByte,\n });\n\n // Inject the preimage into every checkpoint input (no-op if echoed)\n for (let i = 0; i < checkpointTx.inputsLength; i++) {\n ensureConditionWitness(checkpointTx, i, preimageBytes);\n }\n\n // Sign input 0 (the checkpoint input)\n const signedCheckpoint = await signer.sign(checkpointTx, [0]);\n return base64.encode(signedCheckpoint.toPSBT());\n }),\n );\n\n // Finalize the transaction\n\n try {\n await arkProvider.finalizeTx(arkTxid, finalCheckpoints);\n } catch (error) {\n logger.error({\n event: \"arkade.claim.continue_finalize_failed\",\n message: \"Failed to finalize pending Arkade claim\",\n error,\n });\n throw error;\n }\n\n logger.info({\n event: \"arkade.claim.finalized\",\n message: \"Arkade claim finalized\",\n data: { arkTxid },\n });\n\n lastResult = {\n txId: arkTxid,\n claimAmount: totalAmount,\n };\n }\n\n if (!lastResult) {\n throw Error(\"Failed continuing claim\");\n }\n // We know lastResult is defined because we checked pendingTxs.length > 0\n return lastResult;\n}\n","import {\n ConditionWitness,\n getArkPsbtFields,\n setArkPsbtField,\n type Transaction,\n} from \"@arkade-os/sdk\";\n\n/**\n * Set the condition witness (the HTLC preimage) on an input unless the input\n * already carries one.\n *\n * `setArkPsbtField` appends, and arkd (btcd PSBT decoder) rejects a PSBT with\n * a duplicate proprietary key. The server may echo the witness we attached\n * before submit on the checkpoints it returns, so every later insertion must\n * be idempotent.\n */\nexport function ensureConditionWitness(\n tx: Transaction,\n inputIndex: number,\n preimage: Uint8Array,\n): void {\n if (getArkPsbtFields(tx, inputIndex, ConditionWitness).length > 0) return;\n setArkPsbtField(tx, inputIndex, ConditionWitness, [preimage]);\n}\n\n/**\n * Attach the preimage to every ark tx input and to every checkpoint input\n * before submit. arkd requires each checkpoint to carry the same condition\n * witness as the ark tx input that spends it.\n */\nexport function attachClaimConditionWitness(\n arkTx: Transaction,\n checkpoints: Transaction[],\n preimage: Uint8Array,\n): void {\n for (let i = 0; i < arkTx.inputsLength; i++) {\n ensureConditionWitness(arkTx, i, preimage);\n }\n for (const checkpoint of checkpoints) {\n for (let i = 0; i < checkpoint.inputsLength; i++) {\n ensureConditionWitness(checkpoint, i, preimage);\n }\n }\n}\n","/**\n * Claim of a native lock (RBTC on Rootstock) through RIF Relay.\n *\n * The lock's claim address is the recipient's RIF smart wallet, fixed at\n * swap creation (`rifSmartWalletAddress`). A relayed request from that smart\n * wallet calls `HTLCNative.redeem`, which pays the smart wallet; the smart\n * wallet then pays the relayer its fee and forwards the rest to its owner,\n * the recipient. Only the owner can sign that request, and the recipient\n * needs no RBTC: the fee comes out of the claimed coin. The first claim\n * deploys the smart wallet in the same request (through the factory); later\n * claims are relayed from the deployed wallet.\n */\n\nimport { keccak256 } from \"../evm/coordinator.js\";\nimport type { EIP712TypedData, EvmSigner } from \"../evm/wallet.js\";\nimport type { GaslessSwapResponse } from \"./gasless.js\";\nimport type { ClaimGaslessResult } from \"./types.js\";\n\n/** A RIF Relay deployment, as `/chain-config` publishes it. */\nexport interface RifRelayConfig {\n /** Relay server base URL (`/chain-info`, `/estimate`, `/relay`). */\n server_url: string;\n relay_hub: string;\n smart_wallet_factory: string;\n /** The implementation the factory's smart wallet proxies delegate to. */\n smart_wallet_template: string;\n /** Verifier of a request that deploys the smart wallet. */\n deploy_verifier: string;\n /** Verifier of a request from a deployed smart wallet. */\n relay_verifier: string;\n}\n\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * The smart wallet index: one wallet per owner, deployed on its first claim\n * and reused afterwards.\n */\nexport const RIF_SMART_WALLET_INDEX = 0;\n\n/**\n * Gas the smart wallet forwards to `HTLCNative.redeem` on a relay request\n * (~60k measured). The relay server rejects a request whose call needs more;\n * unused gas is not charged.\n */\nexport const RIF_CLAIM_CALL_GAS = 100_000n;\n\n/**\n * Gas for the fee payment to the relayer (a plain transfer to its EOA), as\n * the reference client sets it: the transfer's estimate minus its 10.5k\n * base the wallet's own call covers.\n */\nconst RIF_FEE_TRANSFER_GAS = 10_500n;\n\n/**\n * Headroom on the relay server's estimate, in percent: the server\n * re-estimates the signed request and rejects a fee below its figure.\n */\nconst RIF_FEE_HEADROOM_PERCENT = 110n;\n\n/** How long a signed request stays valid. The server wants at least 12 h. */\nconst RIF_REQUEST_VALIDITY_SECS = 2 * 24 * 60 * 60;\n\n/**\n * Upper bound the server's worker nonce must not exceed when it relays.\n * It only stops a relayer from sitting on the request; the HTLC timelock\n * and `validUntilTime` bound that already, and the SDK has no node to read\n * the worker's nonce from, so the bound is left open.\n */\nconst RIF_RELAY_MAX_NONCE = Number.MAX_SAFE_INTEGER;\n\nconst RELAY_DATA_TYPE = [\n { name: \"gasPrice\", type: \"uint256\" },\n { name: \"feesReceiver\", type: \"address\" },\n { name: \"callForwarder\", type: \"address\" },\n { name: \"callVerifier\", type: \"address\" },\n];\n\n/** `RelayRequest` of a deploy (factory domain): `recoverer` + `index`, no `gas`. */\nconst DEPLOY_REQUEST_TYPE = [\n { name: \"relayHub\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"tokenContract\", type: \"address\" },\n { name: \"recoverer\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"tokenAmount\", type: \"uint256\" },\n { name: \"tokenGas\", type: \"uint256\" },\n { name: \"validUntilTime\", type: \"uint256\" },\n { name: \"index\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"relayData\", type: \"RelayData\" },\n];\n\n/** `RelayRequest` from a deployed wallet (wallet domain): `gas`, no `recoverer` / `index`. */\nconst RELAY_REQUEST_TYPE = [\n { name: \"relayHub\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"tokenContract\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"gas\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"tokenAmount\", type: \"uint256\" },\n { name: \"tokenGas\", type: \"uint256\" },\n { name: \"validUntilTime\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"relayData\", type: \"RelayData\" },\n];\n\n/** What the relay server reports at `/chain-info`. */\ninterface RifChainInfo {\n feesReceiver: string;\n relayHubAddress: string;\n minGasPrice: string;\n chainId: string;\n ready: boolean;\n}\n\n/** What the relay server answers at `/estimate` (all decimal strings). */\ninterface RifEstimate {\n gasPrice: string;\n estimation: string;\n requiredNativeAmount: string;\n}\n\n/** The smart wallet a claim is relayed from. */\nexport interface RifSmartWallet {\n address: string;\n /** Whether it exists on chain; if not, the claim deploys it. */\n deployed: boolean;\n /** The nonce the next request must carry (factory's per owner, or the wallet's). */\n nonce: bigint;\n}\n\n/** One request, before the fee is fixed. */\ninterface UnpricedRequest {\n wallet: RifSmartWallet;\n owner: string;\n data: string;\n htlc: string;\n relay: RifRelayConfig;\n chainInfo: RifChainInfo;\n validUntilTime: number;\n}\n\nexport interface RifRelayClaimParams {\n swap: GaslessSwapResponse;\n /** The swap preimage (hex, with or without 0x prefix) */\n preimage: string;\n /** Owner of the smart wallet: signs the relay request, receives the coin. */\n signer: EvmSigner;\n relay: RifRelayConfig;\n /** Test seam; defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Test seam: seconds since the epoch. */\n now?: () => number;\n}\n\n/**\n * Claim a native lock through RIF Relay. The coin, less the relayer's fee,\n * lands at `signer.address`, which must own the lock's claim address.\n */\nexport async function claimNativeViaRifRelay(\n params: RifRelayClaimParams,\n): Promise<ClaimGaslessResult> {\n const { swap, preimage, signer, relay } = params;\n const fetchFn = params.fetch ?? fetch;\n const now = params.now ?? (() => Math.floor(Date.now() / 1000));\n if (signer.chainId !== swap.evm_chain_id) {\n throw new Error(\n `Wallet is on chain ${signer.chainId}, but the claim must be sent on chain ${swap.evm_chain_id}.`,\n );\n }\n\n const chainInfo = await rifGet<RifChainInfo>(\n fetchFn,\n relay.server_url,\n \"/chain-info\",\n );\n if (!chainInfo.ready) {\n throw new Error(\"RIF Relay server is not ready; retry in a minute.\");\n }\n if (Number(chainInfo.chainId) !== swap.evm_chain_id) {\n throw new Error(\n `RIF Relay server serves chain ${chainInfo.chainId}, the swap is on chain ${swap.evm_chain_id}.`,\n );\n }\n\n // Only the owner of the lock's claim address can claim it.\n const owner = signer.address;\n const claimAddress = swap.client_evm_address;\n if (\n rifSmartWalletAddress(relay, owner).toLowerCase() !==\n claimAddress.toLowerCase()\n ) {\n throw new Error(\n `Wallet ${owner} does not own this swap's claim address ${claimAddress}; ` +\n \"connect the wallet the swap pays out to.\",\n );\n }\n const wallet = await rifSmartWallet(signer, relay, owner);\n\n // The redeem pays the smart wallet (the lock's claim address): that is\n // what the verifier credits toward the fee, and the wallet forwards the rest.\n const unpriced: UnpricedRequest = {\n wallet,\n owner,\n data: encodeNativeRedeem({\n preimage: preimage.startsWith(\"0x\") ? preimage : `0x${preimage}`,\n amount: BigInt(swap.evm_expected_sats),\n sender: swap.server_evm_address,\n timelock: BigInt(swap.evm_refund_locktime),\n }),\n htlc: swap.evm_htlc_address,\n relay,\n chainInfo,\n validUntilTime: now() + RIF_REQUEST_VALIDITY_SECS,\n };\n\n // Estimate unsigned with no fee, as the server requires, at the floor\n // price; then price the fee at the higher of that and the server's price.\n const minGasPrice = BigInt(chainInfo.minGasPrice);\n const estimate = await rifPost<RifEstimate>(\n fetchFn,\n relay.server_url,\n \"/estimate\",\n rifEnvelope(\n buildRifRequest(unpriced, 0n, minGasPrice),\n \"SERVER_SIGNATURE_REQUIRED\",\n ),\n );\n const serverGasPrice = BigInt(estimate.gasPrice);\n const gasPrice = serverGasPrice > minGasPrice ? serverGasPrice : minGasPrice;\n const fee = rifFee(BigInt(estimate.estimation), gasPrice);\n const amount = BigInt(swap.evm_expected_sats);\n if (fee >= amount) {\n throw new Error(\n `RIF Relay fee ${fee} wei is not below the claimed ${amount} wei.`,\n );\n }\n\n const request = buildRifRequest(unpriced, fee, gasPrice);\n const signature = await signer.signTypedData(\n rifTypedData(request, swap.evm_chain_id),\n );\n const relayed = await rifPost<{ signedTx: string; txHash?: string }>(\n fetchFn,\n relay.server_url,\n \"/relay\",\n rifEnvelope(request, signature),\n );\n const txHash = relayed.txHash ?? keccak256(relayed.signedTx);\n\n const receipt = await signer.waitForReceipt(txHash);\n if (receipt.status !== \"success\") {\n throw new Error(`RIF Relay claim transaction ${txHash} reverted.`);\n }\n return {\n id: swap.id,\n status: \"clientredeemed\",\n txHash,\n message: `HTLCNative.redeem relayed by RIF Relay from smart wallet ${wallet.address} (fee ${fee} wei)`,\n };\n}\n\n/** `estimation × gasPrice` plus headroom. */\nexport function rifFee(estimation: bigint, gasPrice: bigint): bigint {\n return (estimation * gasPrice * RIF_FEE_HEADROOM_PERCENT) / 100n;\n}\n\n/** A RIF request: the signed fields, as the server's JSON wants them. */\nexport interface RifRequest {\n kind: \"deploy\" | \"relay\";\n /** EIP-712 `verifyingContract`: the factory for a deploy, else the wallet. */\n verifyingContract: string;\n request: Record<string, string | number>;\n relayData: {\n gasPrice: string;\n feesReceiver: string;\n callForwarder: string;\n callVerifier: string;\n };\n relayHub: string;\n}\n\nfunction buildRifRequest(\n u: UnpricedRequest,\n tokenAmount: bigint,\n gasPrice: bigint,\n): RifRequest {\n const tokenGas = tokenAmount === 0n ? 0n : RIF_FEE_TRANSFER_GAS;\n const common = {\n relayHub: u.relay.relay_hub,\n from: u.owner,\n to: u.htlc,\n tokenContract: ZERO_ADDRESS,\n value: \"0\",\n nonce: u.wallet.nonce.toString(),\n tokenAmount: tokenAmount.toString(),\n tokenGas: tokenGas.toString(),\n validUntilTime: u.validUntilTime,\n data: u.data,\n };\n const feesReceiver = u.chainInfo.feesReceiver;\n if (!u.wallet.deployed) {\n return {\n kind: \"deploy\",\n verifyingContract: u.relay.smart_wallet_factory,\n request: {\n ...common,\n recoverer: ZERO_ADDRESS,\n index: RIF_SMART_WALLET_INDEX,\n },\n relayData: {\n gasPrice: gasPrice.toString(),\n feesReceiver,\n callForwarder: u.relay.smart_wallet_factory,\n callVerifier: u.relay.deploy_verifier,\n },\n relayHub: u.relay.relay_hub,\n };\n }\n return {\n kind: \"relay\",\n verifyingContract: u.wallet.address,\n request: { ...common, gas: RIF_CLAIM_CALL_GAS.toString() },\n relayData: {\n gasPrice: gasPrice.toString(),\n feesReceiver,\n callForwarder: u.wallet.address,\n callVerifier: u.relay.relay_verifier,\n },\n relayHub: u.relay.relay_hub,\n };\n}\n\n/** The `RelayRequest` the owner signs, for `EvmSigner.signTypedData`. */\nexport function rifTypedData(\n req: RifRequest,\n chainId: number,\n): EIP712TypedData {\n const uint = new Set([\n \"value\",\n \"gas\",\n \"nonce\",\n \"tokenAmount\",\n \"tokenGas\",\n \"validUntilTime\",\n \"index\",\n ]);\n const message: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(req.request)) {\n message[key] = uint.has(key) ? BigInt(value) : value;\n }\n message.relayData = {\n ...req.relayData,\n gasPrice: BigInt(req.relayData.gasPrice),\n };\n return {\n domain: {\n name: \"RSK Enveloping Transaction\",\n version: \"2\",\n chainId,\n verifyingContract: req.verifyingContract,\n },\n types: {\n RelayRequest:\n req.kind === \"deploy\" ? DEPLOY_REQUEST_TYPE : RELAY_REQUEST_TYPE,\n RelayData: RELAY_DATA_TYPE,\n },\n primaryType: \"RelayRequest\",\n message,\n };\n}\n\nfunction rifEnvelope(req: RifRequest, signature: string) {\n return {\n relayRequest: { request: req.request, relayData: req.relayData },\n metadata: {\n relayHubAddress: req.relayHub,\n relayMaxNonce: RIF_RELAY_MAX_NONCE,\n signature,\n },\n };\n}\n\n// keccak256(\"redeem(bytes32,uint256,address,uint256)\")[:4]\nconst HTLC_NATIVE_REDEEM_SELECTOR = \"0xd592e483\";\n// keccak256(\"nonce(address)\")[:4], the factory's per-owner deploy nonce\nconst FACTORY_NONCE_SELECTOR = \"0x70ae92d2\";\n// keccak256(\"nonce()\")[:4], the wallet's relay nonce\nconst WALLET_NONCE_SELECTOR = \"0xaffed0e0\";\n\n/** `HTLCNative.redeem(preimage, amount, sender, timelock)`, called by the claim address. */\nfunction encodeNativeRedeem(p: {\n preimage: string;\n amount: bigint;\n sender: string;\n timelock: bigint;\n}): string {\n return (\n HTLC_NATIVE_REDEEM_SELECTOR +\n word(p.preimage) +\n word(p.amount) +\n word(p.sender) +\n word(p.timelock)\n );\n}\n\n/**\n * The smart wallet `owner` claims from: the factory's CREATE2 proxy for\n * (`owner`, no recoverer, `RIF_SMART_WALLET_INDEX`) around the template, as\n * `factory.getSmartWalletAddress` computes it. A native lock on a RIF Relay\n * chain is created with this as its claim address. Lowercase hex.\n */\nexport function rifSmartWalletAddress(\n relay: RifRelayConfig,\n owner: string,\n): string {\n const salt = keccak256(\n `0x${strip0x(owner).toLowerCase()}${\"0\".repeat(40)}${word(BigInt(RIF_SMART_WALLET_INDEX))}`,\n );\n const initCodeHash = keccak256(\n `0x602d3d8160093d39f3363d3d373d3d3d3d363d73${strip0x(relay.smart_wallet_template).toLowerCase()}5af43d923d90803e602b57fd5bf3`,\n );\n const hash = keccak256(\n `0xff${strip0x(relay.smart_wallet_factory).toLowerCase()}${strip0x(salt)}${strip0x(initCodeHash)}`,\n );\n return `0x${hash.slice(-40)}`;\n}\n\n/**\n * The owner's smart wallet, whether it is deployed, and the nonce its next\n * request carries.\n */\nexport async function rifSmartWallet(\n signer: EvmSigner,\n relay: RifRelayConfig,\n owner: string,\n): Promise<RifSmartWallet> {\n const address = rifSmartWalletAddress(relay, owner);\n // A wallet that is not deployed has no code: the call returns no data.\n const walletNonce = strip0x(\n await signer.call({ to: address, data: WALLET_NONCE_SELECTOR }),\n );\n if (walletNonce.length >= 64) {\n return { address, deployed: true, nonce: BigInt(`0x${walletNonce}`) };\n }\n const factoryNonce = await signer.call({\n to: relay.smart_wallet_factory,\n data: FACTORY_NONCE_SELECTOR + word(owner),\n });\n return { address, deployed: false, nonce: BigInt(factoryNonce) };\n}\n\nfunction strip0x(hex: string): string {\n return hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n}\n\nfunction word(value: string | bigint): string {\n const hex =\n typeof value === \"bigint\"\n ? value.toString(16)\n : strip0x(value).toLowerCase();\n return hex.padStart(64, \"0\");\n}\n\nasync function rifGet<T>(\n fetchFn: typeof fetch,\n baseUrl: string,\n path: string,\n): Promise<T> {\n return rifResponse<T>(await fetchFn(`${baseUrl}${path}`), path);\n}\n\nasync function rifPost<T>(\n fetchFn: typeof fetch,\n baseUrl: string,\n path: string,\n body: unknown,\n): Promise<T> {\n const response = await fetchFn(`${baseUrl}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return rifResponse<T>(response, path);\n}\n\n/** The server answers rejections with HTTP 200 and `{ error }`. */\nasync function rifResponse<T>(response: Response, path: string): Promise<T> {\n const text = await response.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n throw new Error(\n `RIF Relay ${path} answered ${response.status}: ${text.slice(0, 200)}`,\n );\n }\n const error = (body as { error?: unknown }).error;\n if (!response.ok || error != null) {\n throw new Error(\n `RIF Relay ${path} rejected the request: ${typeof error === \"string\" ? error : text.slice(0, 200)}`,\n );\n }\n return body as T;\n}\n\n/**\n * The swap's claim needs the claim destination's wallet to sign, through\n * RIF Relay or paying its own gas: `claim()` cannot do it unattended. Call\n * `claimEvmWithSigner(id, signer)` with that wallet.\n */\nexport class WalletClaimRequiredError extends Error {\n constructor(\n readonly swapId: string,\n readonly chainId: number,\n message?: string,\n ) {\n super(\n message ??\n `Swap ${swapId} is claimed through RIF Relay on chain ${chainId}: ` +\n \"call claimEvmWithSigner with the wallet that receives the coin.\",\n );\n this.name = \"WalletClaimRequiredError\";\n }\n}\n","/**\n * Claim a BTC/Arkade/Lightning → EVM swap by publishing\n * `coordinator.redeemAndExecute` **client-side** as a paymaster-sponsored\n * EIP-7702 UserOp, instead of asking the server to submit it.\n *\n * Why: the server-submitted path builds the DEX leg with a fixed gas limit and\n * the legacy (Uniswap) router, which breaks LI.FI-only targets like EURe. Here\n * the SDK fetches LI.FI calldata from `/dex-calldata`, signs the redeem digest\n * with the swap's own derived key, and the Alchemy bundler simulates+sponsors\n * the UserOp — so gas is estimated (no OOG) and the user needs no ETH.\n *\n * The publisher is the swap's *derived* EVM key (it already signs the EIP-712\n * redeem authorization), wrapped as a 7702 smart account — fully self-contained.\n */\n\nimport type { Hex } from \"viem\";\nimport { arbitrum } from \"viem/chains\";\nimport { createSwapSmartAccountClient } from \"../cctp-inbound/smartAccount.js\";\nimport type { AaConfig } from \"../cctp-inbound/types.js\";\nimport {\n buildRedeemDigest,\n type CoordinatorCall,\n computeCoordinatorCallsHash,\n encodeRedeemAndExecute,\n signEvmDigest,\n} from \"../evm/index.js\";\nimport { keyToKernelOwnerSigner } from \"../evm/key-signer.js\";\nimport type { GaslessSwapResponse } from \"./gasless.js\";\nimport type { ClaimGaslessResult } from \"./types.js\";\n\n/** Parameters for a sponsored-UserOp claim. */\nexport interface UserOpClaimParams {\n /** Swap preimage/secret (hex, with or without 0x). */\n preimage: string;\n /** The swap's derived EVM signing key (raw bytes). */\n secretKey: Uint8Array;\n /** The swap data from the server. */\n swap: GaslessSwapResponse;\n /** EVM address tokens are ultimately swept to. */\n destination: string;\n /**\n * The exact `approve` + swap calls from `POST /dex-calldata/fund` (built with\n * `recipient = coordinator` so the coordinator's `_sweep` can deliver). Used\n * verbatim so the locally-computed `callsHash` matches what we sign.\n */\n calls: CoordinatorCall[];\n /** Slippage floor for the coordinator `_sweep` (smallest target-token units). */\n minAmountOut: bigint;\n /** AA config (bundler URL + Gas Manager policy id) — required for sponsorship. */\n aa: AaConfig;\n}\n\n/** Everything needed to build a signed `redeemAndExecute` transaction. */\nexport type RedeemTxParams = Omit<UserOpClaimParams, \"aa\">;\n\n/**\n * Builds the `redeemAndExecute` call for the coordinator: EIP-712 digest over\n * the claim, signed with the swap's derived EVM key, then ABI-encoded. The\n * coordinator does not care who submits the transaction - only the signature\n * matters - so the same `{ to, data }` can go out as a sponsored UserOp\n * ({@link claimViaUserOp}) or from any wallet that pays its own gas\n * (`claimViaSigner`).\n */\nexport function buildRedeemAndExecuteTx(params: RedeemTxParams): {\n to: string;\n data: string;\n} {\n const { preimage, secretKey, swap, destination, calls, minAmountOut } =\n params;\n const secretHex = preimage.startsWith(\"0x\") ? preimage : `0x${preimage}`;\n const wbtcAddress = swap.wbtc_address;\n const amount = BigInt(swap.evm_expected_sats);\n const targetTokenAddress = String(swap.target_token.token_id);\n const sweepToken =\n targetTokenAddress.toLowerCase() !== wbtcAddress.toLowerCase()\n ? targetTokenAddress\n : wbtcAddress;\n\n // The SDK now owns the calls, so it computes the signed `callsHash` itself\n // (parity-tested against Solidity `abi.encode(Call[])`).\n const callsHash = computeCoordinatorCallsHash(calls);\n\n const digest = buildRedeemDigest({\n htlcAddress: swap.evm_htlc_address,\n chainId: swap.evm_chain_id,\n preimage: secretHex,\n amount,\n token: wbtcAddress,\n sender: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n caller: swap.evm_coordinator_address,\n destination,\n sweepToken,\n minAmountOut,\n callsHash,\n htlcVersion: swap.evm_htlc_version,\n });\n const sig = signEvmDigest(secretKey, digest);\n\n const { to, data } = encodeRedeemAndExecute(swap.evm_coordinator_address, {\n preimage: secretHex,\n amount,\n token: wbtcAddress,\n sender: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n calls,\n sweepToken,\n minAmountOut,\n destination,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n });\n return { to, data };\n\n // ── Publish ──────────────────────────────────────────────────────────────\n // Default mode: paymaster-sponsored 7702 UserOp via the Alchemy bundler. The\n // bundler simulates (so gas is estimated, no OOG) and the Gas Manager policy\n // sponsors it, so the swap's derived account needs no ETH.\n //\n // TODO(self-funded claims): to support clients without a sponsoring\n // paymaster (e.g. third-party integrators publishing from a funded EOA),\n // branch here on whether `aa` is present:\n // - sponsored (today): the path below.\n // - self-funded: take an `EvmSigner` from the caller (their wallet) and\n // `await signer.sendTransaction({ to, data })` then\n // `signer.waitForReceipt(hash)`. That publisher must hold native gas;\n // the coordinator accepts any caller, so no other change is needed.\n}\n\n/**\n * Build, sign and publish `redeemAndExecute` as a sponsored UserOp.\n */\nexport async function claimViaUserOp(\n params: UserOpClaimParams,\n): Promise<ClaimGaslessResult> {\n const { secretKey, swap, aa } = params;\n const { to, data } = buildRedeemAndExecuteTx(params);\n const signer = keyToKernelOwnerSigner(secretKey, swap.evm_chain_id);\n const { client } = await createSwapSmartAccountClient({\n signer,\n aa,\n chain: arbitrum,\n });\n\n const userOpHash = await client.sendUserOperation({\n calls: [{ to: to as Hex, data: data as Hex, value: 0n }],\n });\n const receipt = await client.waitForUserOperationReceipt({\n hash: userOpHash,\n });\n // Included-but-reverted resolves with success=false rather than throwing\n // (same as cctp-inbound/submit.ts). Surface it so a plain claim can fall\n // back to the server path and a DEX claim reports a real failure.\n if (!receipt.success) {\n throw new Error(\n `redeemAndExecute UserOp ${userOpHash} reverted on-chain ` +\n `(tx ${receipt.receipt.transactionHash})` +\n (receipt.reason ? `: ${receipt.reason}` : \"\"),\n );\n }\n\n return {\n id: swap.id,\n status: \"clientredeemed\",\n txHash: receipt.receipt.transactionHash,\n message: \"redeemAndExecute published via sponsored UserOp\",\n };\n}\n","import { buildNativeClaimTx } from \"../evm/native.js\";\nimport type { EvmSigner } from \"../evm/wallet.js\";\nimport {\n getRevertReason,\n simulateTransaction,\n txTypeFor,\n} from \"../evm/wallet.js\";\nimport type { ClaimGaslessResult } from \"./types.js\";\nimport {\n buildRedeemAndExecuteTx,\n type RedeemTxParams,\n} from \"./userop-claim.js\";\n\nexport interface SignerClaimParams extends RedeemTxParams {\n /** The wallet that submits the claim and pays its gas. */\n signer: EvmSigner;\n}\n\n/**\n * Claims an EVM-targeted swap from the user's own wallet.\n *\n * Same signed `redeemAndExecute` calldata as the sponsored UserOp path, but\n * broadcast by `signer` (a connected wallet) which pays the gas. This is the\n * fallback when no bundler / paymaster is configured or the sponsored claim\n * keeps failing: the swap's derived key still authorises the redeem, the\n * wallet only carries the transaction.\n */\nexport async function claimViaSigner(\n params: SignerClaimParams,\n): Promise<ClaimGaslessResult> {\n const { signer, swap } = params;\n if (signer.chainId !== swap.evm_chain_id) {\n throw new Error(\n `Wallet is on chain ${signer.chainId}, but the claim must be sent on chain ${swap.evm_chain_id}.`,\n );\n }\n const native =\n (swap as { evm_htlc_kind?: string }).evm_htlc_kind === \"native\";\n const tx = native\n ? buildNativeClaimTx({ ...params, caller: signer.address })\n : buildRedeemAndExecuteTx(params);\n await simulateTransaction(signer, tx, \"Claim transaction\");\n const txHash = await signer.sendTransaction({\n ...tx,\n ...(native ? { type: txTypeFor(signer.chainId) } : {}),\n });\n const receipt = await signer.waitForReceipt(txHash);\n const minedHash = native ? receipt.transactionHash || txHash : txHash;\n if (receipt.status !== \"success\") {\n const reason = await getRevertReason(\n signer,\n minedHash,\n receipt.blockNumber,\n );\n throw new Error(`Claim transaction reverted: ${reason}`);\n }\n if (native && minedHash.toLowerCase() !== txHash.toLowerCase()) {\n // Wallet cancellation receipts can also have status \"success\". Only a\n // replacement of the same authorized claim counts as a completed claim.\n const mined = await signer.getTransaction(minedHash).catch(() => undefined);\n if (!mined) {\n // A lagging RPC cannot distinguish a speed-up from a cancellation.\n // Neither report success nor invite a new claim without verification.\n throw new Error(\n `Replacement transaction ${minedHash} was mined, but its claim could not yet be verified. Check the swap status or transaction before submitting another claim.`,\n );\n }\n if (\n mined.to?.toLowerCase() !== tx.to.toLowerCase() ||\n mined.from.toLowerCase() !== signer.address.toLowerCase() ||\n mined.input.toLowerCase() !== tx.data.toLowerCase()\n ) {\n throw new Error(\n \"The wallet replaced or cancelled the claim transaction. The claim was not submitted; try again from the payout wallet.\",\n );\n }\n }\n return {\n id: swap.id,\n status: \"clientredeemed\",\n txHash: minedHash,\n message: `${native ? \"Claim\" : \"redeemAndExecute\"} published from wallet ${signer.address}`,\n };\n}\n","/**\n * Redeem module for Lendaswap swaps.\n *\n * Provides redeem/claim logic for completing swaps:\n * - Server-side gasless claims for Arkade/Lightning-to-EVM swaps\n * - Manual claiming with call data for other EVM swaps\n * - Arkade VHTLC claiming for EVM-to-Arkade swaps\n * - Coordinator redeemAndExecute for Arkade-to-EVM swaps\n */\n\nimport type { ArkadeToEvmSwapResponse } from \"../api/client.js\";\nimport { buildEthereumClaimData } from \"./ethereum.js\";\nimport {\n type ArkadeClaimData,\n type ClaimResult,\n type CoordinatorClaimData,\n getChainFromTokenId,\n getClaimChainFromChainName,\n type RedeemContext,\n} from \"./types.js\";\n\n// Re-export Arkade claim\nexport {\n type ArkadeClaimParams,\n type ArkadeClaimResult,\n buildArkadeClaim,\n continueArkadeClaim,\n} from \"./arkade.js\";\n// Re-export utilities from ethereum module\nexport { encodeClaimSwapCallData, uuidToBytes32 } from \"./ethereum.js\";\n// Re-export gasless claim\nexport { claimViaGasless, type GaslessClaimParams } from \"./gasless.js\";\nexport {\n claimNativeViaRifRelay,\n RIF_SMART_WALLET_INDEX,\n type RifRelayClaimParams,\n type RifRelayConfig,\n rifSmartWallet,\n rifSmartWalletAddress,\n WalletClaimRequiredError,\n} from \"./rif-relay.js\";\nexport { claimViaSigner, type SignerClaimParams } from \"./signer-claim.js\";\n// Re-export types\nexport type {\n ArkadeClaimData,\n ClaimChain,\n ClaimGaslessResult,\n ClaimResult,\n CoordinatorClaimData,\n EthereumClaimData,\n RedeemContext,\n} from \"./types.js\";\nexport { getChainFromTokenId } from \"./types.js\";\nexport {\n buildRedeemAndExecuteTx,\n claimViaUserOp,\n type RedeemTxParams,\n type UserOpClaimParams,\n} from \"./userop-claim.js\";\n\n/**\n * Claims a swap by revealing the preimage.\n *\n * The claim method depends on the swap direction and target chain:\n * - **Arkade/Lightning-to-EVM**: Server-side gasless claim via coordinator\n * - **Other EVM swaps**: Returns call data for manual claiming\n * - **Arkade**: Returns data needed for `buildArkadeClaim()`\n *\n * @param id - The UUID of the swap.\n * @param secret - The preimage/secret (32-byte hex string, with or without 0x prefix).\n * @param ctx - The context containing the API client and getSwap function.\n * @param destination - (Optional) EVM address for receiving tokens. Required for Arkade-to-EVM\n * swaps to fetch fresh DEX calldata.\n * @returns A ClaimResult with the outcome.\n *\n * @example\n * ```ts\n * const result = await claim(swapId, storedSwap.preimage, ctx, \"0x1234...\");\n * if (result.success) {\n * if (result.coordinatorClaimData) {\n * // Arkade/Lightning-to-EVM: gasless claim via server\n * console.log(\"TX Hash:\", result.txHash);\n * } else if (result.chain === \"arkade\") {\n * // Arkade claim needs user's keys\n * await buildArkadeClaim({ ...result.arkadeClaimData, ... });\n * } else {\n * // Manual EVM claim\n * console.log(\"Call data:\", result.ethereumClaimData?.callData);\n * }\n * }\n * ```\n */\nexport async function claim(\n id: string,\n secret: string,\n ctx: RedeemContext,\n destination?: string,\n): Promise<ClaimResult> {\n // Get the swap to determine target chain\n const swap = await ctx.getSwap(id);\n\n // Check if this is an arkade_to_evm swap (uses coordinator redeemAndExecute)\n if (\"direction\" in swap && swap.direction === \"arkade_to_evm\") {\n return buildCoordinatorClaimData(\n id,\n swap as unknown as ArkadeToEvmSwapResponse,\n ctx,\n destination,\n );\n }\n\n // target_token may be a string (TokenId) or object (TokenInfo with chain + token_id)\n const chain =\n typeof swap.target_token === \"object\" &&\n swap.target_token !== null &&\n \"chain\" in swap.target_token\n ? getClaimChainFromChainName(\n (swap.target_token as { chain: string }).chain,\n )\n : getChainFromTokenId(swap.target_token as string);\n\n if (!chain) {\n return {\n success: false,\n message: `Unknown target chain for token: ${JSON.stringify(swap.target_token)}. Cannot determine claim method.`,\n };\n }\n\n // Arkade claims return data for manual execution with user's keys\n if (chain === \"arkade\") {\n // For EVM-to-Arkade swaps, we need specific fields from the swap\n // @ts-expect-error\n const arkadeSwap = swap as {\n sender_pk: string;\n server_pk: string;\n network: string;\n unilateral_claim_delay?: number;\n unilateral_refund_delay?: number;\n unilateral_refund_without_receiver_delay?: number;\n htlc_address_arkade?: string;\n vhtlc_refund_locktime?: number;\n };\n return buildArkadeClaimData(arkadeSwap);\n }\n\n // EVM claims (Ethereum, Polygon, Arbitrum) return data for manual execution\n return buildEthereumClaimData(id, secret, swap, chain);\n}\n\n/**\n * Builds the claim data for an Arkade-to-EVM swap (coordinator redeemAndExecute).\n *\n * The user must:\n * 1. Build the EIP-712 digest using `buildRedeemDigest()` from `evm/coordinator`\n * 2. Sign the digest with their EVM wallet\n * 3. Build the transaction using `encodeRedeemAndExecute()`\n * 4. Submit the transaction to the coordinator contract\n *\n * @param id - The swap ID\n * @param swap - The swap response\n * @param ctx - The redeem context with API client\n * @param destination - Optional EVM address for receiving tokens. If provided and the swap\n * involves a DEX swap (target != WBTC), fresh calldata is fetched.\n */\nasync function buildCoordinatorClaimData(\n id: string,\n swap: ArkadeToEvmSwapResponse,\n ctx: RedeemContext,\n destination?: string,\n): Promise<ClaimResult> {\n // WBTC address from server response, fall back to well-known addresses\n const WBTC_BY_CHAIN_ID: Record<number, string> = {\n 137: \"0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6\", // Polygon\n 1: \"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599\", // Ethereum\n 42161: \"0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f\", // Arbitrum\n };\n const wbtcAddress = swap.wbtc_address ?? WBTC_BY_CHAIN_ID[swap.evm_chain_id];\n if (!wbtcAddress) {\n return {\n success: false,\n message: `Cannot determine WBTC address for chain ID ${swap.evm_chain_id}`,\n };\n }\n\n // target_token.token_id contains the ERC-20 contract address for the final token\n const targetTokenAddress = String(swap.target_token.token_id);\n\n // Check if this swap involves a DEX swap (target token is different from WBTC)\n const needsDexSwap =\n targetTokenAddress.toLowerCase() !== wbtcAddress.toLowerCase();\n\n let dexCallData: { to: string; data: string; value: string } | undefined;\n\n // Fetch fresh DEX calldata if destination is provided and swap needs DEX\n if (destination && needsDexSwap) {\n const response = await ctx.apiClient.GET(\n \"/swap/{id}/redeem-and-swap-calldata\",\n {\n params: {\n path: { id },\n query: { destination },\n },\n },\n );\n\n if (response.error) {\n return {\n success: false,\n message: `Failed to fetch DEX calldata: ${response.error.error || \"Unknown error\"}`,\n };\n }\n\n if (response.data.dex_calldata) {\n dexCallData = {\n to: response.data.dex_calldata.to,\n data: response.data.dex_calldata.data,\n value: response.data.dex_calldata.value,\n };\n }\n }\n\n const coordinatorClaimData: CoordinatorClaimData = {\n htlcAddress: swap.evm_htlc_address,\n coordinatorAddress: swap.evm_coordinator_address,\n chainId: swap.evm_chain_id,\n amount: swap.evm_expected_sats,\n wbtcAddress,\n sender: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n dexCallData,\n targetTokenAddress,\n network: swap.network,\n };\n\n const message = destination\n ? \"Arkade-to-EVM claims require EIP-712 signing. Use buildRedeemDigest() and encodeRedeemAndExecute() with the provided data.\"\n : \"Arkade-to-EVM claims require EIP-712 signing. Note: No destination provided - call claim() again with your EVM address to fetch fresh DEX calldata.\";\n\n return {\n success: true,\n message,\n coordinatorClaimData,\n };\n}\n\n/**\n * Builds the claim data for an Arkade swap (EVM-to-Arkade direction).\n *\n * For Arkade claims, the user needs to call `buildArkadeClaim` with their\n * secret key and destination address. This function extracts the necessary\n * parameters from the swap response.\n */\nfunction buildArkadeClaimData(swap: {\n sender_pk: string;\n server_pk: string;\n network: string;\n unilateral_claim_delay?: number;\n unilateral_refund_delay?: number;\n unilateral_refund_without_receiver_delay?: number;\n htlc_address_arkade?: string;\n vhtlc_refund_locktime?: number;\n}): ClaimResult {\n if (!swap.htlc_address_arkade) {\n return {\n success: false,\n message: \"Swap does not have an Arkade HTLC address.\",\n chain: \"arkade\",\n };\n }\n\n const arkadeClaimData: ArkadeClaimData = {\n lendaswapPubKey: swap.sender_pk,\n arkadeServerPubKey: swap.server_pk,\n vhtlcAddress: swap.htlc_address_arkade,\n refundLocktime: swap.vhtlc_refund_locktime ?? 0,\n unilateralClaimDelay: swap.unilateral_claim_delay ?? 0,\n unilateralRefundDelay: swap.unilateral_refund_delay ?? 0,\n unilateralRefundWithoutReceiverDelay:\n swap.unilateral_refund_without_receiver_delay ?? 0,\n network: swap.network,\n };\n\n return {\n success: true,\n message:\n \"Arkade claims require your secret key. Use buildArkadeClaim() with the provided data.\",\n chain: \"arkade\",\n arkadeClaimData,\n };\n}\n","/**\n * Collaborative refund for Arkade-to-EVM swaps.\n *\n * Unlike the `refundWithoutReceiver` path (which requires the CLTV locktime\n * to expire), the collaborative refund uses the `refund` script leaf — a\n * 3-of-3 multisig between sender (client), receiver (lendaswap), and the\n * Arkade server. Lendaswap cosigns via the backend collab-refund endpoint,\n * making the refund instant (no locktime wait).\n *\n * Two flows handle the two VTXO states:\n * - **Spendable VTXOs**: offchain send (one-shot submitTx; finalizeTx only on older arkd)\n * - **Recoverable / mixed VTXOs**: delegate batch (intent + forfeits → settle)\n */\n\nimport {\n ArkAddress,\n buildOffchainTx,\n CSVMultisigTapscript,\n combineTapscriptSigs,\n type IndexerProvider,\n networks,\n type OperatorProvider,\n Proof,\n RestIndexerProvider,\n RestOperatorProvider,\n SingleKey,\n setArkPsbtField,\n Transaction,\n type VHTLC,\n VtxoTaprootTree,\n} from \"@arkade-os/sdk\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { base64, hex } from \"@scure/base\";\nimport { Address, OutScript, SigHash } from \"@scure/btc-signer\";\n\nimport type { ApiClient } from \"../api/client.js\";\nimport {\n getNetworkHrp,\n getNetworkName,\n resolveArkadeServerUrlByName,\n} from \"../arkade-network.js\";\nimport { submitOffchainTxOneShot } from \"../arkade-submit.js\";\nimport {\n ARKADE_HTLC_SCRIPT_VERSION_STRICT,\n StrictVhtlcScript,\n} from \"../strict-vhtlc.js\";\n\n// P2A is the zero-value anchor output (OP_1 0x4e73)\nconst P2A_SCRIPT = new Uint8Array([0x51, 0x02, 0x4e, 0x73]);\nconst P2A = { script: P2A_SCRIPT, amount: 0n };\n\nfunction secondsToTimelock(\n seconds: number,\n): VHTLC.Options[\"unilateralClaimDelay\"] {\n return { type: \"seconds\" as const, value: BigInt(seconds) };\n}\n\nfunction parseXOnlyPubKey(pubKeyHex: string): Uint8Array {\n const bytes = hex.decode(pubKeyHex);\n if (bytes.length === 33) return bytes.slice(1);\n if (bytes.length === 32) return bytes;\n throw new Error(\n `Invalid public key length: expected 32 or 33, got ${bytes.length}`,\n );\n}\n\nfunction parsePreimageHash(hashLock: string): Uint8Array {\n const hashLockBytes = hex.decode(hashLock);\n if (hashLockBytes.length === 32) {\n return ripemd160(hashLockBytes);\n }\n if (hashLockBytes.length === 20) {\n return hashLockBytes;\n }\n throw new Error(\n `Invalid hash lock length: expected 20 or 32, got ${hashLockBytes.length}`,\n );\n}\n\nfunction formatApiError(error: unknown): string {\n if (typeof error === \"string\") return error;\n if (error && typeof error === \"object\") {\n if (\n \"error\" in error &&\n typeof (error as { error: unknown }).error === \"string\"\n ) {\n return (error as { error: string }).error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n // fall through\n }\n }\n return String(error);\n}\n\n/** Parameters for collaborative refund. */\ninterface BaseCollabRefundArkadeToEvmParams {\n userSecretKey: string;\n userPubKey: string;\n lendaswapPubKey: string;\n arkadeServerPubKey: string;\n hashLock: string;\n vhtlcAddress: string;\n refundLocktime: number;\n unilateralClaimDelay: number;\n unilateralRefundDelay: number;\n unilateralRefundWithoutReceiverDelay: number;\n destinationAddress: string;\n network: string;\n arkadeServerUrl?: string;\n swapId: string;\n apiClient: ApiClient;\n arkadeHtlcScriptVersion?: number;\n}\n\nexport type CollabRefundArkadeToEvmParams = BaseCollabRefundArkadeToEvmParams;\n\nexport interface CollabRefundArkadeToEvmResult {\n txId: string;\n refundAmount: bigint;\n}\n\n/**\n * Build the VHTLC script and verify the address matches.\n */\nfunction buildRefundScriptVhtlc(params: BaseCollabRefundArkadeToEvmParams) {\n const userPkBytes = parseXOnlyPubKey(params.userPubKey);\n const lendaswapPkBytes = parseXOnlyPubKey(params.lendaswapPubKey);\n const serverPkBytes = parseXOnlyPubKey(params.arkadeServerPubKey);\n const preimageHashBytes = parsePreimageHash(params.hashLock);\n\n const networkName = getNetworkName(params.network);\n\n const options = {\n sender: userPkBytes,\n receiver: lendaswapPkBytes,\n server: serverPkBytes,\n preimageHash: preimageHashBytes,\n refundLocktime: BigInt(params.refundLocktime),\n unilateralClaimDelay: secondsToTimelock(params.unilateralClaimDelay),\n unilateralRefundDelay: secondsToTimelock(params.unilateralRefundDelay),\n unilateralRefundWithoutReceiverDelay: secondsToTimelock(\n params.unilateralRefundWithoutReceiverDelay,\n ),\n };\n\n if (\n params.arkadeHtlcScriptVersion !== undefined &&\n params.arkadeHtlcScriptVersion !== ARKADE_HTLC_SCRIPT_VERSION_STRICT\n ) {\n throw new Error(\n `Unsupported Arkade HTLC script version: ${params.arkadeHtlcScriptVersion}`,\n );\n }\n const vhtlc = new StrictVhtlcScript(options);\n\n const hrp = getNetworkHrp(networkName);\n const computedAddress = vhtlc.address(hrp, serverPkBytes).encode();\n if (computedAddress !== params.vhtlcAddress) {\n throw new Error(\n `VHTLC address mismatch: computed ${computedAddress}, expected ${params.vhtlcAddress}`,\n );\n }\n\n return { vhtlc, networkName };\n}\n\n/**\n * Collaborative refund for spendable VTXOs.\n *\n * Uses the `refund` script leaf (3-of-3: sender + receiver + server).\n * The client signs as sender, POSTs to `/collab-refund` for lendaswap's\n * receiver signature, then submits to Arkade for the server signature.\n */\nexport async function collabRefundArkadeToEvmOffchain(\n params: BaseCollabRefundArkadeToEvmParams,\n): Promise<CollabRefundArkadeToEvmResult> {\n const { vhtlc, networkName } = buildRefundScriptVhtlc(params);\n\n const serverUrl = resolveArkadeServerUrlByName(\n networkName,\n params.arkadeServerUrl,\n );\n\n const arkProvider: OperatorProvider = new RestOperatorProvider(serverUrl);\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n const serverInfo = await arkProvider.getInfo();\n\n const vhtlcPkScript = hex.encode(vhtlc.pkScript);\n\n const { vtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n spendableOnly: true,\n });\n\n if (vtxos.length === 0) {\n throw new Error(\"No spendable VTXOs found at the VHTLC address\");\n }\n\n const totalAmount = vtxos.reduce((acc, v) => acc + BigInt(v.value), 0n);\n if (totalAmount === 0n) {\n throw new Error(\"Total VTXO amount is zero\");\n }\n\n const tapTree = vhtlc.encode();\n const refundLeafScript = vhtlc.refund();\n\n const checkpointTapscript = CSVMultisigTapscript.decode(\n hex.decode(serverInfo.checkpointTapscript),\n );\n\n const inputs = vtxos.map((v) => ({\n txid: v.txid,\n vout: v.vout,\n value: v.value,\n tapTree,\n tapLeafScript: refundLeafScript,\n }));\n\n const destination = ArkAddress.decode(params.destinationAddress);\n const outputs = [{ script: destination.pkScript, amount: totalAmount }];\n\n const { arkTx, checkpoints } = buildOffchainTx(\n inputs,\n outputs,\n checkpointTapscript,\n );\n\n // Snapshot checkpoint PSBTs BEFORE signing — signer.sign() may mutate\n // shared internal state between arkTx and checkpoints.\n const unsignedCheckpointPsbts = checkpoints.map((cp) =>\n base64.encode(cp.toPSBT()),\n );\n\n const signer = SingleKey.fromHex(params.userSecretKey);\n const signedArkTx = await signer.sign(arkTx);\n // Sign every checkpoint up front too (one-shot submit).\n const userSignedCheckpoints = await Promise.all(\n checkpoints.map((cp) => signer.sign(cp)),\n );\n\n // POST to lendaswap backend for receiver cosigning.\n // The backend cosigns both ark_tx (for the 3-of-3 refund leaf) and\n // checkpoint_txs (which also need the receiver signature).\n const collabRes = await params.apiClient.POST(\n \"/api/swap/arkade-evm/{id}/collab-refund\",\n {\n params: { path: { id: params.swapId } },\n body: {\n ark_tx: base64.encode(signedArkTx.toPSBT()),\n checkpoint_txs: unsignedCheckpointPsbts,\n },\n },\n );\n\n if (!collabRes.data) {\n throw new Error(\n `Collaborative refund cosign failed: ${formatApiError(collabRes.error)}`,\n );\n }\n\n // Merge the receiver's (lendaswap) checkpoint sigs into our own, so each\n // checkpoint carries both user-side sigs of the 3-of-3 before submit.\n const receiverCheckpoints = new Map(\n collabRes.data.checkpoint_txs.map((cp) => {\n const tx = Transaction.fromPSBT(base64.decode(cp));\n return [tx.id, tx] as const;\n }),\n );\n const fullySignedCheckpoints = userSignedCheckpoints.map((userSigned) => {\n const receiverSigned = receiverCheckpoints.get(userSigned.id);\n if (!receiverSigned) {\n throw new Error(\n `Collaborative refund cosign returned no checkpoint ${userSigned.id}`,\n );\n }\n return combineTapscriptSigs(receiverSigned, userSigned);\n });\n\n // The backend added the receiver sig to our signed ark tx; submit it with\n // the fully signed checkpoints. arkd finalizes in one call, or — if it is\n // too old for one-shot — the helper merges our sigs back and finalizes.\n const { arkTxid } = await submitOffchainTxOneShot(\n arkProvider,\n Transaction.fromPSBT(base64.decode(collabRes.data.ark_tx)),\n checkpoints,\n fullySignedCheckpoints,\n );\n\n return { txId: arkTxid, refundAmount: totalAmount };\n}\n\n/**\n * Collaborative refund for recoverable / mixed VTXOs via the delegate flow.\n *\n * Uses the `refund` script leaf. The client signs intent + forfeit PSBTs,\n * POSTs to `/collab-refund-delegate` for receiver cosigning, then settles\n * via `/delegate/settle`.\n */\nexport async function collabRefundArkadeToEvmDelegate(\n params: BaseCollabRefundArkadeToEvmParams,\n): Promise<{ commitmentTxid: string }> {\n const { vhtlc, networkName } = buildRefundScriptVhtlc(params);\n\n const serverUrl = resolveArkadeServerUrlByName(\n networkName,\n params.arkadeServerUrl,\n );\n\n const arkProvider: OperatorProvider = new RestOperatorProvider(serverUrl);\n const indexerProvider: IndexerProvider = new RestIndexerProvider(serverUrl);\n const serverInfo = await arkProvider.getInfo();\n\n // Fetch cosigner public key\n const cosignerRes = await params.apiClient.GET(\"/api/delegate/cosigner-pk\");\n if (!cosignerRes.data) {\n throw new Error(\n `Failed to fetch cosigner pk: ${formatApiError(cosignerRes.error)}`,\n );\n }\n const cosignerPkHex = cosignerRes.data.cosigner_pk;\n\n const btcNetwork = networks[networkName];\n const forfeitDecoded = Address(btcNetwork).decode(serverInfo.forfeitAddress);\n if (!forfeitDecoded) {\n throw new Error(\n `Unrecognised forfeit address: ${serverInfo.forfeitAddress}`,\n );\n }\n const forfeitPkScript = OutScript.encode(forfeitDecoded);\n\n const vhtlcPkScript = hex.encode(vhtlc.pkScript);\n\n const { vtxos: allVtxos } = await indexerProvider.getVtxos({\n scripts: [vhtlcPkScript],\n });\n const vtxos = allVtxos.filter((v) => !v.isSpent);\n\n if (vtxos.length === 0) {\n throw new Error(\"No settleable VTXOs found at the VHTLC address\");\n }\n\n const totalAmount = vtxos.reduce((acc, v) => acc + BigInt(v.value), 0n);\n if (totalAmount === 0n) {\n throw new Error(\"Total VTXO amount is zero\");\n }\n\n const destination = ArkAddress.decode(params.destinationAddress);\n\n const now = Math.floor(Date.now() / 1000);\n const intentMessage: Proof.RegisterMessage = {\n type: \"register\",\n onchain_output_indexes: [],\n valid_at: now,\n expire_at: now + 120,\n cosigners_public_keys: [cosignerPkHex],\n };\n\n const tapLeafScript = vhtlc.refund();\n const tapTree = vhtlc.encode();\n const pkScriptBytes = hex.decode(vhtlcPkScript);\n\n const intentInputs = vtxos.map((v) => ({\n txid: hex.decode(v.txid),\n index: v.vout,\n witnessUtxo: {\n script: pkScriptBytes,\n amount: BigInt(v.value),\n },\n tapLeafScript: [tapLeafScript],\n sighashType: SigHash.ALL,\n }));\n\n const intentProof = Proof.create(intentMessage, intentInputs, [\n { script: destination.pkScript, amount: totalAmount },\n ]);\n\n for (let i = 0; i < vtxos.length; i++) {\n setArkPsbtField(intentProof, i + 1, VtxoTaprootTree, tapTree);\n }\n\n const signer = SingleKey.fromHex(params.userSecretKey);\n const signedIntentProof = await signer.sign(intentProof);\n\n // Build forfeit PSBTs\n const dust = serverInfo.dust;\n const signedForfeitPsbts: string[] = [];\n\n for (const v of vtxos) {\n const vtxoAmount = BigInt(v.value);\n\n const forfeitTx = new Transaction({\n version: 3,\n lockTime: 0,\n });\n\n forfeitTx.addInput({\n txid: hex.decode(v.txid),\n index: v.vout,\n witnessUtxo: {\n script: pkScriptBytes,\n amount: vtxoAmount,\n },\n tapLeafScript: [tapLeafScript],\n sighashType: SigHash.ALL_ANYONECANPAY,\n });\n\n forfeitTx.addOutput({\n script: forfeitPkScript,\n amount: vtxoAmount + dust,\n });\n\n forfeitTx.addOutput(P2A);\n\n setArkPsbtField(forfeitTx, 0, VtxoTaprootTree, tapTree);\n\n const signedForfeit = await signer.sign(forfeitTx);\n signedForfeitPsbts.push(base64.encode(signedForfeit.toPSBT()));\n }\n\n // POST to lendaswap backend for receiver cosigning\n const collabRes = await params.apiClient.POST(\n \"/api/swap/arkade-evm/{id}/collab-refund-delegate\",\n {\n params: { path: { id: params.swapId } },\n body: {\n intent_proof: base64.encode(signedIntentProof.toPSBT()),\n forfeit_psbts: signedForfeitPsbts,\n },\n },\n );\n\n if (!collabRes.data) {\n throw new Error(\n `Collaborative delegate cosign failed: ${formatApiError(collabRes.error)}`,\n );\n }\n\n // Settle via delegate endpoint\n const settleRes = await params.apiClient.POST(\"/api/delegate/settle\", {\n body: {\n intent_proof: collabRes.data.intent_proof,\n intent_message: Proof.encodeMessage(intentMessage),\n forfeit_psbts: collabRes.data.forfeit_psbts,\n cosigner_pk: cosignerPkHex,\n swap_id: null,\n preimage: null,\n },\n });\n\n if (!settleRes.data) {\n throw new Error(\n `Delegate settle failed: ${formatApiError(settleRes.error)}`,\n );\n }\n\n return { commitmentTxid: settleRes.data.commitment_txid };\n}\n","/**\n * Type definitions for swap storage.\n *\n * These types define the schema for persisted swap data.\n * The version field enables schema migrations when the structure changes.\n */\n\nimport type { GetSwapResponse } from \"../api/client.js\";\nimport type { EvmFundingTerms } from \"../evm/funding-pins.js\";\n\n/** Current schema version for stored swaps */\nexport const SWAP_STORAGE_VERSION = 2;\n\n/** One entry of {@link StoredSwap.evmRehashes}. */\nexport interface EvmRehashRecord {\n /**\n * The `rehash` transaction. Empty while a sponsored move is sent but not\n * yet seen included; it is then followed only through the receipt its\n * {@link userOpHash} leads to, never inferred from the lock's state.\n */\n txid: string;\n /** The sponsored UserOp that carries the move, hashed before it is sent. */\n userOpHash?: string;\n /** The hash the lock was under before this move (0x-prefixed hex). */\n fromHashLock: string;\n /** The payment hash of the new invoice (0x-prefixed hex). */\n hashLock: string;\n /** The timelock the lock continues under (unix seconds). */\n timelock: number;\n}\n\n/**\n * The payment hash an EVM → Lightning swap's lock must use, fixed by this\n * client when it created the swap. See {@link StoredSwap.lightningPaymentHash}.\n */\nexport interface LightningPaymentHash {\n /** The payment hash (0x-prefixed hex). */\n hash: string;\n /**\n * `invoice`: read from the invoice the caller supplied, so the server had\n * no say in it. `server-invoice`: the swap was created from a Lightning\n * address or LNURL, which the server resolves; the hash was read from\n * the invoice it returned (checked against its `hash_lock` and payout\n * amount), so it is only as honest as that resolution.\n */\n source: \"invoice\" | \"server-invoice\";\n}\n\n/**\n * Extended swap data stored locally.\n *\n * Contains both the API response and client-side parameters needed\n * for claim/refund operations. This matches the Rust SDK's\n * `ExtendedSwapStorageData` pattern.\n *\n * @example\n * ```ts\n * const storedSwap: StoredSwap = {\n * version: SWAP_STORAGE_VERSION,\n * swapId: \"uuid-here\",\n * keyIndex: 0,\n * response: await client.getSwap(\"uuid-here\"),\n * publicKey: \"02...\",\n * preimage: \"abc123...\",\n * preimageHash: \"def456...\",\n * secretKey: \"789...\",\n * storedAt: Date.now(),\n * updatedAt: Date.now(),\n * };\n * ```\n */\nexport interface StoredSwap {\n /** Schema version for migrations */\n version: number;\n\n /** The swap ID (primary key) */\n swapId: string;\n\n /** Key derivation index used for this swap */\n keyIndex: number;\n\n /** Full API response from GetSwap endpoint */\n response: GetSwapResponse;\n\n /** Compressed public key (hex-encoded, 33 bytes) */\n publicKey: string;\n\n /** Preimage for claiming HTLCs (hex-encoded, 32 bytes) */\n preimage: string;\n\n /** SHA256 hash of preimage / hash lock (hex-encoded, 32 bytes) */\n preimageHash: string;\n\n /** Secret key for signing refund transactions (hex-encoded, 32 bytes) */\n secretKey: string;\n\n /** Timestamp when the swap was first stored locally (ms since epoch) */\n storedAt: number;\n\n /** Timestamp when the swap was last updated locally (ms since epoch) */\n updatedAt: number;\n\n /** Target address for receiving funds (e.g., BTC address for EVM→Bitcoin swaps) */\n targetAddress?: string;\n\n /**\n * Pinned CCTP bridge claim recipient for non-EVM destinations (Solana): the\n * destination USDC ATA (base58), resolved at create time. Lets a bare\n * `claim(swapId)` — e.g. the background auto-claim worker — route the burn\n * without the caller re-deriving it.\n */\n bridgeRecipient?: string;\n\n /**\n * The Solana wallet pubkey owning {@link bridgeRecipient}, pinned only when\n * the ATA still needs creation (`recipientSetup`) — its presence tells the\n * claim to use the ATA-creating forwarder variant, matching the bridge fee\n * committed at create time.\n */\n bridgeRecipientWallet?: string;\n\n /**\n * The tx this client knows funded an EVM-sourced swap: the one it sent\n * (corrected to the mined hash once the receipt is in), the relay\n * reported, or one a refund found through the server's copy. Kept beside\n * `response` because every server refresh replaces that copy, and the\n * server only learns the txid once its monitor has indexed the funding.\n * Since a refund may fill it from the server, it is only a hint: a rehash\n * trusts a funding receipt for what it shows under\n * {@link lightningPaymentHash}, whichever tx it came from.\n */\n evmFundTxid?: string;\n\n /**\n * For an EVM → Lightning swap, the payment hash this client fixed at\n * creation. Every funding path refuses to lock under any other hash (the\n * server could otherwise pick one whose preimage it knows and claim\n * without paying), and a rehash only moves a lock created under it. Kept\n * beside `response`, which every server refresh replaces; a swap without\n * it (recovered, or created by an older SDK) can be refunded but neither\n * funded nor retried. EVM → Bitcoin / Arkade swaps need no such field:\n * their hash is {@link preimageHash}, which this client generates.\n */\n lightningPaymentHash?: LightningPaymentHash;\n\n /**\n * For an EVM-sourced swap, the funding terms read from its creation\n * response: the coordinator (the only Permit2 spender this client signs\n * for), HTLC, claimer, timelock, tokens and input. Every funding payload\n * must match them and is signed from them; never updated from a later\n * server answer. A swap without it (recovered, or created by an older\n * SDK) can be refunded but not funded.\n */\n evmFundingTerms?: EvmFundingTerms;\n\n /** The HTLCCoordinator the funding went through; pins the refund target. */\n evmCoordinatorAddress?: string;\n\n /**\n * The rehashes this client sent for an EVM → Lightning swap, oldest\n * first: each moves the lock from `fromHashLock` to `hashLock` /\n * `timelock` in `txid`. Kept beside `response` because the server's copy\n * switches hash and funding tx once its monitor confirms a move, while a\n * refund is built from the funding tx's `SwapCreated` under the first\n * entry's `fromHashLock`, followed through each `SwapRehashed`.\n */\n evmRehashes?: EvmRehashRecord[];\n\n /**\n * Source-chain CCTP burn of a CCTP-inbound swap, recorded as soon as it is\n * broadcast. The USDC has left the source chain from then on: `fundSwap`\n * resumes the Arbitrum settlement from it instead of burning again, and\n * `recoverCctpInboundSwap` recovers the USDC with it if settlement fails.\n */\n cctpBurnTxid?: string;\n\n /**\n * The last block height at which a Solana {@link cctpBurnTxid} can land.\n * Resuming gives the burn up only once the chain is past it, so an RPC that\n * cannot find an older burn never causes a second one.\n */\n cctpBurnLastValidBlockHeight?: number;\n}\n","/**\n * Storage module for persisting wallet and swap data.\n *\n * This module provides a pluggable storage interface that can be implemented\n * for different backends (IndexedDB, SQLite, etc.).\n */\n\nimport type { GetSwapResponse } from \"../api/client.js\";\nimport type { StoredSwap } from \"./types.js\";\n\nexport type {\n EvmRehashRecord,\n LightningPaymentHash,\n StoredSwap,\n} from \"./types.js\";\nexport { SWAP_STORAGE_VERSION } from \"./types.js\";\n\n/**\n * Storage interface for wallet data (mnemonic, key index).\n *\n * Implementations should handle persistence of sensitive wallet data.\n * For browser environments, consider using IndexedDB with encryption.\n * For desktop/mobile, consider using SQLite with secure storage.\n */\nexport interface WalletStorage {\n /**\n * Get the stored mnemonic phrase.\n * @returns The mnemonic phrase, or null if not stored.\n */\n getMnemonic(): Promise<string | null>;\n\n /**\n * Store the mnemonic phrase.\n * @param mnemonic - The mnemonic phrase to store.\n */\n setMnemonic(mnemonic: string): Promise<void>;\n\n /**\n * Get the current key derivation index.\n * @returns The current key index, defaults to 0 if not set.\n */\n getKeyIndex(): Promise<number>;\n\n /**\n * Set the key derivation index.\n * @param index - The new key index.\n */\n setKeyIndex(index: number): Promise<void>;\n\n /**\n * Increment and return the current key index.\n * @returns The index before incrementing (the one to use).\n */\n incrementKeyIndex(): Promise<number>;\n\n /**\n * Clear all wallet data from storage.\n */\n clear(): Promise<void>;\n}\n\n/**\n * Storage interface for swap data.\n *\n * Stores `StoredSwap` records which contain both the API response\n * and client-side parameters needed for claim/refund operations.\n */\nexport interface SwapStorage {\n /**\n * Get swap data by ID.\n * @param swapId - The swap ID.\n * @returns The stored swap data, or null if not found.\n */\n get(swapId: string): Promise<StoredSwap | null>;\n\n /**\n * Store a new swap.\n * @param swap - The swap data to store (must include swapId).\n */\n store(swap: StoredSwap): Promise<void>;\n\n /**\n * Update an existing swap's API response.\n * @param swapId - The swap ID.\n * @param response - The updated API response.\n * @throws Error if swap is not found.\n */\n update(swapId: string, response: GetSwapResponse): Promise<void>;\n\n /**\n * Delete swap data by ID.\n * @param swapId - The swap ID.\n */\n delete(swapId: string): Promise<void>;\n\n /**\n * List all swap IDs.\n * @returns Array of swap IDs.\n */\n list(): Promise<string[]>;\n\n /**\n * Get all stored swaps.\n * @returns Array of all stored swap data.\n */\n getAll(): Promise<StoredSwap[]>;\n\n /**\n * Clear all swap data from storage.\n */\n clear(): Promise<void>;\n}\n\n/**\n * In-memory implementation of WalletStorage.\n *\n * Useful for testing or temporary sessions where persistence is not required.\n * Data is lost when the application is closed.\n *\n * @example\n * ```ts\n * const storage = new InMemoryWalletStorage();\n * await storage.setMnemonic(\"your mnemonic phrase\");\n * ```\n */\nexport class InMemoryWalletStorage implements WalletStorage {\n #mnemonic: string | null = null;\n #keyIndex = 0;\n\n async getMnemonic(): Promise<string | null> {\n return this.#mnemonic;\n }\n\n async setMnemonic(mnemonic: string): Promise<void> {\n this.#mnemonic = mnemonic;\n }\n\n async getKeyIndex(): Promise<number> {\n return this.#keyIndex;\n }\n\n async setKeyIndex(index: number): Promise<void> {\n this.#keyIndex = index;\n }\n\n async incrementKeyIndex(): Promise<number> {\n const current = this.#keyIndex;\n this.#keyIndex = current + 1;\n return current;\n }\n\n async clear(): Promise<void> {\n this.#mnemonic = null;\n this.#keyIndex = 0;\n }\n}\n\n/**\n * In-memory implementation of SwapStorage.\n *\n * Useful for testing or temporary sessions where persistence is not required.\n * Data is lost when the application is closed.\n *\n * @example\n * ```ts\n * const storage = new InMemorySwapStorage();\n * await storage.store({ swapId: \"swap-id\", ... });\n * ```\n */\nexport class InMemorySwapStorage implements SwapStorage {\n readonly #data = new Map<string, StoredSwap>();\n\n async get(swapId: string): Promise<StoredSwap | null> {\n return this.#data.get(swapId) ?? null;\n }\n\n async store(swap: StoredSwap): Promise<void> {\n this.#data.set(swap.swapId, swap);\n }\n\n async update(swapId: string, response: GetSwapResponse): Promise<void> {\n const existing = this.#data.get(swapId);\n if (!existing) {\n throw new Error(`Swap not found: ${swapId}`);\n }\n this.#data.set(swapId, {\n ...existing,\n response,\n updatedAt: Date.now(),\n });\n }\n\n async delete(swapId: string): Promise<void> {\n this.#data.delete(swapId);\n }\n\n async list(): Promise<string[]> {\n return Array.from(this.#data.keys());\n }\n\n async getAll(): Promise<StoredSwap[]> {\n return Array.from(this.#data.values());\n }\n\n async clear(): Promise<void> {\n this.#data.clear();\n }\n}\n\n/**\n * Factory function type for creating storage instances.\n *\n * This allows the Client to accept different storage backends.\n */\nexport type StorageFactory = {\n createWalletStorage: () => WalletStorage;\n createSwapStorage: () => SwapStorage;\n};\n\n/**\n * In-memory storage factory.\n *\n * Creates in-memory storage instances for testing or temporary sessions.\n */\nexport const inMemoryStorageFactory: StorageFactory = {\n createWalletStorage: () => new InMemoryWalletStorage(),\n createSwapStorage: () => new InMemorySwapStorage(),\n};\n","/**\n * `ChainConfigResponse` — per-EVM-chain metadata clients need that the\n * protocol doesn't otherwise surface (BTC-pegged pivot today; HTLC and\n * coordinator contract addresses planned). Static per session.\n *\n * Hand-written; identity-shaped with the OpenAPI codegen today.\n */\nimport type { RifRelayConfig } from \"../redeem/rif-relay.js\";\nimport type { Chain } from \"./chain.js\";\n\nexport interface TokenRef {\n /** Lowercase hex, `0x`-prefixed. */\n address: string;\n decimals: number;\n symbol: string;\n}\n\nexport interface ChainConfigEntry {\n /** EVM chain id as a string (`\"1\"`, `\"137\"`, `\"42161\"`). */\n chain: Chain;\n /**\n * The chain's BTC-pegged token (tBTC v2 on Arbitrum / Ethereum, WBTC\n * on Polygon). Used as the DEX pivot when composing a quote for any\n * BTC↔this-chain pair.\n */\n btc_pegged_token: TokenRef;\n /**\n * How many `btc_pegged_token` units equal 1 BTC, as a decimal string.\n * `\"1\"` for tBTC (1:1 redeemable); the live WBTC/BTC rate (~0.998) for\n * WBTC. Used for the direct BTC↔pegged conversion (the leg with no DEX\n * hop): multiply BTC sats by this, then scale by the token's decimals.\n * Slow-moving but not static — refresh on the same cadence as a quote.\n */\n btc_peg_rate: string;\n /**\n * Where a native lock on this chain is claimed: RIF Relay, from a smart\n * wallet owned by the claim destination, relayer paid out of the claimed\n * coin. Absent on Rootstock = the payout wallet submits and pays gas.\n */\n rif_relay?: RifRelayConfig;\n}\n\nexport interface ChainConfigResponse {\n chains: ChainConfigEntry[];\n}\n\n// -- wire shapes (identity for now) --\n\nexport interface WireTokenRef {\n address: string;\n decimals: number;\n symbol: string;\n}\n\nexport interface WireChainConfigEntry {\n chain: Chain;\n btc_pegged_token: WireTokenRef;\n btc_peg_rate: string;\n rif_relay?: RifRelayConfig | null;\n}\n\nexport interface WireChainConfigResponse {\n chains: WireChainConfigEntry[];\n}\n\nexport function fromWireChainConfigResponse(\n wire: WireChainConfigResponse,\n): ChainConfigResponse {\n return {\n chains: wire.chains.map((c) => ({\n chain: c.chain,\n btc_pegged_token: {\n address: c.btc_pegged_token.address,\n decimals: c.btc_pegged_token.decimals,\n symbol: c.btc_pegged_token.symbol,\n },\n btc_peg_rate: c.btc_peg_rate,\n ...(c.rif_relay ? { rif_relay: { ...c.rif_relay } } : {}),\n })),\n };\n}\n","/**\n * `DexQuoteResponse` — DEX-leg pricing for a same-chain EVM swap.\n *\n * Hand-written; identity-shaped with the OpenAPI codegen today. The\n * shape covers the response of `POST /dex-quote` plus a `Token` /\n * `TokenAmount` / `DexQuoteAmount` value type the request and response\n * share.\n */\n\n/**\n * Asset identifier. EVM today; Solana variant reserved for future use.\n *\n * Tagged on `kind` so consumers can switch and the type widens\n * additively as new chain kinds land.\n */\nexport type Token =\n | { kind: \"evm\"; chain_id: number; address: string }\n | { kind: \"solana\"; address: string };\n\n/**\n * Pinned-side amount on the wire — direction + smallest-unit value.\n */\nexport type DexQuoteAmount =\n | { kind: \"exact_in\"; value: string }\n | { kind: \"exact_out\"; value: string };\n\n/**\n * Smallest-unit amount paired with the associated token's symbol and\n * decimal places.\n */\nexport interface TokenAmount {\n raw: string;\n decimals: number;\n symbol?: string;\n}\n\n/**\n * The bridge protocol a {@link BridgeRate} is for — the `router` discriminant\n * of the union. Switch on it exhaustively.\n */\nexport type BridgeRouter = \"cctp\" | \"layerzero\";\n\n/**\n * Fee model for the cross-chain bridge leg of a quote, tagged by protocol\n * (`router`). Present for any bridged quote; each protocol is a variant with\n * exactly its own fields, so `switch` on `router` rather than assuming a shape.\n *\n * The bridge settles inside the single Arbitrum `Call[]` the SDK submits (no\n * extra user op) — this just says what (if anything) to subtract from the\n * DEX-leg output to get the delivered amount.\n *\n * - **`cctp`**: Circle's Forwarding Service deducts a percentage\n * (`proportional_fee_millionths`) + a flat fee (`flat` / `flat_with_setup`) from the\n * bridged USDC.\n * - **`layerzero`**: no token-denominated deduction — the bridged USDT0\n * arrives in full. The messaging fee is ETH the server pays on the claim and\n * charges in sats (`native_fee_sats`), added to the quote's network fee.\n */\nexport type BridgeRate =\n | {\n router: \"cctp\";\n /**\n * The token every amount in this variant is denominated in\n * (`flat`, `flat_with_setup`, and the `amount` the percentage applies\n * to) — the remote bridged USDC from the request. Check it matches the\n * token you're deducting from before applying; a future asset-denominated\n * fee would need a conversion.\n */\n fee_token: Token;\n /**\n * CCTP percentage fee rate in **millionths** (parts per million): apply\n * as `floor(amount * proportional_fee_millionths / 1_000_000)`. It's Circle's\n * `minimumFee` (basis points, e.g. `1.3`) pre-scaled ×100 to a clean\n * integer — `round(minimumFee_bps * 100)`. E.g. `\"130\"` = 1.3 bps =\n * 0.013% = `130 / 1_000_000`. Stringified u128.\n */\n proportional_fee_millionths: string;\n /** Flat USDC fee deducted from the bridged amount, recipient already provisioned. Outbound: `forwardFee.high`; inbound: `\"0\"`. Stringified u64. */\n flat: string;\n /** Flat-fee variant including a fresh non-EVM recipient's ATA rent (Solana). Equals `flat` otherwise; same units. Stringified u64. */\n flat_with_setup: string;\n }\n | {\n router: \"layerzero\";\n /** LayerZero messaging fee in sats (the live ETH fee converted at the current rate); add it to the network fee. Stringified u64. */\n native_fee_sats: string;\n };\n\nexport interface DexQuoteResponse {\n /** End-to-end input amount the user sends (incl. any bridge gross-up for exact-out). */\n expected_amount_in: TokenAmount;\n /** End-to-end output amount the user receives (net of any bridge fee for exact-in). */\n estimated_amount_out: TokenAmount;\n /** Rough end-to-end settlement ETA in seconds; `0` for a same-chain swap. */\n estimated_settlement_seconds: number;\n /** Router that priced the DEX leg (`\"uniswap_v3\"`, `\"lifi\"`, …). Informational. */\n router: string;\n cache_ttl_seconds: number;\n /**\n * Cross-chain bridge fee model, tagged by protocol. Present for any bridged\n * quote — `{ router: \"cctp\", … }` (a USDC deduction) or\n * `{ router: \"layerzero\", … }` (a sats fee, no deduction); `undefined` only for plain\n * same-chain quotes.\n */\n bridge_rate?: BridgeRate;\n /**\n * The bridge fee actually deducted for this quote, in the bridged token's\n * smallest units (USDC for CCTP), stringified. Already reflected in the\n * end-to-end amounts above — surfaced so the SDK can report it as a line\n * item. `undefined` for same-chain and OFT.\n */\n bridge_fee?: string;\n}\n\n// -- wire shapes (identical to the SDK types for now; explicit so we\n// can let the wire diverge later without touching SDK call sites) --\n\nexport type WireToken = Token;\nexport type WireDexQuoteAmount = DexQuoteAmount;\n\nexport interface WireTokenAmount {\n raw: string;\n decimals: number;\n symbol?: string | null;\n}\n\nexport type WireBridgeRate =\n | {\n router: \"cctp\";\n fee_token: WireToken;\n proportional_fee_millionths: string;\n flat: string;\n flat_with_setup: string;\n }\n | { router: \"layerzero\"; native_fee_sats: string };\n\nexport interface WireDexQuoteResponse {\n expected_amount_in: WireTokenAmount;\n estimated_amount_out: WireTokenAmount;\n estimated_settlement_seconds: number;\n router: string;\n cache_ttl_seconds: number;\n bridge_rate?: WireBridgeRate | null;\n bridge_fee?: string | null;\n}\n\nfunction fromWireTokenAmount(wire: WireTokenAmount): TokenAmount {\n return {\n raw: wire.raw,\n decimals: wire.decimals,\n symbol: wire.symbol ?? undefined,\n };\n}\n\nexport function fromWireDexQuoteResponse(\n wire: WireDexQuoteResponse,\n): DexQuoteResponse {\n return {\n expected_amount_in: fromWireTokenAmount(wire.expected_amount_in),\n estimated_amount_out: fromWireTokenAmount(wire.estimated_amount_out),\n estimated_settlement_seconds: wire.estimated_settlement_seconds,\n router: wire.router,\n cache_ttl_seconds: wire.cache_ttl_seconds,\n bridge_rate: wire.bridge_rate\n ? fromWireBridgeRate(wire.bridge_rate)\n : undefined,\n bridge_fee: wire.bridge_fee ?? undefined,\n };\n}\n\nfunction fromWireBridgeRate(wire: WireBridgeRate): BridgeRate {\n if (wire.router === \"cctp\") {\n return {\n router: \"cctp\",\n fee_token: wire.fee_token,\n proportional_fee_millionths: wire.proportional_fee_millionths,\n flat: wire.flat,\n flat_with_setup: wire.flat_with_setup,\n };\n }\n return { router: \"layerzero\", native_fee_sats: wire.native_fee_sats };\n}\n","/**\n * `NetworkFeesResponse` — per-pair gas/mining sats at current prices.\n *\n * Hand-written; identity-shaped with the OpenAPI codegen today.\n */\nimport type { Chain } from \"./chain.js\";\n\nexport interface NetworkFee {\n /**\n * Sats incurred on the source chain (BTC mining when source is\n * Bitcoin; EVM gas-to-sats for HTLC claim when source is an EVM\n * chain; `0` for Arkade / Lightning).\n */\n source_sats: number;\n /**\n * Sats incurred on the target chain (EVM gas-to-sats for HTLC create\n * when target is an EVM chain; BTC mining when target is Bitcoin;\n * `0` for Arkade / Lightning).\n */\n target_sats: number;\n}\n\nexport interface NetworkFeePairEntry {\n source: Chain;\n target: Chain;\n fees: NetworkFee;\n}\n\nexport interface NetworkFeesResponse {\n pairs: NetworkFeePairEntry[];\n}\n\nexport interface WireNetworkFee {\n source_sats: number;\n target_sats: number;\n}\n\nexport interface WireNetworkFeePairEntry {\n source: Chain;\n target: Chain;\n fees: WireNetworkFee;\n}\n\nexport interface WireNetworkFeesResponse {\n pairs: WireNetworkFeePairEntry[];\n}\n\nexport function fromWireNetworkFeePairEntry(\n wire: WireNetworkFeePairEntry,\n): NetworkFeePairEntry {\n return {\n source: wire.source,\n target: wire.target,\n fees: {\n source_sats: wire.fees.source_sats,\n target_sats: wire.fees.target_sats,\n },\n };\n}\n\nexport function fromWireNetworkFeesResponse(\n wire: WireNetworkFeesResponse,\n): NetworkFeesResponse {\n return { pairs: wire.pairs.map(fromWireNetworkFeePairEntry) };\n}\n","/**\n * `QuoteResponse` — end-to-end pricing for a swap between BTC and an\n * EVM/Arkade/Lightning target.\n *\n * Hand-written rather than re-exported from the OpenAPI codegen so the\n * SDK surface stays stable across wire-format evolution. The shape is\n * currently identity-mapped with what `GET /quote` returns; future\n * SDK-only additions land here as `?:` fields without requiring a\n * server-side schema bump.\n *\n * Numeric u64 fields ship as plain `number` (the wire serializes them as\n * JSON numbers, and BTC sats easily fit under 2^53). Stringified u128\n * fields (`source_amount`, `target_amount`, …) ship as `string` to dodge\n * the JS `Number` precision cliff for 18-decimal tokens.\n */\nexport interface QuoteResponse {\n /** Exchange rate: how much of the EVM token you get/pay per BTC. */\n exchange_rate: string;\n /**\n * Network fee estimate (in satoshis) — covers server-paid gas for\n * HTLC create/claim + BTC mining fee when applicable.\n */\n network_fee: number;\n /**\n * Gasless network fee estimate (in satoshis) — covers the additional\n * gas the server pays to execute the DEX swap on behalf of the user\n * (redeemAndExecute via the coordinator contract).\n */\n gasless_network_fee: number;\n /** Protocol fee (in satoshis). */\n protocol_fee: number;\n /** Protocol fee rate (as decimal, e.g., 0.0025 = 0.25%). */\n protocol_fee_rate: number;\n /** Minimum BTC value of the swap in satoshis. */\n min_amount: number;\n /** Maximum BTC value of the swap in satoshis. */\n max_amount: number;\n /** Pre-calculated source amount in smallest unit of source token (pre-fee). */\n source_amount: string;\n /** Pre-calculated target amount in smallest unit of target token (pre-fee). */\n target_amount: string;\n /**\n * Net source amount: what the user actually sends including all fees.\n * Equals `source_amount` when the user provided `source_amount`;\n * otherwise `source_amount + fees_in_source_units`.\n */\n net_source_amount: string;\n /**\n * Net target amount: what the user actually receives after all fees.\n * Equals `target_amount` when the user provided `target_amount`;\n * otherwise `target_amount - fees_in_target_units`.\n */\n net_target_amount: string;\n /**\n * Token-denominated bridge fee (6 decimals for USDC or Tron USDT).\n * Only present when `bridge_target_chain` was specified in the quote\n * request, or for inbound CCTP swaps.\n */\n bridge_fee?: number | null;\n}\n\n/**\n * Wire payload shape for `GET /quote` — matches the OpenAPI-generated\n * type. Internal use only.\n */\nexport interface WireQuoteResponse {\n exchange_rate: string;\n network_fee: number;\n gasless_network_fee: number;\n protocol_fee: number;\n protocol_fee_rate: number;\n min_amount: number;\n max_amount: number;\n source_amount: string;\n target_amount: string;\n net_source_amount: string;\n net_target_amount: string;\n bridge_fee?: number | null;\n}\n\n/**\n * Translate the wire payload into the SDK-facing type.\n *\n * Identity-shaped today. Lives as a function (not just a cast) so future\n * wire-vs-SDK divergence (renames, type changes, normalization) has an\n * obvious place to land without touching call sites.\n */\nexport function fromWireQuoteResponse(wire: WireQuoteResponse): QuoteResponse {\n return {\n exchange_rate: wire.exchange_rate,\n network_fee: wire.network_fee,\n gasless_network_fee: wire.gasless_network_fee,\n protocol_fee: wire.protocol_fee,\n protocol_fee_rate: wire.protocol_fee_rate,\n min_amount: wire.min_amount,\n max_amount: wire.max_amount,\n source_amount: wire.source_amount,\n target_amount: wire.target_amount,\n net_source_amount: wire.net_source_amount,\n net_target_amount: wire.net_target_amount,\n bridge_fee: wire.bridge_fee ?? undefined,\n };\n}\n","/**\n * `ReferralFeeResponse` — the referral / extra-fee delta for a referral code.\n *\n * Hand-written; identity-shaped with the OpenAPI codegen today. The fourth\n * quote-composition primitive: `compose` adds `extra_fee_rate` on top of the\n * per-pair `fee_percentage` from `/swap-pairs`.\n */\n\nexport interface ReferralFeeResponse {\n /**\n * Extra fee as a **decimal fraction** (e.g. `0.005` = 0.5% = 50 bps), added\n * on top of the per-pair `fee_percentage` (also a fraction) — compose as\n * `fee_percentage + extra_fee_rate`, no conversion. `0` when there's\n * no/unknown referral and no `extraFees`. (The input `extraFees` is in bps;\n * this output is a fraction — the server converts once.)\n */\n extra_fee_rate: number;\n /**\n * Negotiated base fee as a decimal fraction. When present it **replaces**\n * the per-pair `fee_percentage` before `extra_fee_rate` is added; absent\n * means the pair fee applies.\n */\n base_fee_rate?: number;\n /** Partner label for the referral code, when registered. Informational. */\n referral_label?: string;\n}\n\nexport interface WireReferralFeeResponse {\n extra_fee_rate: number;\n base_fee_rate?: number | null;\n referral_label?: string | null;\n}\n\nexport function fromWireReferralFeeResponse(\n wire: WireReferralFeeResponse,\n): ReferralFeeResponse {\n return {\n extra_fee_rate: wire.extra_fee_rate,\n base_fee_rate: wire.base_fee_rate ?? undefined,\n referral_label: wire.referral_label ?? undefined,\n };\n}\n","/**\n * `SwapPairsResponse` — supported swap routes with limits and base\n * protocol fee per pair.\n *\n * Hand-written; identity-shaped with the OpenAPI codegen today.\n */\nimport type { Chain } from \"./chain.js\";\n\nexport interface SwapPairInfo {\n source: Chain;\n target: Chain;\n /** Minimum BTC amount in satoshis. */\n min_sats: number;\n /** Maximum BTC amount in satoshis. */\n max_sats: number;\n /**\n * Fee percentage as a decimal (e.g. 0.0025 = 0.25%).\n */\n fee_percentage: number;\n /**\n * Flat network fee in satoshis charged on every swap of this pair on\n * top of `fee_percentage` (`0` for pairs that do not charge one).\n */\n network_fee_sats: number;\n}\n\nexport interface SwapPairsResponse {\n pairs: SwapPairInfo[];\n}\n\nexport interface WireSwapPairInfo {\n source: Chain;\n target: Chain;\n min_sats: number;\n max_sats: number;\n fee_percentage: number;\n network_fee_sats: number;\n}\n\nexport interface WireSwapPairsResponse {\n pairs: WireSwapPairInfo[];\n}\n\nexport function fromWireSwapPairInfo(wire: WireSwapPairInfo): SwapPairInfo {\n return {\n source: wire.source,\n target: wire.target,\n min_sats: wire.min_sats,\n max_sats: wire.max_sats,\n fee_percentage: wire.fee_percentage,\n network_fee_sats: wire.network_fee_sats,\n };\n}\n\nexport function fromWireSwapPairsResponse(\n wire: WireSwapPairsResponse,\n): SwapPairsResponse {\n return { pairs: wire.pairs.map(fromWireSwapPairInfo) };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { base58check } from \"@scure/base\";\n\n/** Decode and validate the Base58Check recipient before it reaches a signing flow. */\nexport function tronAddressToBytes32(address: string): `0x${string}` {\n if (address.length !== 34) throw new Error(\"Invalid Tron address length\");\n const decoded = base58check(sha256).decode(address);\n if (decoded.length !== 21 || decoded[0] !== 0x41) {\n throw new Error(\"Invalid Tron address prefix\");\n }\n const account = decoded.slice(1);\n if (account.every((b) => b === 0))\n throw new Error(\"Zero Tron recipient is not allowed\");\n return `0x${Array.from(account, (b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n .padStart(64, \"0\")}`;\n}\n\nexport function isValidTronAddress(address: string): boolean {\n try {\n tronAddressToBytes32(address);\n return true;\n } catch {\n return false;\n }\n}\n","import type { SwapStatus } from \"./api/client.js\";\n\nexport type SwapStatusHandler = (swapId: string, status: SwapStatus) => void;\n\nexport interface SwapStatusWatcher {\n /**\n * Subscribe to status updates for the given swap ids. `onUpdate` fires for\n * every status change of any id in the set. Returns an unsubscribe function\n * that removes this handler from all of the passed ids at once (equivalent\n * to calling `unsubscribe(ids, onUpdate)`).\n */\n subscribe(ids: string[], onUpdate: SwapStatusHandler): () => void;\n /**\n * Remove `onUpdate` from the given swap ids. Any id whose subscriber set\n * becomes empty is unsubscribed on the wire; the socket closes once no ids\n * remain. No-op if `onUpdate` wasn't registered for those ids.\n */\n unsubscribe(ids: string[], onUpdate: SwapStatusHandler): void;\n /** Force-close the socket and drop all subscribers. */\n close(): void;\n}\n\nconst MIN_RECONNECT_MS = 1000;\nconst MAX_RECONNECT_MS = 30000;\n\ntype Channel = \"swap_status\";\n\ninterface SubscribeFrame {\n op: \"subscribe\";\n channel: Channel;\n args: string[];\n}\n\ninterface UnsubscribeFrame {\n op: \"unsubscribe\";\n channel: Channel;\n args: string[];\n}\n\ninterface DataFrame {\n channel: Channel;\n data: Record<string, SwapStatus>;\n}\n\ninterface AckFrame {\n op: \"subscribed\" | \"unsubscribed\";\n channel: Channel;\n args: string[];\n}\n\ninterface ErrorFrame {\n op: string;\n message: string;\n}\n\nfunction httpToWs(baseUrl: string): string {\n const url = baseUrl.replace(/\\/$/, \"\");\n if (url.startsWith(\"https://\"))\n return `wss://${url.slice(\"https://\".length)}/ws`;\n if (url.startsWith(\"http://\"))\n return `ws://${url.slice(\"http://\".length)}/ws`;\n return `${url}/ws`;\n}\n\nexport function createSwapStatusWatcher(baseUrl: string): SwapStatusWatcher {\n const url = httpToWs(baseUrl);\n const subscribers = new Map<string, Set<SwapStatusHandler>>();\n let socket: WebSocket | null = null;\n let reconnectAttempt = 0;\n let reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n let closingIntentionally = false;\n\n function ensureSocket(): void {\n if (socket && socket.readyState !== WebSocket.CLOSED) return;\n closingIntentionally = false;\n socket = new WebSocket(url);\n\n socket.addEventListener(\"open\", () => {\n reconnectAttempt = 0;\n const ids = Array.from(subscribers.keys());\n if (ids.length > 0) sendSubscribe(ids);\n });\n\n socket.addEventListener(\"message\", (evt) => {\n let parsed: DataFrame | AckFrame | ErrorFrame;\n try {\n parsed = JSON.parse(evt.data as string);\n } catch {\n return;\n }\n if (\"data\" in parsed && parsed.channel === \"swap_status\") {\n for (const [swapId, status] of Object.entries(parsed.data)) {\n const set = subscribers.get(swapId);\n if (set) {\n for (const cb of set) cb(swapId, status);\n }\n }\n }\n });\n\n socket.addEventListener(\"close\", () => {\n socket = null;\n if (closingIntentionally || subscribers.size === 0) return;\n scheduleReconnect();\n });\n\n socket.addEventListener(\"error\", () => {\n try {\n socket?.close();\n } catch {}\n });\n }\n\n function scheduleReconnect(): void {\n if (reconnectTimer) return;\n const delay = Math.min(\n MAX_RECONNECT_MS,\n MIN_RECONNECT_MS * 2 ** reconnectAttempt,\n );\n reconnectAttempt += 1;\n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n if (subscribers.size > 0) ensureSocket();\n }, delay);\n }\n\n function sendSubscribe(ids: string[]): void {\n if (ids.length === 0 || socket?.readyState !== WebSocket.OPEN) return;\n const frame: SubscribeFrame = {\n op: \"subscribe\",\n channel: \"swap_status\",\n args: ids,\n };\n socket.send(JSON.stringify(frame));\n }\n\n function sendUnsubscribe(ids: string[]): void {\n if (ids.length === 0 || socket?.readyState !== WebSocket.OPEN) return;\n const frame: UnsubscribeFrame = {\n op: \"unsubscribe\",\n channel: \"swap_status\",\n args: ids,\n };\n socket.send(JSON.stringify(frame));\n }\n\n function closeIfIdle(): void {\n if (subscribers.size > 0) return;\n closingIntentionally = true;\n if (reconnectTimer) {\n clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n try {\n socket?.close();\n } catch {}\n socket = null;\n }\n\n function unsubscribe(ids: string[], onUpdate: SwapStatusHandler): void {\n const toUnsubscribe: string[] = [];\n for (const id of ids) {\n const set = subscribers.get(id);\n if (!set) continue;\n set.delete(onUpdate);\n if (set.size === 0) {\n subscribers.delete(id);\n toUnsubscribe.push(id);\n }\n }\n if (toUnsubscribe.length > 0) sendUnsubscribe(toUnsubscribe);\n closeIfIdle();\n }\n\n return {\n subscribe(ids, onUpdate) {\n const newlyAdded: string[] = [];\n for (const id of ids) {\n let set = subscribers.get(id);\n if (!set) {\n set = new Set();\n subscribers.set(id, set);\n newlyAdded.push(id);\n }\n set.add(onUpdate);\n }\n ensureSocket();\n if (newlyAdded.length > 0) sendSubscribe(newlyAdded);\n\n return () => unsubscribe(ids, onUpdate);\n },\n unsubscribe,\n close() {\n subscribers.clear();\n closeIfIdle();\n },\n };\n}\n","import {\n type ApiClient,\n type ArkadeToEvmSwapResponse,\n type ArkadeToLightningSwapResponse,\n type BtcToArkadeSwapResponse,\n type BulkStatusResponse,\n type components,\n createApiClient,\n type EvmToArkadeSwapResponse,\n type EvmToBitcoinSwapResponse,\n type EvmToLightningSwapResponse,\n type GetSwapResponse,\n type LightningToArkadeSwapResponse,\n type LightningToBitcoinSwapResponse,\n type paths,\n type RedeemAndSwapResponse,\n type StatusResponse,\n type TokenInfos,\n} from \"./api/client.js\";\nimport { getVhtlcAmounts, type VhtlcAmounts } from \"./arkade.js\";\nimport {\n CCTP_DOMAINS,\n type CctpChainName,\n USDC_ADDRESSES,\n} from \"./cctp/constants.js\";\nimport { computeCctpFastFee, getCachedCctpFee } from \"./cctp/fee.js\";\nimport {\n cctpMetaForChainId,\n isCctpOnlySource,\n} from \"./cctp-inbound/chainMap.js\";\nimport { CctpInboundClient } from \"./cctp-inbound/client.js\";\nimport type {\n CctpFundSwapResult,\n CctpProgressStep,\n} from \"./cctp-inbound/fundSwap.js\";\nimport {\n type RecoverCctpInboundResult,\n type RecoveryProgress,\n recoverCctpInbound,\n} from \"./cctp-inbound/recover.js\";\nimport type {\n CctpFundSwapFromSolanaResult,\n SolanaCctpProgressStep,\n} from \"./cctp-inbound/solana/fundSwap.js\";\nimport type { SolanaSigner } from \"./cctp-inbound/solana/types.js\";\nimport type { AaConfig } from \"./cctp-inbound/types.js\";\nimport {\n type ComposeQuoteParams,\n composeQuote as composeQuoteHelper,\n UnsupportedComposeQuotePath,\n} from \"./compose-quote.js\";\nimport {\n type ArkadeToEvmSwapOptions,\n type ArkadeToEvmSwapResult,\n type ArkadeToLightningSwapOptions,\n type ArkadeToLightningSwapResult,\n type BitcoinToArkadeSwapOptions,\n type BitcoinToArkadeSwapResult,\n type BitcoinToEvmSwapOptions,\n type BitcoinToEvmSwapResult,\n type BitcoinToLightningSwapOptions,\n type BitcoinToLightningSwapResult,\n type CreateSwapContext,\n type CreateSwapOptions,\n type CreateSwapResult,\n createArkadeToEvmSwapGeneric,\n createArkadeToLightningSwap,\n createBitcoinToArkadeSwap,\n createBitcoinToEvmSwap,\n createBitcoinToLightningSwap,\n createEvmToArkadeSwapGeneric,\n createEvmToBitcoinSwap,\n createEvmToLightningSwap,\n createLightningToArkadeSwap,\n createLightningToBitcoinSwap,\n createLightningToEvmSwap,\n type EvmToArkadeSwapGenericOptions,\n type EvmToArkadeSwapGenericResult,\n type EvmToBitcoinSwapOptions,\n type EvmToBitcoinSwapResult,\n type EvmToLightningSwapOptions,\n type EvmToLightningSwapResult,\n type LightningToArkadeSwapOptions,\n type LightningToArkadeSwapResult,\n type LightningToBitcoinSwapOptions,\n type LightningToBitcoinSwapResult,\n type LightningToEvmSwapOptions,\n type LightningToEvmSwapResult,\n} from \"./create/index.js\";\nimport { delegateClaim, delegateRefund } from \"./delegate.js\";\nimport {\n ElectrumWsClient,\n electrumBroadcastTransaction,\n electrumFetchTransactionOutputs,\n electrumFindOutputByAddress,\n electrumWaitForOutputByAddress,\n} from \"./electrum-ws.js\";\nimport {\n broadcastTransactionWithRetry,\n type EsploraUrls,\n fetchFeeRateEstimate,\n fetchTransactionOutputs,\n fetchWithTimeout,\n findOutputByAddress,\n} from \"./esplora.js\";\nimport {\n type CheckedFunding,\n checkFundingPayload,\n type EvmFundingTerms,\n type ExpectedFunding,\n type FundingPayload,\n type FundingPins,\n} from \"./evm/funding-pins.js\";\nimport {\n buildCollabRefundEvmDigest,\n buildCollabRefundEvmTypedData,\n buildEip2612PermitDigest,\n buildPermit2FundingDigest,\n buildPermit2TypedData,\n type CollabRefundEvmDigestParams,\n type CollabRefundEvmTypedData,\n decodeSwapCreatedLog,\n depositorIsSender,\n deriveEvmAddress,\n encodeApproveCallData,\n encodeDepositsCallData,\n encodeExecuteAndCreateWithPermit2,\n encodeHtlcErc20IsActiveCallData,\n encodeHtlcErc20RefundBySigCallData,\n encodeHtlcErc20RefundCallData,\n encodeHtlcErc20RehashCallData,\n encodeHtlcNativeRefundBySigCallData,\n encodeHtlcNativeRefundCallData,\n encodeHtlcNativeRehashCallData,\n encodeHtlcSwapsCallData,\n encodeNativeRefundTo,\n encodeRefundTo,\n findSwapCreated,\n findSwapRehashed,\n HTLC_SWAP_STATE,\n htlcSwapKey,\n isKernelDelegation,\n KERNEL_DELEGATION_TARGET,\n kernelErc1271Digest,\n NATIVE_TOKEN_ADDRESS,\n normalizeBytes32,\n PERMIT2_ADDRESS,\n type Permit2SignedFundingCallData,\n refundForAsOwnRefund,\n type SwapCreatedLog,\n signEvmDigest,\n signEvmMessage,\n type UnsignedPermit2FundingData,\n wrapKernelErc1271Signature,\n} from \"./evm/index.js\";\nimport { keyToKernelOwnerSigner } from \"./evm/key-signer.js\";\nimport { encodeNativeCreate } from \"./evm/native.js\";\nimport { decodeRefundCall, encodeRefundCall } from \"./evm/refund-call.js\";\nimport {\n decodeUint256,\n type EvmSigner,\n encodeAllowanceCall,\n encodeBalanceOfCall,\n encodeMaxApproveData,\n gasLimitFor,\n getRevertReason,\n parseSignature,\n simulateTransaction,\n type TxReceipt,\n txTypeFor,\n} from \"./evm/wallet.js\";\nimport {\n createSdkLogger,\n type Logger,\n type LogLevel,\n type SdkLogger,\n} from \"./logging.js\";\nimport { PROTOCOL_HEADERS } from \"./protocol.js\";\nimport { nativeHtlcKind } from \"./redeem/gasless.js\";\nimport {\n buildArkadeClaim,\n type ClaimGaslessResult,\n type ClaimResult,\n claimViaSigner,\n claimViaUserOp,\n continueArkadeClaim,\n claimViaGasless as gaslessClaim,\n claim as redeemClaim,\n} from \"./redeem/index.js\";\nimport {\n claimNativeViaRifRelay,\n type RifRelayConfig,\n rifSmartWalletAddress,\n WalletClaimRequiredError,\n} from \"./redeem/rif-relay.js\";\nimport {\n type BitcoinNetwork,\n buildArkadeRefund,\n buildOnchainClaimTransaction,\n buildOnchainRefundTransaction,\n collabRefundArkadeToEvmDelegate,\n collabRefundArkadeToEvmOffchain,\n verifyHtlcAddress,\n} from \"./refund/index.js\";\nimport {\n bytesToHex,\n hexToBytes,\n Signer,\n type SwapParams,\n} from \"./signer/index.js\";\nimport {\n type EvmRehashRecord,\n type LightningPaymentHash,\n type StoredSwap,\n SWAP_STORAGE_VERSION,\n type SwapStorage,\n type WalletStorage,\n} from \"./storage/index.js\";\nimport {\n recoveredKeysChange,\n SwapVerificationError,\n storedPayoutTarget,\n swapTermsChange,\n unboundTerms,\n withStoredTerms,\n} from \"./swap-verification.js\";\nimport {\n ALL_EVM_CHAIN_IDS,\n isArkade,\n isBridgedTarget,\n isBtcOnchain,\n isEvmSwapSource,\n isEvmToken,\n isLightning,\n isNativeLockTarget,\n isSolanaToken,\n isTronToken,\n toChainName,\n} from \"./tokens.js\";\nimport {\n type Chain,\n type ChainConfigResponse,\n type DexQuoteAmount,\n type DexQuoteResponse,\n fromWireChainConfigResponse,\n fromWireDexQuoteResponse,\n fromWireNetworkFeesResponse,\n fromWireQuoteResponse,\n fromWireReferralFeeResponse,\n fromWireSwapPairsResponse,\n type NetworkFeesResponse,\n type QuoteResponse,\n type ReferralFeeResponse,\n type SwapPairsResponse,\n type Token,\n type WireChain,\n type WireChainConfigResponse,\n type WireDexQuoteResponse,\n type WireNetworkFeesResponse,\n type WireQuoteResponse,\n type WireReferralFeeResponse,\n type WireSwapPairsResponse,\n} from \"./types/index.js\";\nimport { USDT0_ADDRESSES } from \"./usdt0-bridge/constants.js\";\nimport { isValidTronAddress } from \"./usdt0-bridge/tron.js\";\nimport {\n CLIENT_AGENT,\n DEFAULT_AA_BUNDLER_URL,\n DEFAULT_AA_POLICY_ID,\n} from \"./version.js\";\nimport {\n createSwapStatusWatcher,\n type SwapStatusHandler,\n type SwapStatusWatcher,\n} from \"./ws.js\";\n\n// Re-export types from create module for backwards compatibility\nexport type {\n ArkadeToEvmSwapOptions,\n ArkadeToEvmSwapResult,\n ArkadeToLightningSwapOptions,\n ArkadeToLightningSwapResult,\n BitcoinToArkadeSwapOptions,\n BitcoinToArkadeSwapResult,\n BitcoinToEvmSwapOptions,\n BitcoinToEvmSwapResponse,\n BitcoinToEvmSwapResult,\n BitcoinToLightningSwapOptions,\n BitcoinToLightningSwapResult,\n BtcToEvmSwapOptions,\n CreateSwapOptions,\n CreateSwapResult,\n EvmChain,\n EvmToArkadeSwapGenericOptions,\n EvmToArkadeSwapGenericResult,\n EvmToArkadeSwapOptions,\n EvmToArkadeSwapResult,\n EvmToBitcoinSwapOptions,\n EvmToBitcoinSwapResult,\n EvmToLightningSwapOptions,\n EvmToLightningSwapResult,\n LightningToBitcoinSwapOptions,\n LightningToBitcoinSwapResult,\n LightningToEvmSwapOptions,\n LightningToEvmSwapResponse,\n LightningToEvmSwapResult,\n UsdcBridgeParams,\n} from \"./create/index.js\";\n\nimport { invoicePaymentHash } from \"./bolt11.js\";\nimport type {\n BitcoinToEvmSwapResponse,\n LightningToEvmSwapResponse,\n} from \"./create/index.js\";\nimport type { CoordinatorCall } from \"./evm/index.js\";\n\n// Re-export coordinator utilities for Arkade-to-EVM redeemAndExecute flow\nexport {\n buildCollabRefundEvmDigest,\n buildCollabRefundEvmTypedData,\n buildEip2612PermitDigest,\n buildPermit2FundingDigest,\n buildRedeemCalls,\n buildRedeemDigest,\n type CollabRefundEvmDigestParams,\n type CollabRefundEvmTypedData,\n type CoordinatorCall,\n type Eip2612PermitParams,\n type ExecuteAndCreateWithPermit2Params,\n encodeExecuteAndCreateWithPermit2,\n encodeRedeemAndExecute,\n encodeRefundTo,\n PERMIT2_ADDRESS,\n type Permit2FundingParams,\n type Permit2SignedFundingCallData,\n type RedeemAndExecuteCallData,\n type RedeemAndExecuteParams,\n type RedeemDigestParams,\n type RefundToParams,\n} from \"./evm/index.js\";\n// Re-export types from redeem module\nexport type {\n ClaimGaslessResult,\n ClaimResult,\n CoordinatorClaimData,\n EthereumClaimData,\n} from \"./redeem/index.js\";\n\n/** How an EVM-targeted swap has to be claimed (see `#classifyEvmClaim`). */\ninterface EvmClaimClassification {\n targetTokenAddr: string;\n dexSwapNeeded: boolean;\n bridgeTargetChain: string | undefined;\n bridgeTargetToken: string | undefined;\n isBridge: boolean;\n isCctpBridge: boolean;\n isSolanaBridge: boolean;\n arbitrumHubClaim: boolean;\n}\n\n/** A support agent's Nostr identity */\nexport interface SupportAgentInfo {\n npub: string;\n}\n\nfunction isStatusResponse(value: unknown): value is StatusResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"healthy\" in value &&\n \"services\" in value\n );\n}\n\nexport interface RecoverSwapsOptions {\n /** Derivation index to start scanning from. Defaults to 0 on the server. */\n startIndex?: number;\n}\n\nexport interface RecoverSwapsResult {\n /** Recovered swaps stored locally. */\n swaps: StoredSwap[];\n /** @deprecated Legacy compatibility field from the API. Prefer `nextIndex`. */\n highestIndex: number;\n /** Derivation index to use for the next new swap. */\n nextIndex: number;\n /** Last derivation index scanned by the server. */\n scannedUntil: number;\n /** True when scanning stopped due to the recovery gap limit. */\n complete: boolean;\n}\n\nexport interface RecoverAllSwapsOptions {\n /** Derivation index to start scanning from. Defaults to 0. */\n startIndex?: number;\n}\n\nexport type RecoverAllSwapsStopReason = \"complete\" | \"error\";\n\nexport interface RecoverAllSwapsResult {\n /** Recovered swaps stored locally, de-duplicated by swap ID. */\n swaps: StoredSwap[];\n /** Derivation index to use for the next new swap. */\n nextIndex: number;\n /** Last derivation index scanned by the server, or null if no scan succeeded. */\n scannedUntil: number | null;\n /** True when recovery stopped because the server reported completion. */\n complete: boolean;\n /** Why recovery stopped. */\n stoppedReason: RecoverAllSwapsStopReason;\n /** Number of successful recovery scans performed. */\n scans: number;\n /** Error message when recovery stopped due to an error. */\n errorMessage?: string;\n /** Original error when recovery stopped due to an error. */\n error?: unknown;\n}\n\n/** Result of attempting a refund */\nexport interface RefundResult {\n /** Whether the refund was successful */\n success: boolean;\n /** Human-readable message about the refund status */\n message: string;\n /** Raw transaction hex (for on-chain refunds) */\n txHex?: string;\n /** Transaction ID (for on-chain refunds) */\n txId?: string;\n /** Amount being refunded in satoshis (after fees) */\n refundAmount?: bigint;\n /** Fee paid in satoshis */\n fee?: bigint;\n /** Whether the transaction was broadcast to the network */\n broadcast?: boolean;\n /** The HTLC address we computed locally (for debugging) */\n htlcAddress?: string;\n /** The HTLC address reported by the server (for debugging) */\n serverHtlcAddress?: string;\n /** EVM refund data (for evm_to_arkade and evm_to_btc swaps) */\n evmRefundData?: {\n /** Address to send the refund transaction to (coordinator or HTLC) */\n to: string;\n /** ABI-encoded calldata for the refund call */\n data: string;\n /** Whether the timelock has already expired (refund is available) */\n timelockExpired: boolean;\n /** Unix timestamp when the timelock expires */\n timelockExpiry: number;\n /**\n * Where the refund pays out: the depositor on the coordinator path,\n * which for a gasless swap is the SDK's own key, not the wallet that\n * submits the transaction.\n */\n recipient?: string;\n };\n}\n\n/** Options for on-chain refund */\nexport interface OnchainRefundOptions {\n /** Destination address to receive refunded BTC */\n destinationAddress: string;\n /** Fee rate in satoshis per virtual byte (default: 2) */\n feeRateSatPerVb?: number;\n /** If true, only build the transaction without broadcasting (default: false) */\n dryRun?: boolean;\n}\n\n/** Options for Arkade (off-chain) refund */\nexport interface ArkadeRefundOptions {\n /** Destination Arkade address to receive refunded BTC */\n destinationAddress: string;\n /** Arkade server URL (optional, uses default based on network) */\n arkadeServerUrl?: string;\n}\n\n/** Options for EVM refund via coordinator */\nexport interface EvmRefundOptions {\n /**\n * Whether to use collaborative refund (server cosigns + submits, gasless, no timelock wait).\n * When false/undefined, the refund requires timelock expiry and the caller submits the tx.\n * @default false\n */\n collaborative?: boolean;\n /**\n * Lets the refund be built from the chain: the locked amount is read off\n * the funding tx's `SwapCreated` log. The server is asked for another\n * funding txid only when none the client knows yields a receipt, and for\n * calldata once the chain path has failed. Its `waitForReceipt` must return\n * the receipt's logs, its `getTransaction` must reject for a hash the node\n * does not know, and it must be on the swap's chain.\n */\n signer?: EvmSigner;\n}\n\n/** The HTLC is no longer open on-chain, so no refund can be built for it. */\nclass HtlcNotActiveError extends Error {}\n\n/** Attempts to write a rehash record before giving up. */\nconst REHASH_RECORD_ATTEMPTS = 3;\nconst REHASH_RECORD_RETRY_MS = 100;\n\n/**\n * A rehash went out (and may be mined) but this client could not record\n * the terms the lock now has. A refund built without the record would\n * target the old lock; `record` is what should have been stored.\n */\nexport class RehashNotRecordedError extends Error {\n constructor(\n public readonly swapId: string,\n public readonly record: EvmRehashRecord,\n public readonly cause: unknown,\n ) {\n super(\n `Rehash ${record.txid} for swap ${swapId} moves the lock to ${record.hashLock} (timelock ${record.timelock}), but the swap storage refused to record it: ${errorMessage(cause)}. Keep these terms; a refund built without them targets a lock that no longer exists.`,\n );\n }\n}\n\n/** The funding tx could not be read from the chain; another txid may work. */\nclass FundingTxUnavailableError extends Error {}\n\n// A funding still in the mempool has nothing to refund yet, and a mined one\n// answers in one round trip, so a pending hash must not hold the refund.\nconst FUNDING_RECEIPT_WAIT_MS = 30_000;\n\n/**\n * How long `fundSwap` waits for the server to take the funding hint. The\n * funding is done by then; the hint only shortens the server's detection.\n */\nconst FUNDING_HINT_TIMEOUT_MS = 5_000;\n/**\n * How often the funding hint is re-sent while the server answers 404 \"not\n * mined yet\": its node may trail the client's by a block or two, or still be\n * on a competing block at the head. Three attempts, a few seconds apart.\n */\nconst FUNDING_HINT_ATTEMPTS = 3;\nconst FUNDING_HINT_RETRY_DELAY_MS = 4_000;\n\n/**\n * The first part of an error body, for a log line. `fetchWithTimeout` only\n * bounds the headers; a body that never ends must not hang the caller, so\n * the read gets its own deadline and the text is cut short.\n */\nasync function readBodyBounded(\n resp: Response,\n timeoutMs: number,\n): Promise<string> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<string>((resolve) => {\n timer = setTimeout(() => resolve(\"<body not read in time>\"), timeoutMs);\n });\n try {\n const text = await Promise.race([resp.text(), deadline]);\n return text.length > 500 ? `${text.slice(0, 500)}…` : text;\n } catch (error) {\n return `<body unreadable: ${error instanceof Error ? error.message : String(error)}>`;\n } finally {\n clearTimeout(timer);\n }\n}\n/**\n * Gas limit for a plain native lock (`HTLCNative.create`), with\n * headroom; the unused part is not charged.\n */\nconst NATIVE_LOCK_GAS = 250_000n;\n/**\n * Fallback gas limit for a Permit2 funding tx when the signer cannot\n * estimate. Permit2 transfer + a two-hop Uniswap V3 route + HTLC creation\n * measured ~504k on Arbitrum (the old 500k cap ran out of gas there), so\n * leave headroom for three hops.\n */\nconst PERMIT2_FUND_GAS = 1_000_000n;\n/** Fallback gas limit for an HTLC refund when the signer cannot estimate. */\nconst REFUND_GAS = 500_000n;\n\nfunction withDeadline<T>(\n promise: Promise<T>,\n ms: number,\n what: string,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(what)), ms);\n });\n return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * A contract read must answer with exactly one ABI word; anything else means\n * the node does not hold the contract, or the transport failed.\n */\nfunction collabRefundPath(label: string): CollabRefundEvmPath {\n if (label === \"direct\" || label === \"coordinator\") return label;\n return \"unavailable\";\n}\n\nfunction collabRefundUnavailable(\n swapId: string,\n params: CollabRefundEvmParams,\n): string {\n return `Collaborative refund is not available for swap ${swapId}: it locks on ${params.htlcKind} HTLC v${params.htlcVersion}, which supports no early refund. Refund after the timelock (${new Date(params.timelock * 1000).toISOString()}) instead.`;\n}\n\n/**\n * The message the depositor signs (EIP-191 / `personal_sign`) to authorize\n * moving swap `swapId` to the invoice with `paymentHash` (0x-prefixed hex).\n * Must match the server's `rehash_evm::authorization_message`.\n */\nexport function rehashAuthorizationMessage(\n swapId: string,\n paymentHash: string,\n): string {\n const hash = `0x${paymentHash.replace(/^0x/, \"\").toLowerCase()}`;\n return `Satora rehash\\nswap: ${swapId}\\ninvoice payment hash: ${hash}`;\n}\n\n/**\n * How much later than the advertised `newTimelock` a signed one may be: a\n * rehash signed for this invoice earlier keeps its timelock, and the clock\n * moved on since the params were fetched.\n */\nconst REHASH_TIMELOCK_TOLERANCE_SECS = 3600;\n\n/**\n * The refund address the Permit2 funding witness binds: the depositor on a\n * deployment that keys locks under it (HTLCErc20 v7 / HTLCNative v2), the\n * coordinator before. Permit2 rejects a witness signed for the wrong one.\n */\n/** The lock-generation context of a checked funding, for the witness. */\nfunction checkedRefundContext(checked: CheckedFunding): {\n coordinator_address: string;\n htlc_kind?: string;\n htlc_version?: number;\n} {\n return {\n coordinator_address: checked.coordinator,\n htlc_kind: checked.htlcKind,\n htlc_version: checked.htlcVersion,\n };\n}\n\nfunction permit2RefundAddress(\n serverData: {\n coordinator_address: string;\n htlc_kind?: string;\n htlc_version?: number;\n },\n depositorAddress: string | undefined,\n): string {\n if (!depositorIsSender(serverData.htlc_kind, serverData.htlc_version)) {\n return serverData.coordinator_address;\n }\n if (!depositorAddress) {\n throw new Error(\n `This swap locks on ${serverData.htlc_kind} HTLC v${serverData.htlc_version}, whose Permit2 witness names the depositor; pass the funding wallet's address`,\n );\n }\n return depositorAddress;\n}\n\n/**\n * The depositor authorized one payment hash; the lock may move only there,\n * and only for about as long as the server advertised. A server answer for\n * any other hash, or a far longer lock, is refused before anything is sent.\n */\nfunction ensureRehashMatchesRequest(\n signature: RehashEvmSignature,\n paymentHash: string,\n params: RehashEvmParams,\n): void {\n const signed = `0x${normalizeBytes32(signature.newPreimageHash)}`;\n if (signed !== `0x${normalizeBytes32(paymentHash)}`) {\n throw new Error(\n `The server signed a rehash to ${signed}, not to the invoice's payment hash ${paymentHash}`,\n );\n }\n if (\n signature.newTimelock >\n params.newTimelock + REHASH_TIMELOCK_TOLERANCE_SECS\n ) {\n throw new Error(\n `The server signed a rehash with timelock ${signature.newTimelock}, later than the advertised ${params.newTimelock}`,\n );\n }\n if (\n signature.htlcAddress.toLowerCase() !== params.htlcAddress.toLowerCase() ||\n `0x${normalizeBytes32(signature.preimageHash)}` !==\n `0x${normalizeBytes32(params.preimageHash)}`\n ) {\n throw new Error(\n \"The server signed a rehash for another lock than the swap's\",\n );\n }\n}\n\n/** This swap's lock as the chain shows it, after the moves this client made. */\ntype OwnEvmLock = SwapCreatedLog & { htlcAddress: string; chainId: number };\n\n/**\n * A rehash moves whichever lock its terms name. A server that named another\n * lock of the same depositor, one it can claim, would have the user move\n * that lock to the new invoice's hash; paying the small invoice would then\n * hand it the preimage. Every term the server names must be this swap's.\n */\nfunction ensureLockIsOwn(\n lock: OwnEvmLock,\n named: {\n htlcAddress: string;\n chainId: number;\n preimageHash: string;\n amount: string;\n token: string;\n sender?: string;\n claimAddress: string;\n timelock: number;\n },\n what: string,\n): void {\n const native = lock.token === NATIVE_TOKEN_ADDRESS.toLowerCase();\n const mismatches = [\n named.htlcAddress.toLowerCase() !== lock.htlcAddress.toLowerCase() &&\n \"htlc address\",\n named.chainId !== lock.chainId && \"chain\",\n `0x${normalizeBytes32(named.preimageHash)}` !== lock.preimageHash &&\n \"preimage hash\",\n BigInt(named.amount) !== lock.amount && \"amount\",\n // A native lock keys a zero asset word whatever the server calls it.\n !native && named.token.toLowerCase() !== lock.token && \"token\",\n named.sender !== undefined &&\n named.sender.toLowerCase() !== lock.refundAddress &&\n \"sender\",\n named.claimAddress.toLowerCase() !== lock.claimAddress && \"claim address\",\n named.timelock !== lock.timelock && \"timelock\",\n ].filter(Boolean);\n if (mismatches.length > 0) {\n throw new Error(\n `${what} another lock than this swap's own (${mismatches.join(\", \")} differ from the lock its funding tx created); refusing to move it`,\n );\n }\n}\n\n/** `rehash` on the HTLC the server signed for, ERC20 or native. */\nfunction rehashCallData(signature: RehashEvmSignature): {\n to: string;\n data: string;\n} {\n const terms = {\n preimageHash: signature.preimageHash,\n amount: BigInt(signature.amount),\n timelock: signature.timelock,\n newPreimageHash: signature.newPreimageHash,\n newTimelock: signature.newTimelock,\n v: signature.v,\n r: signature.r,\n s: signature.s,\n };\n return signature.htlcKind === \"native\"\n ? encodeHtlcNativeRehashCallData(signature.htlcAddress, terms)\n : encodeHtlcErc20RehashCallData(signature.htlcAddress, {\n ...terms,\n token: signature.token,\n });\n}\n\n/** `refundBySig` on the HTLC the server signed for, ERC20 or native. */\nfunction refundBySigCallData(signature: CollabRefundEvmSignature): {\n to: string;\n data: string;\n} {\n const terms = {\n preimageHash: signature.preimageHash,\n amount: BigInt(signature.amount),\n timelock: signature.timelock,\n v: signature.v,\n r: signature.r,\n s: signature.s,\n };\n return signature.htlcKind === \"native\"\n ? encodeHtlcNativeRefundBySigCallData(signature.htlcAddress, terms)\n : encodeHtlcErc20RefundBySigCallData(signature.htlcAddress, {\n ...terms,\n token: signature.token,\n });\n}\n\nfunction decodeCallWord(result: string, what: string): bigint {\n const clean = result.replace(/^0x/i, \"\");\n if (clean.length !== 64) {\n throw new Error(\n `${what} returned ${clean.length === 0 ? \"no data\" : \"malformed data\"}; the node may not hold the contract`,\n );\n }\n return BigInt(`0x${clean}`);\n}\n\nfunction uniqueAddresses(values: (string | null | undefined)[]): string[] {\n return [\n ...new Set(values.flatMap((value) => (value ? [value.toLowerCase()] : []))),\n ];\n}\n\n/**\n * Simulates, sends and confirms one call from `signer`, returning the hash\n * that mined. `waitForReceipt` follows wallet replacements, and a cancel\n * mines with status success without running the call, so a replacement\n * counts only when it is the same call repriced.\n */\nasync function sendCall(\n signer: EvmSigner,\n call: { to: string; data: string },\n label: string,\n options: {\n fallbackGas?: bigint;\n /** Runs once the tx is broadcast, before waiting for its receipt. */\n onSent?: (hash: string) => Promise<void>;\n } = {},\n): Promise<string> {\n await simulateTransaction(signer, call, label);\n const sent = await signer.sendTransaction({\n to: call.to,\n data: call.data,\n type: txTypeFor(signer.chainId),\n gas: await gasLimitFor(signer, call, options.fallbackGas ?? REFUND_GAS),\n });\n await options.onSent?.(sent);\n const receipt = await signer.waitForReceipt(sent);\n if (receipt.status !== \"success\") {\n const reason = await getRevertReason(signer, sent, receipt.blockNumber);\n throw new Error(`${label} reverted: ${reason}`);\n }\n const mined = receipt.transactionHash || sent;\n if (\n mined.toLowerCase() !== sent.toLowerCase() &&\n !(await isSameCall(signer, mined, call))\n ) {\n throw new Error(\n `${label} ${sent} was replaced by ${mined}, which is not the same call; the wallet may have cancelled it`,\n );\n }\n return mined;\n}\n\nasync function isSameCall(\n signer: EvmSigner,\n hash: string,\n call: { to: string; data: string },\n): Promise<boolean> {\n try {\n const tx = await signer.getTransaction(hash);\n return (\n tx?.to?.toLowerCase() === call.to.toLowerCase() &&\n tx.input.toLowerCase() === call.data.toLowerCase()\n );\n } catch {\n return false;\n }\n}\n\nfunction dedupeTxids(txids: (string | null | undefined)[]): string[] {\n const seen = new Set<string>();\n const unique: string[] = [];\n for (const txid of txids) {\n if (!txid || seen.has(txid.toLowerCase())) continue;\n seen.add(txid.toLowerCase());\n unique.push(txid);\n }\n return unique;\n}\n\n/** The EVM lock's hash as this client fixed it, if it has it. */\nfunction clientHashLockOf(stored: StoredSwap): string | undefined {\n switch (stored.response.direction) {\n case \"evm_to_lightning\":\n return stored.lightningPaymentHash?.hash;\n case \"evm_to_bitcoin\":\n case \"evm_to_arkade\":\n return stored.preimageHash\n ? `0x${normalizeBytes32(stored.preimageHash)}`\n : undefined;\n default:\n return undefined;\n }\n}\n\n/** The EVM lock's hash as a swap response names it. */\nfunction evmHashLockOf(swap: GetSwapResponse): string {\n const named = swap as { evm_hash_lock?: string; hash_lock?: string };\n const hash =\n swap.direction === \"evm_to_bitcoin\" ? named.evm_hash_lock : named.hash_lock;\n if (!hash) throw new Error(`Swap ${swap.id} names no EVM hash lock`);\n return hash;\n}\n\nfunction evmSourceLeg(stored: StoredSwap) {\n const rehashes = stored.evmRehashes?.length ? stored.evmRehashes : undefined;\n const swap = stored.response as\n | (EvmToArkadeSwapResponse & { direction: \"evm_to_arkade\" })\n | (EvmToBitcoinSwapResponse & { direction: \"evm_to_bitcoin\" })\n | (EvmToLightningSwapResponse & { direction: \"evm_to_lightning\" });\n return {\n chainId: swap.evm_chain_id,\n htlcAddress: swap.evm_htlc_address,\n // The hash the lock was created under: the one this client fixed when\n // it has it (the server's copy is only a fallback for a swap recovered\n // without it, and switches to the current hash once a rehash is\n // confirmed). The funding tx's SwapCreated is under the first hash, and\n // the rehashes are followed from there.\n hashLock:\n rehashes?.[0]?.fromHashLock ??\n clientHashLockOf(stored) ??\n (swap.direction === \"evm_to_bitcoin\"\n ? swap.evm_hash_lock\n : swap.hash_lock),\n claimAddress: swap.server_evm_address,\n timelock: rehashes?.at(-1)?.timelock ?? swap.evm_refund_locktime,\n // This client's own record first, then the server's copy (which names\n // the rehash tx once a rehash is confirmed; that one carries no\n // SwapCreated and is skipped as unavailable).\n fundTxids: dedupeTxids([stored.evmFundTxid, swap.evm_fund_txid]),\n rehashes,\n // The server names the coordinator on the Lightning direction only.\n coordinatorAddress:\n stored.evmCoordinatorAddress ??\n (swap.direction === \"evm_to_lightning\"\n ? swap.evm_coordinator_address\n : undefined),\n // Read from the creation terms first, which a server refresh cannot\n // rewrite; a swap recorded before they named the version falls back to\n // the server's copy.\n depositorIsSender:\n stored.evmFundingTerms?.htlcVersion !== undefined\n ? depositorIsSender(\n stored.evmFundingTerms.htlcKind,\n stored.evmFundingTerms.htlcVersion,\n )\n : depositorIsSender(swap.evm_htlc_kind, swap.evm_htlc_version),\n };\n}\n\n/**\n * Whether the swap's creation terms name a direct native lock: an HTLCNative\n * the wallet funds itself, with the native placeholder where a coordinator\n * would be. Older SDKs recorded that wallet as `evmCoordinatorAddress`; on\n * such a swap the record names the sender, not a coordinator, and must not\n * fail the coordinator check on a retry. Read from the creation terms, which\n * a server refresh cannot rewrite.\n */\nfunction isDirectNativeLock(terms: EvmFundingTerms): boolean {\n return (\n terms.htlcKind === \"native\" &&\n terms.coordinator.toLowerCase() === NATIVE_TOKEN_ADDRESS.toLowerCase()\n );\n}\n\n/**\n * Whether a receipt proves its tx created no lock under `hashLock`: its logs\n * are there and none is a `SwapCreated` under that hash, on any contract and\n * with any terms. A receipt without logs proves nothing.\n */\nfunction provesNoLockUnder(receipt: TxReceipt, hashLock: string): boolean {\n if (receipt.logs === undefined) return false;\n const hash = `0x${normalizeBytes32(hashLock)}`;\n return !receipt.logs.some(\n (log) =>\n log.topics.some((topic) => `0x${normalizeBytes32(topic)}` === hash) ||\n decodeSwapCreatedLog(log)?.preimageHash === hash,\n );\n}\n\n/** Result of a collaborative EVM refund */\nexport interface CollabRefundEvmResult {\n /** Swap ID */\n id: string;\n /** On-chain transaction hash */\n txHash: string;\n /** Success message */\n message: string;\n}\n\n/** Parameters for building CollabRefund EIP-712 typed data (returned by getCollabRefundEvmParams) */\nexport interface CollabRefundEvmParams {\n /** HTLCCoordinator contract address (EIP-712 verifyingContract) */\n coordinatorAddress: string;\n /** Server's signer EOA address (the `caller` field in the EIP-712 struct) */\n serverSignerAddress: string;\n /** Preimage hash (0x-prefixed, 32-byte hex) */\n preimageHash: string;\n /** WBTC amount locked in the HTLC (decimal string) */\n amount: string;\n /** WBTC token address */\n token: string;\n /** Claim address (server's EVM address) */\n claimAddress: string;\n /** HTLC timelock (unix timestamp) */\n timelock: number;\n /** EVM chain ID */\n chainId: number;\n /** Token the depositor receives (always the BTC-pegged HTLC token, tBTC/WBTC) — the EIP-712 `sweepToken` field */\n sweepToken: string;\n /** Minimum output amount for the sweep — the EIP-712 `minAmountOut` field */\n minAmountOut: string;\n /** keccak256(abi.encode(calls)) for the exact calls array signed in CollabRefund */\n callsHash: string;\n /**\n * EIP-712 domain version of the coordinator at `coordinatorAddress`.\n * Absent on servers predating the field — treat as 3.\n */\n coordinatorVersion?: number;\n /** The HTLC the swap locks on. */\n htlcAddress: string;\n /** Its `VERSION` (HTLCErc20 v7 / HTLCNative v2 refund directly). */\n htlcVersion: number;\n /** `\"erc20\"` or `\"native\"`. */\n htlcKind: string;\n /**\n * How this swap refunds early: `\"direct\"` (the depositor sends\n * `refundBySig` with the server's signature), `\"coordinator\"` (the\n * depositor signs `CollabRefund`, the server submits), or\n * `\"unavailable\"` (wait for the timelock).\n */\n refundPath: CollabRefundEvmPath;\n}\n\n/** See {@link CollabRefundEvmParams.refundPath}. */\nexport type CollabRefundEvmPath = \"direct\" | \"coordinator\" | \"unavailable\";\n\n/**\n * The server's `Refund` signature for a direct collaborative refund, with\n * the exact lock terms it covers. Only `sender` may submit it.\n */\nexport interface CollabRefundEvmSignature {\n id: string;\n htlcAddress: string;\n htlcVersion: number;\n htlcKind: string;\n chainId: number;\n preimageHash: string;\n amount: string;\n token: string;\n /** The depositor the signature is bound to as `msg.sender`. */\n sender: string;\n claimAddress: string;\n timelock: number;\n v: number;\n r: string;\n s: string;\n}\n\n/**\n * A stuck EVM → Lightning swap's lock, as the server would move it to a new\n * invoice (`GET /rehash-evm/params`).\n */\nexport interface RehashEvmParams {\n id: string;\n htlcAddress: string;\n htlcVersion: number;\n htlcKind: string;\n chainId: number;\n preimageHash: string;\n amount: string;\n token: string;\n /** The depositor the lock was created under, when the server recorded it. */\n sender?: string;\n claimAddress: string;\n timelock: number;\n /** The timelock a rehash signed now would continue under. */\n newTimelock: number;\n /** The new invoice may ask for at most this many sats. */\n maxInvoiceAmountSats: number;\n /** The new invoice must stay valid at least this long (seconds). */\n minInvoiceValiditySecs: number;\n}\n\n/**\n * The server's `Rehash` signature with the exact `rehash` arguments it is\n * valid for; only `sender` may submit it.\n */\nexport interface RehashEvmSignature {\n id: string;\n htlcAddress: string;\n htlcVersion: number;\n htlcKind: string;\n chainId: number;\n preimageHash: string;\n amount: string;\n token: string;\n sender: string;\n claimAddress: string;\n timelock: number;\n newPreimageHash: string;\n newTimelock: number;\n v: number;\n r: string;\n s: string;\n}\n\n/** Result of retrying a stuck EVM → Lightning swap with a new invoice. */\nexport interface RetrySwapWithInvoiceResult {\n id: string;\n /** The `rehash` transaction. */\n txHash: string;\n /** The payment hash of the new invoice; the lock continues under it. */\n newPreimageHash: string;\n newTimelock: number;\n}\n\nexport interface ContinueRefundedEvmSwapInfo {\n eligible: boolean;\n reason?: string;\n smartAccountAddress?: string;\n token?: {\n chain: Chain;\n address: string;\n symbol: string;\n decimals: number;\n };\n amount?: string;\n balance?: string;\n oldSwap?: GetSwapResponse;\n}\n\n/** What a continued swap pays out to. */\nexport type ContinueTarget = \"bitcoin\" | \"arkade\" | \"lightning\";\n\nexport interface ContinueRefundedEvmSwapResult {\n oldSwapId: string;\n newSwapId: string;\n txHash: string;\n userOpHash: string;\n smartAccountAddress: string;\n amount: string;\n token: {\n chain: Chain;\n address: string;\n symbol: string;\n decimals: number;\n };\n}\n\n/** General refund options — the method picks the right variant based on swap type */\nexport type RefundOptions =\n | OnchainRefundOptions\n | ArkadeRefundOptions\n | EvmRefundOptions;\n\n/** Options for Arkade (off-chain) claim */\nexport interface ArkadeClaimOptions {\n /** Destination Arkade address to receive claimed BTC */\n destinationAddress: string;\n /** Arkade server URL (optional, uses default based on network) */\n arkadeServerUrl?: string;\n /**\n * If the VTXO has not been indexed yet (status `not_funded`), keep\n * polling for up to this many milliseconds before giving up. The\n * server-funded WS update can race ahead of the Arkade indexer; a\n * short wait absorbs that lag without surfacing a transient error.\n * Set to `0` to fail immediately. Default: 30_000.\n */\n waitForVtxoMs?: number;\n}\n\n/** Options for claiming a swap */\nexport interface ClaimOptions {\n /** Wallet that submits an EVM claim and pays gas when sponsorship is unavailable. */\n signer?: EvmSigner;\n /**\n * @deprecated For Arkade-to-EVM swaps, the destination is now set at swap creation time\n * and stored on the server. This option is ignored for arkade_to_evm swaps.\n */\n destination?: string;\n /**\n * Bitcoin destination address for on-chain claims (evm_to_bitcoin and\n * lightning_to_bitcoin); falls back to the address the swap was created with.\n */\n destinationAddress?: string;\n /**\n * Fee rate in sat/vB for on-chain Bitcoin claims (default: the explorer's\n * two-block estimate, at least 2)\n */\n feeRateSatPerVb?: number;\n /**\n * For EVM-to-Bitcoin claims: if the funding (HTLC) output has not been\n * indexed by the block explorer yet, keep polling for up to this many\n * milliseconds before giving up. The server can broadcast the funding tx\n * just before the client tries to claim, so the explorer/indexer races\n * behind; a short wait absorbs that lag without surfacing a transient\n * error. Set to `0` to fail immediately. Default: 30_000.\n */\n waitForFundingMs?: number;\n /**\n * For EVM-to-Bitcoin claims: how many times to retry broadcasting the\n * claim transaction on transient failures (e.g. the broadcast node has\n * not seen the funding tx yet). Default: 5.\n */\n broadcastRetries?: number;\n /**\n * Optional non-EVM bridge recipient (e.g. a Solana base58 SPL pubkey).\n * Required when the swap's `bridge_target_chain` is non-EVM, since the\n * EIP-712 `destination` field can only carry an EVM address. Forwarded\n * to both `redeem-and-swap-calldata` and `claim-gasless` so the rebuilt\n * `calls_hash` matches.\n *\n * For Solana: this is the recipient's USDC **associated token account\n * (ATA)** — derive it from the wallet pubkey before passing.\n */\n bridgeRecipient?: string;\n /**\n * Optional Solana wallet pubkey, supplied alongside `bridgeRecipient`\n * when the recipient's USDC ATA does **not** yet exist. Triggers the\n * extended 65-byte forwarding hookData so Circle creates the ATA at\n * mint time. Omit when the ATA already exists.\n */\n bridgeRecipientWallet?: string;\n}\n\n/** Result of getting EVM funding call data */\nexport interface EvmFundingCallData {\n /** Call data for approving token spend (ERC20 approve) */\n approve: {\n /** Token contract address to call */\n to: string;\n /** Encoded approve(spender, amount) call data */\n data: string;\n };\n /** Call data for creating the swap (from server) */\n createSwap: {\n /** HTLC contract address to call */\n to: string;\n /** Encoded createSwap call data (from server) */\n data: string;\n };\n}\n\n/** Internal type for VHTLC claim/refund parameters extracted from a stored swap. */\ninterface ArkadeVhtlcParams {\n userSecretKey: string;\n userPubKey: string;\n lendaswapPubKey: string;\n arkadeServerPubKey: string;\n vhtlcAddress: string;\n refundLocktime: number;\n unilateralClaimDelay: number;\n unilateralRefundDelay: number;\n unilateralRefundWithoutReceiverDelay: number;\n network: string;\n preimage: string;\n preimageHash: string;\n arkadeHtlcScriptVersion?: number;\n}\n\ntype BaseUnitAmount = bigint;\ntype AmountInput = number | BaseUnitAmount;\n\nconst serializeAmountInput = (\n amount: AmountInput | undefined,\n): string | undefined => (amount == null ? undefined : amount.toString());\n\n/** Parameters for {@link Client.getQuote}. */\nexport interface GetQuoteParams {\n /** Source blockchain (e.g. \"Arkade\", \"Polygon\", \"Bitcoin\"). */\n sourceChain: Chain;\n /** Source token: contract address for EVM tokens, or \"btc\" for BTC. */\n sourceToken: string;\n /** Target blockchain. */\n targetChain: Chain;\n /** Target token: contract address for EVM tokens, or \"btc\" for BTC. */\n targetToken: string;\n /** Amount in smallest unit of source token (mutually exclusive with targetAmount). */\n sourceAmount?: AmountInput;\n /** Amount in smallest unit of target token (mutually exclusive with sourceAmount). */\n targetAmount?: AmountInput;\n /** Optional referral code to apply referral pricing to the quote. */\n referralCode?: string;\n /**\n * Optional per-swap fee surcharge in basis points\n * (0..=max_extra_fee_bps configured on the matching developer key).\n * Must be passed identically here and on the corresponding createSwap\n * so the quoted fee matches what's charged.\n */\n extraFees?: number;\n /**\n * Optional Lightning destination (BOLT11 invoice, lightning address or\n * LNURL) for Arkade/EVM → Lightning quotes. When set, the quote is served\n * by `/quote/lightning-send` and prices the swap with the provider's\n * REAL Lightning send fee for that exact payment instead of the flat\n * network-fee estimate. Invoices pin the payout (amount params are\n * ignored); addresses/LNURLs use the provided source or target amount.\n * Ignored for any other pair; on failure the quote silently falls back\n * to the estimate.\n */\n lightningDestination?: string;\n /**\n * Optional ATA-existence hint for non-EVM CCTP destinations\n * (Solana). `true` = recipient has no USDC ATA yet, `false` =\n * recipient already holds USDC. Omit to let the backend fall back\n * to its conservative default.\n */\n bridgeRecipientSetup?: boolean;\n}\n\n/** Source chains `/quote/lightning-send` can price. */\nexport type LightningSendSourceChain =\n | \"Arkade\"\n | \"Bitcoin\"\n | \"1\"\n | \"137\"\n | \"42161\"\n | \"30\"\n | \"31\";\n\n/**\n * Parameters for {@link Client.getLightningSendQuote}. Exactly one of the\n * destination fields must be set; `lightningAddress`/`lnurl` additionally\n * require exactly one of the amount fields.\n */\nexport interface GetLightningSendQuoteParams {\n /**\n * Source chain of the swap: \"Arkade\" (default), \"Bitcoin\" (on-chain)\n * or an EVM chain id (\"137\", \"1\", \"42161\"). EVM sources also need\n * `sourceToken`.\n */\n sourceChain?: LightningSendSourceChain;\n /** ERC-20 contract address of the source token (EVM sources only). */\n sourceToken?: string;\n /**\n * Total to lock on the source chain, in the source token's smallest\n * unit (sats for Arkade and Bitcoin, token units for EVM); fees are\n * deducted from the Lightning payout (send-max). `lightningAddress`/`lnurl` only;\n * mutually exclusive with `targetAmountSats`.\n */\n sourceAmount?: bigint | number | string;\n /**\n * @deprecated Use `sourceAmount`. Arkade-only spelling of the source\n * amount in sats; ignored when `sourceAmount` is given.\n */\n sourceAmountSats?: number;\n /**\n * BOLT11 invoice the user wants paid; its amount pins the payout.\n * `sourceAmount` cannot be combined with it.\n */\n lightningInvoice?: string;\n /** Lightning address (`user@domain`). */\n lightningAddress?: string;\n /** LNURL-pay string (`lnurl1...`). */\n lnurl?: string;\n /**\n * Amount the recipient should receive over Lightning in satoshis; fees\n * are added on top. With `lightningInvoice` it must match the invoice.\n */\n targetAmountSats?: number;\n /** Optional referral code (falls back to the client default). */\n referralCode?: string;\n /**\n * Optional per-swap fee surcharge in basis points\n * (0..=max_extra_fee_bps configured on the matching developer key).\n * Must be passed identically on the corresponding createSwap.\n */\n extraFees?: number;\n}\n\n/**\n * Exact quote for a swap paying out over Lightning. Amounts in sats unless\n * noted.\n */\nexport interface LightningSendQuote {\n /**\n * Total the user locks on the source chain (payout + fees), in the\n * source token's smallest unit: sats for Arkade, token units for EVM.\n */\n sourceAmount: string;\n /**\n * @deprecated Use `sourceAmount`. Set only for Arkade sources, where the\n * source unit is sats; `undefined` for EVM sources (token units).\n */\n sourceAmountSats?: number;\n /** Paid out on the Lightning invoice. */\n targetAmountSats: number;\n /** Protocol fee. */\n protocolFeeSats: number;\n /**\n * Network fee: the provider-quoted Lightning send fee (plus the server's\n * HTLC claim gas for EVM sources).\n */\n networkFeeSats: number;\n /** Protocol fee rate (as decimal, e.g. 0.003 = 0.30%). */\n protocolFeeRate: number;\n /** Minimum payout for this route, in sats. */\n minAmountSats: number;\n /** Maximum payout for this route, in sats. */\n maxAmountSats: number;\n /**\n * Source tokens (human-readable units) per 1 BTC locked, as `/quote`\n * reports it. \"1\" for Arkade and Bitcoin sources, where the source is\n * already sats.\n */\n exchangeRate: string;\n}\n\n/**\n * Classify a raw Lightning destination string. Addresses contain `@`,\n * LNURLs are bech32 strings with the `lnurl` HRP, and anything else\n * starting with `ln` is treated as a BOLT11 invoice.\n */\nfunction classifyLightningDestination(\n destination: string,\n): \"invoice\" | \"address\" | \"lnurl\" | undefined {\n const d = destination.trim().toLowerCase();\n if (d.includes(\"@\")) return \"address\";\n if (d.startsWith(\"lnurl1\")) return \"lnurl\";\n if (d.startsWith(\"ln\")) return \"invoice\";\n return undefined;\n}\n\n/**\n * Options for a sats-denominated (Arkade or on-chain Bitcoin) → Lightning\n * create from the generic `createSwap` inputs. A BOLT11 invoice pins the\n * payout (`targetAmount` is an optional cross-check, `sourceAmount` is not\n * applicable); an LNURL or lightning address takes exactly one of the two.\n */\nfunction satsToLightningOptions(\n options: CreateSwapOptions,\n sourceName: string,\n): ArkadeToLightningSwapOptions {\n const destination = options.targetAddress;\n const kind = classifyLightningDestination(destination);\n const common = {\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n };\n if (kind === \"invoice\") {\n if (options.sourceAmount != null) {\n throw new Error(\n \"sourceAmount cannot be combined with a BOLT11 invoice destination (the invoice fixes the payout)\",\n );\n }\n return {\n lightningInvoice: destination,\n ...(options.targetAmount != null\n ? { targetAmountSats: Number(options.targetAmount) }\n : {}),\n ...common,\n };\n }\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\n `Provide exactly one of sourceAmount (sats to lock on ${sourceName}) or targetAmount (sats to receive over Lightning) for ${sourceName} → Lightning swaps`,\n );\n }\n const amount =\n options.sourceAmount != null\n ? { sourceAmountSats: Number(options.sourceAmount) }\n : { targetAmountSats: Number(options.targetAmount) };\n if (kind === \"lnurl\") {\n return { lnurl: destination, ...amount, ...common };\n }\n return { lightningAddress: destination, ...amount, ...common };\n}\n\nconst DEFAULT_BASE_URL = \"https://api.satora.io/\";\n\n/**\n * Default Esplora URLs by network. Each list is tried in order, so an\n * outage of the primary explorer fails over to the next one.\n */\nconst DEFAULT_ESPLORA_URLS: Record<string, string[]> = {\n mainnet: [\"https://mempool.space/api\", \"https://blockstream.info/api\"],\n signet: [\"https://mutinynet.com/api\"],\n regtest: [\"http://localhost:3000\"],\n};\n\n/**\n * Default Electrum WebSocket endpoints by network — Satora's own Fulcrum for\n * mainnet, nothing elsewhere. Used when no `electrumWsUrl` is configured, so\n * Bitcoin lookups get push-driven funding detection out of the box; Esplora\n * remains the automatic fallback on any Electrum failure, so an outage of\n * this endpoint degrades to plain Esplora behavior rather than breaking.\n */\nexport const DEFAULT_ELECTRUM_WS_URLS: Record<string, string> = {\n mainnet: \"wss://electrs.satora.io\",\n};\n\n/** Configuration options for the Lendaswap client. */\nexport interface ClientConfig {\n /** The base URL of the Lendaswap API. */\n baseUrl: string;\n /**\n * Optional default referral code (`referral_id` on the swap backend).\n * If set, every `createSwap` / `getQuote` call that doesn't pass its\n * own `referralCode` will use this value. Useful for SDK consumers\n * that always attribute swaps to the same developer key.\n */\n referralCode?: string;\n /** Optional default headers to send with SDK API requests. */\n defaultHeaders?: Record<string, string>;\n /**\n * Optional Esplora API URL(s) for Bitcoin lookups and broadcasting.\n * When a list is given, each URL is tried in order (fallback on failure).\n */\n esploraUrl?: string | string[];\n /**\n * Optional Electrum server WebSocket URL (e.g. \"wss://electrs.satora.io\").\n * Bitcoin lookups, broadcasts, and funding waits go to this server first —\n * with `blockchain.scripthash.subscribe` push notifications replacing\n * polling for funding detection. Esplora remains the fallback whenever the\n * Electrum server is unreachable or errors. Unset, mainnet defaults to\n * Satora's Fulcrum (see `DEFAULT_ELECTRUM_WS_URLS`); other networks stay\n * Esplora-only.\n */\n electrumWsUrl?: string;\n /** Optional Arkade server URL (e.g. \"https://arkade.computer\"). Falls back to network-based defaults. */\n arkadeServerUrl?: string;\n /**\n * Optional account-abstraction config (bundler + Gas Manager policy).\n * Required when using the CCTP-inbound flow; a clear error is thrown\n * on first CCTP API call if omitted.\n */\n aa?: AaConfig;\n /**\n * Optional Solana JSON-RPC URL, used to build and confirm the USDC burn of\n * a swap funded from Solana ({@link Client.fundSwapFromSolana}).\n */\n solanaRpcUrl?: string;\n /** Optional logger sink. The SDK is silent by default. */\n logger?: Logger;\n /** Minimum log level to emit. Defaults to `silent`. */\n logLevel?: LogLevel;\n}\n\n/**\n * Account-abstraction config baked into official npm builds (sponsored gas\n * for CCTP-inbound settlement and UserOp claims).\n */\nfunction defaultAaConfig(): AaConfig | undefined {\n if (!DEFAULT_AA_BUNDLER_URL) return undefined;\n return {\n bundlerUrl: DEFAULT_AA_BUNDLER_URL,\n ...(DEFAULT_AA_POLICY_ID\n ? { paymasterPolicyId: DEFAULT_AA_POLICY_ID }\n : {}),\n };\n}\n\n/**\n * Builder for creating a Lendaswap client with a fluent API.\n *\n * The `build()` method is async and returns a fully initialized client.\n *\n * @example\n * ```ts\n * // Create client with new wallet (generates mnemonic)\n * const client = await Client.builder()\n * .withSignerStorage(new IdbWalletStorage())\n * .build();\n *\n * // Create client with existing mnemonic\n * const client = await Client.builder()\n * .withSignerStorage(new IdbWalletStorage())\n * .withMnemonic(\"abandon abandon abandon ...\")\n * .build();\n *\n * // Create client from a BIP32 extended private key (ephemeral — never persisted).\n * // Useful when the secret lives in an env var, KMS, or external secure store.\n * const client = await Client.builder()\n * .withXprv(\"xprv9s21ZrQH143K...\")\n * .build();\n *\n * // Create client without storage (stateless, generates new mnemonic)\n * const client = await Client.builder().build();\n * ```\n */\nexport class ClientBuilder {\n #baseUrl: string = DEFAULT_BASE_URL;\n #referralCode?: string;\n #defaultHeaders?: Record<string, string>;\n #esploraUrl?: string | string[];\n #electrumWsUrl?: string;\n #arkadeServerUrl?: string;\n #signerStorage?: WalletStorage;\n #swapStorage?: SwapStorage;\n #mnemonic?: string;\n #xprv?: string;\n #aa?: AaConfig;\n #solanaRpcUrl?: string;\n #logger?: Logger;\n #logLevel?: LogLevel;\n\n /**\n * Sets the base URL for the API.\n * @param baseUrl - The base URL of the Lendaswap API.\n * @returns The builder instance for chaining.\n */\n withBaseUrl(baseUrl: string): this {\n this.#baseUrl = baseUrl;\n return this;\n }\n\n /**\n * Sets a default referral code for every `createSwap` / `getQuote`\n * call. Per-call `referralCode` always wins.\n * @returns The builder instance for chaining.\n */\n withReferralCode(referralCode: string): this {\n this.#referralCode = referralCode;\n return this;\n }\n\n /**\n * @deprecated Use {@link withReferralCode}. Kept as a backwards-compat\n * alias for SDK consumers that haven't migrated from the old\n * `X-Org-Code` model — both sides flow through the same per-call\n * `referral_code` plumbing now.\n */\n withOrgCode(orgCode: string): this {\n return this.withReferralCode(orgCode);\n }\n\n /**\n * Sets default headers to send with SDK API requests.\n * @param headers - Headers merged into API requests made by the SDK.\n * @returns The builder instance for chaining.\n */\n withDefaultHeaders(headers: Record<string, string>): this {\n this.#defaultHeaders = {\n ...this.#defaultHeaders,\n ...headers,\n };\n return this;\n }\n\n /**\n * Sets the Esplora API URL(s) for Bitcoin lookups and broadcasting.\n *\n * Pass a list to enable fallback: each URL is tried in order until one\n * responds. If not set, network-based defaults are used.\n *\n * @param esploraUrl - Esplora API base URL, or a list tried in order.\n * @returns The builder instance for chaining.\n */\n withEsploraUrl(esploraUrl: string | string[]): this {\n this.#esploraUrl = esploraUrl;\n return this;\n }\n\n /**\n * Sets an Electrum server WebSocket URL (Fulcrum `ws`/`wss` port) for\n * Bitcoin chain access. It is preferred over Esplora for lookups and\n * broadcasts, and funding waits become push-driven via\n * `blockchain.scripthash.subscribe`. Esplora stays as the fallback.\n * If not set, mainnet defaults to Satora's Fulcrum\n * (see {@link DEFAULT_ELECTRUM_WS_URLS}); other networks stay Esplora-only.\n *\n * @param electrumWsUrl - e.g. `wss://electrs.satora.io`\n * @returns The builder instance for chaining.\n */\n withElectrumWsUrl(electrumWsUrl: string): this {\n this.#electrumWsUrl = electrumWsUrl;\n return this;\n }\n\n /**\n * Sets the Arkade server URL for VHTLC operations (claim, refund, amounts).\n *\n * If not set, defaults are used based on the network:\n * - bitcoin: https://arkade.computer\n * - signet: wa\n *\n * @param arkadeServerUrl - The Arkade server base URL.\n * @returns The builder instance for chaining.\n */\n withArkadeServerUrl(arkadeServerUrl: string): this {\n this.#arkadeServerUrl = arkadeServerUrl;\n return this;\n }\n\n /**\n * Sets the storage backend for signer data (mnemonic and key index).\n * @param storage - The storage implementation to use.\n * @returns The builder instance for chaining.\n */\n withSignerStorage(storage: WalletStorage): this {\n this.#signerStorage = storage;\n return this;\n }\n\n /**\n * Sets the storage backend for swap data.\n *\n * When configured, swaps will be automatically persisted after creation.\n *\n * @param storage - The swap storage implementation to use.\n * @returns The builder instance for chaining.\n */\n withSwapStorage(storage: SwapStorage): this {\n this.#swapStorage = storage;\n return this;\n }\n\n /**\n * Sets the mnemonic phrase to use for the signer.\n *\n * If provided, this mnemonic will be used instead of loading from storage\n * or generating a new one. The mnemonic will be persisted to storage if\n * storage is configured.\n *\n * @param mnemonic - The BIP39 mnemonic phrase (12, 15, 18, 21, or 24 words).\n * @returns The builder instance for chaining.\n */\n withMnemonic(mnemonic: string): this {\n this.#mnemonic = mnemonic;\n return this;\n }\n\n /**\n * Sets a BIP32 extended private key (xprv) to use for the signer.\n *\n * The xprv is treated as ephemeral: it is **never** persisted to signer\n * storage, even if storage is configured. The caller is responsible for\n * supplying it on every `build()` (e.g. from an env var, KMS, or vault).\n * Storage, if configured, is still used for the swap key index counter.\n *\n * Cannot be combined with `withMnemonic()`.\n *\n * @param xprv - The base58check-encoded extended private key.\n * @returns The builder instance for chaining.\n * @throws Error if `xprv` is empty or whitespace-only — fail fast on a\n * misconfigured secret rather than silently falling back to storage.\n */\n withXprv(xprv: string): this {\n if (typeof xprv !== \"string\" || xprv.trim().length === 0) {\n throw new Error(\"withXprv() requires a non-empty xprv string\");\n }\n this.#xprv = xprv;\n return this;\n }\n\n /**\n * Sets the account-abstraction config (bundler + Gas Manager policy).\n *\n * Official npm builds ship a baked-in default (Satora's sponsored\n * bundler + policy, the same values the hosted frontend uses); calling\n * this overrides it. Local/dev builds have no default, so this is\n * required when using the CCTP-inbound swap flow (any non-Arbitrum\n * EVM chain as the source). The settlement UserOp — `receiveMessage`\n * + `USDC.approve(Permit2)` + `executeAndCreateWithPermit2` — is\n * submitted via the Kernel smart account owned by the consumer's\n * connected wallet, sponsored by the Gas Manager so users need no\n * ETH on Arbitrum.\n *\n * @param aa - Bundler URL + paymaster policy id.\n * @returns The builder instance for chaining.\n */\n withAa(aa: AaConfig): this {\n this.#aa = aa;\n return this;\n }\n\n /**\n * Sets the Solana JSON-RPC URL used to fund swaps from Solana\n * ({@link Client.fundSwapFromSolana}): it fetches the blockhash, simulates\n * the USDC burn and confirms it. Public endpoints rate-limit hard; use a\n * dedicated one in production.\n */\n withSolanaRpcUrl(url: string): this {\n this.#solanaRpcUrl = url;\n return this;\n }\n\n /**\n * Sets the logger sink used by the SDK.\n *\n * The SDK is silent by default. Pair this with `withLogLevel()` to opt in\n * to runtime logs.\n */\n withLogger(logger: Logger): this {\n this.#logger = logger;\n return this;\n }\n\n /**\n * Sets the minimum log level emitted by the SDK.\n *\n * Defaults to `silent`.\n */\n withLogLevel(logLevel: LogLevel): this {\n this.#logLevel = logLevel;\n return this;\n }\n\n /**\n * Builds and returns a fully initialized Client instance.\n *\n * Initialization order:\n * 1. If `withXprv()` was called, use that xprv (ephemeral, never stored)\n * 2. Else if `withMnemonic()` was called, use that mnemonic\n * 3. Else if storage is configured and contains a mnemonic, load it\n * 4. Else generate a new mnemonic\n *\n * The mnemonic is persisted to storage if storage is configured. An xprv\n * is never persisted.\n *\n * @returns A promise that resolves to a fully initialized Client.\n * @throws Error if the provided mnemonic or xprv is invalid, or if both\n * `withMnemonic()` and `withXprv()` were called.\n */\n async build(): Promise<Client> {\n if (this.#xprv && this.#mnemonic) {\n throw new Error(\n \"withMnemonic() and withXprv() are mutually exclusive — pick one\",\n );\n }\n\n let signer: Signer;\n\n if (this.#xprv) {\n // Ephemeral xprv — never touch signer storage for the secret\n signer = Signer.fromXprv(this.#xprv);\n } else if (this.#mnemonic) {\n // Use provided mnemonic\n signer = Signer.fromMnemonic(this.#mnemonic);\n if (this.#signerStorage) {\n await this.#signerStorage.setMnemonic(this.#mnemonic);\n }\n } else if (this.#signerStorage) {\n // Try to load from storage\n const storedMnemonic = await this.#signerStorage.getMnemonic();\n if (storedMnemonic) {\n signer = Signer.fromMnemonic(storedMnemonic);\n } else {\n // Generate new and persist\n signer = Signer.generate();\n // Signer.generate() always populates mnemonic\n await this.#signerStorage.setMnemonic(signer.mnemonic as string);\n }\n } else {\n // No storage, generate new (stateless mode)\n signer = Signer.generate();\n }\n\n return new Client(\n {\n baseUrl: this.#baseUrl.replace(/\\/+$/, \"\"),\n referralCode: this.#referralCode,\n defaultHeaders: this.#defaultHeaders,\n esploraUrl: Array.isArray(this.#esploraUrl)\n ? this.#esploraUrl.map((url) => url.replace(/\\/+$/, \"\"))\n : this.#esploraUrl?.replace(/\\/+$/, \"\"),\n electrumWsUrl: this.#electrumWsUrl?.replace(/\\/+$/, \"\"),\n arkadeServerUrl: this.#arkadeServerUrl?.replace(/\\/+$/, \"\"),\n aa: this.#aa ?? defaultAaConfig(),\n solanaRpcUrl: this.#solanaRpcUrl,\n logger: this.#logger,\n logLevel: this.#logLevel,\n },\n signer,\n this.#signerStorage,\n this.#swapStorage,\n );\n }\n}\n\n/**\n * Main client for interacting with the Lendaswap API.\n *\n * The client manages:\n * - API communication\n * - Signer (HD wallet) for key derivation\n * - Storage for persisting mnemonic and key index\n *\n * Use `Client.builder()` to create a new instance.\n *\n * @example\n * ```ts\n * const client = await Client.builder()\n * .withSignerStorage(new IdbWalletStorage())\n * .build();\n *\n * // Get mnemonic (for backup)\n * const mnemonic = client.getMnemonic();\n *\n * // Derive swap parameters\n * const params = await client.deriveSwapParams();\n * ```\n */\n/**\n * Chain the AA config (bundler, paymaster, 7702 Kernel delegation) applies\n * to. Must match `createSwapSmartAccountClient` in `cctp-inbound/smartAccount.ts`.\n */\nconst AA_CHAIN_ID = 42161;\n\nexport class Client {\n readonly #apiClient: ApiClient;\n readonly #config: ClientConfig;\n #signer: Signer;\n /**\n * Short-TTL memo for `composeQuote`'s session-static primitives\n * (`/swap-pairs`, `/chain-config`, `/referral-fee`) so a keystroke-driven UI\n * doesn't re-fetch them on every recompute. Keyed by request; caches the\n * in-flight promise so concurrent recomputes share one round-trip, and evicts\n * on rejection so errors aren't sticky. `/network-fees` is intentionally not\n * cached — it tracks live gas.\n */\n readonly #composeStaticCache = new Map<\n string,\n { promise: Promise<unknown>; expiry: number }\n >();\n readonly #signerStorage?: WalletStorage;\n readonly #swapStorage?: SwapStorage;\n #statusWatcher: SwapStatusWatcher | null = null;\n #cctpInbound: CctpInboundClient | null = null;\n #electrumWs: ElectrumWsClient | null = null;\n readonly #logger: SdkLogger;\n\n /**\n * Creates a new Client instance.\n *\n * Use `Client.builder()` instead of calling this constructor directly.\n *\n * @internal\n */\n constructor(\n config: ClientConfig,\n signer: Signer,\n signerStorage?: WalletStorage,\n swapStorage?: SwapStorage,\n ) {\n this.#config = config;\n this.#apiClient = createApiClient({\n baseUrl: config.baseUrl,\n defaultHeaders: config.defaultHeaders,\n });\n this.#signer = signer;\n this.#signerStorage = signerStorage;\n this.#swapStorage = swapStorage;\n this.#logger = createSdkLogger({\n logger: config.logger,\n logLevel: config.logLevel,\n });\n }\n\n #apiHeaders(extra?: Record<string, string>): Record<string, string> {\n return {\n \"X-Lendaswap-Client\": CLIENT_AGENT,\n ...PROTOCOL_HEADERS,\n ...(this.#config.defaultHeaders ?? {}),\n ...(extra ?? {}),\n };\n }\n\n /**\n * Subscribe to status updates for one or more swaps over a shared WebSocket.\n * The socket is opened lazily on first call and closed automatically when\n * the last subscriber unsubscribes.\n *\n * @param swapIds Swap ids to watch.\n * @param onUpdate Fires with `(swapId, status)` for every status change of\n * any id in the set.\n * @returns Unsubscribe function that removes `onUpdate` from all of the\n * passed ids at once.\n */\n subscribeToSwaps(swapIds: string[], onUpdate: SwapStatusHandler): () => void {\n if (!this.#statusWatcher) {\n this.#statusWatcher = createSwapStatusWatcher(this.#config.baseUrl);\n }\n return this.#statusWatcher.subscribe(swapIds, onUpdate);\n }\n\n /**\n * Remove `onUpdate` from the given swap ids.\n */\n unsubscribeFromSwaps(swapIds: string[], onUpdate: SwapStatusHandler): void {\n this.#statusWatcher?.unsubscribe(swapIds, onUpdate);\n }\n\n /** Force-close the shared swap-status socket. */\n closeSwapStatusSocket(): void {\n this.#statusWatcher?.close();\n this.#statusWatcher = null;\n }\n\n /**\n * Creates a new ClientBuilder for fluent configuration.\n * @returns A new ClientBuilder instance.\n */\n static builder(): ClientBuilder {\n return new ClientBuilder();\n }\n\n /** The underlying typed API client for direct API access. */\n get api(): ApiClient {\n return this.#apiClient;\n }\n\n /** The base URL of the API. */\n get baseUrl(): string {\n return this.#config.baseUrl;\n }\n\n /**\n * Namespace for CCTP-inbound swap primitives (source-chain burn,\n * IRIS attestation, settlement UserOp). Requires `withAa(...)` on\n * the builder — throws with a clear error otherwise.\n *\n * For simple integrations prefer `Client.fundSwap(swapId, signer)`\n * which auto-dispatches to the CCTP path when needed; drop down to\n * `client.cctpInbound.*` when you need step-by-step progress control.\n */\n get cctpInbound(): CctpInboundClient {\n if (!this.#cctpInbound) {\n if (!this.#config.aa) {\n throw new Error(\n \"CCTP-inbound flow requires AA config. Call `.withAa({ bundlerUrl, paymasterPolicyId })` on the ClientBuilder before `.build()`.\",\n );\n }\n this.#cctpInbound = new CctpInboundClient({\n apiClient: this.#apiClient,\n aa: this.#config.aa,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n }\n return this.#cctpInbound;\n }\n\n /** The swap storage, if configured. */\n get swapStorage(): SwapStorage | undefined {\n return this.#swapStorage;\n }\n\n // =========================================================================\n // Signer Methods\n // =========================================================================\n\n /**\n * Gets the mnemonic phrase.\n *\n * Store this securely - it's the only way to recover the wallet.\n *\n * @returns The BIP39 mnemonic phrase.\n * @throws Error if the wallet was initialized from an xprv (no mnemonic exists).\n */\n getMnemonic(): string {\n const mnemonic = this.#signer.mnemonic;\n if (!mnemonic) {\n throw new Error(\n \"No mnemonic available — wallet was initialized from an xprv\",\n );\n }\n return mnemonic;\n }\n\n /**\n * Loads a mnemonic phrase, replacing the current signer.\n *\n * The new mnemonic is persisted to storage if storage is configured.\n *\n * @param mnemonic - The BIP39 mnemonic phrase to load.\n * @throws Error if the mnemonic is invalid.\n */\n async loadMnemonic(mnemonic: string): Promise<void> {\n this.#signer = Signer.fromMnemonic(mnemonic);\n if (this.#signerStorage) {\n await this.#signerStorage.setMnemonic(mnemonic);\n }\n }\n\n /**\n * Derives a deterministic Nostr private key from the wallet mnemonic.\n *\n * Uses the NIP-06 derivation path so the same mnemonic always produces\n * the same Nostr identity.\n *\n * @returns The 32-byte Nostr private key as a hex string.\n */\n getNostrKeyHex(): string {\n return this.#signer.deriveNostrKeyHex();\n }\n\n /**\n * Gets the user ID extended public key for wallet recovery.\n *\n * This can be shared with the server for recovering swap history.\n *\n * @returns The hex-encoded user ID xpub.\n */\n getUserIdXpub(): string {\n return this.#signer.getUserIdXpubString();\n }\n\n /**\n * Derives swap parameters at the next available index.\n *\n * Automatically increments the key index in storage (if configured).\n *\n * @returns The derived swap parameters.\n */\n async deriveSwapParams(): Promise<SwapParams> {\n let index = 0;\n if (this.#signerStorage) {\n index = await this.#signerStorage.incrementKeyIndex();\n }\n return this.#signer.deriveSwapParams(index);\n }\n\n /**\n * Derives swap parameters at a specific index.\n *\n * Does not modify the stored key index. Useful for recovery scenarios.\n *\n * @param index - The key index to derive.\n * @returns The derived swap parameters.\n */\n deriveSwapParamsAtIndex(index: number): SwapParams {\n return this.#signer.deriveSwapParams(index);\n }\n\n /**\n * Get the deterministic EVM address for this SDK key.\n *\n * This address is reused across all gasless swaps, so a single\n * Permit2 approval is sufficient for multiple swaps.\n *\n * @returns Checksummed EVM address (0x-prefixed).\n */\n getEvmAddress(): string {\n const { secretKey } = this.#signer.deriveEvmKey();\n return deriveEvmAddress(secretKey);\n }\n\n /**\n * Get the EVM signing key, derived deterministically from the mnemonic.\n *\n * @internal\n */\n #getEvmSigningKey(): string {\n return bytesToHex(this.#signer.deriveEvmKey().secretKey);\n }\n\n /**\n * Sign an EIP-712 digest (Permit2 witness or EIP-2612 permit) with the\n * SDK-controlled EVM key in the format the verifying contract will\n * accept for `depositor`.\n *\n * A sponsored UserOp claim delegates the SDK's EVM address to Kernel V3.3\n * via EIP-7702. From then on the address has code, so Permit2 verifies\n * through Kernel's `isValidSignature` instead of `ecrecover`. In that case\n * this returns Kernel's ERC-1271 envelope (66 bytes: `0x00 || sig` over\n * the `Kernel(bytes32 hash)` wrapper). Otherwise a plain 65-byte\n * `r || s || v` signature. `delegated` comes from\n * {@link Client.#isKernelDelegated}.\n */\n #signDepositorDigest(\n evmKey: string,\n depositor: string,\n chainId: number,\n digest: string,\n delegated: boolean,\n ): string {\n const toSign = delegated\n ? kernelErc1271Digest(digest, depositor, chainId)\n : digest;\n const sig = signEvmDigest(evmKey, toSign);\n const compact = `0x${sig.r.replace(/^0x/, \"\")}${sig.s.replace(/^0x/, \"\")}${sig.v\n .toString(16)\n .padStart(2, \"0\")}`;\n return delegated ? wrapKernelErc1271Signature(compact) : compact;\n }\n\n /**\n * Whether the depositor must sign in Kernel's ERC-1271 envelope on\n * `chainId`.\n *\n * `serverHint` is the calldata endpoint's `depositor_delegation`: the\n * EIP-7702 target the depositor's code points at on the source chain,\n * `null` for a plain EOA. A delegation is per chain and this SDK holds\n * no RPC for most chains, so the server's view is authoritative. Only\n * when an older server omits the field do we fall back to probing the\n * AA RPC, which is Arbitrum-only.\n *\n * A delegation to anything other than Kernel V3.3 cannot be signed for\n * by this SDK (Permit2 would hand the signature to unknown code), so it\n * throws rather than let the relayer dry-run explain it.\n */\n /**\n * The calldata endpoint's `depositor_delegation` describes the swap's\n * recorded `client_evm_address`. For gasless swaps that is the SDK's own\n * key; for non-gasless swaps it is the user's wallet, which may differ\n * from the key this SDK signs Permit2 with. Only hand the hint on when\n * it was looked up for the address we actually sign for; otherwise the\n * caller falls back to probing.\n */\n #delegationHintFor(\n swap: { client_evm_address?: string | null },\n depositor: string,\n hint: string | null | undefined,\n ): string | null | undefined {\n const hinted = swap.client_evm_address?.toLowerCase();\n return hinted && hinted === depositor.toLowerCase() ? hint : undefined;\n }\n\n async #isKernelDelegated(\n address: string,\n chainId: number,\n serverHint: string | null | undefined,\n ): Promise<boolean> {\n if (serverHint !== undefined) {\n if (serverHint === null) return false;\n if (serverHint.toLowerCase() === KERNEL_DELEGATION_TARGET.toLowerCase()) {\n return true;\n }\n throw new Error(\n `Depositor ${address} is EIP-7702-delegated to ${serverHint} on chain ${chainId}, ` +\n `which this SDK cannot sign for. Expected Kernel V3.3 (${KERNEL_DELEGATION_TARGET}) ` +\n `or a plain EOA. Revoke the delegation or use a separate key for gasless deposits.`,\n );\n }\n if (chainId !== AA_CHAIN_ID) return false;\n const rpcUrl = this.#config.aa?.rpcUrl ?? this.#config.aa?.bundlerUrl;\n if (!rpcUrl) return false;\n const { createPublicClient, http } = await import(\"viem\");\n const publicClient = createPublicClient({ transport: http(rpcUrl) });\n try {\n const code = await publicClient.getCode({\n address: address as `0x${string}`,\n });\n return isKernelDelegation(code);\n } catch (e) {\n // Fall back to the plain signature; if the address is in fact\n // delegated the server's pre-broadcast dry-run rejects it with a\n // clear reason instead of burning gas.\n this.#logger.warn({\n event: \"client.isKernelDelegated.codeLookupFailed\",\n message:\n \"could not read code to detect Kernel delegation; assuming plain EOA\",\n data: { address, error: e instanceof Error ? e.message : String(e) },\n });\n return false;\n }\n }\n\n /**\n * Select the SDK-controlled EVM key that signs and publishes the claim of\n * an inbound (BTC / Arkade / Lightning → EVM) swap.\n *\n * New swaps are created with the per-swap key as `claiming_address`, so\n * the sponsored claim's EIP-7702 delegation never lands on the wallet-level\n * deposit address. Swaps created before that still carry the wallet-level\n * address and keep claiming with it.\n */\n #getClaimEvmSigningKey(storedSwap: StoredSwap): string {\n const swapKey = storedSwap.secretKey;\n const clientAddress = (\n storedSwap.response as { client_evm_address?: string }\n ).client_evm_address?.toLowerCase();\n if (\n swapKey &&\n clientAddress &&\n clientAddress === deriveEvmAddress(swapKey).toLowerCase()\n ) {\n return swapKey;\n }\n return this.#getEvmSigningKey();\n }\n\n /**\n * Select the SDK-controlled EVM key that matches the swap's recorded depositor.\n *\n * Current gasless EVM-sourced swaps use the deterministic wallet-level EVM key;\n * older gasless swaps may have used the per-swap key. Non-gasless SDK-funded\n * swaps still use the per-swap key even though client_evm_address may point at\n * the user's wallet rather than the later Permit2 depositor.\n */\n #getCollabRefundEvmSigningKey(\n storedSwap: StoredSwap,\n walletMethod = \"collabRefundEvmWithSigner\",\n ): string {\n const swapKey = storedSwap.secretKey;\n const response = storedSwap.response as {\n client_evm_address?: string;\n gasless?: boolean;\n };\n\n if (!response.gasless) {\n return swapKey;\n }\n\n const deterministicKey = this.#getEvmSigningKey();\n const deterministicAddress = deriveEvmAddress(deterministicKey);\n const swapAddress = deriveEvmAddress(swapKey);\n const clientAddress = response.client_evm_address?.toLowerCase();\n\n if (\n clientAddress === deterministicAddress.toLowerCase() ||\n !clientAddress\n ) {\n return deterministicKey;\n }\n if (clientAddress === swapAddress.toLowerCase()) {\n return swapKey;\n }\n\n throw new Error(\n `Cannot sign for this swap with an SDK-controlled key: swap depositor is ${\n response.client_evm_address ?? \"unknown\"\n }, but SDK-controlled addresses are ${deterministicAddress} (current gasless key) and ${swapAddress} (legacy per-swap key). Use ${walletMethod} with the depositor wallet instead.`,\n );\n }\n\n /**\n * Gets the current key index from storage.\n * @returns The current key index, or 0 if no storage is configured.\n */\n async getKeyIndex(): Promise<number> {\n if (this.#signerStorage) {\n return this.#signerStorage.getKeyIndex();\n }\n return 0;\n }\n\n /**\n * Sets the key index in storage.\n *\n * Useful for recovery scenarios where you need to set the index\n * to a specific value.\n *\n * @param index - The new key index.\n * @throws Error if no storage is configured.\n */\n async setKeyIndex(index: number): Promise<void> {\n if (!this.#signerStorage) {\n throw new Error(\"No signer storage configured\");\n }\n await this.#signerStorage.setKeyIndex(index);\n }\n\n // =========================================================================\n // Health & Info\n // =========================================================================\n\n /**\n * Gets the aggregated status of the API and its external dependencies.\n *\n * Returns the status body for both healthy (200) and unhealthy (503) responses.\n * @throws Error if the status response is missing or malformed.\n */\n async getStatus(): Promise<StatusResponse> {\n const { data, error } = await this.#apiClient.GET(\"/status\");\n\n if (error) {\n // openapi-fetch puts non-2xx response bodies in `error`.\n // /status returns StatusResponse for both 200 and expected 503 responses.\n if (isStatusResponse(error)) {\n return error;\n }\n\n throw new Error(`Failed to get status: ${JSON.stringify(error)}`);\n }\n\n return data;\n }\n\n /**\n * Checks the health status of the API.\n * @deprecated Use {@link getStatus} for detailed dependency health.\n * @returns A promise that resolves to \"ok\" if the API is healthy.\n * @throws Error if the health check fails.\n */\n async healthCheck(): Promise<string> {\n const { data, error } = await this.#apiClient.GET(\"/health\");\n if (error) {\n throw new Error(`Health check failed: ${JSON.stringify(error)}`);\n }\n return data ?? \"ok\";\n }\n\n /**\n * Gets the version information of the API.\n * @returns A promise that resolves to the version info containing tag and commit hash.\n * @throws Error if the request fails.\n */\n async getVersion(): Promise<{ tag: string; commit_hash: string }> {\n const { data, error } = await this.#apiClient.GET(\"/version\");\n if (error) {\n throw new Error(`Failed to get version: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No version data returned\");\n }\n return data;\n }\n\n /**\n * Gets the list of support agent npubs from the backend config.\n * @returns A promise that resolves to an array of support agent info objects.\n * @throws Error if the request fails.\n */\n async getSupportAgents(): Promise<SupportAgentInfo[]> {\n const baseUrl = this.#config.baseUrl.replace(/\\/$/, \"\");\n const resp = await fetch(`${baseUrl}/support-agents`, {\n headers: this.#apiHeaders(),\n });\n if (!resp.ok) {\n throw new Error(`Failed to get support agents: ${resp.status}`);\n }\n const data: { agents: SupportAgentInfo[] } = await resp.json();\n return data.agents;\n }\n\n /**\n * Gets the current Median Time Past (MTP) and tip block height.\n * @returns A promise that resolves to the MTP timestamp and tip height.\n * @throws Error if the request fails or MTP is not yet available.\n */\n async getMtp(): Promise<{ mtp: number; tip_height: number }> {\n const { data, error } = await this.#apiClient.GET(\"/mtp\");\n if (error) {\n throw new Error(`Failed to get MTP: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"MTP not available yet\");\n }\n return data;\n }\n\n // =========================================================================\n // Tokens & Asset Pairs\n // =========================================================================\n\n /**\n * Gets the list of supported tokens.\n * @returns A promise that resolves to an array of token information.\n * @throws Error if the request fails.\n */\n async getTokens(): Promise<TokenInfos> {\n const { data, error } = await this.#apiClient.GET(\"/tokens\");\n if (error || !data) {\n throw new Error(`Failed to get tokens: ${JSON.stringify(error)}`);\n }\n return data;\n }\n\n /**\n * Gets all supported swap pairs with their limits (in satoshis) and base fee percentages.\n * @returns A promise that resolves to all swap pairs with limits and fees.\n * @throws Error if the request fails.\n */\n async getSwapPairs(): Promise<SwapPairsResponse> {\n const { data, error } = await this.#apiClient.GET(\"/swap-pairs\");\n if (error || !data) {\n throw new Error(`Failed to get swap pairs: ${JSON.stringify(error)}`);\n }\n return fromWireSwapPairsResponse(data as WireSwapPairsResponse);\n }\n\n /**\n * Per-EVM-chain configuration — BTC-pegged pivot token today, HTLC\n * and coordinator contract addresses planned. Static at the\n * timescale of an SDK session; callers should fetch once and cache.\n */\n async getChainConfig(): Promise<ChainConfigResponse> {\n const { data, error } = await this.#apiClient.GET(\"/chain-config\");\n if (error || !data) {\n throw new Error(`Failed to get chain config: ${JSON.stringify(error)}`);\n }\n return fromWireChainConfigResponse(data as WireChainConfigResponse);\n }\n\n /**\n * The RIF Relay a native lock on EVM chain `chainId` is claimed through,\n * or `undefined` when no relay is configured. A swap claimed through\n * RIF Relay needs the receiving wallet to sign: `claimEvmWithSigner`.\n */\n async getRifRelay(chainId: number): Promise<RifRelayConfig | undefined> {\n const config = await this.#composeStatic(\"chain-config\", () =>\n this.getChainConfig(),\n );\n return config.chains.find((c) => String(c.chain) === String(chainId))\n ?.rif_relay;\n }\n\n /**\n * The claim address of a native lock on a chain that claims through RIF\n * Relay: the recipient's smart wallet, which only the recipient's wallet\n * can claim from (the server rejects any other). `undefined` elsewhere.\n */\n async #rifClaimAddress(options: {\n targetAddress: string;\n tokenAddress: string;\n evmChainId: number;\n bridgeParams?: unknown;\n }): Promise<string | undefined> {\n if (options.bridgeParams != null) return undefined;\n if (!isNativeLockTarget(String(options.evmChainId), options.tokenAddress)) {\n return undefined;\n }\n const relay = await this.getRifRelay(options.evmChainId);\n return relay\n ? rifSmartWalletAddress(relay, options.targetAddress)\n : undefined;\n }\n\n /** The RIF Relay a swap's claim must go through, if it is a native lock there. */\n async #rifRelayForClaim(\n swap: ArkadeToEvmSwapResponse,\n ): Promise<RifRelayConfig | undefined> {\n if (!nativeHtlcKind(swap)) return undefined;\n return this.getRifRelay(swap.evm_chain_id);\n }\n\n /**\n * The referral/extra-fee delta for a referral code — a decimal fraction to\n * add on top of `getSwapPairs()`'s per-pair `fee_percentage` when composing\n * a quote. The fourth composition primitive; the server resolves the key's\n * default/cap logic (and 400s if `extraFees` exceeds the key's cap), so the\n * client never handles bps.\n */\n async getReferralFee(params: {\n referralCode?: string;\n extraFees?: number;\n }): Promise<ReferralFeeResponse> {\n const { data, error } = await this.#apiClient.GET(\"/referral-fee\", {\n params: {\n query: { ref: params.referralCode, extra_fees: params.extraFees },\n },\n });\n if (error || !data) {\n throw new Error(`Failed to get referral fee: ${JSON.stringify(error)}`);\n }\n return fromWireReferralFeeResponse(data as WireReferralFeeResponse);\n }\n\n /**\n * Per-pair network-fee estimates in sats at current gas/mining prices.\n *\n * One of three primitives a client combines to compose an end-to-end\n * quote (alongside `getSwapPairs()` and `getDexQuote()`). The values\n * come from the server's gas cache, which refreshes every ~15s;\n * clients can poll at the same cadence.\n */\n async getNetworkFees(): Promise<NetworkFeesResponse> {\n const { data, error } = await this.#apiClient.GET(\"/network-fees\");\n if (error || !data) {\n throw new Error(`Failed to get network fees: ${JSON.stringify(error)}`);\n }\n return fromWireNetworkFeesResponse(data as WireNetworkFeesResponse);\n }\n\n /**\n * Price-discovery quote for the EVM leg of a foreign-target swap.\n *\n * Companion to `/dex-calldata`: same request shape minus the\n * execution-time fields. The response carries a `cache_ttl_seconds`\n * hint clients should honour as their cache window.\n *\n * @param params.from Source asset (`Token::Evm` today; `Solana` rejected).\n * @param params.to Target asset.\n * @param params.amount `{ kind: \"exact_in\" | \"exact_out\", value: string }` — `value` is a\n * stringified `u256` in smallest units.\n * @param params.slippageBps Slippage tolerance the SDK will use at execution. Bounded\n * server-side; out-of-range values throw.\n */\n async getDexQuote(params: {\n from: Token;\n to: Token;\n amount: DexQuoteAmount;\n slippageBps: number;\n /**\n * `true` when the CCTP recipient's USDC account doesn't exist yet (fresh\n * non-EVM recipient, e.g. Solana) — folds the higher ATA-setup flat fee.\n */\n recipientSetup?: boolean;\n }): Promise<DexQuoteResponse> {\n const { data, error } = await this.#apiClient.POST(\"/dex-quote\", {\n body: {\n from: params.from,\n to: params.to,\n amount: params.amount,\n slippage_bps: params.slippageBps,\n cctp_recipient_setup: params.recipientSetup,\n },\n });\n if (error || !data) {\n throw new Error(`Failed to get DEX quote: ${JSON.stringify(error)}`);\n }\n return fromWireDexQuoteResponse(data as WireDexQuoteResponse);\n }\n\n /**\n * Compose an end-to-end `QuoteResponse` from the three primitives\n * (`/swap-pairs` + `/network-fees` + `/dex-quote`) instead of hitting\n * the server-composed `/quote`.\n *\n * Drop-in compatible with the subset of `getQuote()` it supports.\n * Throws `UnsupportedComposeQuotePath` for paths v0 doesn't handle\n * (bridges, target-amount-pinned, Lightning/Arkade pivots, etc.) —\n * callers should fall back to `getQuote()` for those.\n *\n * Fetches `/swap-pairs` and `/network-fees` on each call. Hot loops\n * can use {@link composeQuote} directly (in `compose-quote.ts`),\n * which takes pre-fetched primitives as a dependency object.\n */\n async composeQuote(params: ComposeQuoteParams): Promise<QuoteResponse> {\n // Only fetch the referral delta when a referral / extra-fee is in play —\n // otherwise it's a guaranteed-zero round-trip. It's session-static per\n // (code, extraFees), so cache it like the other primitives.\n const referralFee =\n params.referralCode != null || params.extraFees != null\n ? this.#composeStatic(\n `referral-fee|${params.referralCode ?? \"\"}|${params.extraFees ?? \"\"}`,\n () =>\n this.getReferralFee({\n referralCode: params.referralCode,\n extraFees: params.extraFees,\n }),\n )\n : Promise.resolve(undefined);\n // `/swap-pairs` and `/chain-config` are static at the session timescale —\n // cache them so keystroke-driven recomputes don't re-fetch. `/network-fees`\n // tracks live gas, so it's always fetched fresh.\n const [swapPairs, networkFees, chainConfig, referral] = await Promise.all([\n this.#composeStatic(\"swap-pairs\", () => this.getSwapPairs()),\n this.getNetworkFees(),\n this.#composeStatic(\"chain-config\", () => this.getChainConfig()),\n referralFee,\n ]);\n return composeQuoteHelper(params, {\n swapPairs,\n networkFees,\n chainConfig,\n referralExtraFeeRate: referral?.extra_fee_rate,\n referralBaseFeeRate: referral?.base_fee_rate,\n getDexQuote: (p) => this.getDexQuote(p),\n });\n }\n\n /** TTL window for `composeQuote`'s static-primitive memo. */\n static readonly #COMPOSE_STATIC_TTL_MS = 60_000;\n\n /**\n * Memoize a session-static compose primitive for {@link Client.#COMPOSE_STATIC_TTL_MS}.\n * Caches the in-flight promise (so concurrent recomputes share one round-trip)\n * and evicts on rejection (so a transient failure isn't cached).\n */\n #composeStatic<T>(key: string, fetcher: () => Promise<T>): Promise<T> {\n const hit = this.#composeStaticCache.get(key);\n if (hit && hit.expiry > Date.now()) {\n return hit.promise as Promise<T>;\n }\n const promise = fetcher();\n const entry = {\n promise,\n expiry: Date.now() + Client.#COMPOSE_STATIC_TTL_MS,\n };\n this.#composeStaticCache.set(key, entry);\n promise.catch(() => {\n // Evict only if this exact entry is still current, so we don't clobber a\n // newer successful fetch that replaced it.\n if (this.#composeStaticCache.get(key) === entry) {\n this.#composeStaticCache.delete(key);\n }\n });\n return promise;\n }\n\n // =========================================================================\n // Quotes\n // =========================================================================\n\n /**\n * Gets a quote for swapping between two tokens.\n *\n * Composes the quote client-side from the `/swap-pairs` + `/network-fees` +\n * `/dex-quote` primitives when it can — BTC↔EVM both directions, direct\n * (hub chains) or bridged (via Arbitrum/CCTP/OFT), including EURe and the\n * accurate Lightning routing fee. Falls back to the server-composed `/quote`\n * for anything compose can't faithfully serve: referral / extra-fee pricing\n * (only the server applies those), Solana destinations, and any path\n * `composeQuote` doesn't handle. The returned shape is identical either way.\n *\n * @param params - Quote parameters.\n * @returns A promise that resolves to the quote response with pricing details.\n * @throws Error if the request fails.\n */\n async getQuote(params: GetQuoteParams): Promise<QuoteResponse> {\n // Arkade/Bitcoin/EVM → Lightning with a concrete destination: serve the\n // quote from /quote/lightning-send, which prices the provider's real\n // send fee for that exact payment. Fall back to the estimate paths on\n // any failure (bad destination, LNURL service down, ...): a create\n // would surface the real error.\n if (\n params.lightningDestination &&\n params.targetChain === \"Lightning\" &&\n (params.sourceChain === \"Arkade\" ||\n params.sourceChain === \"Bitcoin\" ||\n isEvmSwapSource(params.sourceChain, params.sourceToken))\n ) {\n try {\n return await this.#lightningSendQuoteAsQuote(\n params,\n params.lightningDestination,\n );\n } catch (err) {\n this.#logger.warn({\n event: \"client.getQuote.lightningSendFallback\",\n message:\n \"exact lightning send quote failed; falling back to estimate\",\n data: { error: err instanceof Error ? err.message : String(err) },\n });\n }\n }\n if (this.#canComposeQuote(params)) {\n try {\n return await this.composeQuote({\n sourceChain: params.sourceChain,\n sourceToken: params.sourceToken,\n targetChain: params.targetChain,\n targetToken: params.targetToken,\n sourceAmount: params.sourceAmount,\n targetAmount: params.targetAmount,\n // Per-call referral wins; fall back to the client default.\n referralCode: params.referralCode ?? this.#config.referralCode,\n extraFees: params.extraFees,\n bridgeRecipientSetup: params.bridgeRecipientSetup,\n });\n } catch (err) {\n if (!(err instanceof UnsupportedComposeQuotePath)) {\n // UnsupportedComposeQuotePath is the expected \"not my path\" signal —\n // fall through silently. Any other error is unexpected; a transient\n // compose failure shouldn't break a quote the server can still\n // serve, so log it and fall back rather than propagate.\n this.#logger.warn({\n event: \"client.getQuote.composeFallback\",\n message: \"composeQuote failed; falling back to server /quote\",\n data: { error: err instanceof Error ? err.message : String(err) },\n });\n }\n }\n }\n return this.#getQuoteFromServer(params);\n }\n\n /**\n * Exact quote for an Arkade, Bitcoin or EVM → Lightning swap, from a\n * concrete destination (BOLT11 invoice, lightning address or LNURL).\n *\n * Unlike {@link getQuote}, whose network fee for Lightning targets is an\n * estimate, this resolves the destination and prices the swap with the\n * provider's actual Lightning send fee — the same numbers `createSwap`\n * persists. Informational only: create re-quotes the fee, which can move\n * between the two calls.\n *\n * @param params - Destination plus pinned amount (see\n * {@link GetLightningSendQuoteParams} for the field rules).\n * @returns The exact quote, all amounts in sats.\n * @throws Error if the request fails or the parameters are invalid.\n */\n async getLightningSendQuote(\n params: GetLightningSendQuoteParams,\n ): Promise<LightningSendQuote> {\n const destinations = [\n params.lightningInvoice,\n params.lightningAddress,\n params.lnurl,\n ].filter((d) => d !== undefined);\n if (destinations.length !== 1) {\n throw new Error(\n \"Provide exactly one of lightningInvoice, lightningAddress or lnurl\",\n );\n }\n\n const sourceAmount = params.sourceAmount ?? params.sourceAmountSats;\n const { data, error } = await this.#apiClient.GET(\"/quote/lightning-send\", {\n params: {\n query: {\n source_chain: params.sourceChain,\n source_token: params.sourceToken,\n source_amount:\n sourceAmount === undefined ? undefined : sourceAmount.toString(),\n lightning_invoice: params.lightningInvoice,\n lightning_address: params.lightningAddress,\n lnurl: params.lnurl,\n target_amount_sats: params.targetAmountSats,\n // Per-call referral wins; fall back to the client default.\n ref: params.referralCode ?? this.#config.referralCode,\n extra_fees: params.extraFees,\n },\n },\n });\n if (error) {\n throw new Error(\n `Failed to get lightning send quote: ${JSON.stringify(error)}`,\n );\n }\n if (!data) {\n throw new Error(\"No lightning send quote data returned\");\n }\n\n const evmSource = isEvmSwapSource(\n params.sourceChain ?? \"Arkade\",\n params.sourceToken ?? \"\",\n );\n return {\n sourceAmount: data.source_amount,\n sourceAmountSats: evmSource ? undefined : Number(data.source_amount),\n targetAmountSats: data.target_amount_sats,\n protocolFeeSats: data.protocol_fee_sats,\n networkFeeSats: data.network_fee_sats,\n protocolFeeRate: data.protocol_fee_rate,\n minAmountSats: data.min_amount_sats,\n maxAmountSats: data.max_amount_sats,\n exchangeRate: data.exchange_rate,\n };\n }\n\n /**\n * Serve an Arkade/Bitcoin/EVM → Lightning `getQuote` from\n * `/quote/lightning-send`, adapted to the `QuoteResponse` shape (the\n * server's rate: 1:1 for Arkade and Bitcoin, DEX-derived for EVM\n * sources; net amounts carry the exact lock/payout including the\n * provider's real send fee).\n */\n async #lightningSendQuoteAsQuote(\n params: GetQuoteParams,\n destination: string,\n ): Promise<QuoteResponse> {\n const kind = classifyLightningDestination(destination);\n if (!kind) {\n throw new Error(`unrecognized lightning destination: ${destination}`);\n }\n const evmSource = isEvmSwapSource(params.sourceChain, params.sourceToken);\n // The invoice pins the payout itself; only address/LNURL flows take a\n // pinned amount (in the source token's smallest unit: sats for Arkade,\n // token units for EVM).\n const sourcePinned = kind !== \"invoice\" && params.sourceAmount != null;\n const sourceAmount = sourcePinned ? String(params.sourceAmount) : undefined;\n const targetAmountSats =\n kind !== \"invoice\" && !sourcePinned && params.targetAmount != null\n ? Number(params.targetAmount)\n : undefined;\n\n const q = await this.getLightningSendQuote({\n sourceChain:\n evmSource || params.sourceChain === \"Bitcoin\"\n ? (params.sourceChain as LightningSendSourceChain)\n : undefined,\n sourceToken: evmSource ? params.sourceToken : undefined,\n sourceAmount,\n lightningInvoice: kind === \"invoice\" ? destination : undefined,\n lightningAddress: kind === \"address\" ? destination : undefined,\n lnurl: kind === \"lnurl\" ? destination : undefined,\n targetAmountSats,\n referralCode: params.referralCode,\n extraFees: params.extraFees,\n });\n\n // Arkade and Bitcoin are 1:1, so the pinned side carries the pre-fee\n // amount on both sides (mirroring the server's /quote for those\n // routes). EVM sources are DEX-priced: the source side is the token\n // amount create persists.\n const sourceAmountOut = evmSource\n ? q.sourceAmount\n : sourcePinned\n ? q.sourceAmount\n : String(q.targetAmountSats);\n const targetAmountOut =\n !evmSource && sourcePinned ? q.sourceAmount : String(q.targetAmountSats);\n return {\n exchange_rate: q.exchangeRate,\n network_fee: q.networkFeeSats,\n gasless_network_fee: 0,\n protocol_fee: q.protocolFeeSats,\n protocol_fee_rate: q.protocolFeeRate,\n min_amount: q.minAmountSats,\n max_amount: q.maxAmountSats,\n source_amount: sourceAmountOut,\n target_amount: targetAmountOut,\n net_source_amount: q.sourceAmount,\n net_target_amount: String(q.targetAmountSats),\n };\n }\n\n /**\n * Whether `getQuote` can serve `params` via client-side `composeQuote`.\n *\n * Compose now covers BTC↔EVM both directions — direct (hub chains) or\n * bridged (via Arbitrum/CCTP/OFT, with `bridge_fee` surfaced), the BTC side\n * Bitcoin/Arkade/Lightning, referral/extra-fee pricing (via `/referral-fee`),\n * and BTC→Solana CCTP (incl. the `bridgeRecipientSetup` ATA surcharge). The\n * response shape is identical to `/quote`; some *values* are more accurate\n * (e.g. the Lightning Boltz fee, EURe), which is fine — only the API contract\n * must stay stable.\n *\n * Stays on `/quote` (compose can't price these):\n * - foreign EVM↔EVM (neither side BTC).\n */\n #canComposeQuote(params: GetQuoteParams): boolean {\n if (isTronToken(params.sourceChain) || isTronToken(params.targetChain))\n return false;\n const sourceIsBtc = params.sourceToken.toLowerCase() === \"btc\";\n const targetIsBtc = params.targetToken.toLowerCase() === \"btc\";\n if (sourceIsBtc === targetIsBtc) return false; // need exactly one BTC side\n // Solana is a CCTP-only *target* — base58 token, allowed for BTC→Solana.\n if (sourceIsBtc && isSolanaToken(params.targetChain)) return true;\n const evmToken = sourceIsBtc ? params.targetToken : params.sourceToken;\n return evmToken.startsWith(\"0x\"); // hex EVM token (rules out Solana base58)\n }\n\n /**\n * Server-composed quote via `/quote` — the fallback path for requests\n * `composeQuote` can't serve (see {@link getQuote}).\n */\n async #getQuoteFromServer(params: GetQuoteParams): Promise<QuoteResponse> {\n // If the target is a bridge-only chain (e.g. USDC on Base), remap the\n // quote request to the token on Arbitrum (source chain the backend knows).\n // Pass bridge_target_chain so the backend includes the bridge fee.\n if (isTronToken(params.sourceChain))\n throw new Error(\"Tron is a payout-only destination\");\n if (\n isTronToken(params.targetChain) &&\n params.targetToken !== USDT0_ADDRESSES.Tron\n ) {\n throw new Error(\"Tron payouts require native USDT\");\n }\n let targetChain = params.targetChain;\n let targetToken = params.targetToken;\n let bridgeTargetChain: string | undefined;\n if (isBridgedTarget(targetChain, targetToken)) {\n bridgeTargetChain = toChainName(targetChain);\n // Determine if this is a USDT0 or USDC bridge token by checking\n // if the target token matches a known USDT0 address on the destination.\n const isUsdt0 = Object.values(USDT0_ADDRESSES).some(\n (addr) => addr.toLowerCase() === params.targetToken.toLowerCase(),\n );\n // Remap to Arbitrum for the DEX quote (cheapest gas, good liquidity).\n targetChain = \"42161\" as Chain;\n targetToken = isUsdt0\n ? USDT0_ADDRESSES.Arbitrum\n : USDC_ADDRESSES.Arbitrum;\n }\n\n // CCTP-only source (USDC on Optimism / Base / Linea / …): the quote\n // endpoint expects the source chain/token the DEX actually runs on\n // (Arbitrum + native USDC), plus `bridge_source_chain` + address so\n // the backend can apply the CCTPv2 fast-transfer fee. All gross-vs-net\n // math happens server-side.\n let sourceChain = params.sourceChain;\n let sourceToken = params.sourceToken;\n let bridgeSourceChain: string | undefined;\n let bridgeSourceTokenAddress: string | undefined;\n const parsedSourceChainId = Number.parseInt(params.sourceChain, 10);\n if (\n !Number.isNaN(parsedSourceChainId) &&\n isCctpOnlySource(parsedSourceChainId)\n ) {\n const source = cctpMetaForChainId(parsedSourceChainId);\n if (params.sourceToken.toLowerCase() !== source.usdc.toLowerCase()) {\n throw new Error(\n `Quote on ${source.name} requires native USDC (${source.usdc}); got ${params.sourceToken}. Only USDC is bridgeable via CCTP.`,\n );\n }\n bridgeSourceChain = source.name;\n bridgeSourceTokenAddress = source.usdc;\n sourceChain = \"42161\" as Chain;\n sourceToken = USDC_ADDRESSES.Arbitrum;\n }\n if (isSolanaToken(params.sourceChain)) {\n if (params.sourceToken !== USDC_ADDRESSES.Solana) {\n throw new Error(\n `Quote on Solana requires native USDC (${USDC_ADDRESSES.Solana}); got ${params.sourceToken}. Only USDC is bridgeable via CCTP.`,\n );\n }\n bridgeSourceChain = \"Solana\";\n bridgeSourceTokenAddress = USDC_ADDRESSES.Solana;\n sourceChain = \"42161\" as Chain;\n sourceToken = USDC_ADDRESSES.Arbitrum;\n }\n\n const query = {\n // Bridge targets have already been remapped to a hub chain above (with\n // the destination carried in `bridge_target_chain`), so the value is a\n // WireChain by construction — narrow it back for the server request.\n source_chain: sourceChain as WireChain,\n source_token: sourceToken,\n target_chain: targetChain as WireChain,\n target_token: targetToken,\n source_amount: serializeAmountInput(params.sourceAmount),\n target_amount: serializeAmountInput(params.targetAmount),\n bridge_target_chain: bridgeTargetChain,\n bridge_source_chain: bridgeSourceChain,\n bridge_source_token_address: bridgeSourceTokenAddress,\n bridge_recipient_setup: params.bridgeRecipientSetup,\n // Per-call referralCode wins; fall back to the client config default\n // (set via withReferralCode / withOrgCode).\n ref: params.referralCode ?? this.#config.referralCode,\n extra_fees: params.extraFees,\n };\n const { data, error } = await this.#apiClient.GET(\"/quote\", {\n params: {\n query:\n query as unknown as paths[\"/quote\"][\"get\"][\"parameters\"][\"query\"],\n },\n });\n if (error) {\n throw new Error(`Failed to get quote: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No quote data returned\");\n }\n\n return fromWireQuoteResponse(data as WireQuoteResponse);\n }\n\n // =========================================================================\n // Swap Status\n // =========================================================================\n\n /**\n * Gets the status and details of a swap by its ID.\n * @param id - The UUID of the swap.\n * @param options - Optional settings.\n * @param options.updateStorage - If true, updates the swap in storage after\n * fetching. A stored swap is only replaced by a copy whose hash locks,\n * lock addresses and invoice payment hashes equal the stored ones, whose\n * `bolt11_invoice`, if any, pays the stored preimage hash, and whose\n * `hash_lock` is the payment hash of its `client_lightning_invoice`, if\n * any. A copy that fails those checks is logged as\n * `client.get_swap.terms_changed`, and stored and returned with the\n * stored copy's hash locks, lock addresses and invoices in place of its\n * own.\n * @returns A promise that resolves to the swap details.\n * @throws Error if the request fails or swap is not found.\n */\n async getSwap(\n id: string,\n options?: { updateStorage?: boolean },\n ): Promise<GetSwapResponse> {\n const { data, error } = await this.#apiClient.GET(\"/swap/{id}\", {\n params: { path: { id } },\n });\n if (error) {\n throw new Error(`Failed to get swap: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n if (options?.updateStorage && this.#swapStorage) {\n // No compare-and-swap around the update: a concurrent getSwap or\n // recovery runs the same checks before it writes, so it cannot change\n // the compared fields between this read and this write.\n const stored = await this.#swapStorage.get(id);\n const changed = stored ? swapTermsChange(stored, data) : undefined;\n if (stored && changed) {\n // Throwing would lock the caller out of a swap's status for good, as\n // a stored copy of terms that never bound fails every refresh.\n this.#logger.warn({\n event: \"client.get_swap.terms_changed\",\n message: changed.message,\n swapId: id,\n data: { field: changed.field },\n });\n const kept = withStoredTerms(stored, data, changed);\n await this.#swapStorage.update(id, kept);\n return kept;\n }\n await this.#swapStorage.update(id, data);\n }\n\n return data;\n }\n\n /**\n * Gets the status of multiple swaps in a single request.\n *\n * Returns only each swap's status (not the full details) so the whole batch\n * is served by one database query. Use {@link getSwap} when you need full\n * details for a specific swap.\n *\n * Unknown IDs are returned in `not_found` rather than throwing, so one bad ID\n * does not fail the whole call. Duplicate IDs are de-duplicated server-side.\n *\n * @param ids - The UUIDs of the swaps to look up (max 100 per request).\n * @returns A promise resolving to `{ statuses, not_found }`.\n * @throws Error if the request fails (e.g. more than 100 IDs, or a network/server error).\n */\n async getBulkStatus(ids: string[]): Promise<BulkStatusResponse> {\n const { data, error } = await this.#apiClient.POST(\"/swap/bulk-status\", {\n body: { ids },\n });\n if (error) {\n throw new Error(`Failed to get swap statuses: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No swap data returned\");\n }\n\n return data;\n }\n\n /**\n * Gets a swap from local storage without making a server request.\n *\n * Use this when you need swap data but don't need the latest status\n * from the server. The stored swap includes the preimage, keys, and\n * the last known swap response.\n *\n * @param id - The UUID of the swap.\n * @returns The stored swap data, or null if not found.\n *\n * @example\n * ```ts\n * const stored = await client.getStoredSwap(swapId);\n * if (stored) {\n * console.log(\"Target:\", stored.response.target_token);\n * console.log(\"Status:\", stored.response.status);\n * }\n * ```\n */\n async getStoredSwap(id: string): Promise<StoredSwap | null> {\n if (!this.#swapStorage) {\n return null;\n }\n return this.#swapStorage.get(id);\n }\n\n /**\n * Gets all stored swaps from local storage.\n *\n * @returns Array of all stored swap data, or empty array if no storage is configured.\n */\n async listAllSwaps(): Promise<StoredSwap[]> {\n if (!this.#swapStorage) {\n return [];\n }\n return this.#swapStorage.getAll();\n }\n\n async deleteSwap(id: string): Promise<void> {\n if (!this.#swapStorage) {\n return;\n }\n await this.#swapStorage.delete(id);\n }\n\n async clearSwapStorage(): Promise<void> {\n if (!this.#swapStorage) {\n return;\n }\n await this.#swapStorage.clear();\n }\n\n /**\n * Recovers all swaps associated with the current wallet from the server.\n *\n * Sends the user's xpub to the server, which returns all swaps belonging\n * to that wallet. For each recovered swap, re-derives the keys using the\n * swap's derivation index and stores it locally.\n *\n * After recovery, the key index is set to `next_index` so that new swaps\n * don't reuse derivation indices.\n *\n * A swap already stored keeps its stored copy if the server's index derives\n * other keys than the stored ones, or if the server's copy fails the checks\n * `getSwap` makes with `updateStorage`. A swap not stored yet is stored only\n * if a Lightning to X invoice pays the hash of the secret derived at the\n * server's index, an X to Lightning hash lock is the payment hash of an\n * invoice for the swap's payout, and an Arkade or Bitcoin to Lightning lock,\n * on a script version this client can refund, rebuilds to its address from\n * that hash and the refund key derived at the server's index. Other\n * directions' lock addresses are not rebuilt. A swap that fails is left out\n * of storage and of the result, with a warning logged.\n *\n * @returns Recovery metadata and the recovered swaps stored locally.\n */\n async recoverSwaps(\n options: RecoverSwapsOptions = {},\n ): Promise<RecoverSwapsResult> {\n const xpub = this.getUserIdXpub();\n this.#logger.info({\n event: \"client.recover.start\",\n message: \"Recovering swaps for wallet\",\n data: { xpub, startIndex: options.startIndex },\n });\n\n const { data, error } = await this.#apiClient.POST(\"/swap/recover\", {\n body: { xpub, start_index: options.startIndex },\n });\n if (error) {\n throw new Error(`Failed to recover swaps: ${JSON.stringify(error)}`);\n }\n if (!data) {\n throw new Error(\"No recovery data returned\");\n }\n\n const storedSwaps: StoredSwap[] = [];\n this.#logger.debug({\n event: \"client.recover.response\",\n message: \"Recovered swap data from server\",\n data: {\n recoveredSwapCount: data.swaps.length,\n highestIndex: data.highest_index,\n nextIndex: data.next_index,\n scannedUntil: data.scanned_until,\n complete: data.complete,\n },\n });\n\n for (const recoveredSwap of data.swaps) {\n const { index, ...response } = recoveredSwap;\n const swapParams = this.deriveSwapParamsAtIndex(index);\n\n // No compare-and-swap, as in getSwap: a concurrent getSwap or recovery\n // runs the same checks before it writes.\n const existing = await this.getStoredSwap(response.id);\n const refused = existing\n ? (recoveredKeysChange(\n existing,\n index,\n bytesToHex(swapParams.preimageHash),\n ) ?? swapTermsChange(existing, response))\n : unboundTerms(response, swapParams);\n if (refused) {\n this.#logger.warn({\n event: existing\n ? \"client.recover.terms_changed\"\n : \"client.recover.terms_refused\",\n message: refused.message,\n swapId: response.id,\n data: {\n field:\n refused instanceof SwapVerificationError\n ? refused.field\n : undefined,\n },\n });\n } else {\n await this.#storeSwap(response.id, swapParams, response);\n }\n\n const stored = await this.getStoredSwap(response.id);\n if (stored) {\n storedSwaps.push(stored);\n }\n }\n\n // Update key index so new swaps don't reuse indices, but never regress an\n // existing local index. Recovery may be run from an old startIndex or return\n // no swaps, in which case data.next_index can be lower than the local index.\n const currentKeyIndex = await this.getKeyIndex();\n const nextKeyIndex = Math.max(currentKeyIndex, data.next_index);\n if (nextKeyIndex !== currentKeyIndex) {\n await this.setKeyIndex(nextKeyIndex);\n }\n\n return {\n swaps: storedSwaps,\n highestIndex: data.highest_index,\n nextIndex: data.next_index,\n scannedUntil: data.scanned_until,\n complete: data.complete,\n };\n }\n\n /**\n * Recovers every swap discoverable for the current wallet.\n *\n * This repeatedly calls `recoverSwaps`, continuing from the last scanned\n * derivation index, until the server reports that recovery is complete or a\n * recovery scan fails. On failure, it returns the progress made so far instead\n * of throwing.\n *\n * Use this for fresh wallets that cannot rely on local recovery state.\n *\n * @returns Aggregated recovery metadata and all recovered swaps stored locally.\n */\n async recoverAllSwaps(\n options: RecoverAllSwapsOptions = {},\n ): Promise<RecoverAllSwapsResult> {\n let startIndex = options.startIndex ?? 0;\n let scans = 0;\n\n const swapsById = new Map<string, StoredSwap>();\n\n let nextIndex = startIndex;\n let scannedUntil: number | null = null;\n\n while (true) {\n let result: RecoverSwapsResult;\n try {\n result = await this.recoverSwaps({ startIndex });\n } catch (error) {\n return {\n swaps: [...swapsById.values()],\n nextIndex,\n scannedUntil,\n complete: false,\n stoppedReason: \"error\",\n scans,\n errorMessage: error instanceof Error ? error.message : String(error),\n error,\n };\n }\n\n scans += 1;\n\n for (const swap of result.swaps) {\n swapsById.set(swap.swapId, swap);\n }\n\n nextIndex = Math.max(nextIndex, result.nextIndex);\n scannedUntil = result.scannedUntil;\n\n if (result.complete) {\n return {\n swaps: [...swapsById.values()],\n nextIndex,\n scannedUntil,\n complete: true,\n stoppedReason: \"complete\",\n scans,\n };\n }\n\n startIndex = result.scannedUntil + 1;\n }\n }\n\n /**\n * Gets VHTLC amounts for an Arkade swap.\n *\n * Queries the Arkade indexer for spendable, spent, and recoverable balances\n * at the VHTLC address associated with a swap. Works for:\n * - BTC → EVM swaps where the source asset is Arkade\n * - EVM → BTC swaps where the target asset is Arkade\n *\n * Reads swap data from local storage (does not contact the server).\n *\n * @param id - The UUID of the swap.\n * @returns The VHTLC amounts in satoshis.\n */\n async amountsForSwap(id: string): Promise<VhtlcAmounts> {\n const stored = await this.getStoredSwap(id);\n if (!stored) {\n throw new Error(`Swap not found in local storage: ${id}`);\n }\n\n const swap = stored.response;\n\n if (\n swap.direction !== \"btc_to_arkade\" &&\n swap.direction !== \"arkade_to_evm\" &&\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"lightning_to_arkade\" &&\n swap.direction !== \"arkade_to_lightning\"\n ) {\n throw new Error(\n `amountsForSwap only applies to VHTLC-based swaps, got ${swap.direction}`,\n );\n }\n\n // Get VHTLC address based on swap direction\n let vhtlcAddress: string | undefined;\n if (swap.direction === \"btc_to_arkade\") {\n vhtlcAddress = (swap as BtcToArkadeSwapResponse).arkade_vhtlc_address;\n } else if (swap.direction === \"lightning_to_arkade\") {\n vhtlcAddress = (swap as LightningToArkadeSwapResponse)\n .arkade_vhtlc_address;\n } else if (swap.direction === \"arkade_to_lightning\") {\n vhtlcAddress = (swap as ArkadeToLightningSwapResponse)\n .arkade_vhtlc_address;\n } else if (\n swap.direction === \"arkade_to_evm\" ||\n swap.direction === \"evm_to_arkade\"\n ) {\n vhtlcAddress = (\n swap as\n | (ArkadeToEvmSwapResponse & { direction: \"arkade_to_evm\" })\n | (EvmToArkadeSwapResponse & { direction: \"evm_to_arkade\" })\n ).btc_vhtlc_address;\n }\n\n if (!vhtlcAddress) {\n throw new Error(\"Swap does not have an Arkade VHTLC address\");\n }\n\n return getVhtlcAmounts({\n vhtlcAddress,\n network: swap.network,\n arkadeServerUrl: this.#config.arkadeServerUrl,\n });\n }\n\n // =========================================================================\n // Redeem\n // =========================================================================\n\n /**\n * Claims a swap by revealing the preimage.\n *\n * Reads swap data and preimage from local storage. The claim method\n * depends on the swap direction and target chain:\n * - **Arkade/Lightning-to-EVM**: Gasless claim via server\n * - **Other EVM swaps**: Returns call data for manual claiming\n * - **Arkade**: Claims via Arkade protocol\n *\n * @param id - The UUID of the swap.\n * @param options - For Arkade/Lightning-to-EVM, destination is set at swap creation.\n * @returns A ClaimResult with the outcome.\n *\n * @example\n * ```ts\n * // Arkade-to-EVM (gasless via server, uses stored target address)\n * const result = await client.claim(swapId);\n *\n * // Other swap types\n * const result = await client.claim(swapId);\n * if (result.success) {\n * console.log(\"Claim TX:\", result.txHash);\n * }\n * ```\n */\n async claim(id: string, options?: ClaimOptions): Promise<ClaimResult> {\n // Check swap storage is configured\n if (!this.#swapStorage) {\n return {\n success: false,\n message:\n \"Swap storage is not configured. Cannot retrieve swap data needed for claim.\",\n };\n }\n\n // Get stored swap data (contains preimage, keys, and swap response)\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage. Cannot claim without stored data.`,\n };\n }\n\n const swap = storedSwap.response;\n const secret = storedSwap.preimage;\n\n // EVM-targeted swaps: use gasless claim via server (SDK signs internally)\n // The destination is the target this client sent at creation, never the\n // server's copy of it.\n if (\n swap.direction === \"arkade_to_evm\" ||\n swap.direction === \"bitcoin_to_evm\" ||\n swap.direction === \"lightning_to_evm\"\n ) {\n const evmSwap = swap as (\n | ArkadeToEvmSwapResponse\n | BitcoinToEvmSwapResponse\n | LightningToEvmSwapResponse\n ) & {\n direction: string;\n };\n const bridgeTargetChain = (evmSwap as { bridge_target_chain?: string })\n .bridge_target_chain;\n const isSolanaBridge = bridgeTargetChain === \"Solana\";\n const isTronBridge = bridgeTargetChain === \"Tron\";\n\n const destination = this.#resolveEvmClaimDestination(storedSwap);\n\n if (!destination) {\n return {\n success: false,\n message:\n \"Gasless claim failed: no target address found. \" +\n \"This swap may have been created before target address storage was implemented.\",\n };\n }\n // Explicit claim options win; otherwise fall back to the recipient\n // pinned on the stored swap at create time — this is what lets a bare\n // `claim(swapId)` (e.g. the background auto-claim worker) route the\n // CCTP burn correctly.\n const bridgeRecipient =\n options?.bridgeRecipient ??\n storedSwap.bridgeRecipient ??\n (isTronBridge ? storedPayoutTarget(storedSwap) : undefined);\n const bridgeRecipientWallet =\n options?.bridgeRecipient !== undefined\n ? options?.bridgeRecipientWallet\n : storedSwap.bridgeRecipientWallet;\n if (isSolanaBridge && !bridgeRecipient) {\n return {\n success: false,\n message:\n \"Solana bridge claim requires `bridgeRecipient` (the recipient's USDC ATA) \" +\n \"in claim options. Derive it via `deriveSolanaUsdcAta` before calling claim.\",\n };\n }\n const gaslessResult =\n (swap.evm_chain_id === 30 || swap.evm_chain_id === 31) &&\n options?.signer\n ? await this.claimEvmWithSigner(id, options.signer, {\n bridgeRecipient,\n bridgeRecipientWallet,\n })\n : await this.claimViaGasless(id, destination, {\n bridgeRecipient,\n bridgeRecipientWallet,\n });\n return {\n success: true,\n message: gaslessResult.message,\n txHash: gaslessResult.txHash,\n };\n }\n\n // Server-funded on-chain HTLC: the user claims BTC with the preimage\n if (\n swap.direction === \"evm_to_bitcoin\" ||\n swap.direction === \"lightning_to_bitcoin\"\n ) {\n return this.#claimOnchainBtc(id, options);\n }\n\n // Check if target is Arkade (handle both string \"btc_arkade\" and TokenInfo object)\n const isArkadeTarget = swap.target_token.chain === \"Arkade\";\n\n if (isArkadeTarget) {\n // Determine destination address based on swap direction\n // The target this client sent at creation, never a fresh server answer.\n const destinationAddress =\n swap.direction === \"btc_to_arkade\" ||\n swap.direction === \"evm_to_arkade\" ||\n swap.direction === \"lightning_to_arkade\"\n ? storedPayoutTarget(storedSwap)\n : undefined;\n\n if (!destinationAddress) {\n return {\n success: false,\n message:\n \"No Arkade destination address found in swap. Use claimArkade() with explicit destinationAddress.\",\n };\n }\n\n const arkadeResult = await this.claimArkade(id, { destinationAddress });\n\n // Convert to ClaimResult format\n return {\n success: arkadeResult.success,\n message: arkadeResult.message,\n chain: \"arkade\",\n txHash: arkadeResult.txId,\n };\n }\n\n // For EVM chains, use the existing claim logic\n return redeemClaim(id, secret, {\n apiClient: this.#apiClient,\n getSwap: () => Promise.resolve(swap),\n });\n }\n\n /** Loads the stored swap + fresh server state for an EVM-targeted claim. */\n async #loadEvmClaimSwap(id: string): Promise<{\n stored: StoredSwap;\n swap: ArkadeToEvmSwapResponse & { direction: string };\n }> {\n if (!this.#swapStorage) {\n throw new Error(\n \"Swap storage is not configured. Cannot retrieve preimage needed for the claim.\",\n );\n }\n const stored = await this.#swapStorage.get(id);\n if (!stored) {\n throw new Error(`Swap ${id} not found in local storage.`);\n }\n const swap = (await this.getSwap(id, {\n updateStorage: true,\n })) as ArkadeToEvmSwapResponse & {\n direction: string;\n };\n if (\n swap.direction !== \"arkade_to_evm\" &&\n swap.direction !== \"bitcoin_to_evm\" &&\n swap.direction !== \"lightning_to_evm\"\n ) {\n throw new Error(\n `Expected an EVM-targeted swap (arkade_to_evm, bitcoin_to_evm or lightning_to_evm), got ${swap.direction}.`,\n );\n }\n return { stored, swap };\n }\n\n /**\n * The EVM address an EVM-targeted claim's Redeem pays out to, from what\n * creation recorded (see {@link storedPayoutTarget}).\n *\n * For Solana and Tron bridge targets the target is not an EVM address and\n * can't satisfy the EIP-712 `address destination` field, so the Redeem pays\n * the swap's claiming key (`client_evm_address`, checked at creation) and\n * the actual destination rides on `bridgeRecipient`. Legacy swaps without a\n * target fall back to the claiming key too.\n */\n #resolveEvmClaimDestination(stored: StoredSwap): string | undefined {\n const swap = stored.response as {\n bridge_target_chain?: string | null;\n client_evm_address?: string | null;\n };\n const bridgeTargetChain = swap.bridge_target_chain;\n if (bridgeTargetChain === \"Solana\" || bridgeTargetChain === \"Tron\") {\n return swap.client_evm_address ?? undefined;\n }\n return storedPayoutTarget(stored) ?? swap.client_evm_address ?? undefined;\n }\n\n /** Static facts about how an EVM-targeted swap has to be claimed. */\n #classifyEvmClaim(\n swap: ArkadeToEvmSwapResponse & { direction: string },\n ): EvmClaimClassification {\n const targetTokenAddr = String(swap.target_token.token_id);\n const dexSwapNeeded =\n targetTokenAddr.toLowerCase() !== swap.wbtc_address.toLowerCase();\n const bridgeSwap = swap as {\n bridge_target_chain?: string | null;\n bridge_target_token_address?: string | null;\n };\n const bridgeTargetChain = bridgeSwap.bridge_target_chain || undefined;\n const bridgeTargetToken =\n bridgeSwap.bridge_target_token_address || undefined;\n const isBridge = bridgeTargetChain != null;\n // A USDT0 target token is a LayerZero OFT bridge; everything else CCTP.\n const isOftBridge =\n isBridge &&\n bridgeTargetToken != null &&\n Object.values(USDT0_ADDRESSES).some(\n (a) => a.toLowerCase() === bridgeTargetToken.toLowerCase(),\n );\n const isCctpBridge = isBridge && !isOftBridge && bridgeTargetToken != null;\n const isSolanaBridge = isBridge && isSolanaToken(bridgeTargetChain);\n\n // TODO: this needs some refactoring, this function is ugly as a naked cat\n // The sponsored path exists for the Arbitrum hub only (Ethereum/Polygon\n // claims and OFT bridges stay on the server-submitted path).\n const arbitrumHubClaim =\n swap.evm_chain_id === 42161 && (!isBridge || isCctpBridge);\n return {\n targetTokenAddr,\n dexSwapNeeded,\n bridgeTargetChain,\n bridgeTargetToken,\n isBridge,\n isCctpBridge,\n isSolanaBridge,\n arbitrumHubClaim,\n };\n }\n\n /**\n * The coordinator calls (DEX / CCTP legs from `/dex-calldata/fund`) and\n * the sweep floor for an Arbitrum-hub claim. Shared by the sponsored\n * UserOp path and the wallet-paid path so both publish identical calldata.\n */\n async #fetchArbitrumHubCalls(\n swap: ArkadeToEvmSwapResponse & { direction: string },\n destination: string,\n cls: EvmClaimClassification,\n {\n bridgeRecipient,\n bridgeRecipientWallet,\n }: { bridgeRecipient?: string; bridgeRecipientWallet?: string },\n ): Promise<{ calls: CoordinatorCall[]; minAmountOut: bigint }> {\n const {\n targetTokenAddr,\n dexSwapNeeded,\n bridgeTargetChain,\n bridgeTargetToken,\n isBridge,\n isCctpBridge,\n isSolanaBridge,\n } = cls;\n let calls: CoordinatorCall[] = [];\n let minAmountOut = BigInt(swap.evm_expected_sats);\n if (dexSwapNeeded) {\n // The swap leg always runs on Arbitrum. For a CCTP target the `to` Token\n // names the destination (USDC on the dest chain / Solana) — the server\n // reads the bridge from it; for same-chain it's the hub target itself.\n const toToken = !isBridge\n ? { kind: \"evm\" as const, chain_id: 42161, address: targetTokenAddr }\n : isSolanaBridge\n ? { kind: \"solana\" as const, address: bridgeTargetToken as string }\n : {\n kind: \"evm\" as const,\n chain_id: Number(ALL_EVM_CHAIN_IDS[bridgeTargetChain as string]),\n address: bridgeTargetToken as string,\n };\n // A Solana bridge target's mint recipient is its USDC ATA, which only\n // rides on `bridgeRecipient` — reject a missing one here with an\n // actionable error instead of round-tripping \"\" to the server (which\n // fails opaquely in `solana_pubkey_to_bytes32`).\n if (isCctpBridge && isSolanaBridge && !bridgeRecipient) {\n throw new Error(\n \"Solana bridge claim requires `bridgeRecipient` (the recipient's USDC ATA).\",\n );\n }\n // CCTP mint recipient: the user's address for EVM (same address cross-\n // chain), the recipient ATA (+ optional wallet for ATA-setup) for Solana.\n const bridgeRecipientParam = !isCctpBridge\n ? undefined\n : isSolanaBridge\n ? {\n kind: \"solana\" as const,\n address: bridgeRecipient ?? \"\",\n wallet: bridgeRecipientWallet,\n }\n : { kind: \"evm\" as const, address: destination };\n\n // Mirror the per-direction slippage floor the legacy server path uses;\n // the coordinator's `_sweep` enforces `min_amount_out` on-chain.\n const slippageBps = swap.direction === \"bitcoin_to_evm\" ? 200 : 100;\n const fundResp = await this.#apiClient.POST(\"/dex-calldata/fund\", {\n body: {\n from: {\n kind: \"evm\",\n chain_id: swap.evm_chain_id,\n address: swap.wbtc_address,\n },\n to: toToken,\n amount: { kind: \"exact_in\", value: String(swap.evm_expected_sats) },\n sender: swap.evm_coordinator_address,\n slippage_bps: slippageBps,\n bridge_recipient: bridgeRecipientParam,\n },\n });\n if (fundResp.error || !fundResp.data) {\n throw new Error(\n `Failed to fetch /dex-calldata/fund: ${JSON.stringify(fundResp.error)}`,\n );\n }\n const payload = fundResp.data.payload;\n if (payload.kind !== \"evm\") {\n throw new Error(\n `Unexpected /dex-calldata payload kind: ${payload.kind}`,\n );\n }\n calls = payload.calls.map((c) => ({\n target: c.target,\n value: BigInt(c.value),\n data: c.data,\n }));\n // A CCTP bridge claim's `_sweep` is a no-op (USDC is forwarded), so the\n // floor is 0; a same-chain claim sweeps the swapped token to destination.\n minAmountOut = isBridge ? 0n : BigInt(fundResp.data.estimated_amount_out);\n }\n return { calls, minAmountOut };\n }\n\n /**\n * Claims an EVM-targeted swap from the user's own wallet, paying gas.\n *\n * Uses the exact `redeemAndExecute` calldata the sponsored UserOp path\n * would publish - the swap's derived key signs the redeem, the wallet only\n * broadcasts - so it works without any AA / paymaster configuration and is\n * the manual fallback when the automatic claim fails. Native claims call\n * HTLCNative directly and require the payout wallet to submit.\n *\n * @param id - Swap ID.\n * @param signer - A connected wallet on the swap's EVM chain.\n * @param options - Bridge recipient details for non-EVM (Solana) targets.\n */\n async claimEvmWithSigner(\n id: string,\n signer: EvmSigner,\n options: { bridgeRecipient?: string; bridgeRecipientWallet?: string } = {},\n ): Promise<ClaimGaslessResult> {\n const { stored, swap } = await this.#loadEvmClaimSwap(id);\n const destination = this.#resolveEvmClaimDestination(stored);\n if (!destination) {\n throw new Error(\n \"No target address found for this swap; cannot build the claim.\",\n );\n }\n if (signer.chainId !== swap.evm_chain_id) {\n throw new Error(\n `Wallet is on chain ${signer.chainId}; switch it to chain ${swap.evm_chain_id} to claim.`,\n );\n }\n const rifRelay = await this.#rifRelayForClaim(swap);\n if (rifRelay) {\n // The lock's claim address is the recipient's smart wallet: only the\n // recipient's wallet can sign its claim, and it receives the coin.\n const result = await claimNativeViaRifRelay({\n swap,\n preimage: stored.preimage,\n signer,\n relay: rifRelay,\n });\n await this.getSwap(id, { updateStorage: true }).catch(() => undefined);\n return result;\n }\n const cls = this.#classifyEvmClaim(swap);\n const native =\n (swap as { evm_htlc_kind?: string }).evm_htlc_kind === \"native\";\n if (!native && !cls.arbitrumHubClaim) {\n throw new Error(\n \"Wallet-paid claims are only supported for Rootstock and Arbitrum-hub swaps (same-chain or CCTP targets).\",\n );\n }\n const bridgeRecipient = options.bridgeRecipient ?? stored.bridgeRecipient;\n const bridgeRecipientWallet =\n options.bridgeRecipient !== undefined\n ? options.bridgeRecipientWallet\n : stored.bridgeRecipientWallet;\n const { calls, minAmountOut } = native\n ? { calls: [], minAmountOut: BigInt(swap.evm_expected_sats) }\n : await this.#fetchArbitrumHubCalls(swap, destination, cls, {\n bridgeRecipient,\n bridgeRecipientWallet,\n });\n const result = await claimViaSigner({\n preimage: stored.preimage,\n secretKey: hexToBytes(this.#getClaimEvmSigningKey(stored)),\n swap,\n destination,\n calls,\n minAmountOut,\n signer,\n });\n // Refresh the stored status so callers see `clientredeemed` right away.\n await this.getSwap(id, { updateStorage: true }).catch(() => undefined);\n return result;\n }\n\n /** Whether an EVM claim can use the existing automatic sponsorship path. */\n canSponsorClaim(swap: GetSwapResponse): boolean {\n return (\n (swap.direction === \"arkade_to_evm\" ||\n swap.direction === \"bitcoin_to_evm\" ||\n swap.direction === \"lightning_to_evm\") &&\n swap.evm_chain_id !== 30 &&\n swap.evm_chain_id !== 31\n );\n }\n\n /**\n * Claims through the existing server relay or configured Arbitrum UserOp.\n * Rootstock requires the payout wallet, using RIF Relay when configured.\n *\n * @param id - The UUID of the swap.\n * @param destination - The EVM address where tokens should be sent.\n * @returns The gasless claim result with transaction hash.\n *\n * @example\n * ```ts\n * const result = await client.claimViaGasless(swapId, \"0xYourAddress\");\n * console.log(\"Claimed! TX:\", result.txHash);\n * ```\n */\n async claimViaGasless(\n id: string,\n destination: string,\n {\n bridgeRecipient,\n bridgeRecipientWallet,\n }: {\n bridgeRecipient?: string;\n bridgeRecipientWallet?: string;\n } = {},\n ): Promise<ClaimGaslessResult> {\n const { stored, swap } = await this.#loadEvmClaimSwap(id);\n if (\n (swap as { bridge_target_chain?: string }).bridge_target_chain === \"Tron\"\n ) {\n bridgeRecipient ??= stored.bridgeRecipient ?? storedPayoutTarget(stored);\n if (!bridgeRecipient || !isValidTronAddress(bridgeRecipient)) {\n throw new Error(\n \"A valid Tron bridge recipient is required to claim this swap\",\n );\n }\n }\n\n // Where clients claim through RIF Relay the server does not relay the\n // claim, and the receiving wallet has to sign it.\n if (await this.#rifRelayForClaim(swap)) {\n throw new WalletClaimRequiredError(id, swap.evm_chain_id);\n }\n\n if (swap.evm_chain_id === 30 || swap.evm_chain_id === 31) {\n throw new WalletClaimRequiredError(\n id,\n swap.evm_chain_id,\n \"Rootstock RIF sponsorship is not configured. Call claimEvmWithSigner() with the payout wallet; the user pays claim gas.\",\n );\n }\n\n // Client-side claim via a paymaster-sponsored UserOp. Covers Arbitrum-hub\n // DEX swaps (e.g. EURe — LI.FI-only, broken on the legacy fixed-gas Uniswap\n // path) and CCTP bridge targets (USDC → Optimism/Base/Solana, all settled on\n // the Arbitrum hub). The SDK fetches the LI.FI swap + CCTP legs from\n // `/dex-calldata/fund` (driven by the `to` Token) and publishes the UserOp\n // itself; the bundler estimates gas and the Gas Manager sponsors it.\n //\n // OFT/USDT0 bridges stay on the legacy path for now (their native LayerZero\n // fee needs an ETH self-fund leg). A swap this path *is* meant to handle must\n // NOT silently degrade to legacy when AA is unconfigured — that legacy path\n // is exactly what's broken — so we throw an actionable error instead.\n //\n // Plain (no-DEX) Arbitrum claims also ride the sponsored UserOp when AA\n // config is present: it takes the server's gas EOA out of the claim path\n // entirely. Unlike DEX/CCTP claims they have a working legacy fallback, so\n // a missing AA config or a failed publish degrades to the\n // server-submitted path instead of throwing.\n const cls = this.#classifyEvmClaim(swap);\n const { arbitrumHubClaim, dexSwapNeeded } = cls;\n if (arbitrumHubClaim && dexSwapNeeded && this.#config.aa == null) {\n throw new Error(\n \"Claiming an Arbitrum EVM DEX/CCTP swap requires AA config for the \" +\n \"sponsored UserOp. Call `.withAa({ bundlerUrl, paymasterPolicyId })` \" +\n \"on the ClientBuilder before `.build()`.\",\n );\n }\n if (arbitrumHubClaim && this.#config.aa != null) {\n // Direct claim default: no DEX leg — the coordinator redeems and\n // sweeps the locked token itself, so the sweep floor is the full HTLC\n // amount.\n const { calls, minAmountOut } = await this.#fetchArbitrumHubCalls(\n swap,\n destination,\n cls,\n { bridgeRecipient, bridgeRecipientWallet },\n );\n try {\n return await claimViaUserOp({\n preimage: stored.preimage,\n secretKey: hexToBytes(this.#getClaimEvmSigningKey(stored)),\n swap,\n destination,\n calls,\n minAmountOut,\n aa: this.#config.aa,\n });\n } catch (e) {\n // DEX/CCTP targets have no working legacy path — surface the failure.\n if (dexSwapNeeded) throw e;\n console.warn(\n `Sponsored UserOp claim failed; falling back to the server-submitted path: ${e}`,\n );\n }\n }\n\n // Always fetch redeem calldata from the server to get calls_hash.\n // For non-WBTC targets this also returns DEX calldata.\n // bridge_recipient is forwarded for non-EVM bridge targets (e.g.\n // Solana) so the server's calls_hash matches what claim-gasless\n // will rebuild below.\n const calldataResponse = await this.#apiClient.GET(\n \"/swap/{id}/redeem-and-swap-calldata\",\n {\n params: {\n path: { id },\n query: {\n destination,\n ...(bridgeRecipient ? { bridge_recipient: bridgeRecipient } : {}),\n ...(bridgeRecipientWallet\n ? { bridge_recipient_wallet: bridgeRecipientWallet }\n : {}),\n } as {\n destination: string;\n bridge_recipient?: string;\n bridge_recipient_wallet?: string;\n },\n },\n },\n );\n if (calldataResponse.error) {\n throw new Error(\n `Failed to fetch redeem calldata: ${calldataResponse.error.error}`,\n );\n }\n\n // Cast to the updated response shape (includes calls_hash and optional dex_calldata).\n // The generated API types may lag behind the server; this will align after regeneration.\n const responseData = calldataResponse.data as RedeemAndSwapResponse;\n\n const targetTokenAddress = String(swap.target_token.token_id);\n const needsDexSwap =\n targetTokenAddress.toLowerCase() !== swap.wbtc_address.toLowerCase();\n\n let dexCalldata: { to: string; data: string; value: string } | undefined;\n if (needsDexSwap && responseData?.dex_calldata) {\n dexCalldata = {\n to: responseData.dex_calldata.to,\n data: responseData.dex_calldata.data,\n value: responseData.dex_calldata.value,\n };\n }\n\n const callsHash = responseData.calls_hash;\n const minAmountOut = BigInt(responseData.min_amount_out);\n\n return gaslessClaim({\n baseUrl: this.#config.baseUrl,\n preimage: stored.preimage,\n secretKey: hexToBytes(this.#getClaimEvmSigningKey(stored)),\n swap,\n destination,\n dexCalldata,\n minAmountOut,\n callsHash,\n bridgeRecipient,\n bridgeRecipientWallet,\n });\n }\n\n /**\n * Claims an Arkade (off-chain) VHTLC swap by revealing the preimage.\n *\n * Automatically selects the best claim method based on VTXO status:\n * - **spendable** VTXOs → offchain spend (submitTx/finalizeTx)\n * - **recoverable** or **mixed** VTXOs → delegated settlement via backend\n *\n * This is used for EVM-to-Arkade and BTC-to-Arkade swaps where the user\n * claims BTC on Arkade after the server has funded the VHTLC.\n *\n * @param id - The UUID of the swap.\n * @param options - Claim options including destination address.\n * @returns The claim result with transaction ID and amount.\n *\n * @example\n * ```ts\n * const result = await client.claimArkade(swapId, {\n * destinationAddress: \"ark1q...\", // Where to receive BTC\n * });\n * if (result.success) {\n * console.log(\"Claim TX:\", result.txId);\n * console.log(\"Amount:\", result.claimAmount);\n * }\n * ```\n */\n async claimArkade(\n id: string,\n options: ArkadeClaimOptions,\n ): Promise<{\n success: boolean;\n message: string;\n txId?: string;\n claimAmount?: bigint;\n }> {\n // Validate options\n if (!options?.destinationAddress) {\n return {\n success: false,\n message:\n \"Destination address is required for Arkade claims. \" +\n 'Provide it via the options parameter: { destinationAddress: \"ark1...\" }',\n };\n }\n\n // Check swap storage is configured\n if (!this.#swapStorage) {\n return {\n success: false,\n message:\n \"Swap storage is not configured. Cannot retrieve the preimage needed for claim.\",\n };\n }\n\n // Get stored swap data (contains preimage and secret key)\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage. The preimage is required to claim.`,\n };\n }\n\n const swap = storedSwap.response;\n\n // Ensure we have an Arkade-target swap\n if (\n swap.direction !== \"btc_to_arkade\" &&\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"lightning_to_arkade\"\n ) {\n return {\n success: false,\n message: `Expected btc_to_arkade, lightning_to_arkade or evm_to_arkade swap, got ${swap.direction}. claimArkade is for swaps targeting Arkade.`,\n };\n }\n\n // Extract common VHTLC parameters\n const claimParams = this.#extractArkadeClaimParams(id, storedSwap);\n\n // Query VTXO status to determine claim method, polling briefly while\n // the Arkade indexer catches up if the funding tx hasn't been seen yet.\n const vtxoStatus = await this.#waitForVtxoStatus(\n id,\n options.waitForVtxoMs ?? 30_000,\n );\n\n if (vtxoStatus === \"not_funded\") {\n return {\n success: false,\n message: `No VTXOs found at the VHTLC address ${claimParams.vhtlcAddress}. The swap may not have been funded yet.`,\n };\n }\n\n if (vtxoStatus === \"spent\") {\n // A submitted-but-not-finalized Arkade offchain tx can make the original\n // VHTLC inputs look spent. Try to resume that pending tx before declaring\n // the claim already spent.\n const continued = await this.continueArkadeClaimSwap(id);\n if (continued.success) return continued;\n return {\n success: false,\n message: \"All VTXOs have already been spent.\",\n };\n }\n\n // Route based on VTXO status:\n // - spendable: offchain spend (faster, no backend dependency)\n // - recoverable/mixed: delegated settlement (handles expired batches)\n if (vtxoStatus === \"spendable\") {\n return this.#claimArkadeOffchain(claimParams, options);\n }\n\n // recoverable or mixed → delegate\n return this.#claimArkadeDelegate(id, claimParams, options);\n }\n\n /**\n * Poll `amountsForSwap` until the VTXO status leaves `not_funded` or\n * the timeout elapses. Returns the most recent status observed.\n *\n * Uses an exponential-ish backoff capped at 2s between probes so the\n * usual case (indexer catches up within a few seconds) feels snappy\n * without hammering the server.\n */\n /**\n * Lazy Electrum-over-WebSocket connection. An explicitly configured\n * `electrumWsUrl` applies on any network; otherwise the per-network\n * default is used (mainnet only — see {@link DEFAULT_ELECTRUM_WS_URLS}),\n * and null means \"no Electrum for this network, use Esplora\". The\n * underlying client connects on first use and closes itself when idle.\n */\n #getElectrumWs(network: BitcoinNetwork): ElectrumWsClient | null {\n const url = this.#config.electrumWsUrl ?? DEFAULT_ELECTRUM_WS_URLS[network];\n if (!url) return null;\n this.#electrumWs ??= new ElectrumWsClient(url, {\n onLog: (level, event, message, data) =>\n this.#logger[level]({ event, message, data }),\n });\n return this.#electrumWs;\n }\n\n /**\n * Locate the on-chain HTLC funding output once.\n *\n * Tries the configured Electrum server first, then Esplora — both prefer\n * the funding txid/vout from the API response (works before the tx is\n * confirmed) before falling back to an address UTXO lookup. Returns null\n * (rather than throwing) when the output is not visible yet, so callers\n * can poll.\n */\n async #findOnchainHtlcOutput(\n esploraUrls: EsploraUrls,\n network: BitcoinNetwork,\n address: string,\n fundTxid: string | undefined,\n fundVout: number | undefined,\n ): Promise<{ txid: string; vout: number; amount: bigint } | null> {\n const electrum = this.#getElectrumWs(network);\n if (electrum) {\n try {\n if (fundTxid && fundVout !== undefined) {\n const txData = await electrumFetchTransactionOutputs(\n electrum,\n fundTxid,\n );\n if (txData?.vout?.[fundVout]) {\n return {\n txid: fundTxid,\n vout: fundVout,\n amount: BigInt(txData.vout[fundVout].value),\n };\n }\n }\n const output = await electrumFindOutputByAddress(\n electrum,\n address,\n network,\n );\n if (output) return output;\n // Not found on our Electrum server: still consult Esplora below.\n // The tx may have propagated to a public explorer's node first.\n } catch (error) {\n this.#logger.warn({\n event: \"client.electrum.lookupFailed\",\n message:\n \"Electrum HTLC output lookup failed, falling back to Esplora\",\n data: {\n address,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n }\n }\n return this.#findOnchainHtlcOutputEsplora(\n esploraUrls,\n address,\n fundTxid,\n fundVout,\n );\n }\n\n /** Esplora-only variant of {@link Client.#findOnchainHtlcOutput}. */\n async #findOnchainHtlcOutputEsplora(\n esploraUrls: EsploraUrls,\n address: string,\n fundTxid: string | undefined,\n fundVout: number | undefined,\n ): Promise<{ txid: string; vout: number; amount: bigint } | null> {\n // Prefer funding info from the API response (works before confirmation).\n if (fundTxid && fundVout !== undefined) {\n const txData = await fetchTransactionOutputs(esploraUrls, fundTxid);\n if (txData?.vout?.[fundVout]) {\n return {\n txid: fundTxid,\n vout: fundVout,\n amount: BigInt(txData.vout[fundVout].value),\n };\n }\n }\n\n // Fallback: query the explorer for UTXOs at the HTLC address.\n try {\n return await findOutputByAddress(esploraUrls, address);\n } catch (error) {\n // Every configured explorer failed — treat as \"not found yet\" so the\n // caller keeps polling, but surface it so a dead explorer isn't\n // mistaken for an unfunded HTLC.\n this.#logger.warn({\n event: \"client.esplora.lookupFailed\",\n message: \"All Esplora endpoints failed for HTLC output lookup\",\n data: {\n address,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n return null;\n }\n }\n\n /**\n * Wait for the on-chain HTLC funding output until it appears or the\n * timeout elapses.\n *\n * With an Electrum server configured the wait is push-driven\n * (`blockchain.scripthash.subscribe`), so it resolves the moment the\n * server sees the funding tx. Without one — or if the subscription\n * fails — it falls back to polling Esplora with an exponential-ish\n * backoff capped at 2s (first probe immediate).\n */\n async #waitForOnchainHtlcOutput(\n esploraUrls: EsploraUrls,\n network: BitcoinNetwork,\n address: string,\n fundTxid: string | undefined,\n fundVout: number | undefined,\n timeoutMs: number,\n ): Promise<{ txid: string; vout: number; amount: bigint } | null> {\n const deadline = Date.now() + Math.max(0, timeoutMs);\n\n const electrum = this.#getElectrumWs(network);\n if (electrum) {\n try {\n const output = await electrumWaitForOutputByAddress(\n electrum,\n address,\n network,\n timeoutMs,\n );\n if (output) return output;\n // Timed out without our server seeing it. One last Esplora check\n // covers a tx that reached a public explorer's node but not ours.\n return await this.#findOnchainHtlcOutputEsplora(\n esploraUrls,\n address,\n fundTxid,\n fundVout,\n );\n } catch (error) {\n this.#logger.warn({\n event: \"client.electrum.waitFailed\",\n message:\n \"Electrum funding subscription failed, falling back to Esplora polling\",\n data: {\n address,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n // Fall through to the Esplora poll loop for the remaining budget.\n }\n }\n\n let delayMs = 500;\n while (true) {\n const output = await this.#findOnchainHtlcOutputEsplora(\n esploraUrls,\n address,\n fundTxid,\n fundVout,\n );\n if (output) return output;\n if (Date.now() >= deadline) return null;\n const remaining = deadline - Date.now();\n const sleepMs = Math.min(delayMs, remaining);\n if (sleepMs <= 0) return null;\n await new Promise((resolve) => setTimeout(resolve, sleepMs));\n delayMs = Math.min(delayMs * 2, 2_000);\n }\n }\n\n /**\n * Broadcast a Bitcoin transaction, preferring the configured Electrum\n * server and falling back to Esplora (with its transient-error retry\n * loop). Re-broadcasting the same tx to both backends is harmless — the\n * network dedupes by txid.\n */\n async #broadcastBtcTx(\n esploraUrls: EsploraUrls,\n network: BitcoinNetwork,\n txHex: string,\n retries = 5,\n ): Promise<string> {\n const electrum = this.#getElectrumWs(network);\n if (electrum) {\n try {\n return await electrumBroadcastTransaction(electrum, txHex);\n } catch (error) {\n this.#logger.warn({\n event: \"client.electrum.broadcastFailed\",\n message: \"Electrum broadcast failed, falling back to Esplora\",\n data: {\n error: error instanceof Error ? error.message : String(error),\n },\n });\n }\n }\n return broadcastTransactionWithRetry(esploraUrls, txHex, retries);\n }\n\n async #waitForVtxoStatus(\n id: string,\n timeoutMs: number,\n ): Promise<VhtlcAmounts[\"vtxoStatus\"]> {\n const deadline = Date.now() + Math.max(0, timeoutMs);\n let delayMs = 500;\n // First probe is immediate; subsequent probes back off.\n while (true) {\n const amounts = await this.amountsForSwap(id);\n if (amounts.vtxoStatus !== \"not_funded\") return amounts.vtxoStatus;\n if (Date.now() >= deadline) return amounts.vtxoStatus;\n const remaining = deadline - Date.now();\n const sleepMs = Math.min(delayMs, remaining);\n if (sleepMs <= 0) return amounts.vtxoStatus;\n await new Promise((resolve) => setTimeout(resolve, sleepMs));\n delayMs = Math.min(delayMs * 2, 2_000);\n }\n }\n\n /**\n * Continue (finalize) a pending Arkade claim.\n *\n * For Arkade-destination swaps (EVM/Bitcoin/Lightning → Arkade), this\n * fetches pending transactions from the Arkade server and finalizes them.\n * Use this when `claimArkade` submitted a claim but it wasn't finalized\n * (e.g. due to a page reload or network interruption).\n *\n * @param id - The UUID of the swap\n * @returns Result with txId and claimAmount on success\n */\n async continueArkadeClaimSwap(id: string): Promise<{\n success: boolean;\n message: string;\n txId?: string;\n claimAmount?: bigint;\n }> {\n if (!this.#swapStorage) {\n return {\n success: false,\n message: \"Swap storage is not configured.\",\n };\n }\n\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage.`,\n };\n }\n\n const swap = storedSwap.response;\n if (\n swap.direction !== \"btc_to_arkade\" &&\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"lightning_to_arkade\"\n ) {\n return {\n success: false,\n message: `Expected an Arkade-destination swap, got ${swap.direction}.`,\n };\n }\n\n const claimParams = this.#extractArkadeClaimParams(id, storedSwap);\n\n try {\n const result = await continueArkadeClaim({\n ...claimParams,\n destinationAddress: \"\", // not needed for continue\n arkadeServerUrl: this.#config.arkadeServerUrl,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n return {\n success: true,\n message: `Arkade claim finalized: ${result.txId}`,\n txId: result.txId,\n claimAmount: result.claimAmount,\n };\n } catch (err) {\n return {\n success: false,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n /**\n * Extracts VHTLC claim parameters from a stored swap.\n * @internal\n */\n #extractArkadeClaimParams(\n _id: string,\n storedSwap: StoredSwap,\n ): ArkadeVhtlcParams {\n const swap = storedSwap.response;\n const fullPubKey = storedSwap.publicKey;\n const userPubKey =\n fullPubKey.length === 66 ? fullPubKey.slice(2) : fullPubKey;\n\n let lendaswapPubKey: string;\n let arkadeServerPubKey: string;\n let vhtlcAddress: string;\n let refundLocktime: number;\n let unilateralClaimDelay: number;\n let unilateralRefundDelay: number;\n let unilateralRefundWithoutReceiverDelay: number;\n let network: string;\n let arkadeHtlcScriptVersion: number | undefined;\n\n if (swap.direction === \"btc_to_arkade\") {\n const s = swap as BtcToArkadeSwapResponse & {\n direction: \"btc_to_arkade\";\n };\n lendaswapPubKey = s.server_vhtlc_pk;\n arkadeServerPubKey = s.arkade_server_pk;\n vhtlcAddress = s.arkade_vhtlc_address;\n refundLocktime = s.vhtlc_refund_locktime;\n unilateralClaimDelay = s.unilateral_claim_delay;\n unilateralRefundDelay = s.unilateral_refund_delay;\n unilateralRefundWithoutReceiverDelay =\n s.unilateral_refund_without_receiver_delay;\n network = s.network;\n arkadeHtlcScriptVersion = s.arkade_htlc_script_version;\n } else if (swap.direction === \"evm_to_arkade\") {\n const s = swap as {\n sender_pk: string;\n arkade_server_pk: string;\n btc_vhtlc_address: string;\n vhtlc_refund_locktime: number;\n unilateral_claim_delay: number;\n unilateral_refund_delay: number;\n unilateral_refund_without_receiver_delay: number;\n network: string;\n arkade_htlc_script_version?: number;\n };\n lendaswapPubKey = s.sender_pk;\n arkadeServerPubKey = s.arkade_server_pk;\n vhtlcAddress = s.btc_vhtlc_address;\n refundLocktime = s.vhtlc_refund_locktime;\n unilateralClaimDelay = s.unilateral_claim_delay;\n unilateralRefundDelay = s.unilateral_refund_delay;\n unilateralRefundWithoutReceiverDelay =\n s.unilateral_refund_without_receiver_delay;\n network = s.network;\n arkadeHtlcScriptVersion = s.arkade_htlc_script_version;\n } else if (swap.direction === \"lightning_to_arkade\") {\n lendaswapPubKey = swap.sender_pk;\n arkadeServerPubKey = swap.arkade_server_pk;\n vhtlcAddress = swap.arkade_vhtlc_address;\n refundLocktime = swap.vhtlc_refund_locktime;\n unilateralClaimDelay = swap.unilateral_claim_delay;\n unilateralRefundDelay = swap.unilateral_refund_delay;\n unilateralRefundWithoutReceiverDelay =\n swap.unilateral_refund_without_receiver_delay;\n network = swap.network;\n arkadeHtlcScriptVersion = swap.arkade_htlc_script_version;\n } else {\n throw Error(`Unsupported direction for Arkade claim: ${swap.direction}`);\n }\n\n return {\n userSecretKey: storedSwap.secretKey,\n userPubKey,\n lendaswapPubKey,\n arkadeServerPubKey,\n vhtlcAddress,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n network,\n preimage: storedSwap.preimage,\n preimageHash: storedSwap.preimageHash,\n arkadeHtlcScriptVersion,\n };\n }\n\n /**\n * Claims via the offchain submitTx/finalizeTx path (spendable VTXOs only).\n * @internal\n */\n async #claimArkadeOffchain(\n params: ArkadeVhtlcParams,\n options: ArkadeClaimOptions,\n ): Promise<{\n success: boolean;\n message: string;\n txId?: string;\n claimAmount?: bigint;\n }> {\n try {\n const result = await buildArkadeClaim({\n ...params,\n destinationAddress: options.destinationAddress,\n arkadeServerUrl:\n options.arkadeServerUrl ?? this.#config.arkadeServerUrl,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n\n return {\n success: true,\n message: \"Arkade claim executed successfully via offchain spend!\",\n txId: result.txId,\n claimAmount: result.claimAmount,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to execute offchain Arkade claim: ${message}`,\n };\n }\n }\n\n /**\n * Claims via the delegated settlement path (works for all VTXO states).\n * @internal\n */\n async #claimArkadeDelegate(\n swapId: string,\n params: ArkadeVhtlcParams,\n options: ArkadeClaimOptions,\n ): Promise<{\n success: boolean;\n message: string;\n txId?: string;\n claimAmount?: bigint;\n }> {\n try {\n const result = await delegateClaim({\n ...params,\n destinationAddress: options.destinationAddress,\n lendaswapApiUrl: this.#config.baseUrl,\n arkadeServerUrl:\n options.arkadeServerUrl ?? this.#config.arkadeServerUrl,\n swapId,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n\n return {\n success: true,\n message: \"Arkade claim executed successfully via delegated settlement!\",\n txId: result.commitmentTxid,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to execute delegated Arkade claim: ${message}`,\n };\n }\n }\n\n // =========================================================================\n // Refund\n // =========================================================================\n\n /**\n * Attempts to refund a swap.\n *\n * Refund behavior depends on the swap type:\n * - **Lightning to EVM**: Cannot refund - Lightning swaps auto-expire if not completed.\n * The invoice will simply expire and no funds are locked.\n * - **Arkade to EVM**: Off-chain refund via Arkade server\n * - **Bitcoin (on-chain) to EVM**: Builds a signed refund transaction that the user\n * must broadcast to reclaim their funds after the locktime.\n *\n * @param id - The UUID of the swap to refund.\n * @param options - Options for on-chain refunds (required for btc_onchain swaps).\n * @returns A RefundResult with the transaction details (for on-chain) or status message.\n * @throws Error if the swap cannot be found, storage is not configured, params are\n * invalid, or an EVM signer is on another chain than the swap.\n *\n * @example\n * ```ts\n * // For on-chain swaps\n * const result = await client.refundSwap(swapId, {\n * destinationAddress: \"bc1q...\",\n * feeRateSatPerVb: 5,\n * });\n * if (result.success) {\n * console.log(\"Broadcast this transaction:\", result.txHex);\n * console.log(\"Transaction ID:\", result.txId);\n * }\n * ```\n */\n async refundSwap(id: string, options?: RefundOptions): Promise<RefundResult> {\n // Get the swap to determine its type\n const storedSwap = await this.getStoredSwap(id);\n if (!storedSwap) {\n throw Error(\"Swap not found\");\n }\n const swap = storedSwap.response;\n\n // Use direction to determine refund method (source_token may be a TokenSummary object)\n const direction = swap.direction;\n\n // Arkade-funded swaps require off-chain refund\n if (direction === \"arkade_to_evm\" || direction === \"arkade_to_lightning\") {\n return this.#buildArkadeRefund(id, swap, options as ArkadeRefundOptions);\n }\n\n // Bitcoin on-chain swaps require on-chain refund transaction\n if (\n direction === \"bitcoin_to_evm\" ||\n direction === \"btc_to_arkade\" ||\n direction === \"bitcoin_to_lightning\"\n ) {\n return this.#buildOnchainRefund(\n id,\n swap,\n options as OnchainRefundOptions | undefined,\n );\n }\n\n // EVM-sourced swaps: collaborative refund or timelock-based refund\n if (\n direction === \"evm_to_arkade\" ||\n direction === \"evm_to_bitcoin\" ||\n direction === \"evm_to_lightning\"\n ) {\n const evmOptions = options as EvmRefundOptions | undefined;\n\n if (evmOptions?.collaborative) {\n return this.#collabRefundEvm(id);\n }\n\n return this.#buildEvmSourceRefund(id, storedSwap, evmOptions?.signer);\n }\n\n return {\n success: false,\n message: `Refund not supported for direction: ${direction}.`,\n };\n }\n\n /**\n * Claims BTC from a server-funded on-chain Taproot HTLC (EVM-to-Bitcoin\n * and Lightning-to-Bitcoin).\n *\n * The user reveals the preimage to spend from the hashlock script path;\n * on Lightning-to-Bitcoin that spend is also what settles the hold\n * invoice the user paid.\n * @internal\n */\n async #claimOnchainBtc(\n id: string,\n options?: ClaimOptions,\n ): Promise<ClaimResult> {\n if (!this.#swapStorage) {\n return {\n success: false,\n message:\n \"Swap storage is not configured. Cannot retrieve preimage and keys needed for claim.\",\n };\n }\n\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage.`,\n };\n }\n\n // Fetch the latest swap state from API\n const swap = (await this.getSwap(id, {\n updateStorage: false,\n })) as (EvmToBitcoinSwapResponse | LightningToBitcoinSwapResponse) & {\n direction: \"evm_to_bitcoin\" | \"lightning_to_bitcoin\";\n };\n\n if (\n swap.direction !== \"evm_to_bitcoin\" &&\n swap.direction !== \"lightning_to_bitcoin\"\n ) {\n return {\n success: false,\n message: `Expected evm_to_bitcoin or lightning_to_bitcoin swap, got ${swap.direction}`,\n };\n }\n\n // Extract BTC HTLC parameters\n const btcHtlcAddress = swap.btc_htlc_address;\n const btcHashLock = swap.btc_hash_lock;\n const btcRefundLocktime = swap.btc_refund_locktime;\n const networkStr = swap.network;\n\n // Get server refund pk (needed to reconstruct the Taproot tree)\n const serverRefundPkRaw = (swap as { btc_server_refund_pk?: string })\n .btc_server_refund_pk;\n if (!serverRefundPkRaw) {\n return {\n success: false,\n message:\n \"Server refund public key not available. The API response may need to be updated.\",\n };\n }\n\n // Map network string\n const networkMap: Record<string, BitcoinNetwork> = {\n bitcoin: \"mainnet\",\n mainnet: \"mainnet\",\n testnet: \"testnet\",\n signet: \"signet\",\n regtest: \"regtest\",\n };\n const network = networkMap[networkStr];\n if (!network) {\n return {\n success: false,\n message: `Unknown Bitcoin network: ${networkStr}`,\n };\n }\n\n // Get user's x-only public key (32 bytes from 33-byte compressed)\n const fullPubKey = storedSwap.publicKey;\n const userClaimPk =\n fullPubKey.length === 66 ? fullPubKey.slice(2) : fullPubKey;\n\n // Strip compressed key prefix if present\n const serverRefundPk =\n serverRefundPkRaw.length === 66\n ? serverRefundPkRaw.slice(2)\n : serverRefundPkRaw;\n\n const btcHtlcScriptVersion = (swap as { btc_htlc_script_version?: number })\n .btc_htlc_script_version;\n\n // Verify HTLC address matches our reconstruction\n const addressMatches = verifyHtlcAddress(\n btcHtlcAddress,\n btcHashLock,\n userClaimPk, // claimer = user (goes in hashlock position)\n serverRefundPk, // refunder = server (goes in timelock position)\n btcRefundLocktime,\n network,\n btcHtlcScriptVersion,\n );\n\n if (!addressMatches) {\n return {\n success: false,\n message:\n `HTLC address mismatch. Computed address does not match server's (${btcHtlcAddress}). ` +\n `Parameters: hashLock='${btcHashLock}', userPk='${userClaimPk}', ` +\n `serverPk='${serverRefundPk}', locktime='${btcRefundLocktime}', network='${network}'`,\n };\n }\n\n // Get the HTLC output info - prefer API data over Esplora lookup\n const esploraUrls =\n this.#config.esploraUrl ?? DEFAULT_ESPLORA_URLS[network];\n if (!esploraUrls || esploraUrls.length === 0) {\n return {\n success: false,\n message: `No Esplora URL configured for network ${network}.`,\n };\n }\n\n // Try to use funding info from the API response (faster, works before confirmation)\n const btcFundTxid = (swap as { btc_fund_txid?: string }).btc_fund_txid;\n const btcFundVout = (swap as { btc_fund_vout?: number }).btc_fund_vout;\n\n // Poll for the funding output: the server can broadcast the funding tx\n // just before the client claims, so the explorer/indexer may race behind.\n const waitForFundingMs = options?.waitForFundingMs ?? 30_000;\n const htlcOutput = await this.#waitForOnchainHtlcOutput(\n esploraUrls,\n network,\n btcHtlcAddress,\n btcFundTxid,\n btcFundVout,\n waitForFundingMs,\n );\n\n if (!htlcOutput) {\n return {\n success: false,\n message: `Could not find UTXO at HTLC address ${btcHtlcAddress} after waiting ${waitForFundingMs}ms. The server may not have funded the HTLC yet.`,\n };\n }\n\n // Prefer the explicit option, then the target this client sent at\n // creation; never the fresh server copy fetched above.\n const destinationAddress =\n options?.destinationAddress ?? storedPayoutTarget(storedSwap);\n if (!destinationAddress) {\n return {\n success: false,\n message:\n \"Destination address is required to claim BTC. \" +\n 'Provide it via options: { destinationAddress: \"bc1p...\" }',\n };\n }\n\n // The claim reveals the preimage and has to confirm before the server\n // can refund, so it pays for a two-block confirmation.\n const feeRateSatPerVb =\n options?.feeRateSatPerVb ??\n Math.max(2, (await fetchFeeRateEstimate(esploraUrls, 2)) ?? 0);\n\n try {\n const result = buildOnchainClaimTransaction({\n fundingTxId: htlcOutput.txid,\n fundingVout: htlcOutput.vout,\n htlcAmount: htlcOutput.amount,\n hashLock: btcHashLock,\n userClaimPubKey: userClaimPk,\n serverRefundPubKey: serverRefundPk,\n userSecretKey: storedSwap.secretKey,\n preimage: storedSwap.preimage,\n refundLocktime: btcRefundLocktime,\n destinationAddress,\n feeRateSatPerVb,\n network,\n btcHtlcScriptVersion,\n });\n\n // Broadcast, retrying transient failures (e.g. the broadcast node has\n // not seen the funding tx yet).\n try {\n await this.#broadcastBtcTx(\n esploraUrls,\n network,\n result.txHex,\n options?.broadcastRetries ?? 5,\n );\n return {\n success: true,\n message: \"BTC claim transaction broadcast successfully!\",\n txHash: result.txId,\n // chain: \"bitcoin\" — not in ClaimChain type\n };\n } catch (broadcastError) {\n const msg =\n broadcastError instanceof Error\n ? broadcastError.message\n : String(broadcastError);\n return {\n success: false,\n message: `Claim transaction built but broadcast failed: ${msg}. TxHex: ${result.txHex}`,\n txHash: result.txId,\n // chain: \"bitcoin\" — not in ClaimChain type\n };\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to build claim transaction: ${msg}`,\n };\n }\n }\n\n /**\n * Builds an on-chain Bitcoin refund transaction.\n * @internal\n */\n async #buildOnchainRefund(\n id: string,\n swap: GetSwapResponse,\n options?: OnchainRefundOptions,\n ): Promise<RefundResult> {\n // Validate options\n if (!options?.destinationAddress) {\n return {\n success: false,\n message:\n \"Destination address is required for on-chain refunds. \" +\n 'Provide it via the options parameter: { destinationAddress: \"bc1q...\" }',\n };\n }\n\n // Check swap storage is configured\n if (!this.#swapStorage) {\n return {\n success: false,\n message:\n \"Swap storage is not configured. Cannot retrieve the secret key needed for refund.\",\n };\n }\n\n // Get stored swap data (contains secret key)\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage. The secret key is required to sign the refund transaction.`,\n };\n }\n\n // Ensure we have an on-chain funded swap\n if (\n swap.direction !== \"bitcoin_to_evm\" &&\n swap.direction !== \"btc_to_arkade\" &&\n swap.direction !== \"bitcoin_to_lightning\"\n ) {\n return {\n success: false,\n message: `Expected bitcoin_to_evm, btc_to_arkade or bitcoin_to_lightning swap, got ${swap.direction}`,\n };\n }\n\n // Extract on-chain HTLC fields based on direction\n // Both directions have the same on-chain HTLC but fields are named differently\n let btcHtlcAddress: string;\n let btcRefundLocktime: number;\n let hashLock: string;\n let serverPubKeyFull: string;\n let networkStr: string;\n\n if (swap.direction === \"btc_to_arkade\") {\n const arkadeSwap = swap as BtcToArkadeSwapResponse & {\n direction: \"btc_to_arkade\";\n };\n btcHtlcAddress = arkadeSwap.btc_htlc_address;\n btcRefundLocktime = arkadeSwap.btc_refund_locktime;\n hashLock = arkadeSwap.hash_lock;\n serverPubKeyFull = arkadeSwap.server_vhtlc_pk;\n networkStr = arkadeSwap.network;\n } else {\n // Bitcoin to EVM and Bitcoin to Lightning name the HTLC fields alike\n const onchainSwap = swap as unknown as {\n btc_htlc_address: string;\n btc_refund_locktime: number;\n btc_hash_lock: string;\n btc_server_pk: string;\n network: string;\n };\n btcHtlcAddress = onchainSwap.btc_htlc_address;\n btcRefundLocktime = onchainSwap.btc_refund_locktime;\n hashLock = onchainSwap.btc_hash_lock;\n serverPubKeyFull = onchainSwap.btc_server_pk;\n networkStr = onchainSwap.network;\n }\n\n // Check the refund locktime against the chain's median time past, which is\n // what CLTV is evaluated against — not the local clock. A clock running fast\n // would pass this check and then have the node reject the transaction as\n // non-final; one running slow would withhold a refund the chain already\n // accepts. Neither is the caller's to diagnose.\n const { mtp } = await this.getMtp();\n if (mtp < btcRefundLocktime) {\n const remainingSeconds = btcRefundLocktime - mtp;\n const remainingMinutes = Math.ceil(remainingSeconds / 60);\n return {\n success: false,\n message:\n `Refund is not yet available. The locktime expires in ${remainingMinutes} minutes ` +\n `of chain time (at ${new Date(btcRefundLocktime * 1000).toISOString()}); ` +\n `the chain's median time is currently ${new Date(mtp * 1000).toISOString()}.`,\n };\n }\n\n // Map network string to BitcoinNetwork type\n const networkMap: Record<string, BitcoinNetwork> = {\n bitcoin: \"mainnet\",\n mainnet: \"mainnet\",\n testnet: \"testnet\",\n signet: \"signet\",\n regtest: \"regtest\",\n };\n const network = networkMap[networkStr];\n if (!network) {\n return {\n success: false,\n message: `Unknown Bitcoin network: ${networkStr}`,\n };\n }\n\n // Get user's x-only public key (32 bytes) from stored swap\n // The stored publicKey is the full compressed pubkey (33 bytes)\n // We need to extract the x-only portion (drop the first byte prefix)\n const fullPubKey = storedSwap.publicKey;\n const userPubKey =\n fullPubKey.length === 66 ? fullPubKey.slice(2) : fullPubKey;\n\n // Strip compressed key prefix if present (33-byte → 32-byte x-only)\n const serverXOnlyPubKey =\n serverPubKeyFull.length === 66\n ? serverPubKeyFull.slice(2)\n : serverPubKeyFull;\n\n const btcHtlcScriptVersion = (swap as { btc_htlc_script_version?: number })\n .btc_htlc_script_version;\n\n // Verify that our computed HTLC address matches the server's address\n const addressMatches = verifyHtlcAddress(\n btcHtlcAddress,\n hashLock,\n serverXOnlyPubKey,\n userPubKey,\n btcRefundLocktime,\n network,\n btcHtlcScriptVersion,\n );\n\n if (!addressMatches) {\n return {\n success: false,\n message:\n `HTLC address mismatch. The computed address does not match the server's address (${btcHtlcAddress}). ` +\n `This could indicate different script construction. ` +\n `Parameters: \\nhashLock='${hashLock}', \\nserverPk='${serverPubKeyFull}', ` +\n `\\nuserPk='${userPubKey}', \\nlocktime='${btcRefundLocktime}',` +\n `\\nnetwork='${network}'`,\n };\n }\n\n // Get the HTLC output info - prefer API data over Esplora lookup\n const esploraUrls =\n this.#config.esploraUrl ?? DEFAULT_ESPLORA_URLS[network];\n if (!esploraUrls || esploraUrls.length === 0) {\n return {\n success: false,\n message: `No Esplora URL configured for network ${network}. Cannot look up funding transaction.`,\n };\n }\n\n // Try to use funding info from the API response (faster, works before confirmation)\n const btcFundTxid = (swap as { btc_fund_txid?: string }).btc_fund_txid;\n const btcFundVout = (swap as { btc_fund_vout?: number }).btc_fund_vout;\n\n const htlcOutput = await this.#findOnchainHtlcOutput(\n esploraUrls,\n network,\n btcHtlcAddress,\n btcFundTxid,\n btcFundVout,\n );\n\n if (!htlcOutput) {\n return {\n success: false,\n message:\n `Could not find UTXO at HTLC address ${btcHtlcAddress}. ` +\n `The address may not have been funded yet.`,\n };\n }\n\n try {\n // Build the refund transaction\n const result = buildOnchainRefundTransaction({\n fundingTxId: htlcOutput.txid,\n fundingVout: htlcOutput.vout,\n htlcAmount: htlcOutput.amount,\n hashLock,\n serverPubKey: serverXOnlyPubKey,\n userPubKey,\n userSecretKey: storedSwap.secretKey,\n refundLocktime: btcRefundLocktime,\n destinationAddress: options.destinationAddress,\n feeRateSatPerVb: options.feeRateSatPerVb ?? 2,\n network,\n btcHtlcScriptVersion,\n });\n\n // If dry run, just return the transaction without broadcasting\n if (options.dryRun) {\n return {\n success: true,\n message:\n \"Refund transaction built successfully (dry run - not broadcast).\",\n txHex: result.txHex,\n txId: result.txId,\n refundAmount: result.refundAmount,\n fee: result.fee,\n broadcast: false,\n htlcAddress: result.htlcAddress,\n serverHtlcAddress: btcHtlcAddress,\n };\n }\n\n // Broadcast the transaction\n const broadcastEsploraUrls =\n this.#config.esploraUrl ?? DEFAULT_ESPLORA_URLS[network];\n if (!broadcastEsploraUrls || broadcastEsploraUrls.length === 0) {\n return {\n success: true,\n message:\n \"Refund transaction built successfully. No Esplora URL configured for broadcast. \" +\n \"Broadcast the txHex manually to the Bitcoin network.\",\n txHex: result.txHex,\n txId: result.txId,\n refundAmount: result.refundAmount,\n fee: result.fee,\n broadcast: false,\n htlcAddress: result.htlcAddress,\n serverHtlcAddress: btcHtlcAddress,\n };\n }\n\n try {\n await this.#broadcastBtcTx(\n broadcastEsploraUrls,\n network,\n result.txHex,\n 0,\n );\n return {\n success: true,\n message: \"Refund transaction broadcast successfully!\",\n txHex: result.txHex,\n txId: result.txId,\n refundAmount: result.refundAmount,\n fee: result.fee,\n broadcast: true,\n htlcAddress: result.htlcAddress,\n serverHtlcAddress: btcHtlcAddress,\n };\n } catch (broadcastError) {\n const broadcastMessage =\n broadcastError instanceof Error\n ? broadcastError.message\n : String(broadcastError);\n return {\n success: true,\n message:\n `Transaction built but broadcast failed: ${broadcastMessage}. ` +\n \"You can broadcast the txHex manually.\",\n txHex: result.txHex,\n txId: result.txId,\n refundAmount: result.refundAmount,\n fee: result.fee,\n broadcast: false,\n htlcAddress: result.htlcAddress,\n serverHtlcAddress: btcHtlcAddress,\n };\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to build refund transaction: ${message}`,\n };\n }\n }\n\n /**\n * Builds and executes an Arkade (off-chain) VHTLC refund.\n *\n * Automatically selects the best refund method based on VTXO status:\n * - **spendable** VTXOs → offchain spend (submitTx/finalizeTx)\n * - **recoverable** or **mixed** VTXOs → delegated settlement via backend\n *\n * @internal\n */\n async #buildArkadeRefund(\n id: string,\n swap: GetSwapResponse,\n options?: ArkadeRefundOptions,\n ): Promise<RefundResult> {\n // Validate options\n if (!options?.destinationAddress) {\n return {\n success: false,\n message:\n \"Destination address is required for Arkade refunds. \" +\n 'Provide it via the options parameter: { destinationAddress: \"ark1...\" }',\n };\n }\n\n // Check swap storage is configured\n if (!this.#swapStorage) {\n return {\n success: false,\n message:\n \"Swap storage is not configured. Cannot retrieve the secret key needed for refund.\",\n };\n }\n\n // Get stored swap data (contains secret key)\n const storedSwap = await this.#swapStorage.get(id);\n if (!storedSwap) {\n return {\n success: false,\n message: `Swap ${id} not found in local storage. The secret key is required to sign the refund transaction.`,\n };\n }\n\n // Ensure we have an arkade_to_evm swap\n if (\n swap.direction !== \"arkade_to_evm\" &&\n swap.direction !== \"arkade_to_lightning\"\n ) {\n return {\n success: false,\n message: `Expected an Arkade-funded swap, got ${swap.direction}`,\n };\n }\n\n // Both directions share the client-funded VHTLC shape; only the\n // address field name differs.\n const s =\n swap.direction === \"arkade_to_evm\"\n ? {\n ...(swap as ArkadeToEvmSwapResponse & {\n direction: \"arkade_to_evm\";\n }),\n vhtlc_address: (swap as ArkadeToEvmSwapResponse).btc_vhtlc_address,\n }\n : {\n ...(swap as ArkadeToLightningSwapResponse & {\n direction: \"arkade_to_lightning\";\n }),\n vhtlc_address: (swap as ArkadeToLightningSwapResponse)\n .arkade_vhtlc_address,\n };\n\n const fullPubKey = storedSwap.publicKey;\n const userPubKey =\n fullPubKey.length === 66 ? fullPubKey.slice(2) : fullPubKey;\n\n const hashLock = s.hash_lock.startsWith(\"0x\")\n ? s.hash_lock.slice(2)\n : s.hash_lock;\n\n // Query VTXO status to determine refund method\n const amounts = await this.amountsForSwap(id);\n const vtxoStatus = amounts.vtxoStatus;\n\n if (vtxoStatus === \"not_funded\" || vtxoStatus === \"spent\") {\n return {\n success: false,\n message:\n vtxoStatus === \"not_funded\"\n ? \"No VTXOs found at the VHTLC address.\"\n : \"All VTXOs have already been spent.\",\n };\n }\n\n const refundParams = {\n userSecretKey: storedSwap.secretKey,\n userPubKey,\n lendaswapPubKey: s.receiver_pk,\n arkadeServerPubKey: s.arkade_server_pk,\n hashLock,\n vhtlcAddress: s.vhtlc_address,\n refundLocktime: s.vhtlc_refund_locktime,\n unilateralClaimDelay: s.unilateral_claim_delay,\n unilateralRefundDelay: s.unilateral_refund_delay,\n unilateralRefundWithoutReceiverDelay:\n s.unilateral_refund_without_receiver_delay,\n destinationAddress: options.destinationAddress,\n network: s.network,\n arkadeHtlcScriptVersion: s.arkade_htlc_script_version,\n };\n\n // Try collaborative refund first (instant, no locktime wait).\n // Falls back to non-collab refund if the server rejects (e.g. unsafe state).\n const collabParams = {\n ...refundParams,\n swapId: id,\n apiClient: this.#apiClient,\n arkadeServerUrl: options.arkadeServerUrl ?? this.#config.arkadeServerUrl,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n };\n\n try {\n if (vtxoStatus === \"spendable\") {\n const result = await collabRefundArkadeToEvmOffchain(collabParams);\n return {\n success: true,\n message:\n \"Arkade refund executed successfully via collaborative offchain spend!\",\n txId: result.txId,\n refundAmount: result.refundAmount,\n broadcast: true,\n };\n }\n // recoverable or mixed → collab delegate\n const result = await collabRefundArkadeToEvmDelegate(collabParams);\n return {\n success: true,\n message:\n \"Arkade refund executed successfully via collaborative delegated settlement!\",\n txId: result.commitmentTxid,\n broadcast: true,\n };\n } catch (collabError) {\n const collabMsg =\n collabError instanceof Error\n ? collabError.message\n : String(collabError);\n this.#logger.warn({\n event: \"arkade.refund.collab_failed\",\n message:\n \"Collaborative refund failed, falling back to non-collaborative refund\",\n swapId: id,\n data: { reason: collabMsg },\n error: collabError,\n });\n }\n\n // Fallback: non-collaborative refund (requires locktime to have expired)\n const now = Math.floor(Date.now() / 1000);\n if (now < s.vhtlc_refund_locktime) {\n const remainingSeconds = s.vhtlc_refund_locktime - now;\n const remainingMinutes = Math.ceil(remainingSeconds / 60);\n return {\n success: false,\n message:\n `Collaborative refund was rejected by the server and non-collaborative refund ` +\n `is not yet available. The VHTLC locktime expires in ${remainingMinutes} minutes ` +\n `(at ${new Date(s.vhtlc_refund_locktime * 1000).toISOString()}).`,\n };\n }\n\n if (vtxoStatus === \"spendable\") {\n return this.#refundArkadeOffchain(refundParams, options);\n }\n\n // recoverable or mixed → delegate\n return this.#refundArkadeDelegate(refundParams, options);\n }\n\n /**\n * Refunds via the offchain submitTx/finalizeTx path (spendable VTXOs only).\n * @internal\n */\n async #refundArkadeOffchain(\n params: {\n userSecretKey: string;\n userPubKey: string;\n lendaswapPubKey: string;\n arkadeServerPubKey: string;\n hashLock: string;\n vhtlcAddress: string;\n refundLocktime: number;\n unilateralClaimDelay: number;\n unilateralRefundDelay: number;\n unilateralRefundWithoutReceiverDelay: number;\n destinationAddress: string;\n network: string;\n arkadeHtlcScriptVersion?: number;\n },\n options: ArkadeRefundOptions,\n ): Promise<RefundResult> {\n try {\n const result = await buildArkadeRefund({\n ...params,\n arkadeServerUrl:\n options.arkadeServerUrl ?? this.#config.arkadeServerUrl,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n\n return {\n success: true,\n message: \"Arkade refund executed successfully via offchain spend!\",\n txId: result.txId,\n refundAmount: result.refundAmount,\n broadcast: true,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to execute offchain Arkade refund: ${message}`,\n };\n }\n }\n\n /**\n * Refunds via the delegated settlement path (works for all VTXO states).\n * @internal\n */\n async #refundArkadeDelegate(\n params: {\n userSecretKey: string;\n userPubKey: string;\n lendaswapPubKey: string;\n arkadeServerPubKey: string;\n hashLock: string;\n vhtlcAddress: string;\n refundLocktime: number;\n unilateralClaimDelay: number;\n unilateralRefundDelay: number;\n unilateralRefundWithoutReceiverDelay: number;\n destinationAddress: string;\n network: string;\n arkadeHtlcScriptVersion?: number;\n },\n options: ArkadeRefundOptions,\n ): Promise<RefundResult> {\n try {\n const result = await delegateRefund({\n ...params,\n lendaswapApiUrl: this.#config.baseUrl,\n arkadeServerUrl:\n options.arkadeServerUrl ?? this.#config.arkadeServerUrl,\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n });\n\n return {\n success: true,\n message:\n \"Arkade refund executed successfully via delegated settlement!\",\n txId: result.commitmentTxid,\n broadcast: true,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to execute delegated Arkade refund: ${message}`,\n };\n }\n }\n\n /**\n * Builds unilateral refund data for an EVM-sourced swap (EVM → Arkade,\n * Bitcoin or Lightning).\n *\n * Every EVM-source funding is created by the HTLCCoordinator, which locks\n * with itself as the HTLC sender and records the depositor. The HTLC's\n * refund key binds that sender, so the wallet must call the coordinator's\n * `refundTo` (which pays the recorded depositor) — a direct `HTLCErc20.refund`\n * from the wallet computes a different key and reverts. That holds for a\n * BTC-pegged source (tBTC, WBTC) just as for a DEX-swapped one: the\n * coordinator is the sender either way. The server's calldata endpoint\n * targets the actual locked amount, which covers the gasless relay fee.\n *\n * @internal\n */\n async #buildCoordinatorRefund(\n id: string,\n leg: ReturnType<typeof evmSourceLeg>,\n check: {\n signer?: EvmSigner;\n /** Who the refund may pay: this client's addresses and the depositor. */\n expectedDepositors: readonly string[];\n },\n ): Promise<RefundResult> {\n const response = await this.#apiClient.GET(\n \"/swap/{id}/refund-and-swap-calldata\",\n {\n params: {\n path: { id },\n },\n },\n );\n\n if (response.error) {\n return {\n success: false,\n message: `Failed to fetch refund calldata: ${response.error.error || \"Unknown error\"}`,\n };\n }\n\n let refund: {\n to: string;\n data: string;\n timelock: number;\n recipient?: string;\n };\n try {\n refund = await this.#bindServerRefund(\n {\n to: response.data.coordinator_address,\n data: response.data.calldata,\n },\n leg,\n check,\n );\n } catch (error) {\n return {\n success: false,\n message: `Refused the server's refund calldata: ${errorMessage(error)}`,\n };\n }\n const timelock = refund.timelock;\n const timelockExpired = Math.floor(Date.now() / 1000) >= timelock;\n return {\n success: true,\n message: timelockExpired\n ? \"EVM refund calldata ready. Submit this transaction with your EVM wallet.\"\n : `Timelock has not expired yet. Refund will be available at ${new Date(timelock * 1000).toISOString()}.`,\n evmRefundData: {\n to: refund.to,\n data: refund.data,\n timelockExpired,\n timelockExpiry: timelock,\n recipient: refund.recipient,\n },\n };\n }\n\n /**\n * The server's refund call, checked and re-encoded by this client. It must\n * be one of the refund calls the server builds (`refundFor` on the HTLC,\n * `refund` on a native HTLC, `refundTo` on the coordinator), on this swap's\n * HTLC or recorded coordinator, for a lock the server claims, and it must\n * pay one of `expectedDepositors`. With a signer the chain is asked too:\n * the lock must be active, and a coordinator must hold its deposit for one\n * of them. The bytes sent are this client's encoding of the checked terms,\n * never the server's.\n */\n async #bindServerRefund(\n server: { to: string; data: string },\n leg: ReturnType<typeof evmSourceLeg>,\n check: { signer?: EvmSigner; expectedDepositors: readonly string[] },\n ): Promise<{\n to: string;\n data: string;\n timelock: number;\n recipient?: string;\n }> {\n const call = decodeRefundCall(server.data);\n const to = server.to.toLowerCase();\n const htlc = leg.htlcAddress.toLowerCase();\n const coordinator = leg.coordinatorAddress?.toLowerCase();\n const signer = check.signer;\n let lockSender: string | undefined;\n let recipient: string | undefined;\n switch (call.kind) {\n case \"refundFor\":\n case \"nativeRefundFor\":\n if (to !== htlc) {\n throw new Error(\n `The server's refund targets ${server.to}, not this swap's HTLC ${leg.htlcAddress}`,\n );\n }\n lockSender = call.sender;\n recipient = call.sender;\n break;\n case \"nativeRefund\":\n // refund pays msg.sender's own lock back to msg.sender.\n if (to !== htlc) {\n throw new Error(\n `The server's refund targets ${server.to}, not this swap's HTLC ${leg.htlcAddress}`,\n );\n }\n lockSender = signer?.address.toLowerCase();\n recipient = lockSender;\n break;\n case \"refundTo\":\n case \"nativeRefundTo\":\n // refundTo pays whoever the coordinator recorded as depositor. A\n // coordinator this client recorded pins the target; without one the\n // server's is taken, since refundTo moves nothing on any other\n // contract, and with a signer its deposit is checked below.\n if (coordinator !== undefined && to !== coordinator) {\n throw new Error(\n `The server's refund targets ${server.to}, not this swap's coordinator ${leg.coordinatorAddress}`,\n );\n }\n if (to === htlc) {\n throw new Error(\n `The server's refundTo targets the HTLC ${leg.htlcAddress} itself`,\n );\n }\n lockSender = to;\n break;\n }\n if (call.claimAddress !== leg.claimAddress.toLowerCase()) {\n throw new Error(\n `The server's refund is for a lock claimed by ${call.claimAddress}, not by this swap's server ${leg.claimAddress}`,\n );\n }\n if (\n recipient !== undefined &&\n !check.expectedDepositors.includes(recipient)\n ) {\n throw new Error(\n `The server's refund would pay ${recipient}, which is none of this client's addresses (${check.expectedDepositors.join(\", \")})`,\n );\n }\n // The chain backs these checks up where it answers; a node that cannot\n // read the contract leaves the call as checked above, which already\n // pays only the lock's own sender or depositor.\n const read = async (\n tx: { to: string; data: string },\n what: string,\n ): Promise<bigint | undefined> => {\n try {\n return decodeCallWord(await (signer as EvmSigner).call(tx), what);\n } catch {\n return undefined;\n }\n };\n if (signer && lockSender !== undefined) {\n const terms = {\n preimageHash: call.preimageHash,\n amount: call.amount,\n token: call.token,\n refundAddress: lockSender,\n claimAddress: call.claimAddress,\n timelock: call.timelock,\n };\n const active = await read(\n encodeHtlcErc20IsActiveCallData(leg.htlcAddress, terms),\n \"isActive\",\n );\n if (active === 0n) {\n throw new Error(\n `The server's refund names a lock (hash lock ${call.preimageHash}) that is not active on ${leg.htlcAddress}`,\n );\n }\n if (call.kind === \"refundTo\" || call.kind === \"nativeRefundTo\") {\n const deposit = await read(\n encodeDepositsCallData(to, htlcSwapKey(terms)),\n \"deposits\",\n );\n if (deposit !== undefined) {\n const depositor = `0x${deposit.toString(16).padStart(40, \"0\")}`;\n if (deposit === 0n || !check.expectedDepositors.includes(depositor)) {\n throw new Error(\n `${server.to} would refund the lock to ${depositor}, which is none of this client's addresses (${check.expectedDepositors.join(\", \")})`,\n );\n }\n recipient = depositor;\n }\n }\n }\n return {\n ...encodeRefundCall(server.to, call),\n timelock: call.timelock,\n recipient,\n };\n }\n\n /**\n * The hash lock an EVM-sourced swap's lock must use, as this client fixed\n * it: its own preimage hash for EVM → Bitcoin / Arkade, the payment hash\n * it recorded at creation for EVM → Lightning. A lock under any other\n * hash may be one whose preimage the server already knows, which it could\n * claim without paying. Throws when the swap has no such record here\n * (recovered onto this device, or created by an older SDK).\n */\n #clientHashLock(\n swapId: string,\n stored: StoredSwap | null | undefined,\n ): string {\n if (!stored) {\n throw new Error(\n `Swap ${swapId} is not in local storage, so the hash its lock must use is unknown; refusing to fund or move it`,\n );\n }\n const direction = stored.response.direction;\n if (direction === \"evm_to_lightning\") {\n if (!stored.lightningPaymentHash) {\n throw new Error(\n `Swap ${swapId} has no payment hash recorded by this client at creation (it was recovered, or created by an older SDK), so the server's hash lock cannot be checked; refusing to fund or move it. Refund it instead.`,\n );\n }\n return `0x${normalizeBytes32(stored.lightningPaymentHash.hash)}`;\n }\n if (direction === \"evm_to_bitcoin\" || direction === \"evm_to_arkade\") {\n return `0x${normalizeBytes32(stored.preimageHash)}`;\n }\n throw new Error(`Swap ${swapId} is ${direction}, not EVM-sourced`);\n }\n\n /**\n * What a funding of an EVM-sourced swap must match: the hash lock this\n * client fixed at creation (its own preimage hash, or the Lightning\n * invoice's payment hash) and the funding terms it recorded from the\n * creation response (coordinator, HTLC, claimer, timelock, tokens,\n * input). Pass it as `expected` when building CCTP-inbound calldata\n * yourself (`buildCctpInboundBatch`). Throws for a swap without them here.\n */\n async getEvmFundingExpectation(\n swapId: string,\n pins?: FundingPins,\n ): Promise<ExpectedFunding> {\n return {\n ...this.#fundingExpectation(swapId, await this.getStoredSwap(swapId)),\n pins,\n };\n }\n\n #fundingExpectation(\n swapId: string,\n stored: StoredSwap | null | undefined,\n ): ExpectedFunding {\n const hashLock = this.#clientHashLock(swapId, stored);\n const terms = stored?.evmFundingTerms;\n if (!terms) {\n throw new Error(\n `Swap ${swapId} has no funding terms recorded by this client at creation (it was recovered, or created by an older SDK), so the server's funding payload cannot be checked; refusing to fund it. Refund it instead.`,\n );\n }\n if (\n stored.evmCoordinatorAddress &&\n stored.evmCoordinatorAddress.toLowerCase() !==\n terms.coordinator.toLowerCase() &&\n !isDirectNativeLock(terms)\n ) {\n throw new Error(\n `Swap ${swapId} was funded through coordinator ${stored.evmCoordinatorAddress}, not the ${terms.coordinator} it was created with`,\n );\n }\n return { hashLock, terms };\n }\n\n /**\n * A server funding payload checked against the swap's recorded terms and\n * hash lock (see {@link checkFundingPayload}), on the swap's chain.\n */\n async #checkedFunding(\n swapId: string,\n payload: FundingPayload,\n chainId: number,\n pins?: FundingPins,\n ): Promise<CheckedFunding> {\n const { hashLock, terms } = this.#fundingExpectation(\n swapId,\n await this.getStoredSwap(swapId),\n );\n if (chainId !== terms.chainId) {\n throw new Error(\n `Swap ${swapId} locks on chain ${terms.chainId}, not ${chainId}`,\n );\n }\n return checkFundingPayload(terms, hashLock, payload, pins);\n }\n\n /** Throws unless `hash` is the one {@link #clientHashLock} fixed. */\n async #ensureClientHashLock(\n swapId: string,\n hash: string,\n what: string,\n ): Promise<void> {\n const expected = this.#clientHashLock(\n swapId,\n await this.getStoredSwap(swapId),\n );\n if (`0x${normalizeBytes32(hash)}` !== expected) {\n throw new Error(\n `The server's ${what} locks under hash ${hash}, not this swap's ${expected}; refusing to sign or send it`,\n );\n }\n }\n\n /**\n * What this client learned when it funded the swap, kept beside the stored\n * `response` because every server refresh replaces that copy.\n */\n async #recordEvmFunding(\n swapId: string,\n funding: { txid: string; coordinatorAddress?: string },\n ): Promise<void> {\n if (!this.#swapStorage) return;\n try {\n const stored = await this.#swapStorage.get(swapId);\n if (!stored) return;\n await this.#swapStorage.store({\n ...stored,\n evmFundTxid: funding.txid,\n evmCoordinatorAddress:\n funding.coordinatorAddress ?? stored.evmCoordinatorAddress,\n updatedAt: Date.now(),\n });\n } catch (error) {\n // The funding is on-chain either way. A bookkeeping failure must not\n // make it look as if it were not, or a caller could fund the swap twice.\n this.#logger.warn({\n event: \"client.fundSwap.recordFailed\",\n message: \"could not record the funding tx on the stored swap\",\n swapId,\n error,\n });\n }\n }\n\n /**\n * Drops the recorded funding tx `txid`, which provably did not fund the\n * swap. Best effort: a record left behind only makes a retry check it.\n */\n async #forgetEvmFunding(swapId: string, txid: string): Promise<void> {\n if (!this.#swapStorage) return;\n try {\n const stored = await this.#swapStorage.get(swapId);\n if (stored?.evmFundTxid?.toLowerCase() !== txid.toLowerCase()) return;\n await this.#swapStorage.store({\n ...stored,\n evmFundTxid: undefined,\n updatedAt: Date.now(),\n });\n } catch (error) {\n this.#logger.warn({\n event: \"client.fundSwap.forgetFailed\",\n message: \"could not drop the failed funding tx from the stored swap\",\n swapId,\n error,\n });\n }\n }\n\n /**\n * The Kernel owner for a swap's sponsored UserOps on Arbitrum (the\n * CCTP-inbound settlement, a sponsored refund, a continuation). The owner's\n * address is the account the funds sit in and must be the swap's depositor,\n * which the paymaster checks before sponsoring. A swap created gasless has the\n * SDK's own key as depositor; that key can sign the EIP-7702 authorization a\n * browser wallet usually cannot. Otherwise the wallet itself is the owner.\n * `hint` is appended to the error when neither is.\n */\n #depositorOwnerSigner(\n swapResponse: GetSwapResponse,\n walletSigner?: EvmSigner,\n hint?: string,\n ): EvmSigner {\n const depositor = (\n swapResponse as { client_evm_address?: string }\n ).client_evm_address?.toLowerCase();\n if (depositor === this.getEvmAddress().toLowerCase()) {\n return this.#keyOwnerSigner();\n }\n if (walletSigner && depositor === walletSigner.address.toLowerCase()) {\n return walletSigner;\n }\n throw new Error(\n `Swap ${swapResponse.id} was created for depositor ${depositor}, ` +\n `which is neither this client's key nor the given wallet.${\n hint ? ` ${hint}` : \"\"\n }`,\n );\n }\n\n /**\n * Record the source-chain CCTP burn of a CCTP-inbound swap. From the moment\n * it is broadcast the USDC has left the source chain, and this hash is what\n * resuming the settlement or recovering the USDC needs, so it is kept beside\n * the stored `response` (every server refresh replaces that copy).\n * `undefined` clears it: the burn reverted or the wallet cancelled it, so\n * nothing left the source chain and the next attempt must burn again.\n * A Solana burn also records the last block height it can land at.\n */\n async #recordCctpBurn(\n swapId: string,\n burnTxHash: string | undefined,\n lastValidBlockHeight?: number,\n ): Promise<void> {\n if (!this.#swapStorage) return;\n try {\n const stored = await this.#swapStorage.get(swapId);\n if (!stored) return;\n await this.#swapStorage.store({\n ...stored,\n cctpBurnTxid: burnTxHash,\n cctpBurnLastValidBlockHeight: lastValidBlockHeight,\n updatedAt: Date.now(),\n });\n } catch (error) {\n // The burn is on-chain either way; a bookkeeping failure must not abort\n // the settlement that follows it.\n this.#logger.warn({\n event: \"client.fundSwap.recordCctpBurnFailed\",\n message: \"could not record the CCTP burn tx on the stored swap\",\n swapId,\n data: { burnTxHash },\n error,\n });\n }\n }\n\n /**\n * Refund calldata for an EVM-sourced swap. With a signer it is built from\n * the funding tx's `SwapCreated` log, since the DEX swap inside that tx\n * decides the locked amount; the log's sender picks `refundTo` on the\n * coordinator or a direct `HTLCErc20.refund`. The server is asked for\n * another txid only when no recorded one yields a receipt, and for the\n * calldata once the chain path has failed.\n */\n async #buildEvmSourceRefund(\n id: string,\n stored: StoredSwap,\n signer?: EvmSigner,\n ): Promise<RefundResult> {\n const leg = evmSourceLeg(stored);\n const ready = (\n refund: { to: string; data: string; recipient: string },\n timelock: number,\n payoutNote: string,\n ): RefundResult => {\n // Wall-clock, like the server path: EvmSigner has no block-time read,\n // and refundEvmWithSigner simulates before sending, so chain time is\n // enforced where a transaction is at stake.\n const timelockExpired = Math.floor(Date.now() / 1000) >= timelock;\n const status = timelockExpired\n ? \"EVM refund calldata ready. Submit this transaction with your EVM wallet.\"\n : `Timelock has not expired yet. Refund will be available at ${new Date(timelock * 1000).toISOString()}.`;\n return {\n success: true,\n message: status + payoutNote,\n evmRefundData: {\n to: refund.to,\n data: refund.data,\n recipient: refund.recipient,\n timelockExpired,\n timelockExpiry: timelock,\n },\n };\n };\n\n const chainFailures: string[] = [];\n // Who a refund may pay: the wallet, the SDK's gasless keys, or the\n // depositor the server recorded, which is all a device without the\n // funding mnemonic knows.\n const sdkAddresses = uniqueAddresses([\n this.getEvmAddress(),\n stored.secretKey ? deriveEvmAddress(stored.secretKey) : undefined,\n ]);\n const expectedDepositors = uniqueAddresses([\n signer?.address,\n ...sdkAddresses,\n (stored.response as { client_evm_address?: string | null })\n .client_evm_address,\n ]);\n if (signer) {\n if (signer.chainId !== leg.chainId) {\n throw new Error(\n `Signer is on chain ${signer.chainId} but swap ${id} was funded on chain ${leg.chainId}`,\n );\n }\n // From v7 the HTLC's refundFor pays the depositor; before, the\n // coordinator's refundTo did.\n const payer = leg.depositorIsSender ? \"The HTLC\" : \"The coordinator\";\n const payoutNote = (recipient: string): string => {\n if (recipient === signer.address.toLowerCase()) return \"\";\n return sdkAddresses.includes(recipient)\n ? ` ${payer} pays the refund to ${recipient}, this SDK's gasless key; run recoverGaslessFunds afterwards to move the tokens.`\n : ` ${payer} pays the refund to the depositor ${recipient}, not to the submitting wallet.`;\n };\n const tried: string[] = [];\n // Only a receipt that could not be read leaves room for another txid.\n let receiptUnavailable = true;\n const fromFundingTx = async (\n fundTxid: string,\n ): Promise<RefundResult | undefined> => {\n tried.push(fundTxid.toLowerCase());\n try {\n const refund = await this.#refundFromFundingTx(signer, {\n ...leg,\n fundTxid,\n expectedDepositors,\n });\n // A coordinator the chain just proved is worth keeping: with it on\n // record, only its own SwapCreated counts next time. From v7 the\n // sender is the depositor, never the coordinator.\n const coordinatorProved =\n !leg.depositorIsSender &&\n refund.sender !== signer.address.toLowerCase() &&\n stored.evmCoordinatorAddress === undefined;\n if (\n fundTxid.toLowerCase() !== stored.evmFundTxid?.toLowerCase() ||\n coordinatorProved\n ) {\n await this.#recordEvmFunding(id, {\n txid: fundTxid,\n coordinatorAddress: coordinatorProved ? refund.sender : undefined,\n });\n }\n return ready(refund, refund.timelock, payoutNote(refund.recipient));\n } catch (error) {\n if (error instanceof HtlcNotActiveError) {\n return { success: false, message: error.message };\n }\n receiptUnavailable = error instanceof FundingTxUnavailableError;\n chainFailures.push(`${fundTxid}: ${errorMessage(error)}`);\n return undefined;\n }\n };\n for (const fundTxid of leg.fundTxids) {\n const result = await fromFundingTx(fundTxid);\n if (result) return result;\n if (!receiptUnavailable) break;\n }\n if (receiptUnavailable) {\n // The wallet may have replaced the recorded tx; the server's monitor\n // saw the one that mined.\n const serverTxid = await this.#serverFundTxid(id).catch(\n () => undefined,\n );\n if (serverTxid && !tried.includes(serverTxid.toLowerCase())) {\n const result = await fromFundingTx(serverTxid);\n if (result) return result;\n }\n if (tried.length === 0) {\n chainFailures.push(\"no funding tx is known for this swap\");\n }\n }\n }\n\n let server: RefundResult;\n try {\n server = await this.#buildCoordinatorRefund(id, leg, {\n signer,\n expectedDepositors,\n });\n } catch (error) {\n server = {\n success: false,\n message: `Failed to fetch refund calldata: ${errorMessage(error)}`,\n };\n }\n if (server.success || chainFailures.length === 0) return server;\n return {\n success: false,\n message: `Refund could not be built from the chain (${chainFailures.join(\"; \")}); ${server.message}`,\n };\n }\n\n /**\n * The server's copy of the funding txid. The stored copy is refreshed on\n * the way, but failing to write it must not cost the txid itself.\n */\n async #serverFundTxid(id: string): Promise<string | undefined> {\n const fresh = await this.getSwap(id);\n try {\n await this.#swapStorage?.update(id, fresh);\n } catch (error) {\n this.#logger.warn({\n event: \"client.refundSwap.refreshNotStored\",\n message: \"could not store the refreshed swap\",\n swapId: id,\n error,\n });\n }\n return (\n (fresh as { evm_fund_txid?: string | null }).evm_fund_txid ?? undefined\n );\n }\n\n async #refundFromFundingTx(\n signer: EvmSigner,\n leg: {\n fundTxid: string;\n htlcAddress: string;\n hashLock: string;\n claimAddress: string;\n coordinatorAddress?: string;\n /** HTLCErc20 v7 / HTLCNative v2: the depositor is the lock's sender. */\n depositorIsSender: boolean;\n expectedDepositors: readonly string[];\n /** Rehashes this client sent, oldest first; the lock continues under the last. */\n rehashes?: readonly EvmRehashRecord[];\n },\n ): Promise<{\n to: string;\n data: string;\n timelock: number;\n sender: string;\n recipient: string;\n }> {\n const self = signer.address.toLowerCase();\n const coordinator = leg.coordinatorAddress?.toLowerCase();\n // Only a lock this client funded counts. From v7 the depositor is the\n // sender, and only it (directly, or through the coordinator's\n // non-reentrant create with its Permit2 signature) can create a lock\n // under its own address. Before, the coordinator was the sender, and\n // its DEX calls cannot target the HTLC, so no decoy can name it either.\n const senders = leg.depositorIsSender\n ? uniqueAddresses([self, ...leg.expectedDepositors])\n : coordinator === undefined\n ? undefined\n : [self, coordinator];\n const { created, terms, hashLock } = await this.#lockFromFundingTx(signer, {\n ...leg,\n senders,\n });\n const active = decodeCallWord(\n await signer.call(\n encodeHtlcErc20IsActiveCallData(leg.htlcAddress, terms),\n ),\n \"isActive\",\n );\n if (active === 0n) {\n await this.#ensureSettled(signer, leg.htlcAddress, terms);\n }\n // A zero asset word is a native lock (`HTLCNative`), whose refund and\n // coordinator `refundTo` take no token parameter.\n const native = created.token === NATIVE_TOKEN_ADDRESS.toLowerCase();\n if (leg.depositorIsSender) {\n // The permissionless `refundFor` pays the lock's sender whoever submits\n // it, so any of this client's wallets can refund the depositor's lock,\n // rehashed or not. It is also what the server builds.\n const { to, data } = encodeRefundCall(leg.htlcAddress, {\n kind: native ? \"nativeRefundFor\" : \"refundFor\",\n preimageHash: terms.preimageHash,\n amount: terms.amount,\n token: terms.token,\n sender: created.refundAddress,\n claimAddress: terms.claimAddress,\n timelock: terms.timelock,\n });\n return {\n to,\n data,\n timelock: terms.timelock,\n sender: created.refundAddress,\n recipient: created.refundAddress,\n };\n }\n const ownHtlc = created.refundAddress === self;\n let recipient = self;\n if (!ownHtlc && leg.rehashes !== undefined) {\n throw new Error(\n `The HTLC for hash lock ${hashLock} was created by ${created.refundAddress} and rehashed; only that sender can refund it`,\n );\n }\n if (!ownHtlc) {\n // refundTo pays whoever the sender recorded as depositor, and anyone\n // may call it: this checks which HTLC was picked, not who may refund.\n const deposit = decodeCallWord(\n await signer.call(\n encodeDepositsCallData(created.refundAddress, created.key),\n ),\n \"deposits\",\n );\n if (deposit === 0n) {\n throw new Error(\n `${created.refundAddress} created the HTLC for hash lock ${hashLock} but holds no deposit for it, so it is not a coordinator this client can refund through`,\n );\n }\n const depositor = `0x${deposit.toString(16).padStart(40, \"0\")}`;\n if (!leg.expectedDepositors.includes(depositor)) {\n throw new Error(\n `${created.refundAddress} would refund the HTLC for hash lock ${hashLock} to ${depositor}, which is none of this client's addresses (${leg.expectedDepositors.join(\", \")})`,\n );\n }\n recipient = depositor;\n }\n const { to, data } = ownHtlc\n ? native\n ? encodeHtlcNativeRefundCallData(leg.htlcAddress, terms)\n : encodeHtlcErc20RefundCallData(leg.htlcAddress, terms)\n : native\n ? encodeNativeRefundTo(created.refundAddress, terms)\n : encodeRefundTo(created.refundAddress, terms);\n return {\n to,\n data,\n timelock: terms.timelock,\n sender: created.refundAddress,\n recipient,\n };\n }\n\n /**\n * The lock the funding tx `leg.fundTxid` created, by its `SwapCreated`\n * log, and the terms it continues under after the recorded rehashes.\n */\n async #lockFromFundingTx(\n signer: EvmSigner,\n leg: {\n fundTxid: string;\n htlcAddress: string;\n hashLock: string;\n claimAddress: string;\n coordinatorAddress?: string;\n /** Who may have created the lock; anyone when omitted. */\n senders?: readonly string[];\n rehashes?: readonly EvmRehashRecord[];\n },\n ): Promise<{\n created: SwapCreatedLog;\n terms: SwapCreatedLog;\n hashLock: string;\n }> {\n // A hash the node does not know would keep waitForReceipt polling until\n // its timeout, or forever on an adapter without one; a known but\n // pending one is bounded below.\n let known: unknown;\n try {\n known = await signer.getTransaction(leg.fundTxid);\n } catch {\n known = null;\n }\n if (!known) {\n throw new FundingTxUnavailableError(\n `Funding tx ${leg.fundTxid} is unknown to the node`,\n );\n }\n let receipt: Awaited<ReturnType<EvmSigner[\"waitForReceipt\"]>>;\n try {\n receipt = await withDeadline(\n signer.waitForReceipt(leg.fundTxid),\n FUNDING_RECEIPT_WAIT_MS,\n `not mined within ${FUNDING_RECEIPT_WAIT_MS / 1000}s`,\n );\n } catch (error) {\n throw new FundingTxUnavailableError(\n `Funding tx ${leg.fundTxid}: ${errorMessage(error)}`,\n );\n }\n if (receipt.status !== \"success\") {\n throw new FundingTxUnavailableError(\n `Funding tx ${leg.fundTxid} reverted`,\n );\n }\n if (!receipt.logs) {\n throw new Error(\n \"Reading the lock from the chain needs the funding receipt's logs, which this signer's waitForReceipt does not return\",\n );\n }\n const hashLock = `0x${normalizeBytes32(leg.hashLock)}`;\n const matches = findSwapCreated(receipt.logs, {\n htlcAddress: leg.htlcAddress,\n hashLock,\n claimAddress: leg.claimAddress,\n senders: leg.senders,\n });\n if (matches.length === 0) {\n // This tx did not fund the swap, so another one may have.\n throw new FundingTxUnavailableError(\n `Funding tx ${leg.fundTxid} carries no SwapCreated log for hash lock ${hashLock} on ${leg.htlcAddress}${\n leg.senders === undefined\n ? \"\"\n : ` created by ${leg.senders.join(\" or \")}`\n }`,\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `Funding tx ${leg.fundTxid} carries ${matches.length} SwapCreated logs for hash lock ${hashLock}; refusing to guess which HTLC to refund`,\n );\n }\n const created = matches[0];\n // After a rehash the lock lives under the new hash and timelock, with\n // the amount, token and parties of the original SwapCreated.\n const terms =\n leg.rehashes === undefined\n ? created\n : await this.#rehashedTerms(\n signer,\n leg.htlcAddress,\n created,\n leg.rehashes,\n );\n return { created, terms, hashLock };\n }\n\n /**\n * Throws for terms that are no longer active. Only a redeemed or\n * refunded lock is settled; a rehashed one moved to terms this client has\n * no record of (another device, or a move whose record is pending), so\n * that error is not final and the server's view of the lock is tried.\n */\n async #ensureSettled(\n signer: EvmSigner,\n htlcAddress: string,\n terms: SwapCreatedLog,\n ): Promise<never> {\n const state = await this.#swapState(signer, htlcAddress, terms.key);\n if (\n state === undefined ||\n state === HTLC_SWAP_STATE.Redeemed ||\n state === HTLC_SWAP_STATE.Refunded\n ) {\n throw new HtlcNotActiveError(\n `The HTLC for hash lock ${terms.preimageHash} on ${htlcAddress} is no longer active; it was already redeemed or refunded`,\n );\n }\n throw new Error(\n state === HTLC_SWAP_STATE.Rehashed\n ? `The HTLC for hash lock ${terms.preimageHash} on ${htlcAddress} was rehashed to terms this client has no record of`\n : `No HTLC is open under hash lock ${terms.preimageHash} and timelock ${terms.timelock} on ${htlcAddress}; this client's record of the lock is stale`,\n );\n }\n\n /**\n * `swaps(key)` on HTLCErc20 v7 / HTLCNative v2; undefined where the\n * contract does not answer it (older generations, which never rehash).\n */\n async #swapState(\n signer: EvmSigner,\n htlcAddress: string,\n key: string,\n ): Promise<bigint | undefined> {\n try {\n return decodeCallWord(\n await signer.call(encodeHtlcSwapsCallData(htlcAddress, key)),\n \"swaps\",\n );\n } catch {\n return undefined;\n }\n }\n\n /**\n * The terms the lock created as `created` continues under after the\n * recorded rehashes: each rehash tx's receipt must carry `SwapRehashed`\n * for the lock's key at that point, moving it to the recorded hash, and\n * the next rehash starts from the key that one produced. Anything else\n * means the record is stale, and the refund is left to the server's view.\n */\n async #rehashedTerms(\n signer: EvmSigner,\n htlcAddress: string,\n created: SwapCreatedLog,\n rehashes: readonly EvmRehashRecord[],\n ): Promise<SwapCreatedLog> {\n let terms = created;\n for (const rehash of rehashes) {\n // A move recorded without its tx is followed only through the receipt\n // its UserOp hash leads to: that the lock left its key, or that a lock\n // exists under the recorded terms, proves nothing (another attempt, or\n // anyone creating a lock under those terms, explains either).\n const txid =\n rehash.txid === \"\" ? await this.#pendingRehashTx(rehash) : rehash.txid;\n if (txid === undefined) continue;\n let receipt: Awaited<ReturnType<EvmSigner[\"waitForReceipt\"]>>;\n try {\n receipt = await withDeadline(\n signer.waitForReceipt(txid),\n FUNDING_RECEIPT_WAIT_MS,\n `not mined within ${FUNDING_RECEIPT_WAIT_MS / 1000}s`,\n );\n } catch (error) {\n throw new Error(`Rehash tx ${txid}: ${errorMessage(error)}`);\n }\n // A rehash recorded on broadcast may have reverted or been replaced\n // by a cancel: mined, but the lock did not move. It is skipped; the\n // lock is still under the terms before it.\n if (receipt.status !== \"success\") continue;\n if (!receipt.logs) {\n throw new Error(\n `Rehash tx ${txid} has no readable logs, so the lock's current terms cannot be verified from the chain`,\n );\n }\n const moved = findSwapRehashed(receipt.logs, {\n htlcAddress,\n key: terms.key,\n });\n if (moved.length === 0) continue;\n const hashLock = `0x${normalizeBytes32(rehash.hashLock)}`;\n if (moved.length !== 1 || moved[0].newPreimageHash !== hashLock) {\n throw new Error(\n `Rehash tx ${txid} moved the HTLC for hash lock ${terms.preimageHash} elsewhere than the recorded ${hashLock}`,\n );\n }\n terms = {\n ...terms,\n preimageHash: hashLock,\n timelock: rehash.timelock,\n key: moved[0].newKey,\n };\n }\n return terms;\n }\n\n /**\n * Fetches the EIP-712 parameters for collaborative EVM HTLC refund.\n *\n * Returns the addresses and values needed to build the `CollabRefund`\n * EIP-712 typed data that the depositor signs.\n *\n * @param swapId - Swap ID\n * @returns CollabRefund parameters\n */\n async getCollabRefundEvmParams(\n swapId: string,\n ): Promise<CollabRefundEvmParams> {\n const response = await this.#apiClient.GET(\n \"/api/swap/{id}/collab-refund-evm/params\",\n {\n params: {\n path: { id: swapId },\n },\n },\n );\n\n if (response.error) {\n throw new Error(\n `Failed to fetch collab refund params: ${response.error.error || \"Unknown error\"}`,\n );\n }\n\n const d = response.data;\n return {\n coordinatorAddress: d.coordinator_address,\n serverSignerAddress: d.server_signer_address,\n preimageHash: d.preimage_hash,\n amount: d.amount,\n token: d.token,\n claimAddress: d.claim_address,\n timelock: d.timelock,\n chainId: d.chain_id,\n sweepToken: d.sweep_token,\n minAmountOut: d.min_amount_out,\n callsHash: d.calls_hash,\n coordinatorVersion: d.coordinator_version,\n htlcAddress: d.htlc_address,\n htlcVersion: d.htlc_version,\n htlcKind: d.htlc_kind,\n refundPath: collabRefundPath(d.refund_path),\n };\n }\n\n /**\n * Fetches the server's `Refund` signature for a direct collaborative\n * refund (`refundPath === \"direct\"`), bound to `depositorAddress` as the\n * HTLC sender. The server signs only in states where it will not fund,\n * and only for the lock's recorded terms; it submits nothing.\n *\n * @param swapId - Swap ID\n * @param depositorAddress - The address that funded the lock and will send `refundBySig`\n */\n async getCollabRefundEvmSignature(\n swapId: string,\n depositorAddress: string,\n ): Promise<CollabRefundEvmSignature> {\n const response = await this.#apiClient.POST(\n \"/api/swap/{id}/collab-refund-evm/signature\",\n {\n params: { path: { id: swapId } },\n body: { depositor_address: depositorAddress },\n },\n );\n if (response.error) {\n throw new Error(\n `Failed to fetch the collab refund signature: ${response.error.error || \"Unknown error\"}`,\n );\n }\n const d = response.data;\n return {\n id: d.id,\n htlcAddress: d.htlc_address,\n htlcVersion: d.htlc_version,\n htlcKind: d.htlc_kind,\n chainId: d.chain_id,\n preimageHash: d.preimage_hash,\n amount: d.amount,\n token: d.token,\n sender: d.sender,\n claimAddress: d.claim_address,\n timelock: d.timelock,\n v: d.v,\n r: d.r,\n s: d.s,\n };\n }\n\n /**\n * Builds the EIP-712 typed data for collaborative EVM refund.\n *\n * The depositor signs this with their wallet (via `eth_signTypedData_v4`\n * or the SDK's `signEvmDigest`) to authorize the server to submit the\n * refund on-chain.\n *\n * @param swapId - Swap ID\n * @returns Typed data and digest for signing\n */\n async buildCollabRefundEvmTypedData(swapId: string): Promise<{\n typedData: CollabRefundEvmTypedData;\n digest: string;\n params: CollabRefundEvmParams;\n }> {\n const params = await this.getCollabRefundEvmParams(swapId);\n\n const digestParams: CollabRefundEvmDigestParams = {\n coordinatorAddress: params.coordinatorAddress,\n chainId: params.chainId,\n preimageHash: params.preimageHash,\n amount: BigInt(params.amount),\n token: params.token,\n claimAddress: params.claimAddress,\n timelock: params.timelock,\n caller: params.serverSignerAddress,\n sweepToken: params.sweepToken,\n minAmountOut: BigInt(params.minAmountOut),\n callsHash: params.callsHash,\n coordinatorVersion: params.coordinatorVersion,\n };\n\n const typedData = buildCollabRefundEvmTypedData(digestParams);\n const digest = buildCollabRefundEvmDigest(digestParams);\n\n return { typedData, digest, params };\n }\n\n /**\n * Performs a collaborative EVM refund using the SDK's embedded wallet.\n *\n * The SDK signs the EIP-712 `CollabRefund` digest with the depositor's\n * derived EVM key and POSTs to the server, which cosigns and submits\n * the transaction on-chain. Gasless for the client — no timelock wait.\n *\n * @param swapId - Swap ID\n * @returns Refund result with transaction hash\n */\n async collabRefundEvmSwap(swapId: string): Promise<CollabRefundEvmResult> {\n // The SDK-controlled EVM key that matches the on-chain depositor.\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap?.secretKey) {\n throw new Error(\n \"No secret key found for this swap. Cannot sign collab refund.\",\n );\n }\n const evmKey = this.#getCollabRefundEvmSigningKey(storedSwap);\n\n const { digest, params } = await this.buildCollabRefundEvmTypedData(swapId);\n if (params.refundPath === \"direct\") {\n return this.#collabRefundEvmSponsored(swapId, params, evmKey);\n }\n if (params.refundPath !== \"coordinator\") {\n throw new Error(collabRefundUnavailable(swapId, params));\n }\n const sig = signEvmDigest(evmKey, digest);\n\n // Derive the on-chain depositor address from the selected EVM signing key.\n const depositorAddress = deriveEvmAddress(evmKey);\n\n // POST to the server\n const response = await this.#apiClient.POST(\n \"/api/swap/{id}/collab-refund-evm\",\n {\n params: { path: { id: swapId } },\n body: {\n v: sig.v,\n r: sig.r,\n s: sig.s,\n depositor_address: depositorAddress,\n },\n },\n );\n\n if (response.error) {\n throw new Error(\n `Collaborative EVM refund failed: ${response.error.error || \"Unknown error\"}`,\n );\n }\n\n return {\n id: response.data.id,\n txHash: response.data.tx_hash,\n message: response.data.message,\n };\n }\n\n /**\n * Submits a pre-signed collaborative EVM refund.\n *\n * Use this when an external wallet (e.g. MetaMask) signs the EIP-712\n * `CollabRefund` digest instead of the SDK's embedded key.\n * Call {@link buildCollabRefundEvmTypedData} first to obtain the typed data\n * for the wallet to sign, then pass the resulting signature here.\n *\n * @param swapId - Swap ID\n * @param body - Signed refund request (signature + refund parameters)\n * @returns Refund result with transaction hash\n */\n async submitCollabRefundEvm(\n swapId: string,\n body: {\n v: number;\n r: string;\n s: string;\n depositor_address: string;\n },\n ): Promise<CollabRefundEvmResult> {\n const response = await this.#apiClient.POST(\n \"/api/swap/{id}/collab-refund-evm\",\n {\n params: { path: { id: swapId } },\n body,\n },\n );\n\n if (response.error) {\n throw new Error(\n `Collaborative EVM refund failed: ${response.error.error || \"Unknown error\"}`,\n );\n }\n\n return {\n id: response.data.id,\n txHash: response.data.tx_hash,\n message: response.data.message,\n };\n }\n\n /**\n * Direct collaborative refund from the SDK key: `refundBySig` as a\n * paymaster-sponsored UserOp from the key's own (EIP-7702) account, so\n * `msg.sender` is the depositor. Arbitrum only, where the paymaster runs.\n */\n async #collabRefundEvmSponsored(\n swapId: string,\n params: CollabRefundEvmParams,\n evmKey: string,\n ): Promise<CollabRefundEvmResult> {\n if (params.chainId !== 42161) {\n throw new Error(\n `Swap ${swapId} locks on HTLC v${params.htlcVersion} on chain ${params.chainId}, where the depositor sends the collaborative refund itself and no paymaster sponsors it. Refund after the timelock with refundSwap, or from the depositor key's wallet with collabRefundEvmWithSigner.`,\n );\n }\n const owner = keyToKernelOwnerSigner(\n hexToBytes(evmKey.replace(/^0x/, \"\")),\n params.chainId,\n );\n const signature = await this.getCollabRefundEvmSignature(\n swapId,\n owner.address,\n );\n const call = refundBySigCallData(signature);\n const { txHash, userOpHash } = await this.#sponsoredUserOp(owner, call);\n this.#logger.info({\n event: \"client.collabRefundEvm.direct\",\n message: \"refundBySig submitted as a sponsored UserOp\",\n swapId,\n data: { txHash, userOpHash },\n });\n return {\n id: swapId,\n txHash,\n message: \"Collaborative refund submitted by the depositor\",\n };\n }\n\n /**\n * Sends one call as a paymaster-sponsored UserOp from `owner`'s Kernel\n * account and waits for it to land; a UserOp that is included but reverts\n * fails rather than reporting its tx hash.\n */\n async #sponsoredUserOp(\n owner: EvmSigner,\n callOrBuilder:\n | { to: string; data: string }\n | ((account: string) => { to: string; data: string }),\n hooks: {\n /**\n * With this hook the UserOp is prepared (gas, paymaster) and signed\n * first, and the hook runs with its hash right before it is sent:\n * a failure before the hook proves it was never sent, one after it\n * does not (the bundler may have taken it and the answer been lost).\n * The hash is undefined if it could not be computed locally.\n */\n onSigned?: (userOpHash: string | undefined) => Promise<void>;\n /** Runs once the bundler took the UserOp, before waiting for it. */\n onSubmitted?: (userOpHash: string) => Promise<void>;\n /** Runs once it is included, whether or not its call succeeded. */\n onIncluded?: (txHash: string, userOpHash: string) => Promise<void>;\n } = {},\n ): Promise<{ txHash: string; userOpHash: string }> {\n if (!this.#config.aa) {\n throw new Error(\n \"A sponsored UserOp requires AA config. Call `.withAa({ bundlerUrl, paymasterPolicyId })` on the ClientBuilder before `.build()`.\",\n );\n }\n const { client, accountAddress } =\n await this.cctpInbound.createSmartAccountClient({\n signer: owner,\n });\n const call =\n typeof callOrBuilder === \"function\"\n ? callOrBuilder(accountAddress)\n : callOrBuilder;\n const calls = [\n {\n to: call.to as `0x${string}`,\n data: call.data as `0x${string}`,\n value: 0n,\n },\n ];\n let userOpHash: string;\n if (hooks.onSigned) {\n // What sendUserOperation does, split so the send itself is the only\n // step whose failure leaves it open whether the UserOp went out.\n const { formatUserOperationRequest, getUserOperationHash } = await import(\n \"viem/account-abstraction\"\n );\n const raw = client as unknown as {\n prepareUserOperation(args: {\n calls: typeof calls;\n }): Promise<Record<string, unknown>>;\n account: {\n signUserOperation(userOperation: unknown): Promise<string>;\n entryPoint: {\n address: `0x${string}`;\n version: \"0.6\" | \"0.7\" | \"0.8\";\n };\n };\n request(\n args: { method: \"eth_sendUserOperation\"; params: unknown[] },\n options?: { retryCount?: number },\n ): Promise<string>;\n };\n const prepared = await raw.prepareUserOperation({ calls });\n const signed = {\n ...prepared,\n signature: await raw.account.signUserOperation(prepared),\n };\n const entryPoint = raw.account.entryPoint;\n let computed: string | undefined;\n try {\n computed = getUserOperationHash({\n chainId: owner.chainId,\n entryPointAddress: entryPoint.address,\n entryPointVersion: entryPoint.version,\n userOperation: signed as never,\n });\n } catch {\n computed = undefined;\n }\n await hooks.onSigned(computed);\n userOpHash = await raw.request(\n {\n method: \"eth_sendUserOperation\",\n params: [\n formatUserOperationRequest(signed as never),\n entryPoint.address,\n ],\n },\n { retryCount: 0 },\n );\n } else {\n userOpHash = await client.sendUserOperation({ calls });\n }\n await hooks.onSubmitted?.(userOpHash);\n const { receipt, success, reason } =\n await client.waitForUserOperationReceipt({\n hash: userOpHash as `0x${string}`,\n });\n await hooks.onIncluded?.(receipt.transactionHash, userOpHash);\n if (!success) {\n throw new Error(\n `Sponsored UserOp ${userOpHash} reverted on-chain${\n reason ? `: ${reason}` : \"\"\n }`,\n );\n }\n return { txHash: receipt.transactionHash, userOpHash };\n }\n\n // =========================================================================\n // Rehash: retry a stuck EVM -> Lightning swap with a new invoice\n // =========================================================================\n\n /**\n * The lock's terms and the constraints a replacement invoice must meet\n * for a stuck EVM → Lightning swap (`GET /api/swap/{id}/rehash-evm/params`).\n */\n async getRehashEvmParams(swapId: string): Promise<RehashEvmParams> {\n const response = await this.#apiClient.GET(\n \"/api/swap/{id}/rehash-evm/params\",\n { params: { path: { id: swapId } } },\n );\n if (response.error) {\n throw new Error(\n `Failed to fetch rehash params: ${response.error.error || \"Unknown error\"}`,\n );\n }\n const d = response.data;\n return {\n id: d.id,\n htlcAddress: d.htlc_address,\n htlcVersion: d.htlc_version,\n htlcKind: d.htlc_kind,\n chainId: d.chain_id,\n preimageHash: d.preimage_hash,\n amount: d.amount,\n token: d.token,\n sender: d.sender ?? undefined,\n claimAddress: d.claim_address,\n timelock: d.timelock,\n newTimelock: d.new_timelock,\n maxInvoiceAmountSats: d.max_invoice_amount_sats,\n minInvoiceValiditySecs: d.min_invoice_validity_secs,\n };\n }\n\n /**\n * Asks the server to sign the lock's move to `invoice`. The depositor\n * proves it asked with an EIP-191 signature over\n * {@link rehashAuthorizationMessage}; the server validates the invoice\n * (amount, validity, routability), records it and returns the `rehash`\n * arguments. Signing the same invoice again returns the same signature.\n */\n async signRehashEvm(\n swapId: string,\n request: {\n invoice: string;\n depositorAddress: string;\n /** 65-byte EIP-191 signature by the depositor, 0x-prefixed hex. */\n depositorSignature: string;\n },\n ): Promise<RehashEvmSignature> {\n const response = await this.#apiClient.POST(\"/api/swap/{id}/rehash-evm\", {\n params: { path: { id: swapId } },\n body: {\n invoice: request.invoice,\n depositor_address: request.depositorAddress,\n depositor_signature: request.depositorSignature,\n },\n });\n if (response.error) {\n throw new Error(\n `Rehash refused: ${response.error.error || \"Unknown error\"}`,\n );\n }\n const d = response.data;\n return {\n id: d.id,\n htlcAddress: d.htlc_address,\n htlcVersion: d.htlc_version,\n htlcKind: d.htlc_kind,\n chainId: d.chain_id,\n preimageHash: d.preimage_hash,\n amount: d.amount,\n token: d.token,\n sender: d.sender,\n claimAddress: d.claim_address,\n timelock: d.timelock,\n newPreimageHash: d.new_preimage_hash,\n newTimelock: d.new_timelock,\n v: d.v,\n r: d.r,\n s: d.s,\n };\n }\n\n /**\n * Retry a stuck EVM → Lightning swap with a new invoice from the\n * depositor's wallet. The server failed to pay the old invoice and gave\n * up (`ServerWontFund`); instead of refunding, the lock moves to the new\n * invoice's payment hash and the server pays that one once the move is\n * confirmed. The user keeps their position: no second DEX round trip.\n *\n * The wallet signs the authorization message (`personal_sign`, so the\n * signer needs `signMessage`) and sends `rehash`; it pays gas.\n *\n * @param swapId - The UUID of the swap\n * @param invoice - A BOLT 11 invoice for at most the swap's payout, valid\n * for at least `minInvoiceValiditySecs` from {@link getRehashEvmParams}\n * @param signer - An {@link EvmSigner} wrapping the depositor's wallet\n */\n async retrySwapWithInvoiceWithSigner(\n swapId: string,\n invoice: string,\n signer: EvmSigner,\n ): Promise<RetrySwapWithInvoiceResult> {\n if (!signer.signMessage) {\n throw new Error(\n \"Retrying with a new invoice needs the signer's `signMessage` (personal_sign) to authorize the rehash\",\n );\n }\n const params = await this.getRehashEvmParams(swapId);\n const paymentHash = invoicePaymentHash(invoice);\n const lock = await this.#ownLockForRehash(swapId, signer);\n ensureLockIsOwn(lock, params, \"The server describes\");\n const message = rehashAuthorizationMessage(swapId, paymentHash);\n const depositorSignature = await signer.signMessage({\n raw: `0x${bytesToHex(new TextEncoder().encode(message))}`,\n });\n const signature = await this.signRehashEvm(swapId, {\n invoice,\n depositorAddress: signer.address,\n depositorSignature,\n });\n ensureRehashMatchesRequest(signature, paymentHash, params);\n ensureLockIsOwn(lock, signature, \"The server signed a rehash of\");\n // Recorded as soon as it is broadcast: a receipt wait that gives up on\n // a tx that mines anyway must not lose the terms the lock now has.\n let sent: string | undefined;\n const txHash = await sendCall(\n signer,\n rehashCallData(signature),\n \"Rehash transaction\",\n {\n onSent: async (hash) => {\n sent = hash;\n await this.#recordEvmRehash(swapId, signature, hash);\n },\n },\n );\n if (sent !== undefined && txHash.toLowerCase() !== sent.toLowerCase()) {\n const replaced = sent.toLowerCase();\n await this.#recordEvmRehash(swapId, signature, txHash, {\n replaces: (entry) => entry.txid.toLowerCase() === replaced,\n });\n }\n return {\n id: swapId,\n txHash,\n newPreimageHash: signature.newPreimageHash,\n newTimelock: signature.newTimelock,\n };\n }\n\n /**\n * Remembers the terms a rehash moved the lock to, so a later refund is\n * built for the lock that exists rather than the one the server still\n * reports until its monitor confirms the move.\n */\n async #recordEvmRehash(\n swapId: string,\n signature: RehashEvmSignature,\n txid: string,\n options: {\n /** The entry this record supersedes; the last match is replaced. */\n replaces?: (entry: EvmRehashRecord) => boolean;\n userOpHash?: string;\n } = {},\n ): Promise<void> {\n if (!this.#swapStorage) return;\n const record: EvmRehashRecord = {\n txid,\n fromHashLock: signature.preimageHash,\n hashLock: signature.newPreimageHash,\n timelock: signature.newTimelock,\n ...(options.userOpHash === undefined\n ? {}\n : { userOpHash: options.userOpHash }),\n };\n let lastError: unknown;\n for (let attempt = 0; attempt < REHASH_RECORD_ATTEMPTS; attempt++) {\n try {\n const stored = await this.#swapStorage.get(swapId);\n if (!stored) return;\n // The server's copy names the rehash tx as the funding tx once it\n // has confirmed the move; the original is what the refund starts\n // from, so it goes on record now if this client never recorded it.\n const serverFundTxid = (\n stored.response as { evm_fund_txid?: string | null }\n ).evm_fund_txid;\n const history = stored.evmRehashes ?? [];\n let replaced = -1;\n if (options.replaces !== undefined) {\n for (let i = history.length - 1; i >= 0; i--) {\n if (options.replaces(history[i])) {\n replaced = i;\n break;\n }\n }\n }\n await this.#swapStorage.store({\n ...stored,\n evmFundTxid: stored.evmFundTxid ?? serverFundTxid ?? undefined,\n evmRehashes:\n replaced === -1\n ? [...history, record]\n : history.map((entry, i) => (i === replaced ? record : entry)),\n updatedAt: Date.now(),\n });\n return;\n } catch (error) {\n lastError = error;\n await new Promise((resolve) =>\n setTimeout(resolve, REHASH_RECORD_RETRY_MS),\n );\n }\n }\n // The lock moves on chain regardless; the caller must know that this\n // client no longer knows under which terms, or a later refund would be\n // built for the old lock.\n this.#logger.error({\n event: \"client.retrySwapWithInvoice.notRecorded\",\n message: \"could not record the rehash in swap storage\",\n swapId,\n error: lastError,\n });\n throw new RehashNotRecordedError(swapId, record, lastError);\n }\n\n /**\n * Fills in a recorded rehash once more of it is known. The pending entry\n * already keeps a refund on the right lock, so failing to write this is\n * logged rather than failing a move that went out.\n */\n async #updateEvmRehash(\n swapId: string,\n signature: RehashEvmSignature,\n txid: string,\n options: {\n replaces: (entry: EvmRehashRecord) => boolean;\n userOpHash: string;\n },\n ): Promise<void> {\n try {\n await this.#recordEvmRehash(swapId, signature, txid, options);\n } catch (error) {\n this.#logger.warn({\n event: \"client.retrySwapWithInvoice.recordNotUpdated\",\n message: \"could not update the pending rehash record\",\n swapId,\n data: { txid, userOpHash: options.userOpHash },\n error,\n });\n }\n }\n\n /**\n * The tx a pending sponsored rehash landed in, asked of the bundler by\n * its UserOp hash; undefined when that cannot be told (no hash recorded,\n * no AA config, not included, or the bundler cannot be reached).\n */\n async #pendingRehashTx(rehash: EvmRehashRecord): Promise<string | undefined> {\n const bundlerUrl = this.#config.aa?.bundlerUrl;\n if (!rehash.userOpHash || !bundlerUrl) return undefined;\n try {\n const response = await fetch(bundlerUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"eth_getUserOperationReceipt\",\n params: [rehash.userOpHash],\n }),\n });\n const json = (await response.json()) as {\n result?: { receipt?: { transactionHash?: string } } | null;\n };\n return json.result?.receipt?.transactionHash ?? undefined;\n } catch {\n return undefined;\n }\n }\n\n /** Removes the last pending rehash record matching `pending`, best effort. */\n async #dropPendingRehash(\n swapId: string,\n pending: (entry: EvmRehashRecord) => boolean,\n ): Promise<void> {\n if (!this.#swapStorage) return;\n try {\n const stored = await this.#swapStorage.get(swapId);\n const history = stored?.evmRehashes;\n if (!stored || !history) return;\n let index = -1;\n for (let i = history.length - 1; i >= 0; i--) {\n if (pending(history[i])) {\n index = i;\n break;\n }\n }\n if (index === -1) return;\n const rest = history.filter((_, i) => i !== index);\n await this.#swapStorage.store({\n ...stored,\n evmRehashes: rest.length > 0 ? rest : undefined,\n updatedAt: Date.now(),\n });\n } catch (error) {\n // A pending record that never landed is skipped on the next read: the\n // lock's state shows no key under its terms.\n this.#logger.warn({\n event: \"client.retrySwapWithInvoice.pendingNotDropped\",\n message: \"could not drop a rehash the bundler never took\",\n swapId,\n error,\n });\n }\n }\n\n /**\n * This swap's lock as the chain shows it, anchored on what this client\n * holds: the payment hash it fixed at creation. A funding receipt from any\n * source (this device's record, the relay's answer, the server's copy)\n * counts only for a `SwapCreated` on the swap's HTLC under that hash,\n * created by the depositor `reader` speaks for, followed through the\n * rehashes recorded here, and still active. Another lock of the same\n * depositor has another hash, and a lock under the user's own hash is\n * one only the user's invoice can unlock, so no server answer can make\n * this a lock the server could claim. Without the recorded hash the\n * rehash is refused.\n */\n async #ownLockForRehash(\n swapId: string,\n reader: EvmSigner,\n ): Promise<OwnEvmLock> {\n const stored = await this.getStoredSwap(swapId);\n if (!stored) {\n throw new Error(\n `Swap ${swapId} is not in local storage, so the lock to move cannot be checked`,\n );\n }\n if (stored.response.direction !== \"evm_to_lightning\") {\n throw new Error(\n `Swap ${swapId} is ${stored.response.direction}; only an EVM -> Lightning swap retries with a new invoice`,\n );\n }\n const ownHash = this.#clientHashLock(swapId, stored);\n const leg = evmSourceLeg(stored);\n const firstFrom = leg.rehashes?.[0]?.fromHashLock;\n if (\n firstFrom !== undefined &&\n `0x${normalizeBytes32(firstFrom)}` !== ownHash\n ) {\n throw new Error(\n `The rehash history of swap ${swapId} starts from ${firstFrom}, not from the payment hash this client fixed (${ownHash})`,\n );\n }\n if (reader.chainId !== leg.chainId) {\n throw new Error(\n `Swap ${swapId} locks on chain ${leg.chainId}, but the signer is connected to chain ${reader.chainId}`,\n );\n }\n const failures: string[] = [];\n const tried = new Set<string>();\n const fromReceipt = async (\n txid: string | undefined,\n ): Promise<OwnEvmLock | undefined> => {\n if (!txid || tried.has(txid.toLowerCase())) return undefined;\n tried.add(txid.toLowerCase());\n try {\n const { terms } = await this.#lockFromFundingTx(reader, {\n ...leg,\n fundTxid: txid,\n hashLock: ownHash,\n // On the generations that rehash, the depositor is the sender.\n senders: [reader.address.toLowerCase()],\n });\n const active = decodeCallWord(\n await reader.call(\n encodeHtlcErc20IsActiveCallData(leg.htlcAddress, terms),\n ),\n \"isActive\",\n );\n if (active === 0n) {\n failures.push(\n `${txid}: the lock under ${terms.preimageHash} is no longer active`,\n );\n return undefined;\n }\n return { ...terms, htlcAddress: leg.htlcAddress, chainId: leg.chainId };\n } catch (error) {\n failures.push(`${txid}: ${errorMessage(error)}`);\n return undefined;\n }\n };\n for (const txid of leg.fundTxids) {\n const lock = await fromReceipt(txid);\n if (lock) return lock;\n }\n // A funding this device did not see (CCTP settlement, a wallet that\n // sent the calldata itself): the server's monitor indexed it.\n const lock = await fromReceipt(\n await this.#serverFundTxid(swapId).catch(() => undefined),\n );\n if (lock) return lock;\n throw new Error(\n `No funding of swap ${swapId} shows an active lock under its payment hash ${ownHash} created by ${reader.address}${\n failures.length > 0 ? ` (${failures.join(\"; \")})` : \"\"\n }; refusing to rehash`,\n );\n }\n\n /**\n * `owner` with chain reads over the AA RPC, for a key whose own signer\n * does not read the chain. Arbitrum only, like the paymaster.\n */\n async #aaChainReader(owner: EvmSigner): Promise<EvmSigner> {\n const rpcUrl = this.#config.aa?.rpcUrl ?? this.#config.aa?.bundlerUrl;\n if (!rpcUrl) {\n throw new Error(\n \"A sponsored rehash reads the lock over the AA RPC; call `.withAa({ bundlerUrl, paymasterPolicyId })` on the ClientBuilder before `.build()`.\",\n );\n }\n const { createPublicClient, http } = await import(\"viem\");\n const { arbitrum } = await import(\"viem/chains\");\n const publicClient = createPublicClient({\n chain: arbitrum,\n transport: http(rpcUrl),\n });\n return {\n ...owner,\n getTransaction: async (hash) => {\n const tx = await publicClient.getTransaction({\n hash: hash as `0x${string}`,\n });\n return { to: tx.to ?? null, input: tx.input, from: tx.from };\n },\n // Only mined txs are read here (the funding tx and recorded rehashes).\n waitForReceipt: async (hash) => {\n const receipt = await publicClient.getTransactionReceipt({\n hash: hash as `0x${string}`,\n });\n return {\n status: receipt.status,\n blockNumber: receipt.blockNumber,\n transactionHash: receipt.transactionHash,\n logs: receipt.logs.map((log) => ({\n address: log.address,\n topics: [...log.topics],\n data: log.data,\n })),\n };\n },\n call: async ({ to, data }) =>\n (\n await publicClient.call({\n to: to as `0x${string}`,\n data: data as `0x${string}`,\n })\n ).data ?? \"0x\",\n };\n }\n\n /**\n * Retry a stuck EVM → Lightning swap with a new invoice when the SDK's\n * key is the depositor (gasless swaps): the key signs the authorization\n * and `rehash` goes out as a paymaster-sponsored UserOp from the key's\n * own account, so no wallet and no gas. Arbitrum only, where the\n * paymaster runs. See {@link retrySwapWithInvoiceWithSigner}.\n */\n async retrySwapWithInvoice(\n swapId: string,\n invoice: string,\n ): Promise<RetrySwapWithInvoiceResult> {\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap?.secretKey) {\n throw new Error(\n \"No secret key found for this swap. Cannot authorize the rehash.\",\n );\n }\n const evmKey = this.#getCollabRefundEvmSigningKey(\n storedSwap,\n \"retrySwapWithInvoiceWithSigner\",\n );\n const params = await this.getRehashEvmParams(swapId);\n if (params.chainId !== 42161) {\n throw new Error(\n `Swap ${swapId} locks on chain ${params.chainId}, where no paymaster sponsors the depositor's rehash. Retry from the depositor key's wallet with retrySwapWithInvoiceWithSigner, or refund.`,\n );\n }\n const owner = keyToKernelOwnerSigner(\n hexToBytes(evmKey.replace(/^0x/, \"\")),\n params.chainId,\n );\n const paymentHash = invoicePaymentHash(invoice);\n const lock = await this.#ownLockForRehash(\n swapId,\n await this.#aaChainReader(owner),\n );\n ensureLockIsOwn(lock, params, \"The server describes\");\n const message = rehashAuthorizationMessage(swapId, paymentHash);\n const signature = await this.signRehashEvm(swapId, {\n invoice,\n depositorAddress: owner.address,\n depositorSignature: signEvmMessage(evmKey, message),\n });\n ensureRehashMatchesRequest(signature, paymentHash, params);\n ensureLockIsOwn(lock, signature, \"The server signed a rehash of\");\n // Recorded before it is submitted, without its tx: a bundler answer or\n // receipt wait that is lost must not lose the terms the lock may now\n // have. A refund reads the lock's state to settle a pending record.\n const newHash = `0x${normalizeBytes32(signature.newPreimageHash)}`;\n const isThisPending = (entry: EvmRehashRecord) =>\n entry.txid === \"\" &&\n entry.userOpHash === undefined &&\n `0x${normalizeBytes32(entry.hashLock)}` === newHash;\n await this.#recordEvmRehash(swapId, signature, \"\");\n let sending = false;\n let signedHash: string | undefined;\n const isThisSigned = (entry: EvmRehashRecord) =>\n entry.txid === \"\" &&\n (signedHash === undefined\n ? isThisPending(entry)\n : entry.userOpHash === signedHash);\n let sponsored: { txHash: string; userOpHash: string };\n try {\n sponsored = await this.#sponsoredUserOp(\n owner,\n rehashCallData(signature),\n {\n onSigned: async (hash) => {\n sending = true;\n if (hash === undefined) return;\n await this.#updateEvmRehash(swapId, signature, \"\", {\n replaces: isThisPending,\n userOpHash: hash,\n });\n signedHash = hash;\n },\n onSubmitted: (hash) =>\n this.#updateEvmRehash(swapId, signature, \"\", {\n replaces: isThisSigned,\n userOpHash: hash,\n }),\n onIncluded: (hash, opHash) =>\n this.#updateEvmRehash(swapId, signature, hash, {\n replaces: (entry) => entry.userOpHash === opHash,\n userOpHash: opHash,\n }),\n },\n );\n } catch (error) {\n // Failed while preparing or signing: it was never sent and cannot\n // land, so the record goes. Once sent, even a lost answer may mean the\n // bundler took it; the record stays, and is followed only through the\n // receipt its UserOp hash leads to.\n if (!sending) await this.#dropPendingRehash(swapId, isThisPending);\n throw error;\n }\n const { txHash, userOpHash } = sponsored;\n this.#logger.info({\n event: \"client.retrySwapWithInvoice.sponsored\",\n message: \"rehash submitted as a sponsored UserOp\",\n swapId,\n data: { txHash, userOpHash },\n });\n return {\n id: swapId,\n txHash,\n newPreimageHash: signature.newPreimageHash,\n newTimelock: signature.newTimelock,\n };\n }\n\n /**\n * Collaborative EVM refund — internal method called by refundSwap.\n * @internal\n */\n async #collabRefundEvm(id: string): Promise<RefundResult> {\n try {\n const result = await this.collabRefundEvmSwap(id);\n return {\n success: true,\n message: `${result.message} (tx: ${result.txHash})`,\n };\n } catch (error) {\n return {\n success: false,\n message: `Collaborative EVM refund failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n // =========================================================================\n // Swap Creation - BTC to EVM\n // =========================================================================\n\n /**\n * Gets the context object for swap creation functions.\n * @internal\n */\n #getCreateContext(): CreateSwapContext {\n return {\n apiClient: this.#apiClient,\n baseUrl: this.#config.baseUrl,\n deriveSwapParams: () => this.deriveSwapParams(),\n evmAddress: this.getEvmAddress(),\n logger: this.#config.logger,\n logLevel: this.#config.logLevel,\n skipKeyIndices: async (n: number) => {\n if (this.#signerStorage) {\n const current = await this.#signerStorage.getKeyIndex();\n await this.#signerStorage.setKeyIndex(current + n);\n }\n },\n storeSwap: (\n swapId,\n swapParams,\n response,\n targetAddress,\n bridge,\n commitments,\n ) =>\n this.#storeSwap(\n swapId,\n swapParams,\n response,\n targetAddress,\n bridge,\n commitments,\n ),\n };\n }\n\n /**\n * Stores a swap in the configured swap storage.\n * @internal\n */\n async #storeSwap(\n swapId: string,\n swapParams: SwapParams,\n response: Record<string, unknown>,\n targetAddress?: string,\n bridge?: { recipient?: string; recipientWallet?: string },\n commitments?: {\n lightningPaymentHash?: LightningPaymentHash;\n evmFundingTerms?: EvmFundingTerms;\n },\n ): Promise<void> {\n if (!this.#swapStorage) return;\n\n // Recovery rebuilds a swap that may already be here; what its funding\n // recorded must survive that.\n const existing = await this.#swapStorage.get(swapId);\n const storedSwap: StoredSwap = {\n version: SWAP_STORAGE_VERSION,\n swapId,\n keyIndex: swapParams.keyIndex,\n response: response as GetSwapResponse,\n publicKey: bytesToHex(swapParams.publicKey),\n preimage: bytesToHex(swapParams.preimage),\n preimageHash: bytesToHex(swapParams.preimageHash),\n secretKey: bytesToHex(swapParams.secretKey),\n storedAt: Date.now(),\n updatedAt: Date.now(),\n // The payout this client asked for; claims pay here, never to a\n // server answer. Recovery rebuilding the swap keeps it.\n targetAddress: targetAddress ?? existing?.targetAddress,\n bridgeRecipient: bridge?.recipient,\n bridgeRecipientWallet: bridge?.recipientWallet,\n evmFundTxid: existing?.evmFundTxid,\n // Fixed at creation and never taken from a server answer: recovery\n // rebuilding the swap keeps it, and a fresh device has none.\n lightningPaymentHash:\n commitments?.lightningPaymentHash ?? existing?.lightningPaymentHash,\n evmFundingTerms:\n commitments?.evmFundingTerms ?? existing?.evmFundingTerms,\n evmCoordinatorAddress: existing?.evmCoordinatorAddress,\n // The rehashes this client sent are what let a refund find the lock\n // that exists; the server's copy names only the current hash.\n evmRehashes: existing?.evmRehashes,\n // A CCTP-inbound burn is the only way to resume or recover once the\n // USDC has left the source chain.\n cctpBurnTxid: existing?.cctpBurnTxid,\n cctpBurnLastValidBlockHeight: existing?.cctpBurnLastValidBlockHeight,\n };\n\n await this.#swapStorage.store(storedSwap);\n }\n\n /**\n * Creates a swap by routing to the correct direction-specific method\n * based on `sourceAsset.chain` and `targetAsset.chain`.\n *\n * Supported directions:\n * - Arkade → EVM\n * - Lightning → EVM\n * - Bitcoin (on-chain) → EVM\n * - Bitcoin (on-chain) → Arkade\n * - Bitcoin (on-chain) → Lightning\n * - Lightning → Bitcoin (on-chain)\n * - EVM → Arkade\n * - EVM → Bitcoin (on-chain)\n * - EVM → Lightning\n *\n * @param options - The swap options including source/target assets, amounts, and addresses.\n * @returns The swap result (response + swapParams).\n * @throws {SwapVerificationError} for a Lightning direction, if the server's\n * terms fail the checks that direction's create method documents. Nothing\n * is stored; do not pay or fund the swap.\n * @throws Error if the swap direction is unsupported or required fields are missing.\n */\n async createSwap(options: CreateSwapOptions): Promise<CreateSwapResult> {\n // Apply config-level referralCode (set via withReferralCode /\n // withOrgCode) as a fallback when the caller didn't pass one. Per-call\n // value always wins.\n options = {\n ...options,\n referralCode: options.referralCode ?? this.#config.referralCode,\n };\n\n // Resolve source/target from either the new Asset form or the legacy TokenInfo form\n const src = options.source ?? options.sourceAsset;\n const tgt = options.target ?? options.targetAsset;\n if (!src || !tgt) {\n throw new Error(\n \"source and target are required (use Asset constants or { chain, tokenId })\",\n );\n }\n\n // Normalize to a common shape with .chain and .token_id\n const sourceAsset: { chain: string; token_id: string } =\n \"token_id\" in src\n ? { chain: src.chain, token_id: src.token_id }\n : { chain: src.chain, token_id: src.tokenId };\n const targetAsset: { chain: string; token_id: string } =\n \"token_id\" in tgt\n ? { chain: tgt.chain, token_id: tgt.token_id }\n : { chain: tgt.chain, token_id: tgt.tokenId };\n\n if (isTronToken(sourceAsset.chain))\n throw new Error(\"Tron is a payout-only destination\");\n const isTronTarget =\n isTronToken(targetAsset.chain) ||\n options.bridgeParams?.targetChain === \"Tron\";\n if (isTronTarget) {\n if (\n isTronToken(targetAsset.chain) &&\n targetAsset.token_id !== USDT0_ADDRESSES.Tron\n ) {\n throw new Error(\"Tron payouts require native USDT\");\n }\n if (!isValidTronAddress(options.targetAddress))\n throw new Error(\"Invalid Tron payout address\");\n }\n let sourceChain = sourceAsset.chain;\n let sourceTokenId = sourceAsset.token_id;\n let targetChain = targetAsset.chain;\n let tokenAddress = targetAsset.token_id;\n\n // If the target is a bridge-only chain (e.g. USDC on Base), automatically\n // remap to the token on Arbitrum for the DEX swap and populate bridgeParams\n // so the backend knows to bridge after. This keeps the remapping logic\n // in one place — SDK consumers just pass their desired target.\n let bridgeParams = options.bridgeParams;\n if (!bridgeParams && isBridgedTarget(targetChain, tokenAddress)) {\n const chainName = toChainName(targetChain as Chain);\n if (chainName) {\n const isUsdt0 = Object.values(USDT0_ADDRESSES).some(\n (addr) => addr.toLowerCase() === tokenAddress.toLowerCase(),\n );\n bridgeParams = {\n targetChain: chainName,\n targetTokenAddress: isUsdt0\n ? USDT0_ADDRESSES[chainName]\n : USDC_ADDRESSES[chainName],\n recipientSetup: options.bridgeRecipientSetup,\n recipient: options.bridgeRecipient,\n recipientWallet: options.bridgeRecipientWallet,\n };\n targetChain = \"42161\"; // Arbitrum\n tokenAddress = isUsdt0\n ? USDT0_ADDRESSES.Arbitrum\n : USDC_ADDRESSES.Arbitrum;\n }\n } else if (bridgeParams) {\n // Caller supplied `bridgeParams` — fold in any top-level hints it\n // didn't set itself (recipientSetup, and the pinned claim recipient).\n bridgeParams = {\n ...bridgeParams,\n recipientSetup:\n bridgeParams.recipientSetup ?? options.bridgeRecipientSetup,\n recipient: bridgeParams.recipient ?? options.bridgeRecipient,\n recipientWallet:\n bridgeParams.recipientWallet ?? options.bridgeRecipientWallet,\n };\n }\n\n if (isTronTarget && bridgeParams) {\n bridgeParams = { ...bridgeParams, recipient: options.targetAddress };\n }\n\n // A CCTP payout pays Circle's fee out of the bridged USDC, and only the\n // claim checks the fee against the output. On a source-pinned swap a\n // small amount can leave nothing to deliver (Ethereum's forwarding fee is\n // over a dollar), so the swap would be funded and never claimable. Refuse\n // it before anything is created. Target-pinned swaps gross the fee up.\n const cctpPayout =\n !options.bridgeParams &&\n bridgeParams != null &&\n bridgeParams.targetTokenAddress?.toLowerCase() ===\n USDC_ADDRESSES[bridgeParams.targetChain]?.toLowerCase();\n if (cctpPayout && options.sourceAmount != null) {\n const quote = await this.getQuote({\n sourceChain: sourceAsset.chain as Chain,\n sourceToken: sourceAsset.token_id,\n targetChain: targetAsset.chain as Chain,\n targetToken: targetAsset.token_id,\n sourceAmount: options.sourceAmount,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n bridgeRecipientSetup: options.bridgeRecipientSetup,\n });\n if (BigInt(quote.net_target_amount) <= 0n) {\n throw new Error(\n `Amount too small to bridge to ${bridgeParams?.targetChain}: the CCTP fee ` +\n `(${quote.bridge_fee ?? \"unknown\"} USDC units) leaves nothing to deliver. ` +\n \"Increase the amount.\",\n );\n }\n }\n\n // Mirror of the outbound remap for CCTP-inbound sources: when the user\n // provides USDC on a chain the backend doesn't accept as a direct swap\n // source (Optimism, Base, Linea, …), rewrite to Arbitrum USDC and\n // populate `inboundBridgeParams` so the backend accounts for the\n // CCTPv2 fast-transfer fee at quote + UserOp-calldata time.\n let inboundBridgeParams = options.inboundBridgeParams;\n const parsedSourceChainId = Number.parseInt(sourceChain, 10);\n if (\n !inboundBridgeParams &&\n !Number.isNaN(parsedSourceChainId) &&\n isCctpOnlySource(parsedSourceChainId)\n ) {\n const source = cctpMetaForChainId(parsedSourceChainId);\n if (sourceTokenId.toLowerCase() !== source.usdc.toLowerCase()) {\n throw new Error(\n `createSwap on ${source.name} requires native USDC (${source.usdc}); got ${sourceTokenId}. Only USDC is bridgeable via CCTP.`,\n );\n }\n inboundBridgeParams = {\n sourceChain: source.name,\n sourceTokenAddress: source.usdc,\n };\n sourceChain = \"42161\";\n sourceTokenId = USDC_ADDRESSES.Arbitrum;\n }\n // USDC on Solana: the same CCTP hop, burned from a Solana wallet (see\n // `fundSwapFromSolana`). A Solana wallet has no EVM account to settle\n // with on Arbitrum, so the swap must use this client's key (gasless).\n if (!inboundBridgeParams && isSolanaToken(sourceChain)) {\n if (sourceTokenId !== USDC_ADDRESSES.Solana) {\n throw new Error(\n `createSwap on Solana requires native USDC (${USDC_ADDRESSES.Solana}); got ${sourceTokenId}. Only USDC is bridgeable via CCTP.`,\n );\n }\n if (!options.gasless) {\n throw new Error(\n \"Swaps funded from Solana must be created with `gasless: true`: they settle on Arbitrum with this client's key.\",\n );\n }\n inboundBridgeParams = {\n sourceChain: \"Solana\",\n sourceTokenAddress: USDC_ADDRESSES.Solana,\n };\n sourceChain = \"42161\";\n sourceTokenId = USDC_ADDRESSES.Arbitrum;\n }\n\n // Arkade → EVM\n if (isArkade(sourceAsset) && isEvmToken(targetChain)) {\n return this.createArkadeToEvmSwapGeneric({\n targetAddress: options.targetAddress,\n tokenAddress,\n evmChainId: Number(targetChain),\n sourceAmount: options.sourceAmount\n ? BigInt(options.sourceAmount)\n : undefined,\n targetAmount: options.targetAmount\n ? BigInt(options.targetAmount)\n : undefined,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n bridgeParams,\n });\n }\n\n // Arkade → Lightning. `targetAddress` carries the Lightning\n // destination: a BOLT11 invoice (\"ln...\"), an LNURL (\"lnurl1...\"),\n // or a lightning address (\"user@domain\").\n if (isArkade(sourceAsset) && isLightning(targetAsset)) {\n return this.createArkadeToLightningSwap(\n satsToLightningOptions(options, \"Arkade\"),\n );\n }\n // Bitcoin (on-chain) → Lightning: the same destination and amount\n // rules, with the lock in an on-chain HTLC.\n if (isBtcOnchain(sourceAsset) && isLightning(targetAsset)) {\n return this.createBitcoinToLightningSwap(\n satsToLightningOptions(options, \"Bitcoin\"),\n );\n }\n\n // Lightning → Arkade\n if (isLightning(sourceAsset) && isArkade(targetAsset)) {\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\n \"Provide exactly one of sourceAmount (invoice sats) or targetAmount (sats to receive on Arkade) for Lightning → Arkade swaps\",\n );\n }\n return this.createLightningToArkadeSwap({\n // The runtime check above guarantees exactly one amount is set;\n // branch so each arm satisfies the XOR options type.\n ...(options.sourceAmount != null\n ? { sourceAmountSats: Number(options.sourceAmount) }\n : { targetAmountSats: Number(options.targetAmount) }),\n targetAddress: options.targetAddress,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n });\n }\n\n // Lightning → Bitcoin (on-chain). `targetAddress` is where the HTLC\n // claim pays out.\n if (isLightning(sourceAsset) && isBtcOnchain(targetAsset)) {\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\n \"Provide exactly one of sourceAmount (invoice sats) or targetAmount (sats to receive on-chain) for Lightning → Bitcoin swaps\",\n );\n }\n return this.createLightningToBitcoinSwap({\n ...(options.sourceAmount != null\n ? { sourceAmountSats: Number(options.sourceAmount) }\n : { targetAmountSats: Number(options.targetAmount) }),\n targetAddress: options.targetAddress,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n });\n }\n\n // Lightning → EVM\n if (isLightning(sourceAsset) && isEvmToken(targetChain)) {\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\n \"Provide exactly one of sourceAmount (sats over Lightning) or targetAmount (token units to receive) for Lightning → EVM swaps\",\n );\n }\n return this.createLightningToEvmSwap({\n targetAddress: options.targetAddress,\n tokenAddress,\n evmChainId: Number(targetChain),\n sourceAmount:\n options.sourceAmount == null\n ? undefined\n : Number(options.sourceAmount),\n targetAmount:\n options.targetAmount == null\n ? undefined\n : BigInt(options.targetAmount),\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n bridgeParams,\n });\n }\n\n // Bitcoin (on-chain) → EVM\n if (isBtcOnchain(sourceAsset) && isEvmToken(targetChain)) {\n return this.createBitcoinToEvmSwap({\n targetAddress: options.targetAddress,\n tokenAddress,\n evmChainId: Number(targetChain),\n sourceAmount:\n options.sourceAmount == null\n ? undefined\n : Number(options.sourceAmount),\n targetAmount:\n options.targetAmount == null\n ? undefined\n : BigInt(options.targetAmount),\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n bridgeParams,\n });\n }\n\n // Bitcoin (on-chain) → Arkade\n if (isBtcOnchain(sourceAsset) && isArkade(targetAsset)) {\n if (options.targetAmount == null) {\n throw new Error(\n \"targetAmount (sats to receive on Arkade) is required for Bitcoin → Arkade swaps\",\n );\n }\n return this.createBitcoinToArkadeSwap({\n satsReceive: Number(options.targetAmount),\n targetAddress: options.targetAddress,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n });\n }\n\n // EVM → Lightning. `targetAddress` carries the Lightning destination:\n // a BOLT11 invoice (\"ln...\"), an LNURL (\"lnurl1...\"), or a lightning\n // address (\"user@domain\").\n if (\n isEvmSwapSource(sourceChain, sourceTokenId) &&\n isLightning(targetAsset)\n ) {\n if (!options.userAddress && !options.gasless) {\n throw new Error(\n \"userAddress is required for EVM → Lightning swaps (unless gasless)\",\n );\n }\n const destination = options.targetAddress;\n const lower = destination.toLowerCase();\n const common = {\n tokenAddress: sourceTokenId,\n evmChainId: Number(sourceChain),\n userAddress: options.userAddress,\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n gasless: options.gasless,\n inboundBridgeParams,\n };\n\n if (!lower.startsWith(\"lnurl\") && lower.startsWith(\"ln\")) {\n if (options.sourceAmount != null) {\n throw new Error(\n \"sourceAmount cannot be combined with a BOLT11 invoice destination (the invoice fixes the payout)\",\n );\n }\n return this.createEvmToLightningSwap({\n lightningInvoice: destination,\n ...(options.targetAmount != null\n ? { targetAmountSats: Number(options.targetAmount) }\n : {}),\n ...common,\n });\n }\n\n if ((options.sourceAmount == null) === (options.targetAmount == null)) {\n throw new Error(\n \"Provide exactly one of sourceAmount (token units to lock) or targetAmount (sats to receive over Lightning) for EVM → Lightning swaps\",\n );\n }\n const amount =\n options.sourceAmount != null\n ? { sourceAmount: BigInt(options.sourceAmount) }\n : { targetAmountSats: Number(options.targetAmount) };\n\n if (lower.startsWith(\"lnurl\")) {\n return this.createEvmToLightningSwap({\n lnurl: destination,\n ...amount,\n ...common,\n });\n }\n return this.createEvmToLightningSwap({\n lightningAddress: destination,\n ...amount,\n ...common,\n });\n }\n\n // EVM → Arkade\n if (isEvmSwapSource(sourceChain, sourceTokenId) && isArkade(targetAsset)) {\n if (!options.userAddress && !options.gasless) {\n throw new Error(\n \"userAddress is required for EVM → Arkade swaps (unless gasless)\",\n );\n }\n return this.createEvmToArkadeSwapGeneric({\n targetAddress: options.targetAddress,\n tokenAddress: sourceTokenId,\n evmChainId: Number(sourceChain),\n userAddress: options.userAddress ?? \"\",\n sourceAmount: options.sourceAmount\n ? BigInt(options.sourceAmount)\n : undefined,\n targetAmount:\n options.targetAmount == null\n ? undefined\n : Number(options.targetAmount),\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n gasless: options.gasless,\n inboundBridgeParams,\n });\n }\n\n // EVM → Bitcoin (on-chain)\n if (\n isEvmSwapSource(sourceChain, sourceTokenId) &&\n isBtcOnchain(targetAsset)\n ) {\n if (!options.userAddress && !options.gasless) {\n throw new Error(\n \"userAddress is required for EVM → Bitcoin swaps (unless gasless)\",\n );\n }\n return this.createEvmToBitcoinSwap({\n tokenAddress: sourceTokenId,\n evmChainId: Number(sourceChain),\n userAddress: options.userAddress ?? \"\",\n targetAddress: options.targetAddress,\n sourceAmount: options.sourceAmount\n ? BigInt(options.sourceAmount)\n : undefined,\n targetAmount:\n options.targetAmount == null\n ? undefined\n : Number(options.targetAmount),\n referralCode: options.referralCode,\n extraFees: options.extraFees,\n gasless: options.gasless,\n inboundBridgeParams,\n });\n }\n\n throw new Error(\n `Unsupported swap direction: ${sourceChain} → ${targetChain}`,\n );\n }\n\n /**\n * Creates a new Arkade-to-EVM swap via the generic chain-agnostic endpoint.\n *\n * Uses the `/swap/arkade/evm` endpoint which supports any ERC-20 token\n * reachable through 1inch aggregation. Returns coordinator address and\n * optional 1inch calldata for the redeem-and-swap flow.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createArkadeToEvmSwapGeneric({\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats\n * });\n * console.log(\"Fund:\", result.response.btc_vhtlc_address);\n * console.log(\"Coordinator:\", result.response.evm_coordinator_address);\n * ```\n */\n async createArkadeToEvmSwapGeneric(\n options: ArkadeToEvmSwapOptions,\n ): Promise<ArkadeToEvmSwapResult> {\n return createArkadeToEvmSwapGeneric(\n options,\n this.#getCreateContext(),\n await this.#rifClaimAddress(options),\n );\n }\n\n /**\n * Creates a new Bitcoin (on-chain) to EVM swap.\n *\n * Automatically derives swap parameters and increments the key index.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createBitcoinToEvmSwap({\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats\n * });\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * ```\n */\n async createBitcoinToEvmSwap(\n options: BitcoinToEvmSwapOptions,\n ): Promise<BitcoinToEvmSwapResult> {\n return createBitcoinToEvmSwap(\n options,\n this.#getCreateContext(),\n await this.#rifClaimAddress(options),\n );\n }\n\n // =========================================================================\n // Swap Creation - Bitcoin (on-chain) to Arkade\n // =========================================================================\n\n /**\n * Creates a new Bitcoin (on-chain) to Arkade swap.\n *\n * The user sends on-chain BTC to a Taproot HTLC address and receives\n * Arkade VTXOs after the server funds the Arkade VHTLC.\n *\n * Automatically derives swap parameters and increments the key index.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createBitcoinToArkadeSwap({\n * satsReceive: 100000, // 100k sats to receive on Arkade\n * targetAddress: \"ark1q...\", // Arkade address\n * });\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * console.log(\"Amount to send:\", result.response.source_amount, \"sats\");\n * ```\n */\n async createBitcoinToArkadeSwap(\n options: BitcoinToArkadeSwapOptions,\n ): Promise<BitcoinToArkadeSwapResult> {\n return createBitcoinToArkadeSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - Lightning to Arkade\n // =========================================================================\n\n /**\n * Creates a new Lightning to Arkade swap.\n *\n * The user pays a Lightning invoice and receives Arkade VTXOs\n * after the server funds the Arkade VHTLC.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's invoice does not pay\n * this swap's hash lock; do not pay it.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * // Provide exactly one of targetAmountSats (receive amount, fees added\n * // on top) or sourceAmountSats (invoice amount, fees deducted from it).\n * const result = await client.createLightningToArkadeSwap({\n * targetAmountSats: 100000, // 100k sats to receive on Arkade\n * targetAddress: \"ark1q...\", // Arkade address\n * });\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\n async createLightningToArkadeSwap(\n options: LightningToArkadeSwapOptions,\n ): Promise<LightningToArkadeSwapResult> {\n return createLightningToArkadeSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - Lightning to Bitcoin\n // =========================================================================\n\n /**\n * Creates a new Lightning to Bitcoin (on-chain) swap.\n *\n * The user pays a hold invoice; the server funds an on-chain HTLC that\n * `claim()` sweeps to `targetAddress`, which settles the invoice.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's hold invoice does not pay\n * the hash of this swap's own secret. Nothing is stored; do not pay it.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * // Provide exactly one of targetAmountSats (receive amount, fees added\n * // on top) or sourceAmountSats (invoice amount, fees deducted from it).\n * const result = await client.createLightningToBitcoinSwap({\n * targetAmountSats: 100000, // 100k sats to receive on-chain\n * targetAddress: \"bc1q...\", // Bitcoin address\n * });\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\n async createLightningToBitcoinSwap(\n options: LightningToBitcoinSwapOptions,\n ): Promise<LightningToBitcoinSwapResult> {\n return createLightningToBitcoinSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - Lightning to EVM\n // =========================================================================\n\n /**\n * Creates a new Lightning to EVM swap.\n *\n * The user pays a hold invoice; the server funds an HTLCErc20 with the\n * same hash lock, and claiming it (gasless) reveals the preimage that\n * settles the held payment. If the swap fails before the claim, the\n * held payment is automatically returned when the hold expires — there\n * is no client-side refund action on this route.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's invoice does not pay\n * this swap's hash lock; do not pay it.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createLightningToEvmSwap({\n * targetAddress: \"0x1234...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * sourceAmount: 100000, // 100k sats over Lightning\n * });\n * console.log(\"Pay this invoice:\", result.response.bolt11_invoice);\n * ```\n */\n async createLightningToEvmSwap(\n options: LightningToEvmSwapOptions,\n ): Promise<LightningToEvmSwapResult> {\n return createLightningToEvmSwap(\n options,\n this.#getCreateContext(),\n await this.#rifClaimAddress(options),\n );\n }\n\n // =========================================================================\n // Swap Creation - Arkade to Lightning\n // =========================================================================\n\n /**\n * Creates a new Arkade to Lightning swap.\n *\n * The user locks Arkade VTXOs in the returned VHTLC\n * (`arkade_vhtlc_address`, `source_amount` sats); the server pays the\n * Lightning invoice and claims the VHTLC. On failure the locked VTXOs\n * come back via `refundSwap()` (collaborative, no locktime wait).\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's hash lock, invoice or\n * VHTLC does not match: a hash lock that is not the payment hash of the\n * invoice it pays, an invoice other than the supplied `lightningInvoice`,\n * a VHTLC address that does not lock to that hash and this swap's refund\n * key, or a script version this client cannot refund. Nothing is stored;\n * do not fund the VHTLC.\n * @throws Error if `lightningInvoice` is not a BOLT11 invoice (before any\n * request is made), or if the swap creation fails.\n *\n * @example\n * ```ts\n * // Destination is one of lightningInvoice (amount pinned by the\n * // invoice), or lightningAddress/lnurl plus one of sourceAmountSats\n * // (send-max) or targetAmountSats (exact payout).\n * const result = await client.createArkadeToLightningSwap({\n * lightningAddress: \"user@wallet.com\",\n * targetAmountSats: 100000,\n * });\n * console.log(\"Fund:\", result.response.arkade_vhtlc_address);\n * console.log(\"Lock amount:\", result.response.source_amount);\n * ```\n */\n async createArkadeToLightningSwap(\n options: ArkadeToLightningSwapOptions,\n ): Promise<ArkadeToLightningSwapResult> {\n return createArkadeToLightningSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - Bitcoin to Lightning\n // =========================================================================\n\n /**\n * Creates a new Bitcoin (on-chain) to Lightning swap.\n *\n * The user sends `source_amount` sats to the returned HTLC address\n * (`btc_htlc_address`); after one confirmation the server pays the\n * Lightning invoice and claims the HTLC. On failure the coins come back\n * via `refundSwap()` once the HTLC's refund locktime has passed.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's hash lock, invoice or HTLC\n * does not match: a hash lock that is not the payment hash of the invoice\n * it pays, an invoice other than the supplied `lightningInvoice`, or an\n * HTLC that does not lock to that hash and this swap's refund key on a\n * script version this client can refund. Nothing is stored; do not fund\n * the HTLC.\n * @throws Error if `lightningInvoice` is not a BOLT11 invoice (before any\n * request is made), or if the swap creation fails.\n *\n * @example\n * ```ts\n * // Destination is one of lightningInvoice (amount pinned by the\n * // invoice), or lightningAddress/lnurl plus one of sourceAmountSats\n * // (send-max) or targetAmountSats (exact payout).\n * const result = await client.createBitcoinToLightningSwap({\n * lightningAddress: \"user@wallet.com\",\n * targetAmountSats: 100000,\n * });\n * console.log(\"Send BTC to:\", result.response.btc_htlc_address);\n * console.log(\"Amount to send:\", result.response.source_amount);\n * ```\n */\n async createBitcoinToLightningSwap(\n options: BitcoinToLightningSwapOptions,\n ): Promise<BitcoinToLightningSwapResult> {\n return createBitcoinToLightningSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - EVM to Arkade\n // =========================================================================\n\n /**\n * Creates a new EVM-to-Arkade swap via the generic endpoint.\n *\n * Uses the chain-agnostic `/swap/evm/arkade` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createEvmToArkadeSwapGeneric({\n * targetAddress: \"ark1q...\",\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * userAddress: \"0x1234...\",\n * sourceAmount: 100000000, // 100 USDC (6 decimals)\n * });\n * console.log(\"HTLC:\", result.response.evm_htlc_address);\n * ```\n */\n async createEvmToArkadeSwapGeneric(\n options: EvmToArkadeSwapGenericOptions,\n ): Promise<EvmToArkadeSwapGenericResult> {\n return createEvmToArkadeSwapGeneric(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Swap Creation - EVM to Lightning\n // =========================================================================\n\n /**\n * Creates a new EVM-to-Lightning swap.\n *\n * The user locks an ERC-20 token in an HTLCErc20 (via the coordinator,\n * `fundSwap` / `fundSwapGasless`) locked to the invoice's payment hash;\n * the server pays the Lightning invoice and claims the HTLC with the\n * revealed preimage. On failure the locked tokens come back via\n * `refundSwap()` (collaborative, no locktime wait).\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws {SwapVerificationError} if the server's hash lock or invoice does\n * not match the invoice supplied or resolved. Nothing is stored; do not\n * fund it.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * // Destination is one of lightningInvoice (amount pinned by the\n * // invoice), or lightningAddress/lnurl plus one of sourceAmount\n * // (send-max, token units) or targetAmountSats (exact payout).\n * const result = await client.createEvmToLightningSwap({\n * lightningAddress: \"user@wallet.com\",\n * targetAmountSats: 100000,\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * userAddress: \"0x1234...\",\n * });\n * console.log(\"HTLC:\", result.response.evm_htlc_address);\n * console.log(\"Lock amount:\", result.response.source_amount);\n * ```\n */\n async createEvmToLightningSwap(\n options: EvmToLightningSwapOptions,\n ): Promise<EvmToLightningSwapResult> {\n return createEvmToLightningSwap(options, this.#getCreateContext());\n }\n\n /**\n * Creates a new EVM-to-Bitcoin (on-chain) swap.\n *\n * Uses the chain-agnostic `/swap/evm/bitcoin` endpoint which supports any\n * ERC-20 token reachable through 1inch aggregation. The user locks tokens\n * in an EVM HTLC and receives BTC to an on-chain Taproot HTLC.\n *\n * @param options - The swap options.\n * @returns The swap response and parameters for storage.\n * @throws Error if the swap creation fails.\n *\n * @example\n * ```ts\n * const result = await client.createEvmToBitcoinSwap({\n * tokenAddress: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\", // USDC on Polygon\n * evmChainId: 137,\n * userAddress: \"0x1234...\",\n * sourceAmount: 100000000n, // 100 USDC (6 decimals)\n * });\n * console.log(\"EVM HTLC:\", result.response.evm_htlc_address);\n * console.log(\"BTC HTLC:\", result.response.btc_htlc_address);\n * ```\n */\n async createEvmToBitcoinSwap(\n options: EvmToBitcoinSwapOptions,\n ): Promise<EvmToBitcoinSwapResult> {\n return createEvmToBitcoinSwap(options, this.#getCreateContext());\n }\n\n // =========================================================================\n // Coordinator Funding (EVM-to-BTC via DEX + HTLC)\n // =========================================================================\n\n /**\n * Gets Permit2-based call data to fund an EVM-to-BTC swap via the HTLCCoordinator.\n *\n * Uses Permit2 for gasless token approval: the user signs an off-chain EIP-712\n * message instead of submitting a separate `approve` tx to the source token.\n *\n * The returned `approve` is a one-time max approval of the source token to the\n * Permit2 contract (can be skipped if already approved). The `executeAndCreate`\n * calldata includes the Permit2 signature and can be submitted by anyone (relayer).\n *\n * @param swapId - The UUID of the swap\n * @param chainId - The EVM chain ID (e.g. 137 for Polygon, 1 for Ethereum)\n * @returns The approve (token → Permit2) and executeAndCreateWithPermit2 call data\n *\n * @example\n * ```ts\n * const funding = await client.getCoordinatorFundingCallDataPermit2(swap.response.id, 137);\n *\n * // Step 1: One-time approve source token to Permit2 (can skip if already done)\n * await wallet.sendTransaction({ to: funding.approve.to, data: funding.approve.data });\n *\n * // Step 2: Execute swap + create HTLC (signed via Permit2)\n * await wallet.sendTransaction({ to: funding.executeAndCreate.to, data: funding.executeAndCreate.data });\n * ```\n */\n async getCoordinatorFundingCallDataPermit2(\n swapId: string,\n chainId: number,\n options?: {\n /** Pins on top of the swap's recorded funding terms. */\n funding?: FundingPins;\n },\n ): Promise<Permit2SignedFundingCallData> {\n // 1. Look up stored swap to get the secret key for signing\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap) {\n throw new Error(\n `Swap ${swapId} not found in local storage. Cannot sign Permit2 message without the secret key.`,\n );\n }\n\n const swap = await this.getSwap(swapId);\n\n if (\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"evm_to_bitcoin\" &&\n swap.direction !== \"evm_to_lightning\"\n ) {\n throw new Error(\n `Expected an EVM-sourced swap, got ${swap.direction}. Permit2 fund method is for EVM-sourced swaps.`,\n );\n }\n\n // 2. Fetch Permit2 funding data from server\n const baseUrl = this.#config.baseUrl.replace(/\\/$/, \"\");\n const url = `${baseUrl}/swap/${swapId}/swap-and-lock-calldata-permit2`;\n\n const resp = await fetch(url, {\n headers: this.#apiHeaders(),\n });\n if (!resp.ok) {\n const body = await resp.text();\n throw new Error(\n `Failed to get Permit2 funding data: ${resp.status} ${body}`,\n );\n }\n\n const serverData = (await resp.json()) as {\n coordinator_address: string;\n htlc_kind?: string;\n htlc_version?: number;\n permit2_address: string;\n source_token_address: string;\n source_amount: string;\n lock_token_address: string;\n preimage_hash: string;\n claim_address: string;\n timelock: number;\n calls: Array<{ target: string; value: string; call_data: string }>;\n calls_hash: string;\n depositor_delegation?: string | null;\n };\n // Spender, lock, tokens, amount and calls are bound to the swap's\n // recorded terms before anything is signed, and signed from them.\n const checked = await this.#checkedFunding(\n swapId,\n serverData,\n chainId,\n options?.funding,\n );\n\n // 3. Generate random Permit2 nonce and deadline\n const nonceBytes = new Uint8Array(32);\n crypto.getRandomValues(nonceBytes);\n const nonce = BigInt(\n `0x${Array.from(nonceBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`,\n );\n const deadline = BigInt(Math.floor(Date.now() / 1000) + 30 * 60); // 30 minutes\n\n const sourceAmount = checked.sourceAmount;\n\n // 4. Build the EIP-712 digest. The witness binds the lock's refund\n // address: the depositor from HTLCErc20 v7 / HTLCNative v2, the\n // coordinator before.\n const evmKey = this.#getEvmSigningKey();\n const depositorAddress = deriveEvmAddress(evmKey);\n const digest = buildPermit2FundingDigest({\n chainId,\n coordinatorAddress: checked.coordinator,\n sourceToken: checked.sourceToken,\n sourceAmount,\n preimageHash: checked.preimageHash,\n lockToken: checked.lockToken,\n claimAddress: checked.claimAddress,\n refundAddress: permit2RefundAddress(\n checkedRefundContext(checked),\n depositorAddress,\n ),\n timelock: checked.timelock,\n callsHash: checked.callsHash,\n nonce,\n deadline,\n });\n\n // 5. Sign with the EVM key (deterministic for new swaps, per-swap for legacy).\n // Kernel-delegated depositors get the ERC-1271 envelope, plain EOAs a\n // compact r || s || v signature.\n const delegated = await this.#isKernelDelegated(\n depositorAddress,\n chainId,\n this.#delegationHintFor(\n swap as { client_evm_address?: string | null },\n depositorAddress,\n serverData.depositor_delegation,\n ),\n );\n const compactSignature = this.#signDepositorDigest(\n evmKey,\n depositorAddress,\n chainId,\n digest,\n delegated,\n );\n\n // 6. Build calls array for the coordinator\n const calls = checked.calls;\n\n // 7. Encode executeAndCreateWithPermit2 calldata\n const encoded = encodeExecuteAndCreateWithPermit2(checked.coordinator, {\n calls,\n preimageHash: checked.preimageHash,\n token: checked.lockToken,\n claimAddress: checked.claimAddress,\n timelock: checked.timelock,\n depositor: depositorAddress,\n sourceToken: checked.sourceToken,\n sourceAmount,\n nonce,\n deadline,\n signature: compactSignature,\n });\n\n // 8. Build approve: source token → Permit2 (max uint256, one-time)\n const maxUint256 = BigInt(\n \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n );\n const approve = encodeApproveCallData(\n checked.sourceToken,\n PERMIT2_ADDRESS,\n maxUint256,\n );\n\n return {\n approve: {\n to: approve.to,\n data: approve.data,\n },\n executeAndCreate: {\n to: encoded.to,\n data: encoded.data,\n },\n };\n }\n\n /**\n * Get unsigned Permit2 funding parameters for the sovereign flow.\n *\n * Returns the EIP-712 typed data structure and all parameters needed\n * for the user's browser wallet to sign via `signTypedData` and then\n * encode + submit the `executeAndCreateWithPermit2` transaction.\n *\n * Unlike `getCoordinatorFundingCallDataPermit2`, this method does NOT\n * sign the Permit2 message — the caller is responsible for obtaining\n * the signature from the user's wallet.\n *\n * @param swapId - The UUID of the swap\n * @param chainId - The EVM chain ID\n * @returns Unsigned Permit2 funding data including typed data for signing\n *\n * @example\n * ```ts\n * const params = await client.getPermit2FundingParamsUnsigned(swapId, chainId);\n *\n * // In the browser with wagmi/viem:\n * const signature = await walletClient.signTypedData(params.typedData);\n *\n * // Encode the final calldata\n * const calldata = encodeExecuteAndCreateWithPermit2(\n * params.coordinatorAddress,\n * {\n * calls: params.calls,\n * preimageHash: params.preimageHash,\n * token: params.lockTokenAddress,\n * claimAddress: params.claimAddress,\n * timelock: params.timelock,\n * depositor: userWalletAddress,\n * sourceToken: params.sourceTokenAddress,\n * sourceAmount: params.sourceAmount,\n * nonce: params.nonce,\n * deadline: params.deadline,\n * signature,\n * },\n * );\n * ```\n */\n async getPermit2FundingParamsUnsigned(\n swapId: string,\n chainId: number,\n /**\n * The address that will sign the Permit2 and fund the lock. Required on\n * HTLCErc20 v7 / HTLCNative v2, whose witness binds it as the lock's\n * refund address; older deployments bind the coordinator and ignore it.\n */\n depositorAddress?: string,\n options?: {\n /** Pins on top of the swap's recorded funding terms. */\n funding?: FundingPins;\n },\n ): Promise<UnsignedPermit2FundingData> {\n const swap = await this.getSwap(swapId);\n\n if (\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"evm_to_bitcoin\" &&\n swap.direction !== \"evm_to_lightning\"\n ) {\n throw new Error(\n `Expected an EVM-sourced swap, got ${swap.direction}. Permit2 fund method is for EVM-sourced swaps.`,\n );\n }\n\n // Fetch Permit2 funding data from server\n const baseUrl = this.#config.baseUrl.replace(/\\/$/, \"\");\n const url = `${baseUrl}/swap/${swapId}/swap-and-lock-calldata-permit2`;\n\n const resp = await fetch(url, {\n headers: this.#apiHeaders(),\n });\n if (!resp.ok) {\n const body = await resp.text();\n throw new Error(\n `Failed to get Permit2 funding data: ${resp.status} ${body}`,\n );\n }\n\n const serverData = (await resp.json()) as {\n coordinator_address: string;\n htlc_kind?: string;\n htlc_version?: number;\n permit2_address: string;\n source_token_address: string;\n source_amount: string;\n lock_token_address: string;\n preimage_hash: string;\n claim_address: string;\n timelock: number;\n calls: Array<{ target: string; value: string; call_data: string }>;\n calls_hash: string;\n };\n // Bound to the swap's recorded terms; what is returned is built from\n // them, so a caller signing it signs only for this swap's lock.\n const checked = await this.#checkedFunding(\n swapId,\n serverData,\n chainId,\n options?.funding,\n );\n\n // Generate random Permit2 nonce and deadline\n const nonceBytes = new Uint8Array(32);\n crypto.getRandomValues(nonceBytes);\n const nonce = BigInt(\n `0x${Array.from(nonceBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`,\n );\n const deadline = BigInt(Math.floor(Date.now() / 1000) + 30 * 60); // 30 minutes\n\n const sourceAmount = checked.sourceAmount;\n const calls = checked.calls;\n\n // Build EIP-712 typed data for wallet signing\n const lockSender = permit2RefundAddress(\n checkedRefundContext(checked),\n depositorAddress,\n );\n const fundingParams = {\n chainId,\n coordinatorAddress: checked.coordinator,\n sourceToken: checked.sourceToken,\n sourceAmount,\n preimageHash: checked.preimageHash,\n lockToken: checked.lockToken,\n claimAddress: checked.claimAddress,\n refundAddress: lockSender,\n timelock: checked.timelock,\n callsHash: checked.callsHash,\n nonce,\n deadline,\n };\n\n const typedData = buildPermit2TypedData(fundingParams);\n\n return {\n coordinatorAddress: checked.coordinator,\n /** The lock's sender: the depositor on HTLCErc20 v7 / HTLCNative v2, the coordinator before. */\n lockSender,\n htlcAddress: checked.htlcAddress,\n sourceTokenAddress: checked.sourceToken,\n sourceAmount,\n lockTokenAddress: checked.lockToken,\n preimageHash: checked.preimageHash,\n claimAddress: checked.claimAddress,\n timelock: checked.timelock,\n calls,\n callsHash: checked.callsHash,\n nonce,\n deadline,\n typedData,\n };\n }\n\n /**\n * Fund an EVM-sourced swap using an external wallet (e.g. MetaMask).\n *\n * Handles the full flow:\n * 1. Check ERC-20 allowance to Permit2 — approve if insufficient\n * 2. Sign the Permit2 EIP-712 typed data\n * 3. Encode and send the `executeAndCreateWithPermit2` transaction\n * 4. Wait for the transaction receipt\n *\n * @param swapId - The UUID of the swap\n * @param signer - An {@link EvmSigner} wrapping the user's wallet\n * @param options - Optional CCTP-path tuning: `maxFee` caps the\n * CCTP fast-transfer fee (defaults to the\n * IRIS-quoted value); `onProgress` receives\n * per-phase updates during the CCTP flow;\n * `signal` aborts the attestation wait. All\n * three are ignored when the swap takes the\n * direct-Permit2 path.\n * @returns The funding transaction hash, plus an optional `cctp`\n * object with `burnTxHash`, `userOpHash`, and\n * `smartAccountAddress` when the CCTP path ran.\n *\n * @example\n * ```ts\n * // Wrap wagmi/viem into an EvmSigner\n * const signer: EvmSigner = {\n * address: walletClient.account.address,\n * chainId: walletClient.chain.id,\n * signTypedData: (td) => walletClient.signTypedData({ ...td, account: walletClient.account }),\n * sendTransaction: (tx) => walletClient.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, type: tx.type, chain, gas: tx.gas }),\n * waitForReceipt: (hash) => publicClient.waitForReceipt({ hash }),\n * getTransaction: (hash) => publicClient.getTransaction({ hash }),\n * call: (tx) => publicClient.call(tx),\n * getBalance: (address) => publicClient.getBalance({ address }),\n * };\n *\n * const { txHash } = await client.fundSwap(swapId, signer);\n * ```\n */\n async fundSwap(\n swapId: string,\n signer: EvmSigner,\n options?: {\n /** CCTP fast-transfer fee cap in USDC units. Only consulted on\n * the CCTP path; defaults to the IRIS-quoted fee. */\n maxFee?: bigint;\n /** Progress callback for the CCTP flow. Ignored on direct path. */\n onProgress?: (step: CctpProgressStep) => void;\n /** Abort signal — cancels the CCTP attestation wait. */\n signal?: AbortSignal;\n /**\n * Reports the source amount the server quoted for this attempt, in the\n * source token's smallest unit, before the wallet prompts for the\n * Permit2 signature (and again should the server re-quote between the\n * approval and the signature). A payout-pinned EVM → Lightning swap is\n * priced afresh on every attempt, so this can differ from the amount\n * stored on the swap. Ignored on the CCTP path.\n */\n onQuote?: (quote: {\n sourceAmount: bigint;\n sourceTokenAddress: string;\n }) => void;\n /**\n * Pins on top of the swap's recorded funding terms: allowed call\n * targets, a higher input limit, a relay fee cap (default 0).\n */\n funding?: FundingPins;\n },\n ): Promise<{ txHash: string; cctp?: CctpFundSwapResult }> {\n // A native lock (RBTC on Rootstock) is one payable transaction to the\n // native HTLC: no token approval, no Permit2, no server calldata.\n // The lock family is pinned on the swap at creation.\n {\n const stored = await this.#swapStorage?.get(swapId);\n const response =\n stored?.response ??\n (await this.getSwap(swapId, { updateStorage: true }));\n if (\n (response.direction === \"evm_to_lightning\" ||\n response.direction === \"evm_to_arkade\" ||\n response.direction === \"evm_to_bitcoin\") &&\n response.evm_htlc_kind === \"native\"\n ) {\n const txHash = await this.#fundNativeLock(\n swapId,\n response,\n signer,\n options?.onQuote,\n );\n return { txHash };\n }\n // Burning on Solana needs a Solana wallet, not an EVM signer.\n if (\n (response as { bridge_source_chain?: string }).bridge_source_chain ===\n \"Solana\"\n ) {\n throw new Error(\n `Swap ${swapId} is funded from Solana; use fundSwapFromSolana with a Solana wallet.`,\n );\n }\n }\n\n // Dispatch the CCTP-inbound path only for chains the backend does\n // NOT accept as a direct swap source (Optimism, Base, Linea, …).\n // Ethereum / Polygon / Arbitrum fund via Permit2 on the source\n // chain even though they're CCTP-supported. Source asset must be\n // native USDC for the chain — otherwise CCTP isn't viable and we\n // surface a clear error instead of silently burning the wrong\n // token through TokenMessenger.\n if (isCctpOnlySource(signer.chainId)) {\n const stored = await this.#swapStorage?.get(swapId);\n const swapResponse =\n stored?.response ??\n (await this.getSwap(swapId, { updateStorage: true }));\n const source = cctpMetaForChainId(signer.chainId);\n // Checked before anything is burned: the settlement refuses calldata\n // locking under any other hash, and USDC burned for it would be left\n // in the account.\n const expected = {\n ...this.#fundingExpectation(swapId, stored),\n pins: options?.funding,\n };\n await this.#ensureClientHashLock(\n swapId,\n evmHashLockOf(swapResponse),\n \"swap\",\n );\n\n // CCTP-inbound swaps are stored against post-hop Arbitrum USDC\n // (`source_token` reports the Arbitrum address), so we validate\n // against the `bridge_source_*` fields the backend sets when the\n // swap was created through the CCTP path. If those are missing\n // the swap wasn't created for a CCTP-inbound flow — reject rather\n // than silently burn USDC through the TokenMessenger.\n const bridgeSourceChain = (\n swapResponse as { bridge_source_chain?: string }\n ).bridge_source_chain;\n const bridgeSourceToken = (\n swapResponse as { bridge_source_token_address?: string }\n ).bridge_source_token_address;\n if (!bridgeSourceChain || !bridgeSourceToken) {\n throw new Error(\n `fundSwap on chain ${signer.chainId} expects a CCTP-inbound swap but the swap has no bridge_source_chain set. ` +\n `Was the swap created against native USDC on a CCTP-only chain?`,\n );\n }\n if (bridgeSourceChain !== source.name) {\n throw new Error(\n `fundSwap signer is on ${source.name} but the swap was created for bridge source ${bridgeSourceChain}.`,\n );\n }\n if (bridgeSourceToken.toLowerCase() !== source.usdc.toLowerCase()) {\n throw new Error(\n `fundSwap on ${source.name} requires native USDC (${source.usdc}), but swap's bridge_source_token_address is ${bridgeSourceToken}. ` +\n `Only native USDC is bridgeable via CCTP.`,\n );\n }\n\n const rawAmount = (swapResponse as { source_amount?: number | string })\n .source_amount;\n if (rawAmount === undefined) {\n throw new Error(\n `Swap ${swapId} has no source_amount — cannot route CCTP fund.`,\n );\n }\n const amount = BigInt(rawAmount);\n\n const destination = cctpMetaForChainId(42161);\n\n // A burn recorded by an interrupted attempt: resume at the\n // attestation instead of burning the USDC a second time. The swap must\n // still be unfunded, or the settlement already landed.\n const recordedBurn = stored?.cctpBurnTxid as `0x${string}` | undefined;\n if (recordedBurn) {\n const fresh = await this.getSwap(swapId, { updateStorage: true });\n if (fresh.status !== \"pending\") {\n throw new Error(\n `Swap ${swapId} is already ${fresh.status}; its CCTP burn ${recordedBurn} was settled.`,\n );\n }\n }\n\n // Only a new burn uses the fee, so resuming one must not depend on the\n // fee service being reachable.\n const maxFee = recordedBurn\n ? 0n\n : (options?.maxFee ??\n computeCctpFastFee(\n await getCachedCctpFee({\n sourceDomain: source.domain,\n destinationDomain: destination.domain,\n }),\n amount,\n ));\n\n const cctp = await this.cctpInbound.fundSwap({\n swapId,\n expected,\n signer,\n ownerSigner: this.#depositorOwnerSigner(\n swapResponse,\n signer,\n \"Create the swap with `gasless: true` to settle through the SDK's key.\",\n ),\n burnTxHash: recordedBurn,\n onBurn: (burnTxHash) => this.#recordCctpBurn(swapId, burnTxHash),\n amount,\n maxFee,\n onProgress: options?.onProgress,\n signal: options?.signal,\n });\n // A hint for a later refund or rehash, which check its receipt.\n if (cctp.transactionHash) {\n await this.#recordEvmFunding(swapId, { txid: cctp.transactionHash });\n }\n return { txHash: cctp.transactionHash ?? cctp.userOpHash, cctp };\n }\n\n // Direct Permit2 path — Ethereum, Polygon, Arbitrum, or any other\n // chain `signer.chainId` specifies. Unchanged from the original\n // behaviour.\n\n // 1. Fetch Permit2 funding params\n const funding = await this.getPermit2FundingParamsUnsigned(\n swapId,\n signer.chainId,\n signer.address,\n { funding: options?.funding },\n );\n options?.onQuote?.({\n sourceAmount: funding.sourceAmount,\n sourceTokenAddress: funding.sourceTokenAddress,\n });\n\n const tokenAddress = funding.sourceTokenAddress;\n const permit2 = PERMIT2_ADDRESS;\n\n // 2. Check balance — fail early before burning gas on approve/execute\n const balanceCall = encodeBalanceOfCall(tokenAddress, signer.address);\n const balanceResult = await signer.call({\n to: balanceCall.to,\n data: balanceCall.data,\n });\n const balance = decodeUint256(balanceResult);\n if (balance < funding.sourceAmount) {\n throw new Error(\n `Insufficient token balance: have ${balance}, need ${funding.sourceAmount}`,\n );\n }\n\n // 3. Check allowance to Permit2 — approve if insufficient\n const allowanceCall = encodeAllowanceCall(\n tokenAddress,\n signer.address,\n permit2,\n );\n const allowanceResult = await signer.call({\n to: allowanceCall.to,\n data: allowanceCall.data,\n });\n const allowance = decodeUint256(allowanceResult);\n\n if (allowance < funding.sourceAmount) {\n // Send approve(Permit2, max)\n const approveData = encodeMaxApproveData(tokenAddress, permit2);\n const approveTxHash = await signer.sendTransaction({\n to: approveData.to,\n data: approveData.data,\n gas: 100_000n,\n });\n\n const approveReceipt = await signer.waitForReceipt(approveTxHash);\n if (approveReceipt.status !== \"success\") {\n const reason = await getRevertReason(\n signer,\n approveTxHash,\n approveReceipt.blockNumber,\n );\n throw new Error(`Token approval failed: ${reason}`);\n }\n }\n\n // 4. Re-fetch fresh funding params (1inch quotes expire quickly)\n const freshFunding = await this.getPermit2FundingParamsUnsigned(\n swapId,\n signer.chainId,\n signer.address,\n { funding: options?.funding },\n );\n if (freshFunding.sourceAmount !== funding.sourceAmount) {\n options?.onQuote?.({\n sourceAmount: freshFunding.sourceAmount,\n sourceTokenAddress: freshFunding.sourceTokenAddress,\n });\n }\n\n // 5. Sign the Permit2 EIP-712 typed data\n const signature = await signer.signTypedData(freshFunding.typedData);\n\n // 6. Encode executeAndCreateWithPermit2 calldata\n const encoded = encodeExecuteAndCreateWithPermit2(\n freshFunding.coordinatorAddress,\n {\n calls: freshFunding.calls,\n preimageHash: freshFunding.preimageHash,\n token: freshFunding.lockTokenAddress,\n claimAddress: freshFunding.claimAddress,\n timelock: freshFunding.timelock,\n depositor: signer.address,\n sourceToken: freshFunding.sourceTokenAddress,\n sourceAmount: freshFunding.sourceAmount,\n nonce: freshFunding.nonce,\n deadline: freshFunding.deadline,\n signature,\n },\n );\n\n // 7. Simulate before sending to catch reverts without burning gas\n await simulateTransaction(signer, encoded, \"Funding transaction\");\n\n // 8. Send the funding transaction, then see it through\n const txHash = await signer.sendTransaction({\n to: encoded.to,\n data: encoded.data,\n gas: await gasLimitFor(signer, encoded, PERMIT2_FUND_GAS),\n });\n const mined = await this.#awaitFunding(swapId, signer, txHash, encoded, {\n htlcAddress: freshFunding.htlcAddress,\n preimageHash: freshFunding.preimageHash,\n claimAddress: freshFunding.claimAddress,\n coordinatorAddress: freshFunding.coordinatorAddress,\n lockSender: freshFunding.lockSender,\n token: freshFunding.lockTokenAddress,\n });\n return { txHash: mined };\n }\n\n /**\n * Fund a swap created with USDC on Solana as its source: burns the USDC on\n * Solana through CCTP with the user's wallet, waits for Circle's\n * attestation, then settles on Arbitrum with one paymaster-sponsored UserOp\n * (`receiveMessage` + Permit2 approval + HTLC creation).\n *\n * The Arbitrum side is always this client's key, so the swap must have been\n * created `gasless`. The burn is recorded on the stored swap as soon as the\n * wallet sends it; calling this again for a still-pending swap resumes from\n * that burn instead of burning twice, and\n * {@link recoverCctpInboundSwap} uses it if the settlement never lands.\n *\n * @param swapId - The UUID of the swap\n * @param signer - The user's Solana wallet, see {@link SolanaSigner}\n * @param options.rpcUrl - Solana JSON-RPC URL; defaults to the one set with\n * `withSolanaRpcUrl` on the builder\n * @param options.maxFee - CCTP fast-transfer fee cap in USDC units;\n * defaults to the IRIS-quoted fee\n * @param options.priorityFeeMicroLamports - Solana priority fee per compute\n * unit; defaults to recent network fees\n * @returns The Arbitrum settlement tx hash (or UserOp hash) and the burn\n */\n async fundSwapFromSolana(\n swapId: string,\n signer: SolanaSigner,\n options?: {\n rpcUrl?: string;\n maxFee?: bigint;\n priorityFeeMicroLamports?: bigint;\n onProgress?: (step: SolanaCctpProgressStep) => void;\n signal?: AbortSignal;\n /**\n * Pins on top of the swap's recorded funding terms: allowed call\n * targets, a higher input limit, a relay fee cap (default 0).\n */\n funding?: FundingPins;\n },\n ): Promise<{ txHash: string; cctp: CctpFundSwapFromSolanaResult }> {\n const rpcUrl = options?.rpcUrl ?? this.#config.solanaRpcUrl;\n if (!rpcUrl) {\n throw new Error(\n \"Funding from Solana needs a Solana RPC URL. Pass `rpcUrl` or call `.withSolanaRpcUrl(url)` on the ClientBuilder.\",\n );\n }\n const stored = await this.#swapStorage?.get(swapId);\n const swapResponse =\n stored?.response ?? (await this.getSwap(swapId, { updateStorage: true }));\n // Checked before anything is burned (see fundSwap's CCTP path).\n const expected = {\n ...this.#fundingExpectation(swapId, stored),\n pins: options?.funding,\n };\n await this.#ensureClientHashLock(\n swapId,\n evmHashLockOf(swapResponse),\n \"swap\",\n );\n const bridge = swapResponse as {\n bridge_source_chain?: string;\n bridge_source_token_address?: string;\n source_amount?: number | string;\n };\n if (bridge.bridge_source_chain !== \"Solana\") {\n throw new Error(\n `Swap ${swapId} is not funded from Solana (bridge source: ${bridge.bridge_source_chain ?? \"none\"}).`,\n );\n }\n if (\n bridge.bridge_source_token_address &&\n bridge.bridge_source_token_address !== USDC_ADDRESSES.Solana\n ) {\n throw new Error(\n `fundSwapFromSolana requires native USDC (${USDC_ADDRESSES.Solana}), but the swap's bridge_source_token_address is ${bridge.bridge_source_token_address}.`,\n );\n }\n if (bridge.source_amount === undefined) {\n throw new Error(\n `Swap ${swapId} has no source_amount — cannot route CCTP fund.`,\n );\n }\n const amount = BigInt(bridge.source_amount);\n\n // A burn recorded by an interrupted attempt: resume from it instead of\n // burning the USDC a second time, if the swap is still unfunded.\n const recordedBurn = stored?.cctpBurnTxid;\n if (recordedBurn) {\n const fresh = await this.getSwap(swapId, { updateStorage: true });\n if (fresh.status !== \"pending\") {\n throw new Error(\n `Swap ${swapId} is already ${fresh.status}; its CCTP burn ${recordedBurn} was settled.`,\n );\n }\n }\n\n // Only a new burn uses the fee, so resuming one must not depend on the\n // fee service being reachable.\n const maxFee = recordedBurn\n ? 0n\n : (options?.maxFee ??\n computeCctpFastFee(\n await getCachedCctpFee({\n sourceDomain: CCTP_DOMAINS.Solana,\n destinationDomain: CCTP_DOMAINS.Arbitrum,\n }),\n amount,\n ));\n\n const { cctpFundSwapFromSolana } = await import(\n \"./cctp-inbound/solana/fundSwap.js\"\n );\n // Built through the namespace so a missing AA config fails clearly.\n const { aa } = this.cctpInbound;\n const cctp = await cctpFundSwapFromSolana(\n { apiClient: this.#apiClient, aa },\n {\n swapId,\n expected,\n signer,\n ownerSigner: this.#depositorOwnerSigner(\n swapResponse,\n undefined,\n \"A swap funded from Solana must be created with `gasless: true`.\",\n ),\n rpcUrl,\n burnSignature: recordedBurn,\n burnLastValidBlockHeight: stored?.cctpBurnLastValidBlockHeight,\n onBurn: (burnSignature, lastValidBlockHeight) =>\n this.#recordCctpBurn(swapId, burnSignature, lastValidBlockHeight),\n amount,\n maxFee,\n priorityFeeMicroLamports: options?.priorityFeeMicroLamports,\n onProgress: options?.onProgress,\n signal: options?.signal,\n },\n );\n if (cctp.transactionHash) {\n await this.#recordEvmFunding(swapId, { txid: cctp.transactionHash });\n }\n return { txHash: cctp.transactionHash ?? cctp.userOpHash, cctp };\n }\n\n /**\n * The USDC balance (6 decimals) of a Solana wallet: what its USDC\n * associated token account holds, the account {@link fundSwapFromSolana}\n * burns from. `0n` when the wallet has none.\n *\n * @param owner - The wallet's public key (base58)\n * @param options.rpcUrl - Solana JSON-RPC URL; defaults to the one set with\n * `withSolanaRpcUrl` on the builder\n */\n async getSolanaUsdcBalance(\n owner: string,\n options?: { rpcUrl?: string },\n ): Promise<bigint> {\n const rpcUrl = options?.rpcUrl ?? this.#config.solanaRpcUrl;\n if (!rpcUrl) {\n throw new Error(\n \"Reading a Solana balance needs a Solana RPC URL. Pass `rpcUrl` or call `.withSolanaRpcUrl(url)` on the ClientBuilder.\",\n );\n }\n const [{ deriveAssociatedTokenAccount }, { getTokenAccountAmount }] =\n await Promise.all([\n import(\"./cctp-inbound/solana/burn.js\"),\n import(\"./cctp-inbound/solana/rpc.js\"),\n ]);\n return getTokenAccountAmount(rpcUrl, deriveAssociatedTokenAccount(owner));\n }\n\n /**\n * Fund a native lock directly with `HTLCNative.create` and the quoted\n * amount as the transaction value. The amount is\n * pinned on the swap (`evm_expected_sats`, in wei): there is no DEX leg,\n * so nothing is re-quoted at funding time.\n */\n async #fundNativeLock(\n swapId: string,\n swap:\n | EvmToLightningSwapResponse\n | EvmToArkadeSwapResponse\n | EvmToBitcoinSwapResponse,\n signer: EvmSigner,\n onQuote?: (quote: {\n sourceAmount: bigint;\n sourceTokenAddress: string;\n }) => void,\n ): Promise<string> {\n if (signer.chainId !== swap.evm_chain_id) {\n throw new Error(\n `fundSwap signer is on chain ${signer.chainId} but the swap locks on chain ${swap.evm_chain_id}`,\n );\n }\n const amount = BigInt(swap.evm_expected_sats);\n // The Bitcoin direction names the EVM hash lock separately from the\n // Bitcoin HTLC's; the other two carry a single hash_lock.\n const hashLock =\n \"evm_hash_lock\" in swap ? swap.evm_hash_lock : swap.hash_lock;\n await this.#ensureClientHashLock(swapId, hashLock, \"native lock\");\n // The coin goes straight to the HTLC named here: it must be the swap's,\n // with the claimer and timelock it was created with.\n const { terms } = this.#fundingExpectation(\n swapId,\n await this.getStoredSwap(swapId),\n );\n if (\n swap.evm_htlc_address.toLowerCase() !== terms.htlcAddress ||\n swap.server_evm_address.toLowerCase() !== terms.claimAddress ||\n swap.evm_refund_locktime !== terms.timelock\n ) {\n throw new Error(\n `The server's swap names HTLC ${swap.evm_htlc_address}, claimer ${swap.server_evm_address} and timelock ${swap.evm_refund_locktime}, not the ${terms.htlcAddress}, ${terms.claimAddress} and ${terms.timelock} it was created with; refusing to fund it`,\n );\n }\n onQuote?.({\n sourceAmount: amount,\n sourceTokenAddress: NATIVE_TOKEN_ADDRESS,\n });\n\n if (swap.evm_coordinator_address.toLowerCase() !== NATIVE_TOKEN_ADDRESS) {\n throw new Error(\n \"This legacy Rootstock swap requires coordinator funding. Create a new swap with the updated backend before funding.\",\n );\n }\n if (\n signer.address.toLowerCase() !== swap.client_evm_address?.toLowerCase()\n ) {\n throw new Error(\n \"Connect the source wallet recorded on this swap to fund RBTC.\",\n );\n }\n const encoded = encodeNativeCreate({\n htlcAddress: swap.evm_htlc_address,\n preimageHash: hashLock,\n amount,\n claimAddress: swap.server_evm_address,\n timelock: swap.evm_refund_locktime,\n });\n\n // Fail before the wallet prompts when the coin is not there; gas comes\n // out of the same balance, so this is a floor, not the exact need.\n if (signer.getBalance) {\n const balance = await signer.getBalance(signer.address);\n if (balance < encoded.value) {\n throw new Error(\n `Insufficient native balance: have ${balance} wei, need ${encoded.value} wei plus gas`,\n );\n }\n }\n\n const lock = {\n htlcAddress: swap.evm_htlc_address,\n preimageHash: hashLock,\n claimAddress: swap.server_evm_address,\n lockSender: signer.address,\n token: NATIVE_TOKEN_ADDRESS,\n };\n await this.#ensureNativeFundingFailed(\n swapId,\n signer,\n [\n (await this.getStoredSwap(swapId))?.evmFundTxid,\n (swap as { evm_fund_txid?: string | null }).evm_fund_txid,\n ],\n hashLock,\n );\n\n await simulateTransaction(signer, encoded, \"Funding transaction\");\n\n const txHash = await signer.sendTransaction({\n to: encoded.to,\n data: encoded.data,\n value: encoded.value,\n type: txTypeFor(signer.chainId),\n gas: await gasLimitFor(signer, encoded, NATIVE_LOCK_GAS),\n });\n // The wallet sends the lock itself: there is no coordinator to record.\n return this.#awaitFunding(swapId, signer, txHash, encoded, lock, {\n forgetFailed: true,\n });\n }\n\n /**\n * Throws unless every funding tx known for this native lock provably did\n * not fund it: it reverted, or the wallet replaced it with a tx whose logs\n * show no lock under the swap's hash. A tx the node does not know, one not\n * mined in time, one that mined, or a replacement without logs may have\n * locked the coin, and funding again could lock it twice.\n */\n async #ensureNativeFundingFailed(\n swapId: string,\n signer: EvmSigner,\n txids: (string | null | undefined)[],\n hashLock: string,\n ): Promise<void> {\n for (const txid of dedupeTxids(txids)) {\n const refuse = (why: string): never => {\n throw new Error(\n `Swap ${swapId} already has funding tx ${txid}, which ${why}; refusing to fund it again. Wait for it, or refund the swap once it lands.`,\n );\n };\n let known: unknown;\n try {\n known = await signer.getTransaction(txid);\n } catch {\n known = null;\n }\n if (!known) refuse(\"the node does not know and may still land\");\n let receipt: TxReceipt;\n try {\n receipt = await withDeadline(\n signer.waitForReceipt(txid),\n FUNDING_RECEIPT_WAIT_MS,\n `not mined within ${FUNDING_RECEIPT_WAIT_MS / 1000}s`,\n );\n } catch {\n return refuse(\"is not mined yet\");\n }\n if (receipt.status !== \"success\") continue;\n const mined = receipt.transactionHash || txid;\n // The call this client sent mined: the HTLC exists whatever the\n // receipt shows. Only a replacement can have done something else.\n if (mined.toLowerCase() === txid.toLowerCase()) {\n refuse(`mined in ${mined}`);\n }\n if (!provesNoLockUnder(receipt, hashLock)) {\n refuse(`was replaced by ${mined}, which may have locked the coin`);\n }\n }\n }\n\n /**\n * Record a sent funding tx, wait for it, and settle which tx funded the\n * swap. Returns the mined hash.\n */\n async #awaitFunding(\n swapId: string,\n signer: EvmSigner,\n txHash: string,\n sent: { to: string; data: string },\n expected: {\n htlcAddress: string;\n preimageHash: string;\n claimAddress: string;\n /** The coordinator the lock went through; none for a direct lock. */\n coordinatorAddress?: string;\n /** The lock's sender: the depositor on HTLCErc20 v7 / HTLCNative v2, the coordinator before. */\n lockSender: string;\n token: string;\n },\n options?: {\n /**\n * Drop the funding record again once the tx provably did not fund the\n * swap (it reverted, or a replacement's logs show no lock under the\n * hash), so a retry is not refused over it.\n */\n forgetFailed?: boolean;\n },\n ): Promise<string> {\n // Recorded before the wait, so an RPC failure on a tx that did mine\n // cannot lose it; corrected below if the wallet replaced the tx.\n await this.#recordEvmFunding(swapId, {\n txid: txHash,\n coordinatorAddress: expected.coordinatorAddress,\n });\n\n const receipt = await signer.waitForReceipt(txHash);\n if (receipt.status !== \"success\") {\n if (options?.forgetFailed) await this.#forgetEvmFunding(swapId, txHash);\n const reason = await getRevertReason(signer, txHash, receipt.blockNumber);\n throw new Error(`Funding transaction failed: ${reason}`);\n }\n // waitForReceipt follows replacements, and a cancel mines with status\n // success and no logs, so a replacement counts as the funding only when\n // the receipt shows the coordinator created this swap's HTLC or, for a\n // signer without logs, when it is the same call repriced.\n const mined = receipt.transactionHash || txHash;\n const replaced = mined.toLowerCase() !== txHash.toLowerCase();\n let created: boolean;\n if (receipt.logs === undefined) {\n this.#logger.warn({\n event: \"client.fundSwap.receiptWithoutLogs\",\n message:\n \"this signer's waitForReceipt returns no logs, so the swap can only be refunded through the server\",\n swapId,\n });\n created = !replaced || (await isSameCall(signer, mined, sent));\n } else {\n created =\n findSwapCreated(receipt.logs, {\n htlcAddress: expected.htlcAddress,\n hashLock: expected.preimageHash,\n claimAddress: expected.claimAddress,\n senders: [expected.lockSender],\n token: expected.token,\n }).length > 0;\n }\n if (!created && replaced) {\n // Only a receipt whose logs show no lock under this hash proves the\n // replacement funded nothing; anything less keeps the record, so a\n // retry is refused over it.\n if (\n options?.forgetFailed &&\n provesNoLockUnder(receipt, expected.preimageHash)\n ) {\n await this.#forgetEvmFunding(swapId, txHash);\n }\n throw new Error(\n `Transaction ${mined} is on-chain but did not create the HTLC; the wallet may have replaced or cancelled the funding`,\n );\n }\n if (!created) {\n // The call this client sent mined with status success, so the HTLC\n // exists whatever this receipt shows; failing here would invite a\n // second funding.\n this.#logger.warn({\n event: \"client.fundSwap.htlcLogNotFound\",\n message:\n \"the funding receipt carries no SwapCreated for this swap, so the swap can only be refunded through the server\",\n swapId,\n data: { txHash: mined },\n });\n }\n if (replaced) {\n await this.#recordEvmFunding(swapId, {\n txid: mined,\n coordinatorAddress: expected.coordinatorAddress,\n });\n }\n\n // Point the server at the funding. It verifies the receipt from its own\n // node, so a lock its monitor missed (a provider answering for an orphan\n // block) is applied now rather than by a later reconciler pass. Best\n // effort — the funding is done whatever the server says.\n await this.#hintEvmFunding(swapId, mined);\n\n // The server may have re-quoted the source amount for this funding;\n // bring the stored copy up to date. Best effort — the funding is done.\n await this.getSwap(swapId, { updateStorage: true }).catch(() => undefined);\n\n return mined;\n }\n\n /**\n * `POST /swap/{id}/evm-funding`: name the transaction that funded the swap.\n * The server believes nothing in the request; it reads the receipt itself\n * and applies the lock exactly as its monitor would. A refusal (an older\n * server without the route, a rate limit) only costs the shortcut.\n *\n * A 404 saying the transaction is not mined means the server's node has\n * no receipt for it yet (it trails the client's node, or sits on a\n * competing block): the hint is sent again a few times before the monitor\n * is left to find the lock. Any other 404 is a server without the route.\n */\n async #hintEvmFunding(swapId: string, txHash: string): Promise<void> {\n const baseUrl = this.#config.baseUrl.replace(/\\/$/, \"\");\n try {\n for (let attempt = 1; ; attempt++) {\n // Bounded: the funding is done, and the server's handler looks the\n // receipt up on its node before answering.\n const resp = await fetchWithTimeout(\n `${baseUrl}/swap/${swapId}/evm-funding`,\n FUNDING_HINT_TIMEOUT_MS,\n {\n method: \"POST\",\n headers: this.#apiHeaders({ \"Content-Type\": \"application/json\" }),\n body: JSON.stringify({\n tx_hash: txHash,\n } satisfies components[\"schemas\"][\"EvmFundingHintRequest\"]),\n },\n );\n if (resp.ok) {\n return;\n }\n const body = await readBodyBounded(resp, FUNDING_HINT_TIMEOUT_MS);\n if (\n resp.status === 404 &&\n /not mined/i.test(body) &&\n attempt < FUNDING_HINT_ATTEMPTS\n ) {\n this.#logger.debug({\n event: \"client.fundSwap.hintNotMinedYet\",\n message:\n \"the server's node has not seen the funding yet; retrying the hint\",\n swapId,\n data: { txHash, attempt, body },\n });\n await new Promise((resolve) =>\n setTimeout(resolve, FUNDING_HINT_RETRY_DELAY_MS),\n );\n continue;\n }\n this.#logger.warn({\n event: \"client.fundSwap.hintRefused\",\n message:\n \"the server did not apply the funding hint; its monitor will pick the funding up\",\n swapId,\n data: { txHash, status: resp.status, body },\n });\n return;\n }\n } catch (error) {\n this.#logger.warn({\n event: \"client.fundSwap.hintFailed\",\n message:\n \"could not reach the server with the funding hint; its monitor will pick the funding up\",\n swapId,\n data: {\n txHash,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n }\n }\n\n /**\n * Refund an EVM-sourced swap using an external wallet.\n *\n * Builds the refund from the funding tx's receipt, asking the server for\n * the funding txid or the calldata only when that fails, then sends it via\n * the provided signer and waits for the receipt.\n *\n * Use this for manual (timelock-based) refunds where the user pays gas.\n * For collaborative (gasless) refunds, use {@link collabRefundEvmWithSigner}.\n *\n * @param swapId - The UUID of the swap\n * @param signer - An {@link EvmSigner} wrapping the user's wallet\n * @returns The refund transaction hash\n */\n async refundEvmWithSigner(\n swapId: string,\n signer: EvmSigner,\n ): Promise<{ txHash: string }> {\n const result = await this.refundSwap(swapId, { signer });\n\n if (!result.evmRefundData) {\n throw new Error(\n `Unable to get EVM refund data for: ${swapId}. ${result.message}`,\n );\n }\n\n if (!result.evmRefundData.timelockExpired) {\n const expiryDate = new Date(\n result.evmRefundData.timelockExpiry * 1000,\n ).toISOString();\n throw new Error(\n `Refund timelock has not expired yet (expires ${expiryDate}). Use collabRefundEvmWithSigner for instant refunds.`,\n );\n }\n\n // Simulate before sending to catch reverts without burning gas\n await simulateTransaction(\n signer,\n result.evmRefundData,\n \"Refund transaction\",\n );\n\n const txHash = await signer.sendTransaction({\n to: result.evmRefundData.to,\n data: result.evmRefundData.data,\n type: txTypeFor(signer.chainId),\n gas: await gasLimitFor(signer, result.evmRefundData, REFUND_GAS),\n });\n\n const receipt = await signer.waitForReceipt(txHash);\n if (receipt.status !== \"success\") {\n const reason = await getRevertReason(signer, txHash, receipt.blockNumber);\n throw new Error(`Refund transaction reverted: ${reason}`);\n }\n\n return { txHash };\n }\n\n /**\n * Collaborative refund of an EVM-sourced swap using an external wallet.\n *\n * Signs the EIP-712 `CollabRefund` digest with the provided signer and\n * submits it to the server, which cosigns and executes the refund on-chain.\n * Gasless for the user — no timelock wait required.\n *\n * For gasless (Permit2) swaps where the SDK's embedded key is the depositor,\n * use {@link collabRefundEvmSwap} instead (no external signer needed).\n *\n * @param swapId - The UUID of the swap\n * @param signer - An {@link EvmSigner} wrapping the user's wallet\n * @returns The refund transaction hash\n */\n async collabRefundEvmWithSigner(\n swapId: string,\n signer: EvmSigner,\n ): Promise<{ txHash: string }> {\n const { typedData, params } =\n await this.buildCollabRefundEvmTypedData(swapId);\n if (params.refundPath === \"direct\") {\n return this.#collabRefundEvmDirect(swapId, signer);\n }\n if (params.refundPath !== \"coordinator\") {\n throw new Error(collabRefundUnavailable(swapId, params));\n }\n\n const signature = await signer.signTypedData(typedData);\n const { v, r, s } = parseSignature(signature);\n\n const result = await this.submitCollabRefundEvm(swapId, {\n v,\n r,\n s,\n depositor_address: signer.address,\n });\n\n return { txHash: result.txHash };\n }\n\n /**\n * Direct collaborative refund from the depositor's wallet: fetch the\n * server's `Refund` signature bound to the signer, then send\n * `refundBySig` from it. The user pays gas; no timelock wait.\n */\n async #collabRefundEvmDirect(\n swapId: string,\n signer: EvmSigner,\n ): Promise<{ txHash: string }> {\n const signature = await this.getCollabRefundEvmSignature(\n swapId,\n signer.address,\n );\n if (signer.chainId !== signature.chainId) {\n throw new Error(\n `Swap ${swapId} locks on chain ${signature.chainId}, but the signer is connected to chain ${signer.chainId}`,\n );\n }\n const txHash = await sendCall(\n signer,\n refundBySigCallData(signature),\n \"Collaborative refund transaction\",\n );\n return { txHash };\n }\n\n async #actualRefundTransfer(\n oldSwap: GetSwapResponse,\n smartAccountAddress: string,\n ): Promise<{ tokenAddress: string; amount: string } | null> {\n const txHash = (oldSwap as { evm_claim_txid?: string | null })\n .evm_claim_txid;\n const rpcUrl = this.#config.aa?.rpcUrl ?? this.#config.aa?.bundlerUrl;\n if (!txHash || !rpcUrl) return null;\n\n const { createPublicClient, http } = await import(\"viem\");\n const { arbitrum } = await import(\"viem/chains\");\n const publicClient = createPublicClient({\n chain: arbitrum,\n transport: http(rpcUrl),\n });\n let receipt: Awaited<ReturnType<typeof publicClient.getTransactionReceipt>>;\n try {\n receipt = await publicClient.getTransactionReceipt({\n hash: txHash as `0x${string}`,\n });\n } catch {\n return null;\n }\n\n const transferTopic =\n \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\";\n const paddedRecipient = smartAccountAddress\n .replace(/^0x/i, \"\")\n .toLowerCase()\n .padStart(64, \"0\");\n\n const transfers = receipt.logs\n .filter(\n (log) =>\n log.topics[0]?.toLowerCase() === transferTopic &&\n log.topics[2]?.replace(/^0x/i, \"\").toLowerCase() === paddedRecipient,\n )\n .map((log) => ({\n tokenAddress: log.address,\n amount: BigInt(log.data).toString(),\n }))\n .filter((t) => BigInt(t.amount) > 0n);\n\n return transfers.at(-1) ?? null;\n }\n\n /**\n * Whether a refunded EVM-sourced swap can be swapped again from its refund:\n * the refunded token must sit in the depositor's Kernel account on\n * Arbitrum. Without `signer` the account is this client's key (swaps\n * created gasless, incl. CCTP-inbound) and balances are read through the AA\n * RPC; pass the owner's signer for any other account.\n */\n async getRefundedEvmSwapContinuation(\n oldSwapId: string,\n signer?: EvmSigner,\n ): Promise<ContinueRefundedEvmSwapInfo> {\n const oldSwap = await this.getSwap(oldSwapId, { updateStorage: true });\n\n if (\n oldSwap.direction !== \"evm_to_arkade\" &&\n oldSwap.direction !== \"evm_to_bitcoin\" &&\n oldSwap.direction !== \"evm_to_lightning\"\n ) {\n return {\n eligible: false,\n reason: `Expected an EVM-sourced swap, got ${oldSwap.direction}.`,\n oldSwap,\n };\n }\n\n if (oldSwap.status === \"clientrefundedserverfunded\") {\n return {\n eligible: false,\n reason:\n \"Swap is in a critical refund state. Please contact support before continuing.\",\n oldSwap,\n };\n }\n\n if (\n oldSwap.status !== \"clientrefunded\" &&\n oldSwap.status !== \"clientrefundedserverrefunded\"\n ) {\n return {\n eligible: false,\n reason: `Swap is ${oldSwap.status}, not refunded.`,\n oldSwap,\n };\n }\n\n const owner = signer ?? this.#keyOwnerSigner();\n const { accountAddress } = await this.cctpInbound.createSmartAccountClient({\n signer: owner,\n });\n const smartAccountAddress = accountAddress;\n const readCall = signer\n ? (tx: { to: string; data: string }) => signer.call(tx)\n : await this.#aaRpcCall();\n\n const chainConfig = await this.getChainConfig();\n const refundChain = \"42161\" as Chain;\n const refundChainConfig = chainConfig.chains.find(\n (c) => c.chain === refundChain,\n );\n if (!refundChainConfig) {\n return {\n eligible: false,\n reason:\n \"Arbitrum chain config is missing; cannot identify refund token.\",\n smartAccountAddress,\n oldSwap,\n };\n }\n\n const sourceTokenAddress = String(oldSwap.source_token.token_id);\n const fallbackCandidates = [\n {\n chain: refundChain,\n address: refundChainConfig.btc_pegged_token.address,\n symbol: refundChainConfig.btc_pegged_token.symbol,\n decimals: refundChainConfig.btc_pegged_token.decimals,\n amount: String(\n (oldSwap as { evm_expected_sats?: number | string })\n .evm_expected_sats,\n ),\n },\n {\n chain: oldSwap.source_token.chain as Chain,\n address: sourceTokenAddress,\n symbol: oldSwap.source_token.symbol,\n decimals: oldSwap.source_token.decimals,\n amount: String(oldSwap.source_amount),\n },\n ];\n\n const actualRefund = await this.#actualRefundTransfer(\n oldSwap,\n smartAccountAddress,\n );\n const actualMeta = actualRefund\n ? fallbackCandidates.find(\n (c) =>\n c.address.toLowerCase() === actualRefund.tokenAddress.toLowerCase(),\n )\n : undefined;\n const candidates = [\n ...(actualRefund\n ? [\n {\n chain: refundChain,\n address: actualRefund.tokenAddress,\n symbol: actualMeta?.symbol ?? \"ERC-20\",\n decimals: actualMeta?.decimals ?? 18,\n amount: actualRefund.amount,\n },\n ]\n : []),\n ...fallbackCandidates,\n ].filter(\n (c, idx, arr) =>\n c.amount !== \"undefined\" &&\n c.address.startsWith(\"0x\") &&\n c.chain === refundChain &&\n arr.findIndex(\n (other) =>\n other.chain === c.chain &&\n other.address.toLowerCase() === c.address.toLowerCase(),\n ) === idx,\n );\n\n for (const candidate of candidates) {\n const balanceCall = encodeBalanceOfCall(\n candidate.address,\n smartAccountAddress,\n );\n const balanceResult = await readCall({\n to: balanceCall.to,\n data: balanceCall.data,\n });\n const balance = decodeUint256(balanceResult || \"0x0\");\n const amount = BigInt(candidate.amount);\n if (balance >= amount) {\n return {\n eligible: true,\n smartAccountAddress,\n token: {\n chain: candidate.chain,\n address: candidate.address,\n symbol: candidate.symbol,\n decimals: candidate.decimals,\n },\n amount: candidate.amount,\n balance: balance.toString(),\n oldSwap,\n };\n }\n }\n\n return {\n eligible: false,\n reason: `No expected refunded balance found in Kernel account ${smartAccountAddress}.`,\n smartAccountAddress,\n oldSwap,\n };\n }\n\n /**\n * Swap the refund of a failed EVM-sourced swap again, instead of leaving it\n * in the depositor's Kernel account: creates a new swap funded from that\n * balance and funds it with a paymaster-sponsored UserOp (no wallet, no\n * gas).\n *\n * @param options.targetAddress - Where the new swap pays out: a Bitcoin\n * address, an Arkade address, or for Lightning a BOLT11 invoice (its amount\n * must be covered by the refund), a Lightning address or an LNURL.\n * @param options.target - The payout type; defaults to the old swap's.\n * @param options.signer - A signer for this client's key; defaults to one\n * derived from it. Any other owner is rejected: the new swap is created\n * gasless, which records this client's key as its depositor, and the\n * paymaster only sponsors funding from the depositor's account.\n */\n async continueRefundedEvmSwap(\n oldSwapId: string,\n options: {\n targetAddress: string;\n target?: ContinueTarget;\n signer?: EvmSigner;\n /** Pins on top of the new swap's recorded funding terms. */\n funding?: FundingPins;\n },\n ): Promise<ContinueRefundedEvmSwapResult> {\n // Checked before anything is created: a swap whose depositor cannot fund\n // it would be left behind unfunded.\n if (\n options.signer &&\n options.signer.address.toLowerCase() !==\n this.getEvmAddress().toLowerCase()\n ) {\n throw new Error(\n `Cannot continue refunded swap ${oldSwapId} with signer ${options.signer.address}: a continuation is funded from this client's key (${this.getEvmAddress()}).`,\n );\n }\n const info = await this.getRefundedEvmSwapContinuation(\n oldSwapId,\n options.signer,\n );\n if (!info.eligible || !info.token || !info.amount || !info.oldSwap) {\n throw new Error(info.reason ?? \"Refunded swap cannot be continued.\");\n }\n\n const target =\n options.target ??\n ({\n evm_to_arkade: \"arkade\",\n evm_to_bitcoin: \"bitcoin\",\n evm_to_lightning: \"lightning\",\n }[info.oldSwap.direction as string] as ContinueTarget | undefined);\n const sourceAmount = BigInt(info.amount);\n const common = {\n tokenAddress: info.token.address,\n evmChainId: 42161,\n userAddress: info.smartAccountAddress ?? \"\",\n gasless: true,\n };\n\n let created: CreateSwapResult;\n if (target === \"arkade\") {\n created = await this.createEvmToArkadeSwapGeneric({\n ...common,\n targetAddress: options.targetAddress,\n sourceAmount,\n });\n } else if (target === \"bitcoin\") {\n created = await this.createEvmToBitcoinSwap({\n ...common,\n targetAddress: options.targetAddress,\n sourceAmount,\n });\n } else if (target === \"lightning\") {\n created = await this.createEvmToLightningSwap({\n ...common,\n ...lightningPayoutOf(options.targetAddress, sourceAmount),\n });\n } else {\n throw new Error(\n `Cannot continue refunded swap with direction ${info.oldSwap.direction}.`,\n );\n }\n\n // `expectedMaxSourceAmount` caps the spend at this refund: a Lightning\n // invoice pins the payout, and one the refund cannot cover must fail\n // rather than draw on unrelated balance in the account.\n const newSwapId = created.response.id;\n const submitted = await this.cctpInbound.submitBalanceUserOp({\n swapId: newSwapId,\n // The new swap's own hash and terms, recorded when it was just\n // created here.\n expected: {\n ...this.#fundingExpectation(\n newSwapId,\n await this.getStoredSwap(newSwapId),\n ),\n pins: options.funding,\n },\n signer: options.signer ?? this.#keyOwnerSigner(),\n expectedMaxSourceAmount: sourceAmount,\n });\n if (submitted.transactionHash) {\n await this.#recordEvmFunding(newSwapId, {\n txid: submitted.transactionHash,\n });\n }\n\n return {\n oldSwapId,\n newSwapId: created.response.id,\n txHash: submitted.transactionHash ?? submitted.userOpHash,\n userOpHash: submitted.userOpHash,\n smartAccountAddress: submitted.smartAccountAddress,\n amount: info.amount,\n token: info.token,\n };\n }\n\n /**\n * Refund an EVM-sourced swap whose depositor is this client's key (created\n * gasless, incl. CCTP-inbound) once its timelock has passed, as a\n * paymaster-sponsored UserOp from that key's Kernel account: no wallet, no\n * gas. The refunded token lands in that account, from where\n * {@link continueRefundedEvmSwap} swaps it again. Arbitrum only, where the\n * paymaster runs.\n *\n * Gasless swaps from older SDK versions were funded from the swap's own\n * key instead; those are refunded from that key's account (a continuation\n * cannot pick the refund up from there).\n */\n async refundEvmSponsored(\n swapId: string,\n ): Promise<{ txHash: string; userOpHash: string }> {\n const aa = this.#config.aa;\n if (!aa) {\n throw new Error(\n \"A sponsored refund requires AA config. Call `.withAa({ bundlerUrl, paymasterPolicyId })` on the ClientBuilder before `.build()`.\",\n );\n }\n const stored = await this.getStoredSwap(swapId);\n if (!stored) {\n throw new Error(`Swap ${swapId} not found in local storage.`);\n }\n const chainId = (stored.response as { evm_chain_id?: number }).evm_chain_id;\n if (chainId !== 42161) {\n throw new Error(\n `Sponsored refunds run on Arbitrum only; swap ${swapId} is on chain ${chainId}. Use refundEvmWithSigner.`,\n );\n }\n // Only the depositor's account is sponsored. A wallet-funded swap's\n // wallet is the depositor and sends the refund itself.\n const { client_evm_address: depositor, gasless } = stored.response as {\n client_evm_address?: string;\n gasless?: boolean;\n };\n let owner: EvmSigner;\n if (depositor?.toLowerCase() === this.getEvmAddress().toLowerCase()) {\n owner = this.#keyOwnerSigner();\n } else if (\n gasless &&\n depositor?.toLowerCase() ===\n deriveEvmAddress(stored.secretKey).toLowerCase()\n ) {\n // A legacy gasless swap, funded from its per-swap key (as the\n // collaborative refund's key selection also allows).\n owner = keyToKernelOwnerSigner(\n hexToBytes(stored.secretKey.replace(/^0x/, \"\")),\n 42161,\n );\n } else {\n throw new Error(\n `Swap ${swapId} was funded by ${depositor}, not this client's key; only gasless swaps can be refunded sponsored. Refund it with \\`refundEvmWithSigner\\` from that wallet.`,\n );\n }\n\n const result = await this.refundSwap(swapId);\n if (!result.evmRefundData) {\n throw new Error(\n `Unable to get EVM refund data for: ${swapId}. ${result.message}`,\n );\n }\n if (!result.evmRefundData.timelockExpired) {\n const expiryDate = new Date(\n result.evmRefundData.timelockExpiry * 1000,\n ).toISOString();\n throw new Error(\n `Refund timelock has not expired yet (expires ${expiryDate}).`,\n );\n }\n\n // On HTLCErc20 v7 / HTLCNative v2 the server returns the permissionless\n // `refundFor`, which the paymaster does not sponsor; the smart account is\n // the lock's sender, so it refunds with its own `refund` instead.\n // An included UserOp can still revert (e.g. the server's collaborative\n // refund won the race); nothing was refunded then, so it fails.\n const refund = result.evmRefundData;\n return this.#sponsoredUserOp(owner, (account) =>\n refundForAsOwnRefund(refund, account),\n );\n }\n\n /** This client's key as the Kernel owner on Arbitrum. */\n #keyOwnerSigner(): EvmSigner {\n return keyToKernelOwnerSigner(this.#signer.deriveEvmKey().secretKey, 42161);\n }\n\n /**\n * An `eth_call` over the AA RPC, for reads on an account this client owns\n * with its key (whose signer does not read the chain).\n */\n async #aaRpcCall(): Promise<\n (tx: { to: string; data: string }) => Promise<string>\n > {\n const rpcUrl = this.#config.aa?.rpcUrl ?? this.#config.aa?.bundlerUrl;\n if (!rpcUrl) {\n throw new Error(\n \"Reading a refunded balance without a signer requires AA config (`.withAa(...)`).\",\n );\n }\n const { createPublicClient, http } = await import(\"viem\");\n const { arbitrum } = await import(\"viem/chains\");\n const publicClient = createPublicClient({\n chain: arbitrum,\n transport: http(rpcUrl),\n });\n return async ({ to, data }) =>\n (\n await publicClient.call({\n to: to as `0x${string}`,\n data: data as `0x${string}`,\n })\n ).data ?? \"0x\";\n }\n\n /**\n * Fund an EVM-sourced swap via the gasless relay.\n *\n * Signs the Permit2 authorization and (optionally) an EIP-2612 permit\n * off-chain, then POSTs them to the server which submits the on-chain\n * transactions on behalf of the user. No wallet or ETH required.\n *\n * @param swapId - The UUID of the swap (must have been created with gasless=true)\n * @returns The relay transaction hash\n *\n * @example\n * ```ts\n * const result = await client.fundSwapGasless(swap.response.id);\n * console.log(\"Funded via relay:\", result.txHash);\n * ```\n */\n async fundSwapGasless(\n swapId: string,\n options?: {\n /**\n * Pins on top of the swap's recorded funding terms. `maxRelayFee`\n * defaults to 0: on a chain whose relay charges a fee (Ethereum) set\n * it, or the funding is refused.\n */\n funding?: FundingPins;\n },\n ): Promise<{ txHash: string }> {\n // 1. Look up stored swap to get the secret key\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap) {\n throw new Error(\n `Swap ${swapId} not found in local storage. Cannot sign without the secret key.`,\n );\n }\n\n const swap = await this.getSwap(swapId);\n\n if (\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"evm_to_bitcoin\" &&\n swap.direction !== \"evm_to_lightning\"\n ) {\n throw new Error(\n `Expected an EVM-sourced swap, got ${swap.direction}. Gasless fund is for EVM-sourced swaps.`,\n );\n }\n\n const chainId = (swap as { evm_chain_id: number }).evm_chain_id;\n\n // 2. Fetch Permit2 funding data (includes fee transfer in calls + EIP-2612 data)\n const baseUrl = this.#config.baseUrl.replace(/\\/$/, \"\");\n const url = `${baseUrl}/swap/${swapId}/swap-and-lock-calldata-permit2`;\n\n const resp = await fetch(url, {\n headers: this.#apiHeaders(),\n });\n if (!resp.ok) {\n const body = await resp.text();\n throw new Error(\n `Failed to get Permit2 funding data: ${resp.status} ${body}`,\n );\n }\n\n const serverData = (await resp.json()) as {\n coordinator_address: string;\n htlc_kind?: string;\n htlc_version?: number;\n permit2_address: string;\n source_token_address: string;\n source_amount: string;\n lock_token_address: string;\n preimage_hash: string;\n claim_address: string;\n timelock: number;\n calls: Array<{ target: string; value: string; call_data: string }>;\n calls_hash: string;\n eip2612?: {\n supported: boolean;\n already_approved: boolean;\n nonce: number;\n domain_separator: string;\n };\n relay_fee?: string;\n depositor_delegation?: string | null;\n };\n // Spender, lock, tokens, amount, calls and relay fee are bound to the\n // swap's recorded terms before anything is signed, and signed from them.\n const checked = await this.#checkedFunding(\n swapId,\n serverData,\n chainId,\n options?.funding,\n );\n\n // 3. Generate random Permit2 nonce and deadline\n const nonceBytes = new Uint8Array(32);\n crypto.getRandomValues(nonceBytes);\n const nonce = BigInt(\n `0x${Array.from(nonceBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`,\n );\n const deadline = BigInt(Math.floor(Date.now() / 1000) + 30 * 60); // 30 minutes\n\n const sourceAmount = checked.sourceAmount;\n\n // 4. Build and sign the Permit2 EIP-712 digest. The witness binds the\n // lock's refund address: the depositor from HTLCErc20 v7 / HTLCNative v2,\n // the coordinator before.\n const evmKey = this.#getEvmSigningKey();\n const depositorAddress = deriveEvmAddress(evmKey);\n const digest = buildPermit2FundingDigest({\n chainId,\n coordinatorAddress: checked.coordinator,\n sourceToken: checked.sourceToken,\n sourceAmount,\n preimageHash: checked.preimageHash,\n lockToken: checked.lockToken,\n claimAddress: checked.claimAddress,\n refundAddress: permit2RefundAddress(\n checkedRefundContext(checked),\n depositorAddress,\n ),\n timelock: checked.timelock,\n callsHash: checked.callsHash,\n nonce,\n deadline,\n });\n // 4b. Use the EVM key (deterministic for new swaps, per-swap for legacy).\n // If the depositor has been delegated to Kernel by a sponsored claim,\n // Permit2 verifies via ERC-1271 and needs Kernel's envelope.\n const delegated = await this.#isKernelDelegated(\n depositorAddress,\n chainId,\n this.#delegationHintFor(\n swap as { client_evm_address?: string | null },\n depositorAddress,\n serverData.depositor_delegation,\n ),\n );\n const compactSignature = this.#signDepositorDigest(\n evmKey,\n depositorAddress,\n chainId,\n digest,\n delegated,\n );\n\n // 6. If EIP-2612 needed (token supports it and not yet approved to Permit2).\n // A Kernel-delegated depositor has code, so the token verifies the permit\n // via ERC-1271: send Kernel's envelope as `signature` instead of v/r/s.\n let eip2612Permit:\n | {\n v?: number;\n r?: string;\n s?: string;\n signature?: string;\n value: string;\n deadline: number;\n nonce: number;\n }\n | undefined;\n\n if (serverData.eip2612?.supported && !serverData.eip2612.already_approved) {\n const maxUint256 = BigInt(\n \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n );\n const eip2612Digest = buildEip2612PermitDigest({\n domainSeparator: serverData.eip2612.domain_separator,\n owner: depositorAddress,\n spender: PERMIT2_ADDRESS,\n value: maxUint256,\n nonce: serverData.eip2612.nonce,\n deadline,\n });\n if (delegated) {\n eip2612Permit = {\n signature: this.#signDepositorDigest(\n evmKey,\n depositorAddress,\n chainId,\n eip2612Digest,\n delegated,\n ),\n value: maxUint256.toString(),\n deadline: Number(deadline),\n nonce: serverData.eip2612.nonce,\n };\n } else {\n const sig = signEvmDigest(evmKey, eip2612Digest);\n eip2612Permit = {\n v: sig.v,\n r: sig.r.replace(/^0x/, \"\"),\n s: sig.s.replace(/^0x/, \"\"),\n value: maxUint256.toString(),\n deadline: Number(deadline),\n nonce: serverData.eip2612.nonce,\n };\n }\n }\n\n // 7. POST to fund-gasless relay endpoint\n const fundUrl = `${baseUrl}/swap/${swapId}/fund-gasless`;\n const fundResp = await fetch(fundUrl, {\n method: \"POST\",\n headers: this.#apiHeaders({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify({\n permit2_nonce: nonce.toString(),\n permit2_deadline: Number(deadline),\n permit2_signature: compactSignature,\n // The checked calls, which the signed calls hash covers.\n calls: checked.calls.map((call) => ({\n target: call.target,\n value: call.value.toString(),\n call_data: call.data,\n })),\n eip2612_permit: eip2612Permit,\n }),\n });\n\n if (!fundResp.ok) {\n const body = await fundResp.text();\n throw new Error(`Gasless fund relay failed: ${fundResp.status} ${body}`);\n }\n\n const result = (await fundResp.json()) as {\n id: string;\n status: string;\n tx_hash: string;\n message: string;\n };\n\n // The relay's txid is the server's word: a hint for a later refund or\n // rehash, which trust a receipt only for a lock under this swap's hash.\n await this.#recordEvmFunding(swapId, {\n txid: result.tx_hash,\n coordinatorAddress: checked.coordinator,\n });\n return { txHash: result.tx_hash };\n }\n\n /**\n * Get the ephemeral depositor key for a gasless swap funded swap.\n *\n * Returns the private key and derived EVM address of the ephemeral\n * depositor used in a gasless swap. Use this to build a wallet/signer\n * for recovering stuck funds via {@link recoverGaslessFunds}.\n *\n * The key is deterministically derived from the user's mnemonic and\n * the swap's key index, so it can be re-derived even if local storage\n * is rebuilt from the mnemonic.\n *\n * @param swapId - The UUID of the swap\n * @returns The depositor's private key (hex) and EVM address\n *\n * @example\n * ```ts\n * const { privateKey, address } = await client.getSwapDepositorKey(swapId);\n * // Build a viem wallet from the key:\n * const account = privateKeyToAccount(privateKey);\n * ```\n */\n async getSwapDepositorKey(\n swapId: string,\n ): Promise<{ privateKey: string; address: string }> {\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap) {\n throw new Error(\n `Swap ${swapId} not found in local storage. Cannot recover without the secret key.`,\n );\n }\n\n const evmKey = this.#getEvmSigningKey();\n const privateKey = evmKey.startsWith(\"0x\") ? evmKey : `0x${evmKey}`;\n const address = deriveEvmAddress(evmKey);\n\n return { privateKey, address };\n }\n\n /**\n * Wallet-level variant of {@link getSwapDepositorKey} — returns the\n * deterministic EVM signing key for this wallet without requiring a\n * specific swap to be stored locally.\n *\n * Same key, same address as {@link getSwapDepositorKey} (both derive\n * from `m/44'/60'/0'/0/0`). Intended for standalone recovery tools\n * where the user supplies the burn details manually and a per-swap\n * record may no longer exist (e.g. fresh device, cleared site data).\n */\n getEvmDepositorKey(): { privateKey: string; address: string } {\n const evmKey = this.#getEvmSigningKey();\n const privateKey = evmKey.startsWith(\"0x\") ? evmKey : `0x${evmKey}`;\n const address = deriveEvmAddress(evmKey);\n return { privateKey, address };\n }\n\n /**\n * Recover the USDC of a CCTP-inbound swap whose Arbitrum settlement never\n * landed: mints it from the recorded burn if that has not happened yet, then\n * sweeps the smart account's USDC to `recipient` on Arbitrum. Both steps are\n * paymaster-sponsored UserOps. Uses the burn {@link fundSwap} recorded and\n * the same owner rule, so a swap created gasless needs no wallet here.\n *\n * @param swapId - The UUID of the CCTP-inbound swap\n * @param recipient - Arbitrum address that receives the recovered USDC\n * @param options.ownerSigner - The owner when the swap's depositor is the\n * user's wallet rather than this client's key\n * @param options.burnTxHash - The burn, when it was not recorded locally\n * (e.g. a funding started on another device); for a swap funded from\n * Solana, the burn's transaction signature\n */\n async recoverCctpInboundSwap(\n swapId: string,\n recipient: string,\n options?: {\n ownerSigner?: EvmSigner;\n burnTxHash?: string;\n onProgress?: (step: RecoveryProgress) => void;\n signal?: AbortSignal;\n },\n ): Promise<RecoverCctpInboundResult> {\n if (!this.#config.aa) {\n throw new Error(\n \"Recovering a CCTP-inbound swap requires AA config. Call `.withAa({ bundlerUrl, paymasterPolicyId })` on the ClientBuilder before `.build()`.\",\n );\n }\n const stored = await this.getStoredSwap(swapId);\n if (!stored) {\n throw new Error(`Swap ${swapId} not found in local storage.`);\n }\n const sourceChain = (stored.response as { bridge_source_chain?: string })\n .bridge_source_chain;\n if (!sourceChain) {\n throw new Error(`Swap ${swapId} is not a CCTP-inbound swap.`);\n }\n const burnTxHash = options?.burnTxHash ?? stored.cctpBurnTxid;\n if (!burnTxHash) {\n throw new Error(\n `No CCTP burn is recorded for swap ${swapId}; pass it as \\`burnTxHash\\`.`,\n );\n }\n return recoverCctpInbound(\n { aa: this.#config.aa },\n {\n signer: this.#depositorOwnerSigner(\n stored.response,\n options?.ownerSigner,\n ),\n burnTxHash,\n sourceChain: sourceChain as CctpChainName,\n recipient: recipient as `0x${string}`,\n onProgress: options?.onProgress,\n signal: options?.signal,\n },\n );\n }\n\n /**\n * Recover ERC-20 tokens stuck in a gasless swap's ephemeral depositor address.\n *\n * When a gasless swap fails after the user transfers tokens to the\n * SDK-derived depositor address but before the Permit2 tx is published,\n * this method sweeps the tokens back to a destination address.\n *\n * Requires an {@link EvmSigner} backed by the depositor's private key\n * (obtainable via {@link getSwapDepositorKey}). The depositor needs\n * a small amount of ETH/POL for gas — the caller must fund it beforehand.\n *\n * @param swapId - The UUID of the swap whose depositor holds stuck tokens\n * @param depositorSigner - An {@link EvmSigner} backed by the depositor's private key\n * @param destination - EVM address to send recovered tokens to\n * @returns The recovery transaction hash and recovered amount\n *\n * @example\n * ```ts\n * // 1. Get the depositor key\n * const { privateKey } = await client.getSwapDepositorKey(swapId);\n *\n * // 2. Build a signer from the depositor key (e.g. with viem)\n * const depositorAccount = privateKeyToAccount(privateKey);\n * const depositorWallet = createWalletClient({ account: depositorAccount, ... });\n * const depositorSigner = buildEvmSigner(depositorWallet, publicClient);\n *\n * // 3. Fund the depositor with ETH for gas, then recover\n * const result = await client.recoverGaslessFunds(swapId, depositorSigner, myAddress);\n * console.log(`Recovered ${result.amount} tokens, tx: ${result.txHash}`);\n * ```\n */\n async recoverGaslessFunds(\n swapId: string,\n depositorSigner: EvmSigner,\n destination: string,\n ): Promise<{ txHash: string; amount: string }> {\n const storedSwap = await this.getStoredSwap(swapId);\n if (!storedSwap) {\n throw new Error(\n `Swap ${swapId} not found in local storage. Cannot recover without the secret key.`,\n );\n }\n\n const swap = await this.getSwap(swapId);\n if (\n swap.direction !== \"evm_to_arkade\" &&\n swap.direction !== \"evm_to_bitcoin\" &&\n swap.direction !== \"evm_to_lightning\"\n ) {\n throw new Error(\n `Expected EVM-sourced swap, got ${swap.direction}. Recovery is only for gasless EVM swaps.`,\n );\n }\n\n const tokenAddress = (swap as { source_token: { token_id: string } })\n .source_token.token_id;\n\n // Check the depositor's token balance\n const { encodeBalanceOfCall, encodeTransferCall, decodeUint256 } =\n await import(\"./evm/wallet.js\");\n const balanceCall = encodeBalanceOfCall(\n tokenAddress,\n depositorSigner.address,\n );\n const balanceResult = await depositorSigner.call(balanceCall);\n\n const balance = decodeUint256(balanceResult || \"0x0\");\n if (balance === 0n) {\n throw new Error(\n `No tokens found at depositor address ${depositorSigner.address}. Nothing to recover.`,\n );\n }\n\n // Transfer all tokens to destination\n const transferCall = encodeTransferCall(tokenAddress, destination, balance);\n const txHash = await depositorSigner.sendTransaction(transferCall);\n\n const receipt = await depositorSigner.waitForReceipt(txHash);\n if (receipt.status !== \"success\") {\n throw new Error(`Recovery transaction reverted: ${txHash}`);\n }\n\n return { txHash, amount: balance.toString() };\n }\n\n /**\n * Check if a swap's VTXO has been received on Arkade.\n *\n * For Arkade-destination swaps (EVM/Bitcoin/Lightning → Arkade), queries the\n * Arkade indexer for VTXOs at the `target_arkade_address` and checks if any\n * VTXO's txid matches the Arkade txid that paid the target address.\n *\n * @param swapId - The UUID of the swap\n * @returns `true` if the received Arkade VTXO was found\n */\n async hasReceivedVtxo(swapId: string): Promise<boolean> {\n const swap = await this.getSwap(swapId);\n\n // Extract target_arkade_address and the Arkade-side txid that pays it.\n let targetArkadeAddress: string | undefined;\n let receiveArkadeTxid: string | null | undefined;\n let network: string | undefined;\n\n if (swap.direction === \"evm_to_arkade\") {\n const s = swap as EvmToArkadeSwapResponse & { direction: string };\n targetArkadeAddress = s.target_arkade_address;\n receiveArkadeTxid = s.btc_claim_txid;\n network = s.network;\n } else if (swap.direction === \"btc_to_arkade\") {\n const s = swap as BtcToArkadeSwapResponse & { direction: string };\n targetArkadeAddress = s.target_arkade_address;\n receiveArkadeTxid = s.arkade_claim_txid;\n network = s.network;\n } else if (swap.direction === \"lightning_to_arkade\") {\n const s = swap as LightningToArkadeSwapResponse & { direction: string };\n targetArkadeAddress = s.target_arkade_address;\n receiveArkadeTxid = s.arkade_claim_txid;\n network = s.network;\n } else {\n throw new Error(\n `hasReceivedVtxo only works for Arkade-destination swaps, got ${swap.direction}`,\n );\n }\n\n if (!receiveArkadeTxid) {\n return false;\n }\n\n const { ArkAddress, RestIndexerProvider } = await import(\"@arkade-os/sdk\");\n const { hex } = await import(\"@scure/base\");\n\n const serverUrl = this.#config.arkadeServerUrl;\n if (!serverUrl) {\n throw new Error(`No Arkade server URL for network: ${network}`);\n }\n\n const decoded = ArkAddress.decode(targetArkadeAddress);\n const pkScript = hex.encode(decoded.pkScript);\n const indexer = new RestIndexerProvider(serverUrl);\n\n const { vtxos } = await indexer.getVtxos({\n scripts: [pkScript],\n });\n\n return vtxos.some((v) => v.txid === receiveArkadeTxid);\n }\n}\n\n/**\n * The Lightning payout fields for a continuation: a BOLT11 invoice pins the\n * payout amount itself; a Lightning address or LNURL is paid the refund,\n * minus fees.\n */\nfunction lightningPayoutOf(\n target: string,\n sourceAmount: bigint,\n):\n | { lightningInvoice: string }\n | { lightningAddress: string; sourceAmount: bigint }\n | { lnurl: string; sourceAmount: bigint } {\n const value = target.trim().replace(/^lightning:/i, \"\");\n if (/^ln(bc|tb|bcrt)[0-9]/i.test(value)) return { lightningInvoice: value };\n if (/^lnurl/i.test(value)) return { lnurl: value, sourceAmount };\n if (value.includes(\"@\")) return { lightningAddress: value, sourceAmount };\n throw new Error(\n `\"${target}\" is not a Lightning invoice, Lightning address or LNURL.`,\n );\n}\n","/**\n * Escrow signing utilities for ark-escrow PSBT exchange protocol.\n *\n * Provides helpers for signing escrow release/refund PSBTs from the\n * browser or Node.js. The arbiter (backend) builds and pre-signs the\n * PSBTs; these functions let the counterparty (Bob or Alice) add their\n * signature before the arbiter merges and submits to Arkade.\n *\n * @see https://github.com/ArkEscrow/ark-escrow for the full protocol.\n */\n\nimport { SingleKey, Transaction } from \"@arkade-os/sdk\";\nimport { hex } from \"@scure/base\";\n\n// -- Base64 helpers (browser-safe, no Buffer dependency) --\n\nfunction b64Decode(s: string): Uint8Array {\n const bin = atob(s);\n const arr = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);\n return arr;\n}\n\nfunction b64Encode(u: Uint8Array): string {\n let bin = \"\";\n for (let i = 0; i < u.length; i++) bin += String.fromCharCode(u[i]);\n return btoa(bin);\n}\n\n/** Whether `script` is a P2TR output script (`OP_1 <32-byte key>`). */\nfunction isP2tr(script: Uint8Array | undefined): boolean {\n return script?.length === 34 && script[0] === 0x51 && script[1] === 0x20;\n}\n\n/**\n * Parse an escrow PSBT built by the arbiter.\n *\n * ark-core records the spend script as `witnessScript` on taproot inputs, next\n * to the tapleaf script that actually matters. A strict PSBT parser rejects\n * that (\"witnessScript without P2WSH\"), so the field is dropped from taproot\n * inputs and the result is parsed again with every check on, the taproot\n * commitment check included. Nothing the signer or the arbiter needs is lost:\n * the leaf script, control block and prevout stay, and the arbiter only takes\n * the signatures from what comes back.\n */\nfunction parseEscrowPsbt(psbt: Uint8Array): Transaction {\n const lenient = Transaction.fromPSBT(psbt, { disableScriptCheck: true });\n let stripped = false;\n for (let i = 0; i < lenient.inputsLength; i++) {\n const input = lenient.getInput(i);\n if (input.witnessScript && isP2tr(input.witnessUtxo?.script)) {\n lenient.updateInput(i, { witnessScript: undefined }, true);\n stripped = true;\n }\n }\n return Transaction.fromPSBT(stripped ? lenient.toPSBT() : psbt);\n}\n\n/** Result of signing an escrow ark transaction. */\nexport interface SignedEscrowTx {\n /** The signed PSBT as a base64 string. */\n signedPsbt: string;\n /** The transaction ID (hex) extracted from the PSBT. */\n txid: string;\n}\n\n/**\n * Sign the escrow ark transaction PSBT.\n *\n * The ark_tx is the main offchain transaction spending the escrow VTXO.\n * The signer adds a tapscript Schnorr signature at input index 0.\n *\n * @param psbtB64 - The ark_tx PSBT as a base64 string (from the arbiter).\n * @param secretKey - The signer's secret key (32 bytes or 64-char hex string).\n * @returns The signed PSBT (base64) and the transaction ID (hex).\n */\nexport function signEscrowArkTx(\n psbtB64: string,\n secretKey: Uint8Array | string,\n): SignedEscrowTx {\n const sk = typeof secretKey === \"string\" ? hex.decode(secretKey) : secretKey;\n const tx = parseEscrowPsbt(b64Decode(psbtB64));\n tx.signIdx(sk, 0);\n\n const txId = tx.id as unknown;\n const txid = txId instanceof Uint8Array ? hex.encode(txId) : String(txId);\n\n return {\n signedPsbt: b64Encode(tx.toPSBT()),\n txid,\n };\n}\n\n/**\n * Sign escrow checkpoint PSBTs.\n *\n * Checkpoint transactions are signed after the Arkade server co-signs\n * the ark_tx. Each checkpoint is signed at input index 0.\n *\n * @param psbtB64s - Array of checkpoint PSBTs as base64 strings.\n * @param secretKey - The signer's secret key (32 bytes or 64-char hex string).\n * @returns Array of signed checkpoint PSBTs as base64 strings.\n */\nexport function signEscrowCheckpoints(\n psbtB64s: string[],\n secretKey: Uint8Array | string,\n): string[] {\n const sk = typeof secretKey === \"string\" ? hex.decode(secretKey) : secretKey;\n return psbtB64s.map((cpB64) => {\n const tx = parseEscrowPsbt(b64Decode(cpB64));\n tx.signIdx(sk, 0);\n return b64Encode(tx.toPSBT());\n });\n}\n\n/** Result of signing delegate escrow PSBTs. */\nexport interface SignedEscrowDelegate {\n /** The signed intent proof PSBT as a base64 string. */\n signedIntentProof: string;\n /** The signed forfeit PSBTs as base64 strings. */\n signedForfeitPsbts: string[];\n}\n\n/**\n * Sign delegate escrow PSBTs (intent proof + forfeits).\n *\n * When the escrow VTXO is recoverable, the arbiter prepares delegate PSBTs\n * instead of the normal offchain PSBTs. The intent proof has one \"toSpend\"\n * reference input at index 0 (not signed) plus real VTXO inputs at index 1+.\n * Forfeit PSBTs have a single input each at index 0.\n *\n * The PSBTs already contain the correct sighash types — the signer just adds\n * their tapscript Schnorr signature.\n *\n * @param intentProofB64 - The intent proof PSBT (base64, from the arbiter).\n * @param forfeitPsbtsB64 - Forfeit PSBTs (base64, one per VTXO).\n * @param secretKey - The signer's secret key (32 bytes or 64-char hex).\n * @returns Signed intent proof + signed forfeit PSBTs.\n */\nexport async function signEscrowDelegate(\n intentProofB64: string,\n forfeitPsbtsB64: string[],\n secretKey: Uint8Array | string,\n): Promise<SignedEscrowDelegate> {\n const sk = typeof secretKey === \"string\" ? secretKey : hex.encode(secretKey);\n const signer = SingleKey.fromHex(sk);\n\n // Sign intent proof — SingleKey.sign handles per-input sighash types\n // (input 0 is the toSpend ref, inputs 1+ are VTXOs with SIGHASH_ALL)\n const intent = parseEscrowPsbt(b64Decode(intentProofB64));\n const signedIntent = await signer.sign(intent);\n\n // Sign forfeits — each has a single VTXO input with SIGHASH_ALL|ANYONECANPAY\n const signedForfeits: string[] = [];\n for (const b64 of forfeitPsbtsB64) {\n const forfeit = parseEscrowPsbt(b64Decode(b64));\n const signed = await signer.sign(forfeit);\n signedForfeits.push(b64Encode(signed.toPSBT()));\n }\n\n return {\n signedIntentProof: b64Encode(signedIntent.toPSBT()),\n signedForfeitPsbts: signedForfeits,\n };\n}\n\n/**\n * Extract the transaction ID from an ark_tx PSBT without signing.\n *\n * Useful when you need the txid for the finalize step but already\n * have the signed PSBT from an earlier step.\n *\n * @param psbtB64 - The ark_tx PSBT as a base64 string.\n * @returns The transaction ID as a hex string.\n */\nexport function getArkTxid(psbtB64: string): string {\n const tx = parseEscrowPsbt(b64Decode(psbtB64));\n const txId = tx.id as unknown;\n return txId instanceof Uint8Array ? hex.encode(txId) : String(txId);\n}\n","/**\n * Price calculation utilities for swap amount conversions.\n *\n * This module provides functions to calculate swap amounts using exchange rates.\n * It handles:\n * - Exchange rate inversion for BTC ↔ EVM token swaps\n * - Forward and reverse amount calculations with fee handling\n *\n * @example\n * ```typescript\n * import {\n * computeExchangeRate,\n * calculateTargetAmount,\n * calculateSourceAmount,\n * } from '@lendasat/lendaswap-sdk';\n *\n * // Compute exchange rate with proper inversion\n * const exchangeRate = computeExchangeRate(rate, isSourceBtc, isTargetEvm);\n *\n * // Calculate target amount from source\n * const targetAmount = calculateTargetAmount(100, exchangeRate, 0.0001, false, true);\n *\n * // Calculate source amount needed for target\n * const sourceAmount = calculateSourceAmount(0.01, exchangeRate, 0.0001, false, true);\n * ```\n */\n\n/**\n * Compute the exchange rate with proper inversion handling.\n *\n * The backend sends rates in the format \"BTC per 1 stablecoin\" for ALL pairs.\n * When the source is BTC and target is a stablecoin/EVM token, we need to\n * invert the rate to get \"stablecoin per 1 BTC\".\n *\n * @param rate - The raw rate from the backend (BTC per 1 stablecoin)\n * @param isSourceBtc - Whether the source token is BTC (Lightning, Arkade, or Onchain)\n * @param isTargetEvmToken - Whether the target token is an EVM token (stablecoins, etc.)\n * @returns The exchange rate as \"1 source = X target\"\n *\n * @example\n * ```typescript\n * const btcPerUsdc = 0.000010773; // ~1 BTC = 92,828 USDC\n *\n * // USDC -> BTC: rate stays as-is (BTC per USDC)\n * computeExchangeRate(btcPerUsdc, false, false); // 0.000010773\n *\n * // BTC -> USDC: rate is inverted (USDC per BTC)\n * computeExchangeRate(btcPerUsdc, true, true); // ~92,828\n * ```\n */\nexport function computeExchangeRate(\n rate: number,\n isSourceBtc: boolean,\n isTargetEvmToken: boolean,\n): number {\n // Backend sends same rate for both directions (BTC per stablecoin).\n // When source is BTC and target is EVM token, invert to get \"EVM per BTC\"\n const needsInversion = isSourceBtc && isTargetEvmToken;\n if (needsInversion) {\n return 1 / rate;\n }\n return rate;\n}\n\n/**\n * Calculate the target amount given a source amount.\n * Uses the exchange rate semantics: 1 source = exchangeRate target\n *\n * Fee handling:\n * - If source is BTC: fee is deducted from source before conversion\n * - If target is BTC: fee is deducted from target after conversion\n *\n * @param sourceAmount - Amount of source asset\n * @param exchangeRate - Rate where 1 source = exchangeRate target\n * @param networkFeeInBtc - Network fee in BTC\n * @param isSourceBtc - Whether source is BTC (fee deducted from source before conversion)\n * @param isTargetBtc - Whether target is BTC (fee deducted from target after conversion)\n * @returns Target amount after fees\n *\n * @example\n * ```typescript\n * const networkFee = 0.0001; // 10,000 sats\n *\n * // USDC -> BTC: 1000 USDC at rate 0.000010773\n * // Target = 1000 * 0.000010773 - 0.0001 = 0.010673 BTC\n * calculateTargetAmount(1000, 0.000010773, networkFee, false, true);\n *\n * // BTC -> USDC: 0.01 BTC at rate 92,824\n * // Target = (0.01 - 0.0001) * 92824 = 918.96 USDC\n * calculateTargetAmount(0.01, 92824, networkFee, true, false);\n * ```\n */\nexport function calculateTargetAmount(\n sourceAmount: number,\n exchangeRate: number,\n networkFeeInBtc: number,\n isSourceBtc: boolean,\n isTargetBtc: boolean,\n): number {\n if (isSourceBtc) {\n // Source is BTC: deduct fee from source, then convert\n const sourceAfterFee = sourceAmount - networkFeeInBtc;\n return sourceAfterFee * exchangeRate;\n }\n // Target is BTC: convert first, then deduct fee\n const targetBeforeFee = sourceAmount * exchangeRate;\n return isTargetBtc ? targetBeforeFee - networkFeeInBtc : targetBeforeFee;\n}\n\n/**\n * Calculate the source amount needed to receive a target amount.\n * Uses the exchange rate semantics: 1 source = exchangeRate target\n *\n * Fee handling (reverse of calculateTargetAmount):\n * - If target is BTC: fee is added to target before reverse conversion\n * - If source is BTC: fee is added to source after reverse conversion\n *\n * @param targetAmount - Desired amount of target asset\n * @param exchangeRate - Rate where 1 source = exchangeRate target\n * @param networkFeeInBtc - Network fee in BTC\n * @param isSourceBtc - Whether source is BTC (fee added to required source)\n * @param isTargetBtc - Whether target is BTC (fee added to target before reverse calc)\n * @returns Source amount needed (including fees)\n *\n * @example\n * ```typescript\n * const networkFee = 0.0001; // 10,000 sats\n *\n * // Want 0.01 BTC, paying with USDC at rate 0.000010773\n * // Source = (0.01 + 0.0001) / 0.000010773 = 937.26 USDC\n * calculateSourceAmount(0.01, 0.000010773, networkFee, false, true);\n *\n * // Want 1000 USDC, paying with BTC at rate 92,824\n * // Source = 1000 / 92824 + 0.0001 = 0.01088 BTC\n * calculateSourceAmount(1000, 92824, networkFee, true, false);\n * ```\n */\nexport function calculateSourceAmount(\n targetAmount: number,\n exchangeRate: number,\n networkFeeInBtc: number,\n isSourceBtc: boolean,\n isTargetBtc: boolean,\n): number {\n if (isTargetBtc) {\n // Target is BTC: add fee to target, then reverse convert\n const targetPlusFee = targetAmount + networkFeeInBtc;\n return targetPlusFee / exchangeRate;\n }\n // Source is BTC: reverse convert first, then add fee\n const sourceBeforeFee = targetAmount / exchangeRate;\n return isSourceBtc ? sourceBeforeFee + networkFeeInBtc : sourceBeforeFee;\n}\n","// Making the module version consumable via require - to prohibit\n// multiple occurrancies of the same module in the same app\n// (dual package hazard, https://nodejs.org/api/packages.html#dual-package-hazard)\nimport _Dexie from \"./dist/dexie.js\";\nconst DexieSymbol = Symbol.for(\"Dexie\");\nconst Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = _Dexie);\nif (_Dexie.semVer !== Dexie.semVer) {\n throw new Error(`Two different versions of Dexie loaded in the same app: ${_Dexie.semVer} and ${Dexie.semVer}`);\n}\nconst { liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp, Entity,\n PropModification, replacePrefix, add, remove,\n DexieYProvider } = Dexie;\nexport { liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp, Dexie, Entity,\n PropModification, replacePrefix, add, remove,\n DexieYProvider};\n \nexport default Dexie;\n","/**\n * IndexedDB storage implementation for browser environments using Dexie.\n *\n * This module provides persistent storage using IndexedDB via Dexie,\n * suitable for web browsers and environments that support IndexedDB.\n */\n\nimport Dexie, { type EntityTable } from \"dexie\";\nimport type { GetSwapResponse } from \"../api/client.js\";\nimport type { StoredSwap, SwapStorage, WalletStorage } from \"./index.js\";\n\nconst DB_NAME = \"lendaswap-v3\";\nconst DB_VERSION = 1;\n\n// Legacy (v2) database constants for migration\nconst V2_DB_NAME = \"lendaswap-v2\";\nconst V2_WALLET_STORE = \"wallet\";\nconst V2_WALLET_KEY = \"default\";\n\n// Wallet record type for the database\ninterface WalletRecord {\n key: string;\n value: string | number;\n}\n\n/**\n * Dexie database class for Lendaswap storage.\n *\n * Schema versions:\n * - v1: Initial schema with wallet and swaps tables\n */\nclass LendaswapDatabase extends Dexie {\n wallet!: EntityTable<WalletRecord, \"key\">;\n swaps!: EntityTable<StoredSwap, \"swapId\">;\n\n constructor() {\n super(DB_NAME);\n\n // Version 1: Initial schema\n this.version(DB_VERSION).stores({\n wallet: \"key\",\n swaps: \"swapId\",\n });\n\n // Future migrations would be added here:\n // this.version(2).stores({ ... }).upgrade(tx => { ... });\n }\n}\n\n// Singleton database instance\nlet dbInstance: LendaswapDatabase | null = null;\n\n/**\n * Get the shared database instance.\n */\nfunction getDatabase(): LendaswapDatabase {\n if (!dbInstance) {\n dbInstance = new LendaswapDatabase();\n }\n return dbInstance;\n}\n\n// Wallet storage keys\nconst MNEMONIC_KEY = \"mnemonic\";\nconst KEY_INDEX_KEY = \"keyIndex\";\n\n/**\n * IndexedDB implementation of WalletStorage using Dexie.\n *\n * Provides persistent storage for wallet data in browser environments.\n * Uses the shared \"lendaswap-v3\" database with a \"wallet\" table.\n *\n * @example\n * ```ts\n * const storage = new IdbWalletStorage();\n * await storage.setMnemonic(\"your mnemonic phrase\");\n * ```\n */\nexport class IdbWalletStorage implements WalletStorage {\n readonly #db: LendaswapDatabase;\n #migratedFromLegacy = false;\n\n constructor() {\n this.#db = getDatabase();\n }\n\n /**\n * Whether a legacy (v2) wallet was migrated during this session.\n *\n * When true, the caller should invoke `client.recoverSwaps()` to\n * restore swap history from the server.\n */\n get migratedFromLegacy(): boolean {\n return this.#migratedFromLegacy;\n }\n\n async getMnemonic(): Promise<string | null> {\n const record = await this.#db.wallet.get(MNEMONIC_KEY);\n if (record?.value) {\n return record.value as string;\n }\n\n // No mnemonic in v3 — try migrating from v2 (legacy WASM SDK)\n const v2Wallet = await readV2Wallet();\n if (!v2Wallet?.mnemonic) {\n return null;\n }\n\n // Persist to v3 so this migration only happens once\n await this.setMnemonic(v2Wallet.mnemonic);\n if (v2Wallet.keyIndex > 0) {\n await this.setKeyIndex(v2Wallet.keyIndex);\n }\n this.#migratedFromLegacy = true;\n\n return v2Wallet.mnemonic;\n }\n\n async setMnemonic(mnemonic: string): Promise<void> {\n await this.#db.wallet.put({ key: MNEMONIC_KEY, value: mnemonic });\n }\n\n async getKeyIndex(): Promise<number> {\n const record = await this.#db.wallet.get(KEY_INDEX_KEY);\n return (record?.value as number) ?? 0;\n }\n\n async setKeyIndex(index: number): Promise<void> {\n await this.#db.wallet.put({ key: KEY_INDEX_KEY, value: index });\n }\n\n async incrementKeyIndex(): Promise<number> {\n // Use a transaction to ensure atomicity\n return this.#db.transaction(\"rw\", this.#db.wallet, async () => {\n const record = await this.#db.wallet.get(KEY_INDEX_KEY);\n const current = (record?.value as number) ?? 0;\n await this.#db.wallet.put({ key: KEY_INDEX_KEY, value: current + 1 });\n return current;\n });\n }\n\n async clear(): Promise<void> {\n await this.#db.wallet.clear();\n }\n}\n\n/**\n * IndexedDB implementation of SwapStorage using Dexie.\n *\n * Provides persistent storage for swap data in browser environments.\n * Uses the shared \"lendaswap-v3\" database with a \"swaps\" table.\n *\n * @example\n * ```ts\n * const storage = new IdbSwapStorage();\n * await storage.store({ swapId: \"swap-id\", ... });\n * ```\n */\nexport class IdbSwapStorage implements SwapStorage {\n readonly #db: LendaswapDatabase;\n\n constructor() {\n this.#db = getDatabase();\n }\n\n async get(swapId: string): Promise<StoredSwap | null> {\n const record = await this.#db.swaps.get(swapId);\n return record ?? null;\n }\n\n async store(swap: StoredSwap): Promise<void> {\n await this.#db.swaps.put(swap);\n }\n\n async update(swapId: string, response: GetSwapResponse): Promise<void> {\n await this.#db.transaction(\"rw\", this.#db.swaps, async () => {\n const existing = await this.#db.swaps.get(swapId);\n if (!existing) {\n throw new Error(`Swap not found: ${swapId}`);\n }\n await this.#db.swaps.put({\n ...existing,\n response,\n updatedAt: Date.now(),\n });\n });\n }\n\n async delete(swapId: string): Promise<void> {\n await this.#db.swaps.delete(swapId);\n }\n\n async list(): Promise<string[]> {\n const records = await this.#db.swaps.toArray();\n return records.map((r) => r.swapId);\n }\n\n async getAll(): Promise<StoredSwap[]> {\n return this.#db.swaps.toArray();\n }\n\n async clear(): Promise<void> {\n await this.#db.swaps.clear();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Legacy v2 wallet migration\n// ---------------------------------------------------------------------------\n\ninterface V2WalletData {\n mnemonic: string | null;\n keyIndex: number;\n}\n\n/**\n * Read wallet data from the legacy v2 (WASM SDK) IndexedDB database.\n *\n * The v2 database (\"lendaswap-v2\") stores wallet data as a single object\n * under key \"default\" in the \"wallet\" object store, with fields:\n * - `mnemonic`: string\n * - `key_index`: number\n *\n * Returns null if the v2 database doesn't exist or has no wallet data.\n */\nfunction readV2Wallet(): Promise<V2WalletData | null> {\n return new Promise((resolve) => {\n if (typeof indexedDB === \"undefined\") {\n resolve(null);\n return;\n }\n\n const request = indexedDB.open(V2_DB_NAME);\n\n // If onupgradeneeded fires, the database didn't exist — abort to\n // prevent creating an empty v2 database.\n request.onupgradeneeded = () => {\n request.transaction?.abort();\n };\n\n request.onerror = () => {\n resolve(null);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (!db.objectStoreNames.contains(V2_WALLET_STORE)) {\n db.close();\n resolve(null);\n return;\n }\n\n try {\n const tx = db.transaction(V2_WALLET_STORE, \"readonly\");\n const store = tx.objectStore(V2_WALLET_STORE);\n const getReq = store.get(V2_WALLET_KEY);\n\n getReq.onsuccess = () => {\n db.close();\n const result = getReq.result;\n if (!result) {\n resolve(null);\n return;\n }\n resolve({\n mnemonic: result.mnemonic ?? null,\n keyIndex:\n typeof result.key_index === \"number\" ? result.key_index : 0,\n });\n };\n\n getReq.onerror = () => {\n db.close();\n resolve(null);\n };\n } catch {\n db.close();\n resolve(null);\n }\n };\n });\n}\n\n/**\n * Storage factory for IndexedDB (browser) storage.\n *\n * Creates IDB-backed storage instances that persist data in the browser.\n */\nexport const idbStorageFactory = {\n createWalletStorage: (): WalletStorage => new IdbWalletStorage(),\n createSwapStorage: (): SwapStorage => new IdbSwapStorage(),\n};\n","/**\n * USD price fetching utilities using CoinGecko API.\n *\n * Provides functions to fetch current USD prices for tokens supported by the SDK.\n *\n * @example\n * ```typescript\n * import { getUsdPrices } from '@lendasat/lendaswap-sdk';\n *\n * const prices = await getUsdPrices([\n * { symbol: \"BTC\", chain: \"Lightning\", token_id: \"btc\", name: \"Bitcoin\", decimals: 0 },\n * { symbol: \"USDC\", chain: \"137\", token_id: \"usdc_pol\", name: \"USDC\", decimals: 6 },\n * ]);\n * // prices is a Map<TokenInfo, number | null>\n * ```\n */\n\nimport type { TokenInfo } from \"./api/client.js\";\nimport { createSdkLogger, type Logger, type LogLevel } from \"./logging.js\";\n\nconst COINGECKO_API = \"https://api.coingecko.com/api/v3\";\n\n/**\n * Mapping from lowercase token symbol to CoinGecko coin ID.\n * Symbols are unique per chain, and the CoinGecko ID only depends on the symbol.\n */\nconst SYMBOL_TO_COINGECKO: Record<string, string> = {\n btc: \"bitcoin\",\n usdc: \"usd-coin\",\n usdt: \"tether\",\n usdt0: \"tether\",\n xaut: \"tether-gold\",\n wbtc: \"wrapped-bitcoin\",\n pol: \"matic-network\",\n eth: \"ethereum\",\n};\n\ninterface CoinGeckoSimplePriceResponse {\n [coinId: string]: {\n usd: number;\n };\n}\n\nexport interface GetUsdPricesOptions {\n /** Optional logger sink. Silent by default. */\n logger?: Logger;\n /** Minimum log level to emit. Defaults to `silent`. */\n logLevel?: LogLevel;\n}\n\n/**\n * Get the CoinGecko ID for a token by its symbol.\n *\n * @returns CoinGecko coin ID or null if not supported\n */\nexport function getCoinGeckoId(token: TokenInfo): string | null {\n return SYMBOL_TO_COINGECKO[token.symbol.toLowerCase()] ?? null;\n}\n\n/**\n * Fetch current USD prices for multiple tokens in a single CoinGecko request.\n *\n * @param tokens - Array of TokenInfo objects\n * @returns Array of `{ token, usdPrice }` results in the same order as input\n */\nexport async function getUsdPrices(\n tokens: TokenInfo[],\n options: GetUsdPricesOptions = {},\n): Promise<{ token: TokenInfo; usdPrice: number | null }[]> {\n const logger = createSdkLogger(options).child({\n module: \"usd-price\",\n operation: \"price.fetch_usd\",\n });\n // Resolve unique CoinGecko IDs we need to fetch\n const coinGeckoIds = new Set<string>();\n for (const token of tokens) {\n const id = getCoinGeckoId(token);\n if (id) coinGeckoIds.add(id);\n }\n\n if (coinGeckoIds.size === 0) {\n return tokens.map((token) => ({ token, usdPrice: null }));\n }\n\n const params = new URLSearchParams({\n ids: [...coinGeckoIds].join(\",\"),\n vs_currencies: \"usd\",\n });\n\n try {\n const response = await fetch(`${COINGECKO_API}/simple/price?${params}`);\n\n if (!response.ok) {\n logger.warn({\n event: \"price.coingecko.http_error\",\n message: \"CoinGecko API returned an error response\",\n data: { status: response.status, statusText: response.statusText },\n });\n return tokens.map((token) => ({ token, usdPrice: null }));\n }\n\n const data: CoinGeckoSimplePriceResponse = await response.json();\n\n return tokens.map((token) => {\n const coinGeckoId = getCoinGeckoId(token);\n if (!coinGeckoId) return { token, usdPrice: null };\n\n const priceData = data[coinGeckoId];\n if (!priceData) return { token, usdPrice: null };\n\n return { token, usdPrice: priceData.usd };\n });\n } catch (error) {\n logger.warn({\n event: \"price.coingecko.fetch_failed\",\n message: \"Failed to fetch USD prices from CoinGecko\",\n error,\n });\n return tokens.map((token) => ({ token, usdPrice: null }));\n }\n}\n"]}
|