@arkade-os/swap 0.0.3 → 0.0.4

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/index.d.cts CHANGED
@@ -1,7 +1,152 @@
1
- import { asset, IWallet, arkade, RestIndexerProvider, Transaction, IContractManager, RestArkProvider, VHTLC, Identity } from '@arkade-os/sdk';
2
- import { A as AssetSwapRepository, a as AssetSwap, M as MarketsCacheEntry, R as RfqStatus, b as RfqTransport, O as OnchainHtlc, C as ChainSource, c as ChainUtxo, d as OnchainHtlcPhase } from './rfq-CCAFoFtR.cjs';
3
- export { e as ARKADE_ASSET, f as ARKADE_BTC, g as AddressMismatch, h as AssetSwapFallbackSecrets, i as AssetSwapStatus, B as BTC_ASSET_ID, D as DerivedSwapSecrets, j as DeterministicSigner, H as HtlcUtxo, I as InMemoryAssetSwapRepository, k as InvoiceFacts, L as LIGHTNING_BTC, l as LIGHTNING_RECEIVE_PAIR, m as LIGHTNING_SEND_PAIR, n as MAX_MIN_CONFIRMATIONS, o as MIN_CLAIM_WINDOW_SECONDS, p as MIN_HEADROOM_SECONDS, q as ONCHAIN_BTC, r as ONCHAIN_CLAIM_MARGIN_SECONDS, s as ONCHAIN_DUST_SATS, t as ONCHAIN_ORDER_MARGIN_SECONDS, u as ONCHAIN_RECEIVE_PAIR, v as ONCHAIN_SECONDS_PER_BLOCK, w as ONCHAIN_SEND_PAIR, x as OnchainHtlcParams, y as OnchainNetwork, z as RFQ_PREIMAGE_TAG, E as RFQ_TERMINAL_STATES, F as RefundBlockedReason, G as RefundNotLocallyPossibleError, J as RelaySocket, K as RfqQuote, N as RfqRefusalReason, S as StoredSwapSecrets, P as SwapRefusal, Q as SwapSecrets, T as addAssetSwap, U as adoptSwapDescriptor, V as arkadeSwapRequest, W as assertFundable, X as assertReceivable, Y as awaitOnchainFill, Z as buildHtlcClaim, _ as buildHtlcRefund, $ as buildPreimageMessage, a0 as claimOnchainFill, a1 as classifyOnchainHtlc, a2 as deriveLightningReceive, a3 as deriveOnchainReceive, a4 as deriveOnchainSend, a5 as derivePreimage, a6 as deriveSwapSecrets, a7 as extractPreimage, a8 as getAssetSwaps, a9 as getAssetSwapsOrThrow, aa as httpTransport, ab as isDeterministicSigner, ac as lightningReceiveRequest, ad as lightningSendRequest, ae as lightningSendVtxoScript, af as newPreimage, ag as newRfqId, ah as offerTermsFromQuote, ai as onchainHtlcScript, aj as onchainReceiveRequest, ak as onchainSendRequest, al as paymentHashOf, am as preimageForRfqSecrets, an as randomSwapSecrets, ao as receiveVtxoScript, ap as relayTransport, aq as requestLightningReceive, ar as requestLightningSend, as as requestOnchainReceive, at as requestOnchainSend, au as rfqPair, av as rfqSecretsOfRecord, aw as rfqSecretsToRecord, ax as senderIdentityForRfqSecrets, ay as senderIdentityForSwapRecord, az as senderPubkeyForRfqSecrets, aA as unilateralClaimDelay, aB as unilateralRefundDelay, aC as unilateralRefundWithoutReceiverDelay, aD as updateAssetSwap, aE as updateAssetSwapBestEffort, aF as verifyLockupAddress, aG as verifyReceiveInvoice } from './rfq-CCAFoFtR.cjs';
4
- import { Network, LocalCardInput, DiscoveredMarket, Side, OfferPlan } from '@arkade-os/solver-discovery';
1
+ import { ProvisionedKey, ProvisionedClaimSecret, asset, IWallet, arkade, RestIndexerProvider, Transaction, IContractManager, RestArkProvider, VHTLC, Identity } from '@arkade-os/sdk';
2
+ import { DiscoveredMarket, Network, LocalCardInput, Side, OfferPlan } from '@arkade-os/solver-discovery';
3
+ import { R as RfqStatus, a as RfqTransport, O as OnchainHtlc, C as ChainSource, b as ChainUtxo, c as OnchainHtlcPhase } from './rfq-DjZlesr4.cjs';
4
+ export { A as ARKADE_ASSET, d as ARKADE_BTC, e as AddressMismatch, H as HtlcUtxo, I as InvoiceFacts, L as LIGHTNING_BTC, f as LIGHTNING_RECEIVE_PAIR, g as LIGHTNING_SEND_PAIR, M as MAX_MIN_CONFIRMATIONS, h as MIN_CLAIM_WINDOW_SECONDS, i as MIN_HEADROOM_SECONDS, j as ONCHAIN_BTC, k as ONCHAIN_CLAIM_MARGIN_SECONDS, l as ONCHAIN_DUST_SATS, m as ONCHAIN_ORDER_MARGIN_SECONDS, n as ONCHAIN_RECEIVE_PAIR, o as ONCHAIN_SECONDS_PER_BLOCK, p as ONCHAIN_SEND_PAIR, q as OnchainHtlcParams, r as OnchainNetwork, s as RFQ_TERMINAL_STATES, t as RelaySocket, u as RfqQuote, v as RfqRefusalReason, S as SwapRefusal, w as arkadeSwapRequest, x as assertFundable, y as assertReceivable, z as awaitOnchainFill, B as buildHtlcClaim, D as buildHtlcRefund, E as claimOnchainFill, F as classifyOnchainHtlc, G as deriveLightningReceive, J as deriveOnchainReceive, K as deriveOnchainSend, N as extractPreimage, P as httpTransport, Q as lightningReceiveRequest, T as lightningSendRequest, U as lightningSendVtxoScript, V as newPreimage, W as newRfqId, X as offerTermsFromQuote, Y as onchainHtlcScript, Z as onchainReceiveRequest, _ as onchainSendRequest, $ as paymentHashOf, a0 as receiveVtxoScript, a1 as relayTransport, a2 as requestLightningReceive, a3 as requestLightningSend, a4 as requestOnchainReceive, a5 as requestOnchainSend, a6 as rfqPair, a7 as unilateralClaimDelay, a8 as unilateralRefundDelay, a9 as unilateralRefundWithoutReceiverDelay, aa as verifyLockupAddress, ab as verifyReceiveInvoice } from './rfq-DjZlesr4.cjs';
5
+
6
+ type AssetSwapStatus = "pending" | "cancelling" | "fulfilled" | "cancelled" | "recoverable" | "awaiting_fill" | "claimable" | "claimed" | "refunded_l1";
7
+ /** The sentinel asset id for BTC itself, as opposed to a 68-hex asset id.
8
+ * Lives here with the {@link AssetSwap} fields it describes so the market and
9
+ * restore layers share one spelling instead of re-typing the literal. */
10
+ declare const BTC_ASSET_ID = "btc";
11
+ interface AssetSwap {
12
+ /** Funding txid — the swap's identity. */
13
+ id: string;
14
+ /** 'btc' or a 68-hex asset id. */
15
+ fromAsset: string;
16
+ toAsset: string;
17
+ /** Atomic amounts as strings (bigint is not JSON-safe). */
18
+ fromAmount: string;
19
+ /** The covenant wantAmount — a floor, the fill pays >= this. */
20
+ toAmount: string;
21
+ swapAddress: string;
22
+ /** Hex pkScript of the swap contract — the indexer monitoring key. */
23
+ swapPkScript: string;
24
+ /** TLV offer — needed to rebuild the contract for cancel. */
25
+ offerHex: string;
26
+ fundingTxid: string;
27
+ spentTxid?: string;
28
+ status: AssetSwapStatus;
29
+ createdAt: number;
30
+ completedAt?: number;
31
+ /** RFQ pair string, e.g. `arkade:BTC->onchain:BTC`. */
32
+ pair?: string;
33
+ /** `sha256(P)`, hex. Public, and how a restore confirms a candidate
34
+ * derivation is the right one. */
35
+ paymentHash?: string;
36
+ /**
37
+ * The wallet descriptor this swap's sender key comes from — a fresh HD
38
+ * child, or a static wallet's `tr(pubkey)`. Public — the signer
39
+ * re-derives from the wallet, so the record carries no key material.
40
+ */
41
+ signingDescriptor?: string;
42
+ /** P, hex, when it cannot be re-derived from the seed: the user supplied
43
+ * it, or the descriptor is static (shared across swaps, so a derived
44
+ * preimage would collide). The swap's only claim secret when present. */
45
+ preimageHex?: string;
46
+ /** The L1 HTLC's pkScript, hex — the chain-watch key. */
47
+ htlcPkScriptHex?: string;
48
+ htlcLocktime?: number;
49
+ /** The L1 funding txid, once observed. */
50
+ l1Txid?: string;
51
+ }
52
+ /** All swaps, newest-first. Insertion order is not chronological — the restore
53
+ * scan rebuilds records in tx-scan order — so sort at read to keep
54
+ * newest-first canonical for every consumer. */
55
+ declare const getAssetSwapsOrThrow: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
56
+ /** The consumer read: a broken backend reads as no swaps rather than crashing
57
+ * a history view. Mutations must use {@link getAssetSwapsOrThrow} instead —
58
+ * swallowing the read there would let "the backend is gone" masquerade as "no
59
+ * such swap" and skip the write silently. */
60
+ declare const getAssetSwaps: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
61
+ /** Add a swap; no-op if the id is already stored. Returns the updated list.
62
+ * THROWS on a failed write — nothing irreversible may happen until this record
63
+ * is durable, so the caller must not fund on a failure. */
64
+ declare const addAssetSwap: (repository: AssetSwapRepository, swap: AssetSwap) => Promise<AssetSwap[]>;
65
+ /** Merge changes into a swap by id. Returns the updated list.
66
+ * THROWS on a failed read or write, like {@link addAssetSwap} — use this for a
67
+ * write that gates something irreversible. Transitions written *after* the
68
+ * irreversible act belong on {@link updateAssetSwapBestEffort}. */
69
+ declare const updateAssetSwap: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<AssetSwap[]>;
70
+ /**
71
+ * {@link updateAssetSwap} for transitions that follow an irreversible action (a
72
+ * broadcast claim, a spent lockup): failing the caller there would report as
73
+ * failed a swap whose funds already moved, and a stale status is recoverable —
74
+ * crash recovery re-derives the true state from the chain
75
+ * (`classifyOnchainHtlc`).
76
+ *
77
+ * `persisted` is the part that must not be hidden: a caller that notifies on a
78
+ * change, or treats one as terminal, has to know the store did not agree.
79
+ */
80
+ declare const updateAssetSwapBestEffort: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<{
81
+ swaps: AssetSwap[];
82
+ persisted: boolean;
83
+ }>;
84
+ /**
85
+ * The record fields a wallet-provisioned secret becomes.
86
+ *
87
+ * `signingDescriptor` is public and always stored — it is what recovers the
88
+ * signer. `preimageHex` is stored only when the wallet says it cannot
89
+ * re-derive P, and is then the swap's only claim secret.
90
+ */
91
+ declare const swapSecretsToRecord: (secrets: ProvisionedKey | ProvisionedClaimSecret) => {
92
+ signingDescriptor: string;
93
+ preimageHex?: string;
94
+ };
95
+
96
+ /** A registry discovery result held for reuse. Refetchable — unlike a swap
97
+ * record, losing it costs one network round trip — but it must survive a cold
98
+ * boot: serving it stale is what keeps quoting alive while a registry is down. */
99
+ interface MarketsCacheEntry {
100
+ markets: DiscoveredMarket[];
101
+ fetchedAt: number;
102
+ }
103
+ /**
104
+ * Everything the package persists, following the monorepo repository
105
+ * convention (versioned interface, AsyncDisposable, one backend per
106
+ * platform — see the Boltz plugin's SwapRepository). Consumers construct
107
+ * exactly one of these; there is no second storage seam.
108
+ *
109
+ * Durable records (swaps) and rebuildable state (the restore scan's txid
110
+ * cursor, the markets cache) live side by side because they share a
111
+ * lifetime: all three belong to one wallet on one device, and a consumer
112
+ * that wipes one wants all three gone.
113
+ *
114
+ * ponytail: no query filters — every consumer reads all swaps and filters
115
+ * in memory; mirror the Boltz plugin's GetSwapsFilter when a consumer needs
116
+ * subset queries.
117
+ */
118
+ interface AssetSwapRepository extends AsyncDisposable {
119
+ readonly version: 1;
120
+ /** Insert or replace a swap by id. Store the record whole: `preimageHex`
121
+ * is secret-bearing — the only claim secret of a swap whose descriptor is
122
+ * not per-swap — and a field-mapped backend that drops it leaves the swap
123
+ * unclaimable. */
124
+ saveSwap(swap: AssetSwap): Promise<void>;
125
+ /** All stored swaps, in no particular order — `getAssetSwaps` is the
126
+ * canonical newest-first read. */
127
+ getAllSwaps(): Promise<AssetSwap[]>;
128
+ /** Sent txids already checked for offer packets (see restore.ts). */
129
+ getScannedTxids(): Promise<Set<string>>;
130
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
131
+ /** Cached registry markets, or undefined on a miss. */
132
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
133
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
134
+ clear(): Promise<void>;
135
+ }
136
+ declare class InMemoryAssetSwapRepository implements AssetSwapRepository {
137
+ readonly version: 1;
138
+ private readonly swaps;
139
+ private readonly scanned;
140
+ private readonly markets;
141
+ saveSwap(swap: AssetSwap): Promise<void>;
142
+ getAllSwaps(): Promise<AssetSwap[]>;
143
+ getScannedTxids(): Promise<Set<string>>;
144
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
145
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
146
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
147
+ clear(): Promise<void>;
148
+ [Symbol.asyncDispose](): Promise<void>;
149
+ }
5
150
 
6
151
  /** The contracts — pure data, shared verbatim with any other implementation. */
7
152
  declare const swapPrograms: Record<"wantAsset" | "wantBtc", ReturnType<typeof arkade.parseArtifact>>;
@@ -738,9 +883,12 @@ declare function readLockupFate(indexer: LockupSpendIndexer, input: {
738
883
  */
739
884
  declare function pushRefundWithoutReceiver(ark: RefundArkProvider, input: {
740
885
  script: InstanceType<typeof VHTLC.ScriptV2>;
741
- /** The `sender` signer. Build it from the swap's `secrets` with
742
- * `senderIdentityForRfqSecrets` — on an HD wallet that resolves from
743
- * the seed, with no stored key bytes anywhere. */
886
+ /** The `sender` signer. Build it from the swap record with
887
+ * {@link senderIdentityForSwapRecord} — on an HD wallet that resolves
888
+ * from the seed, with no stored key bytes anywhere, and every way the
889
+ * wallet can fail to produce it arrives as one typed
890
+ * {@link RefundNotLocallyPossibleError} the manager reads as permanent
891
+ * rather than retrying for the rest of the refund window. */
744
892
  sender: Identity;
745
893
  vtxos: readonly LockupVtxo[];
746
894
  /** Defaults to the contract's own committed refund destination. */
@@ -887,7 +1035,7 @@ declare function pushClaim(ark: ClaimArkProvider, input: {
887
1035
  /** The receive-direction covenant (see `receiveVtxoScript`). */
888
1036
  script: InstanceType<typeof VHTLC.ScriptV2>;
889
1037
  /** The trader's `receiver` signer. Build it from the swap's `secrets`
890
- * with `senderIdentityForRfqSecrets` — on an HD wallet that resolves
1038
+ * with `contractSigner` — on an HD wallet that resolves
891
1039
  * from the seed, with no stored key bytes anywhere. */
892
1040
  receiver: Identity;
893
1041
  /** `P`, 32 bytes — the trader generated it at request time. */
@@ -942,6 +1090,50 @@ declare function claimReceiveLockup(indexer: RefundIndexer, ark: ClaimArkProvide
942
1090
  amount: number;
943
1091
  }>;
944
1092
 
1093
+ /**
1094
+ * Why a wallet cannot produce a swap's spending key.
1095
+ *
1096
+ * A swap-lifecycle concern, not a key-provisioning one — which is why it
1097
+ * lives here and not in the SDK: `RfqSwapManager` reads it to decide a refund
1098
+ * is impossible rather than merely failing, and stops grinding against a push
1099
+ * that can never work for the whole refund window.
1100
+ */
1101
+
1102
+ type RefundBlockedReason =
1103
+ /** The record carries no `signingDescriptor`. */
1104
+ "no-secrets"
1105
+ /** The descriptor belongs to another wallet's key. */
1106
+ | "foreign-descriptor"
1107
+ /**
1108
+ * This wallet holds the key but cannot sign with it — a watch-only
1109
+ * identity, or a remote signer that is not attached. Unlike the other two
1110
+ * this can stop being true without changing wallets, so it is worth
1111
+ * telling apart: "attach your signer", not "restore the other wallet".
1112
+ */
1113
+ | "unsignable-wallet";
1114
+ /**
1115
+ * The wallet cannot produce this swap's spending key, so no local refund is
1116
+ * possible: not a failure to retry, a capability this wallet does not have.
1117
+ */
1118
+ declare class RefundNotLocallyPossibleError extends Error {
1119
+ readonly reason: RefundBlockedReason;
1120
+ readonly name = "RefundNotLocallyPossibleError";
1121
+ constructor(reason: RefundBlockedReason, message: string, options?: {
1122
+ cause?: unknown;
1123
+ });
1124
+ }
1125
+ /**
1126
+ * The signer for a swap record's `signingDescriptor`, or a typed refusal.
1127
+ *
1128
+ * **Wire `refundArkade` here, not to `contractSigner` directly.** The SDK
1129
+ * answers about a descriptor; only this knows that a record without one is a
1130
+ * permanent refusal rather than a `TypeError` at the push site — which the
1131
+ * manager would treat as retryable.
1132
+ */
1133
+ declare function senderIdentityForSwapRecord(wallet: IWallet, record: {
1134
+ signingDescriptor?: string;
1135
+ }): Promise<Identity>;
1136
+
945
1137
  /** The contract type a swap lockup registers under. `@arkade-os/sdk`'s handler
946
1138
  * for `VHTLC.ScriptV2` — the covenant script this corridor builds. */
947
1139
  declare const SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
@@ -1737,4 +1929,4 @@ interface RfqSwapOutcome {
1737
1929
  txid?: string;
1738
1930
  }
1739
1931
 
1740
- export { type ArkadeRefundResult, AssetSwap, AssetSwapRepository, ChainSource, ChainUtxo, type ClaimArkProvider, type ClaimPacketInput, type DiscoverMarketsOptions, IndexedDbAssetSwapRepository, type LightningReceiveSwap, type LightningSendSwap, LockupAmountMismatchError, type LockupContractWriter, type LockupFate, LockupNeedsRecoveryError, LockupRegistrationFailed, type LockupSpendIndexer, type LockupVtxo, MarketsCacheEntry, OFFER_PACKET_TYPE, type Offer, type OfferContractRetirer, type OfferSwapWatcher, OnchainHtlc, OnchainHtlcPhase, type OnchainSendAction, type OnchainSendSwap, type PlanError, QUOTE_OPTIONS, REFUND_MTP_LAG_SECONDS, RFQ_RESOLVED_STATES, RFQ_SWAP_TERMINAL_STATES, type RefundArkProvider, type RefundIndexer, type RefundOutcome, type RestoreIndexer, RfqStatus, type RfqSwap, type RfqSwapActionName, type RfqSwapLockup, RfqSwapManager, type RfqSwapManagerCallbacks, type RfqSwapManagerConfig, type RfqSwapManagerDeps, type RfqSwapManagerEvents, type RfqSwapOutcome, type RfqSwapState, RfqTransport, SWAP_LOCKUP_CONTRACT_KIND, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_TYPE, type SealedClaimPacket, type SpendKind, type SwapContractRegistry, type Tx, type WatchOfferSwapsParams, awaitLockupFunding, awaitRfqResolution, cancelOffer, claimReceiveLockup, classifyDepositSpend, classifySpend, createOffer, decodeOffer, discoverMarkets, encodeOffer, findLockupVtxos, findMarket, isRfqSwapTerminal, isRfqTerminal, makeCachedFeedFetch, nextOnchainAction, offerVtxoScript, pushClaim, pushRefundWithoutReceiver, readLockupFate, refundIfUnresolved, registerLockupContract, restoreAssetSwaps, retireSettledOfferContracts, sealClaimPacket, spendTxidsOf, spendUpdate, swapPrograms, validatePlan, watchOfferSwaps };
1932
+ export { type ArkadeRefundResult, type AssetSwap, type AssetSwapRepository, type AssetSwapStatus, BTC_ASSET_ID, ChainSource, ChainUtxo, type ClaimArkProvider, type ClaimPacketInput, type DiscoverMarketsOptions, InMemoryAssetSwapRepository, IndexedDbAssetSwapRepository, type LightningReceiveSwap, type LightningSendSwap, LockupAmountMismatchError, type LockupContractWriter, type LockupFate, LockupNeedsRecoveryError, LockupRegistrationFailed, type LockupSpendIndexer, type LockupVtxo, type MarketsCacheEntry, OFFER_PACKET_TYPE, type Offer, type OfferContractRetirer, type OfferSwapWatcher, OnchainHtlc, OnchainHtlcPhase, type OnchainSendAction, type OnchainSendSwap, type PlanError, QUOTE_OPTIONS, REFUND_MTP_LAG_SECONDS, RFQ_RESOLVED_STATES, RFQ_SWAP_TERMINAL_STATES, type RefundArkProvider, type RefundBlockedReason, type RefundIndexer, RefundNotLocallyPossibleError, type RefundOutcome, type RestoreIndexer, RfqStatus, type RfqSwap, type RfqSwapActionName, type RfqSwapLockup, RfqSwapManager, type RfqSwapManagerCallbacks, type RfqSwapManagerConfig, type RfqSwapManagerDeps, type RfqSwapManagerEvents, type RfqSwapOutcome, type RfqSwapState, RfqTransport, SWAP_LOCKUP_CONTRACT_KIND, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_TYPE, type SealedClaimPacket, type SpendKind, type SwapContractRegistry, type Tx, type WatchOfferSwapsParams, addAssetSwap, awaitLockupFunding, awaitRfqResolution, cancelOffer, claimReceiveLockup, classifyDepositSpend, classifySpend, createOffer, decodeOffer, discoverMarkets, encodeOffer, findLockupVtxos, findMarket, getAssetSwaps, getAssetSwapsOrThrow, isRfqSwapTerminal, isRfqTerminal, makeCachedFeedFetch, nextOnchainAction, offerVtxoScript, pushClaim, pushRefundWithoutReceiver, readLockupFate, refundIfUnresolved, registerLockupContract, restoreAssetSwaps, retireSettledOfferContracts, sealClaimPacket, senderIdentityForSwapRecord, spendTxidsOf, spendUpdate, swapPrograms, swapSecretsToRecord, updateAssetSwap, updateAssetSwapBestEffort, validatePlan, watchOfferSwaps };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,152 @@
1
- import { asset, IWallet, arkade, RestIndexerProvider, Transaction, IContractManager, RestArkProvider, VHTLC, Identity } from '@arkade-os/sdk';
2
- import { A as AssetSwapRepository, a as AssetSwap, M as MarketsCacheEntry, R as RfqStatus, b as RfqTransport, O as OnchainHtlc, C as ChainSource, c as ChainUtxo, d as OnchainHtlcPhase } from './rfq-CCAFoFtR.js';
3
- export { e as ARKADE_ASSET, f as ARKADE_BTC, g as AddressMismatch, h as AssetSwapFallbackSecrets, i as AssetSwapStatus, B as BTC_ASSET_ID, D as DerivedSwapSecrets, j as DeterministicSigner, H as HtlcUtxo, I as InMemoryAssetSwapRepository, k as InvoiceFacts, L as LIGHTNING_BTC, l as LIGHTNING_RECEIVE_PAIR, m as LIGHTNING_SEND_PAIR, n as MAX_MIN_CONFIRMATIONS, o as MIN_CLAIM_WINDOW_SECONDS, p as MIN_HEADROOM_SECONDS, q as ONCHAIN_BTC, r as ONCHAIN_CLAIM_MARGIN_SECONDS, s as ONCHAIN_DUST_SATS, t as ONCHAIN_ORDER_MARGIN_SECONDS, u as ONCHAIN_RECEIVE_PAIR, v as ONCHAIN_SECONDS_PER_BLOCK, w as ONCHAIN_SEND_PAIR, x as OnchainHtlcParams, y as OnchainNetwork, z as RFQ_PREIMAGE_TAG, E as RFQ_TERMINAL_STATES, F as RefundBlockedReason, G as RefundNotLocallyPossibleError, J as RelaySocket, K as RfqQuote, N as RfqRefusalReason, S as StoredSwapSecrets, P as SwapRefusal, Q as SwapSecrets, T as addAssetSwap, U as adoptSwapDescriptor, V as arkadeSwapRequest, W as assertFundable, X as assertReceivable, Y as awaitOnchainFill, Z as buildHtlcClaim, _ as buildHtlcRefund, $ as buildPreimageMessage, a0 as claimOnchainFill, a1 as classifyOnchainHtlc, a2 as deriveLightningReceive, a3 as deriveOnchainReceive, a4 as deriveOnchainSend, a5 as derivePreimage, a6 as deriveSwapSecrets, a7 as extractPreimage, a8 as getAssetSwaps, a9 as getAssetSwapsOrThrow, aa as httpTransport, ab as isDeterministicSigner, ac as lightningReceiveRequest, ad as lightningSendRequest, ae as lightningSendVtxoScript, af as newPreimage, ag as newRfqId, ah as offerTermsFromQuote, ai as onchainHtlcScript, aj as onchainReceiveRequest, ak as onchainSendRequest, al as paymentHashOf, am as preimageForRfqSecrets, an as randomSwapSecrets, ao as receiveVtxoScript, ap as relayTransport, aq as requestLightningReceive, ar as requestLightningSend, as as requestOnchainReceive, at as requestOnchainSend, au as rfqPair, av as rfqSecretsOfRecord, aw as rfqSecretsToRecord, ax as senderIdentityForRfqSecrets, ay as senderIdentityForSwapRecord, az as senderPubkeyForRfqSecrets, aA as unilateralClaimDelay, aB as unilateralRefundDelay, aC as unilateralRefundWithoutReceiverDelay, aD as updateAssetSwap, aE as updateAssetSwapBestEffort, aF as verifyLockupAddress, aG as verifyReceiveInvoice } from './rfq-CCAFoFtR.js';
4
- import { Network, LocalCardInput, DiscoveredMarket, Side, OfferPlan } from '@arkade-os/solver-discovery';
1
+ import { ProvisionedKey, ProvisionedClaimSecret, asset, IWallet, arkade, RestIndexerProvider, Transaction, IContractManager, RestArkProvider, VHTLC, Identity } from '@arkade-os/sdk';
2
+ import { DiscoveredMarket, Network, LocalCardInput, Side, OfferPlan } from '@arkade-os/solver-discovery';
3
+ import { R as RfqStatus, a as RfqTransport, O as OnchainHtlc, C as ChainSource, b as ChainUtxo, c as OnchainHtlcPhase } from './rfq-DjZlesr4.js';
4
+ export { A as ARKADE_ASSET, d as ARKADE_BTC, e as AddressMismatch, H as HtlcUtxo, I as InvoiceFacts, L as LIGHTNING_BTC, f as LIGHTNING_RECEIVE_PAIR, g as LIGHTNING_SEND_PAIR, M as MAX_MIN_CONFIRMATIONS, h as MIN_CLAIM_WINDOW_SECONDS, i as MIN_HEADROOM_SECONDS, j as ONCHAIN_BTC, k as ONCHAIN_CLAIM_MARGIN_SECONDS, l as ONCHAIN_DUST_SATS, m as ONCHAIN_ORDER_MARGIN_SECONDS, n as ONCHAIN_RECEIVE_PAIR, o as ONCHAIN_SECONDS_PER_BLOCK, p as ONCHAIN_SEND_PAIR, q as OnchainHtlcParams, r as OnchainNetwork, s as RFQ_TERMINAL_STATES, t as RelaySocket, u as RfqQuote, v as RfqRefusalReason, S as SwapRefusal, w as arkadeSwapRequest, x as assertFundable, y as assertReceivable, z as awaitOnchainFill, B as buildHtlcClaim, D as buildHtlcRefund, E as claimOnchainFill, F as classifyOnchainHtlc, G as deriveLightningReceive, J as deriveOnchainReceive, K as deriveOnchainSend, N as extractPreimage, P as httpTransport, Q as lightningReceiveRequest, T as lightningSendRequest, U as lightningSendVtxoScript, V as newPreimage, W as newRfqId, X as offerTermsFromQuote, Y as onchainHtlcScript, Z as onchainReceiveRequest, _ as onchainSendRequest, $ as paymentHashOf, a0 as receiveVtxoScript, a1 as relayTransport, a2 as requestLightningReceive, a3 as requestLightningSend, a4 as requestOnchainReceive, a5 as requestOnchainSend, a6 as rfqPair, a7 as unilateralClaimDelay, a8 as unilateralRefundDelay, a9 as unilateralRefundWithoutReceiverDelay, aa as verifyLockupAddress, ab as verifyReceiveInvoice } from './rfq-DjZlesr4.js';
5
+
6
+ type AssetSwapStatus = "pending" | "cancelling" | "fulfilled" | "cancelled" | "recoverable" | "awaiting_fill" | "claimable" | "claimed" | "refunded_l1";
7
+ /** The sentinel asset id for BTC itself, as opposed to a 68-hex asset id.
8
+ * Lives here with the {@link AssetSwap} fields it describes so the market and
9
+ * restore layers share one spelling instead of re-typing the literal. */
10
+ declare const BTC_ASSET_ID = "btc";
11
+ interface AssetSwap {
12
+ /** Funding txid — the swap's identity. */
13
+ id: string;
14
+ /** 'btc' or a 68-hex asset id. */
15
+ fromAsset: string;
16
+ toAsset: string;
17
+ /** Atomic amounts as strings (bigint is not JSON-safe). */
18
+ fromAmount: string;
19
+ /** The covenant wantAmount — a floor, the fill pays >= this. */
20
+ toAmount: string;
21
+ swapAddress: string;
22
+ /** Hex pkScript of the swap contract — the indexer monitoring key. */
23
+ swapPkScript: string;
24
+ /** TLV offer — needed to rebuild the contract for cancel. */
25
+ offerHex: string;
26
+ fundingTxid: string;
27
+ spentTxid?: string;
28
+ status: AssetSwapStatus;
29
+ createdAt: number;
30
+ completedAt?: number;
31
+ /** RFQ pair string, e.g. `arkade:BTC->onchain:BTC`. */
32
+ pair?: string;
33
+ /** `sha256(P)`, hex. Public, and how a restore confirms a candidate
34
+ * derivation is the right one. */
35
+ paymentHash?: string;
36
+ /**
37
+ * The wallet descriptor this swap's sender key comes from — a fresh HD
38
+ * child, or a static wallet's `tr(pubkey)`. Public — the signer
39
+ * re-derives from the wallet, so the record carries no key material.
40
+ */
41
+ signingDescriptor?: string;
42
+ /** P, hex, when it cannot be re-derived from the seed: the user supplied
43
+ * it, or the descriptor is static (shared across swaps, so a derived
44
+ * preimage would collide). The swap's only claim secret when present. */
45
+ preimageHex?: string;
46
+ /** The L1 HTLC's pkScript, hex — the chain-watch key. */
47
+ htlcPkScriptHex?: string;
48
+ htlcLocktime?: number;
49
+ /** The L1 funding txid, once observed. */
50
+ l1Txid?: string;
51
+ }
52
+ /** All swaps, newest-first. Insertion order is not chronological — the restore
53
+ * scan rebuilds records in tx-scan order — so sort at read to keep
54
+ * newest-first canonical for every consumer. */
55
+ declare const getAssetSwapsOrThrow: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
56
+ /** The consumer read: a broken backend reads as no swaps rather than crashing
57
+ * a history view. Mutations must use {@link getAssetSwapsOrThrow} instead —
58
+ * swallowing the read there would let "the backend is gone" masquerade as "no
59
+ * such swap" and skip the write silently. */
60
+ declare const getAssetSwaps: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
61
+ /** Add a swap; no-op if the id is already stored. Returns the updated list.
62
+ * THROWS on a failed write — nothing irreversible may happen until this record
63
+ * is durable, so the caller must not fund on a failure. */
64
+ declare const addAssetSwap: (repository: AssetSwapRepository, swap: AssetSwap) => Promise<AssetSwap[]>;
65
+ /** Merge changes into a swap by id. Returns the updated list.
66
+ * THROWS on a failed read or write, like {@link addAssetSwap} — use this for a
67
+ * write that gates something irreversible. Transitions written *after* the
68
+ * irreversible act belong on {@link updateAssetSwapBestEffort}. */
69
+ declare const updateAssetSwap: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<AssetSwap[]>;
70
+ /**
71
+ * {@link updateAssetSwap} for transitions that follow an irreversible action (a
72
+ * broadcast claim, a spent lockup): failing the caller there would report as
73
+ * failed a swap whose funds already moved, and a stale status is recoverable —
74
+ * crash recovery re-derives the true state from the chain
75
+ * (`classifyOnchainHtlc`).
76
+ *
77
+ * `persisted` is the part that must not be hidden: a caller that notifies on a
78
+ * change, or treats one as terminal, has to know the store did not agree.
79
+ */
80
+ declare const updateAssetSwapBestEffort: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<{
81
+ swaps: AssetSwap[];
82
+ persisted: boolean;
83
+ }>;
84
+ /**
85
+ * The record fields a wallet-provisioned secret becomes.
86
+ *
87
+ * `signingDescriptor` is public and always stored — it is what recovers the
88
+ * signer. `preimageHex` is stored only when the wallet says it cannot
89
+ * re-derive P, and is then the swap's only claim secret.
90
+ */
91
+ declare const swapSecretsToRecord: (secrets: ProvisionedKey | ProvisionedClaimSecret) => {
92
+ signingDescriptor: string;
93
+ preimageHex?: string;
94
+ };
95
+
96
+ /** A registry discovery result held for reuse. Refetchable — unlike a swap
97
+ * record, losing it costs one network round trip — but it must survive a cold
98
+ * boot: serving it stale is what keeps quoting alive while a registry is down. */
99
+ interface MarketsCacheEntry {
100
+ markets: DiscoveredMarket[];
101
+ fetchedAt: number;
102
+ }
103
+ /**
104
+ * Everything the package persists, following the monorepo repository
105
+ * convention (versioned interface, AsyncDisposable, one backend per
106
+ * platform — see the Boltz plugin's SwapRepository). Consumers construct
107
+ * exactly one of these; there is no second storage seam.
108
+ *
109
+ * Durable records (swaps) and rebuildable state (the restore scan's txid
110
+ * cursor, the markets cache) live side by side because they share a
111
+ * lifetime: all three belong to one wallet on one device, and a consumer
112
+ * that wipes one wants all three gone.
113
+ *
114
+ * ponytail: no query filters — every consumer reads all swaps and filters
115
+ * in memory; mirror the Boltz plugin's GetSwapsFilter when a consumer needs
116
+ * subset queries.
117
+ */
118
+ interface AssetSwapRepository extends AsyncDisposable {
119
+ readonly version: 1;
120
+ /** Insert or replace a swap by id. Store the record whole: `preimageHex`
121
+ * is secret-bearing — the only claim secret of a swap whose descriptor is
122
+ * not per-swap — and a field-mapped backend that drops it leaves the swap
123
+ * unclaimable. */
124
+ saveSwap(swap: AssetSwap): Promise<void>;
125
+ /** All stored swaps, in no particular order — `getAssetSwaps` is the
126
+ * canonical newest-first read. */
127
+ getAllSwaps(): Promise<AssetSwap[]>;
128
+ /** Sent txids already checked for offer packets (see restore.ts). */
129
+ getScannedTxids(): Promise<Set<string>>;
130
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
131
+ /** Cached registry markets, or undefined on a miss. */
132
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
133
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
134
+ clear(): Promise<void>;
135
+ }
136
+ declare class InMemoryAssetSwapRepository implements AssetSwapRepository {
137
+ readonly version: 1;
138
+ private readonly swaps;
139
+ private readonly scanned;
140
+ private readonly markets;
141
+ saveSwap(swap: AssetSwap): Promise<void>;
142
+ getAllSwaps(): Promise<AssetSwap[]>;
143
+ getScannedTxids(): Promise<Set<string>>;
144
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
145
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
146
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
147
+ clear(): Promise<void>;
148
+ [Symbol.asyncDispose](): Promise<void>;
149
+ }
5
150
 
6
151
  /** The contracts — pure data, shared verbatim with any other implementation. */
7
152
  declare const swapPrograms: Record<"wantAsset" | "wantBtc", ReturnType<typeof arkade.parseArtifact>>;
@@ -738,9 +883,12 @@ declare function readLockupFate(indexer: LockupSpendIndexer, input: {
738
883
  */
739
884
  declare function pushRefundWithoutReceiver(ark: RefundArkProvider, input: {
740
885
  script: InstanceType<typeof VHTLC.ScriptV2>;
741
- /** The `sender` signer. Build it from the swap's `secrets` with
742
- * `senderIdentityForRfqSecrets` — on an HD wallet that resolves from
743
- * the seed, with no stored key bytes anywhere. */
886
+ /** The `sender` signer. Build it from the swap record with
887
+ * {@link senderIdentityForSwapRecord} — on an HD wallet that resolves
888
+ * from the seed, with no stored key bytes anywhere, and every way the
889
+ * wallet can fail to produce it arrives as one typed
890
+ * {@link RefundNotLocallyPossibleError} the manager reads as permanent
891
+ * rather than retrying for the rest of the refund window. */
744
892
  sender: Identity;
745
893
  vtxos: readonly LockupVtxo[];
746
894
  /** Defaults to the contract's own committed refund destination. */
@@ -887,7 +1035,7 @@ declare function pushClaim(ark: ClaimArkProvider, input: {
887
1035
  /** The receive-direction covenant (see `receiveVtxoScript`). */
888
1036
  script: InstanceType<typeof VHTLC.ScriptV2>;
889
1037
  /** The trader's `receiver` signer. Build it from the swap's `secrets`
890
- * with `senderIdentityForRfqSecrets` — on an HD wallet that resolves
1038
+ * with `contractSigner` — on an HD wallet that resolves
891
1039
  * from the seed, with no stored key bytes anywhere. */
892
1040
  receiver: Identity;
893
1041
  /** `P`, 32 bytes — the trader generated it at request time. */
@@ -942,6 +1090,50 @@ declare function claimReceiveLockup(indexer: RefundIndexer, ark: ClaimArkProvide
942
1090
  amount: number;
943
1091
  }>;
944
1092
 
1093
+ /**
1094
+ * Why a wallet cannot produce a swap's spending key.
1095
+ *
1096
+ * A swap-lifecycle concern, not a key-provisioning one — which is why it
1097
+ * lives here and not in the SDK: `RfqSwapManager` reads it to decide a refund
1098
+ * is impossible rather than merely failing, and stops grinding against a push
1099
+ * that can never work for the whole refund window.
1100
+ */
1101
+
1102
+ type RefundBlockedReason =
1103
+ /** The record carries no `signingDescriptor`. */
1104
+ "no-secrets"
1105
+ /** The descriptor belongs to another wallet's key. */
1106
+ | "foreign-descriptor"
1107
+ /**
1108
+ * This wallet holds the key but cannot sign with it — a watch-only
1109
+ * identity, or a remote signer that is not attached. Unlike the other two
1110
+ * this can stop being true without changing wallets, so it is worth
1111
+ * telling apart: "attach your signer", not "restore the other wallet".
1112
+ */
1113
+ | "unsignable-wallet";
1114
+ /**
1115
+ * The wallet cannot produce this swap's spending key, so no local refund is
1116
+ * possible: not a failure to retry, a capability this wallet does not have.
1117
+ */
1118
+ declare class RefundNotLocallyPossibleError extends Error {
1119
+ readonly reason: RefundBlockedReason;
1120
+ readonly name = "RefundNotLocallyPossibleError";
1121
+ constructor(reason: RefundBlockedReason, message: string, options?: {
1122
+ cause?: unknown;
1123
+ });
1124
+ }
1125
+ /**
1126
+ * The signer for a swap record's `signingDescriptor`, or a typed refusal.
1127
+ *
1128
+ * **Wire `refundArkade` here, not to `contractSigner` directly.** The SDK
1129
+ * answers about a descriptor; only this knows that a record without one is a
1130
+ * permanent refusal rather than a `TypeError` at the push site — which the
1131
+ * manager would treat as retryable.
1132
+ */
1133
+ declare function senderIdentityForSwapRecord(wallet: IWallet, record: {
1134
+ signingDescriptor?: string;
1135
+ }): Promise<Identity>;
1136
+
945
1137
  /** The contract type a swap lockup registers under. `@arkade-os/sdk`'s handler
946
1138
  * for `VHTLC.ScriptV2` — the covenant script this corridor builds. */
947
1139
  declare const SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
@@ -1737,4 +1929,4 @@ interface RfqSwapOutcome {
1737
1929
  txid?: string;
1738
1930
  }
1739
1931
 
1740
- export { type ArkadeRefundResult, AssetSwap, AssetSwapRepository, ChainSource, ChainUtxo, type ClaimArkProvider, type ClaimPacketInput, type DiscoverMarketsOptions, IndexedDbAssetSwapRepository, type LightningReceiveSwap, type LightningSendSwap, LockupAmountMismatchError, type LockupContractWriter, type LockupFate, LockupNeedsRecoveryError, LockupRegistrationFailed, type LockupSpendIndexer, type LockupVtxo, MarketsCacheEntry, OFFER_PACKET_TYPE, type Offer, type OfferContractRetirer, type OfferSwapWatcher, OnchainHtlc, OnchainHtlcPhase, type OnchainSendAction, type OnchainSendSwap, type PlanError, QUOTE_OPTIONS, REFUND_MTP_LAG_SECONDS, RFQ_RESOLVED_STATES, RFQ_SWAP_TERMINAL_STATES, type RefundArkProvider, type RefundIndexer, type RefundOutcome, type RestoreIndexer, RfqStatus, type RfqSwap, type RfqSwapActionName, type RfqSwapLockup, RfqSwapManager, type RfqSwapManagerCallbacks, type RfqSwapManagerConfig, type RfqSwapManagerDeps, type RfqSwapManagerEvents, type RfqSwapOutcome, type RfqSwapState, RfqTransport, SWAP_LOCKUP_CONTRACT_KIND, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_TYPE, type SealedClaimPacket, type SpendKind, type SwapContractRegistry, type Tx, type WatchOfferSwapsParams, awaitLockupFunding, awaitRfqResolution, cancelOffer, claimReceiveLockup, classifyDepositSpend, classifySpend, createOffer, decodeOffer, discoverMarkets, encodeOffer, findLockupVtxos, findMarket, isRfqSwapTerminal, isRfqTerminal, makeCachedFeedFetch, nextOnchainAction, offerVtxoScript, pushClaim, pushRefundWithoutReceiver, readLockupFate, refundIfUnresolved, registerLockupContract, restoreAssetSwaps, retireSettledOfferContracts, sealClaimPacket, spendTxidsOf, spendUpdate, swapPrograms, validatePlan, watchOfferSwaps };
1932
+ export { type ArkadeRefundResult, type AssetSwap, type AssetSwapRepository, type AssetSwapStatus, BTC_ASSET_ID, ChainSource, ChainUtxo, type ClaimArkProvider, type ClaimPacketInput, type DiscoverMarketsOptions, InMemoryAssetSwapRepository, IndexedDbAssetSwapRepository, type LightningReceiveSwap, type LightningSendSwap, LockupAmountMismatchError, type LockupContractWriter, type LockupFate, LockupNeedsRecoveryError, LockupRegistrationFailed, type LockupSpendIndexer, type LockupVtxo, type MarketsCacheEntry, OFFER_PACKET_TYPE, type Offer, type OfferContractRetirer, type OfferSwapWatcher, OnchainHtlc, OnchainHtlcPhase, type OnchainSendAction, type OnchainSendSwap, type PlanError, QUOTE_OPTIONS, REFUND_MTP_LAG_SECONDS, RFQ_RESOLVED_STATES, RFQ_SWAP_TERMINAL_STATES, type RefundArkProvider, type RefundBlockedReason, type RefundIndexer, RefundNotLocallyPossibleError, type RefundOutcome, type RestoreIndexer, RfqStatus, type RfqSwap, type RfqSwapActionName, type RfqSwapLockup, RfqSwapManager, type RfqSwapManagerCallbacks, type RfqSwapManagerConfig, type RfqSwapManagerDeps, type RfqSwapManagerEvents, type RfqSwapOutcome, type RfqSwapState, RfqTransport, SWAP_LOCKUP_CONTRACT_KIND, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_TYPE, type SealedClaimPacket, type SpendKind, type SwapContractRegistry, type Tx, type WatchOfferSwapsParams, addAssetSwap, awaitLockupFunding, awaitRfqResolution, cancelOffer, claimReceiveLockup, classifyDepositSpend, classifySpend, createOffer, decodeOffer, discoverMarkets, encodeOffer, findLockupVtxos, findMarket, getAssetSwaps, getAssetSwapsOrThrow, isRfqSwapTerminal, isRfqTerminal, makeCachedFeedFetch, nextOnchainAction, offerVtxoScript, pushClaim, pushRefundWithoutReceiver, readLockupFate, refundIfUnresolved, registerLockupContract, restoreAssetSwaps, retireSettledOfferContracts, sealClaimPacket, senderIdentityForSwapRecord, spendTxidsOf, spendUpdate, swapPrograms, swapSecretsToRecord, updateAssetSwap, updateAssetSwapBestEffort, validatePlan, watchOfferSwaps };