@arkade-os/swap 0.1.0-rc.13 → 0.1.0-rc.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +11 -0
  2. package/dist/advanced.cjs +1028 -1006
  3. package/dist/advanced.d.cts +145 -279
  4. package/dist/advanced.d.ts +145 -279
  5. package/dist/advanced.js +14 -8
  6. package/dist/{chunk-SC3SAY3X.js → chunk-4WPDXLXH.js} +501 -271
  7. package/dist/chunk-A3SHHRX4.js +104 -0
  8. package/dist/{chunk-KRXPQQJ7.js → chunk-BBP25BWH.js} +198 -218
  9. package/dist/{chunk-ZDFMD4FA.js → chunk-RX3WPV5D.js} +356 -584
  10. package/dist/errors-BcOgFV-F.d.ts +1559 -0
  11. package/dist/errors-n6IHTG-Z.d.cts +1559 -0
  12. package/dist/index.cjs +1406 -1331
  13. package/dist/index.d.cts +69 -186
  14. package/dist/index.d.ts +69 -186
  15. package/dist/index.js +102 -158
  16. package/dist/lockupContract-B_jNbjrG.d.ts +215 -0
  17. package/dist/lockupContract-ZsftgqMc.d.cts +215 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +227 -600
  20. package/dist/node/index.d.ts +227 -600
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +11 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer--1zVkNsV.d.ts +261 -0
  27. package/dist/offer-DsP1q6GE.d.cts +261 -0
  28. package/dist/protocol.cjs +747 -1012
  29. package/dist/protocol.d.cts +120 -255
  30. package/dist/protocol.d.ts +120 -255
  31. package/dist/protocol.js +146 -149
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BY6GUQiW.d.ts +2233 -0
  41. package/dist/repository-C32GKpR5.d.cts +2233 -0
  42. package/dist/{rfq-BWE8qkV2.d.ts → rfq-60PGpQ_x.d.cts} +178 -408
  43. package/dist/{rfq-BWE8qkV2.d.cts → rfq-60PGpQ_x.d.ts} +178 -408
  44. package/dist/{watch-D8Z78RAV.d.ts → watch-Cejw5cNQ.d.cts} +12 -30
  45. package/dist/{watch-C4ReJR5z.d.cts → watch-D8uzWrHc.d.ts} +12 -30
  46. package/package.json +2 -2
  47. package/dist/chunk-U7VWWTL6.js +0 -66
  48. package/dist/errors-LXMcNhNS.d.ts +0 -2222
  49. package/dist/errors-XUs8r0LT.d.cts +0 -2222
  50. package/dist/lockupContract-BhMebZCb.d.cts +0 -650
  51. package/dist/lockupContract-CAiN97fX.d.ts +0 -650
  52. package/dist/repository-BJLuVFQ0.d.ts +0 -3436
  53. package/dist/repository-DsR3b0JJ.d.cts +0 -3436
@@ -0,0 +1,215 @@
1
+ import { RestIndexerProvider, Transaction, VHTLC, IContractManager } from '@arkade-os/sdk';
2
+ import { a as Offer } from './offer-DsP1q6GE.cjs';
3
+ import { e as AssetSwap } from './repository-C32GKpR5.cjs';
4
+
5
+ /**
6
+ * The subset of a wallet transaction record the swap scan reads. No `assets`: see
7
+ * {@link classifySpend} for why a net asset delta cannot classify a spend.
8
+ */
9
+ interface Tx {
10
+ type: string;
11
+ /** The virtual (ark) txid; the funding tx's identity. */
12
+ redeemTxid: string;
13
+ boardingTxid?: string;
14
+ roundTxid?: string;
15
+ /** Unix seconds. */
16
+ createdAt?: number;
17
+ }
18
+ /** The indexer surface the restore scan needs — narrower than a full provider. */
19
+ type RestoreIndexer = Pick<RestIndexerProvider, "getVirtualTxs" | "getVtxos">;
20
+ /**
21
+ * What became of a deposit, as the spending transaction reports it. `indeterminate` is
22
+ * the absence of an answer; the caller decides whether to retry.
23
+ */
24
+ type SpendKind = "cancelled" | "fulfilled" | "indeterminate";
25
+ /**
26
+ * Classify a spend by the covenant leaf it took (a submitted ark tx keeps each input's
27
+ * `tapLeafScript`). `fulfill` is the solver paying; every other leaf returns the deposit.
28
+ * Not by asset movement: once registered, the deposit is the wallet's own coin, so an
29
+ * asset offer's cancel nets to zero exactly like its fill. Leaves also survive batching.
30
+ *
31
+ * **`exit` reports `cancelled`, like `cancel`.** Reporting it `indeterminate` would leave
32
+ * the swap `pending` forever: re-queued every scan, and never retired.
33
+ *
34
+ * **Pass the checkpoint (`vtxo.spentBy`), not the ark tx.** Only the checkpoint spends the
35
+ * deposit outpoint; the ark tx spends the checkpoint's output, so it always yields
36
+ * `indeterminate`. {@link classifyDepositSpend} tries both.
37
+ *
38
+ * @param operatorPubkey - The key the covenant was *funded* against. A rotated key fails
39
+ * the script match and yields `indeterminate` rather than a guess.
40
+ */
41
+ declare function classifySpend(offer: Offer, operatorPubkey: Uint8Array, spendTx: Transaction, deposit: {
42
+ txid: string;
43
+ vout: number;
44
+ }): SpendKind;
45
+ /** The txids that may hold a deposit's spend, checkpoint first (it carries the outpoint). */
46
+ declare const spendTxidsOf: (vtxo: {
47
+ spentBy?: string;
48
+ arkTxId?: string;
49
+ }) => string[];
50
+ /**
51
+ * Classify a deposit's spend across both halves of it (`spentBy` and `arkTxId`, which
52
+ * may be the same id for a settlement), taking the first definite answer.
53
+ */
54
+ declare function classifyDepositSpend(offer: Offer, operatorPubkey: Uint8Array, spendTxs: Iterable<Transaction>, deposit: {
55
+ txid: string;
56
+ vout: number;
57
+ }): SpendKind;
58
+ /**
59
+ * Scan the given candidates for offer packets and rebuild the AssetSwap records the store
60
+ * lost. Returns the rebuilt swaps plus the txids that got an authoritative answer, which
61
+ * the caller persists so they are never fetched again.
62
+ *
63
+ * A spent deposit is classified from its spending tx's covenant leaf
64
+ * ({@link classifySpend}), fetched from the indexer. An unclassifiable spend leaves the
65
+ * funding txid unanswered for a later scan: nothing sticky is written on a guess.
66
+ *
67
+ * @param opts.operatorPubkey - The key the covenants were funded against. A rotated key
68
+ * leaves affected swaps unresolved rather than misclassified.
69
+ */
70
+ declare function restoreAssetSwaps(indexer: RestoreIndexer, txs: Tx[], existingIds: ReadonlySet<string>, opts: {
71
+ operatorPubkey: Uint8Array;
72
+ scanned?: ReadonlySet<string>;
73
+ reopen?: AssetSwap[];
74
+ /** Address prefix; given, a rebuilt record names the covenant's address (#680). */
75
+ hrp?: string;
76
+ }): Promise<{
77
+ restored: AssetSwap[];
78
+ scannedTxids: string[];
79
+ }>;
80
+
81
+ interface SealedClaimPacket {
82
+ /** `ephPub(33) ‖ nonce(12) ‖ ciphertext`, base64 (93 bytes decoded). The legacy
83
+ * `claim_packet` shape: usable only via covclaimd's Reveal API, which silently
84
+ * needs both sides on the SAME covclaimd. Prefer {@link SealedClaimPacket.packet}. */
85
+ ciphertext: string;
86
+ /**
87
+ * covclaimd's serialised `ClaimPacket` body, base64: TLV `0x01` ciphertext and `0x03`
88
+ * covclaimd_pub_key. **This is what `claim_packet` should carry** (§ 7.1.2). The
89
+ * solver stamps it as Arkade extension packet `0x04`; covclaimd filters on `0x03`, so
90
+ * the client alone chooses which covclaimd.
91
+ *
92
+ * `0x02` arkade_script is deliberately absent: the covenant commits to
93
+ * `taggedHash("ArkScriptHash", script)`, so only the funder's copy is guaranteed to
94
+ * match (see {@link appendArkadeScript}); a client-derived one could strand the claim.
95
+ */
96
+ packet: string;
97
+ }
98
+ interface ClaimPacketInput {
99
+ preimage: Uint8Array;
100
+ /** covclaimd's public key, 33-byte compressed (from its /v1 info). */
101
+ covclaimdPubkey: Uint8Array;
102
+ }
103
+ /**
104
+ * Seal a preimage to covclaimd.
105
+ *
106
+ * The ephemeral key and nonce CANNOT be caller-supplied: AES-GCM under a repeated
107
+ * (key, nonce) pair is a total break (forgery and plaintext recovery).
108
+ */
109
+ declare function sealClaimPacket(input: ClaimPacketInput): Promise<SealedClaimPacket>;
110
+ /** `ephPub(33) ‖ nonce(12) ‖ preimage(32) ‖ GCM tag(16)`. Distinguishes the two
111
+ * `claim_packet` shapes: a TLV body carrying it is ≥96 bytes, so lengths cannot collide. */
112
+ declare const SEALED_CIPHERTEXT_LENGTH = 93;
113
+ /** The Arkade extension packet type covclaimd scans the arkd tx stream for. */
114
+ declare const CLAIM_PACKET_TYPE = 4;
115
+ /**
116
+ * Stamp the covenant script into a client's packet — the solver's half.
117
+ *
118
+ * Appending rather than rebuilding is safe: covclaimd's `DeserializeClaim` is
119
+ * order-agnostic, so `0x01, 0x03, 0x02` reads back like its own `0x01, 0x02, 0x03`.
120
+ */
121
+ declare const appendArkadeScript: (body: Uint8Array, arkadeScript: Uint8Array) => Uint8Array;
122
+ type ClaimPacketShape = {
123
+ kind: "ciphertext";
124
+ } | {
125
+ kind: "packet";
126
+ body: Uint8Array;
127
+ covclaimdPubkey?: Uint8Array;
128
+ needsArkadeScript: boolean;
129
+ };
130
+ /**
131
+ * Which of the two `claim_packet` shapes a base64 field carries.
132
+ *
133
+ * Never throws: anything not unambiguously a packet reads as the legacy ciphertext,
134
+ * keeping the Reveal-API path rather than failing a swap over an unfamiliar field.
135
+ */
136
+ declare const claimPacketShape: (b64: string) => ClaimPacketShape;
137
+
138
+ /** The contract type a swap lockup registers under: the SDK's handler for `VHTLC.ScriptV2`.
139
+ *
140
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
141
+ */
142
+ declare const SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
143
+ /** @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`. */
144
+ declare const SWAP_LOCKUP_CONTRACT_LABEL = "Arkade RFQ swap lockup";
145
+ /** @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`. */
146
+ declare const SWAP_LOCKUP_CONTRACT_KIND = "rfq-swap-lockup";
147
+ /** The write seam registration needs; a real `ContractManager` satisfies it.
148
+ *
149
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
150
+ */
151
+ type LockupContractWriter = Pick<IContractManager, "createContract">;
152
+ /** The read seam {@link lockupContractParams} needs.
153
+ *
154
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
155
+ */
156
+ type LockupContractReader = Pick<IContractManager, "getContracts">;
157
+ /**
158
+ * No row for a lockup a record claims was funded. The record is fine and its money may be at the
159
+ * address; the wallet's copy of the covenant is missing (store cleared, or a different store
160
+ * registered it). The remedy is a store, not a re-quote.
161
+ *
162
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
163
+ */
164
+ declare class LockupContractMissing extends Error {
165
+ /** The lockup whose row is absent. */
166
+ readonly address: string;
167
+ /** Its pkScript hex — the key the row would have been under. */
168
+ readonly script: string;
169
+ constructor(address: string, script: string);
170
+ }
171
+ /**
172
+ * The lockup could not be written locally: "the quote is fine and your own store failed", unlike
173
+ * {@link SwapRefusal} / {@link AddressMismatch} ("never fund it"). Thrown by `client.accept()`.
174
+ *
175
+ * Nothing is funded yet and on receive legs the invoice never left, so retrying the request is
176
+ * the recovery. `script` lets a caller still holding the swap retry `registerLockupContract`
177
+ * alone; it is NOT enough to resume a request that threw here (no invoice or `secrets`).
178
+ */
179
+ declare class LockupRegistrationFailed extends Error {
180
+ /** The lockup address that was never registered — never fund it: nothing
181
+ * is watching it. */
182
+ readonly address: string;
183
+ /** The covenant the row would have been written from, so the write is retryable without a
184
+ * quote. */
185
+ readonly script: InstanceType<typeof VHTLC.ScriptV2>;
186
+ constructor(script: InstanceType<typeof VHTLC.ScriptV2>, address: string, cause: unknown);
187
+ }
188
+ /**
189
+ * Register a lockup covenant so its VTXOs are watched and — via `vhtlc-v2`'s handler, never
190
+ * generically spendable — kept out of ordinary coin selection.
191
+ *
192
+ * The row carries script-level facts only: rows are keyed by script and first-writer-wins, so
193
+ * anything per-swap written here is stale from the second swap onward. Taking the derived script
194
+ * means the row cannot describe a script other than its key.
195
+ *
196
+ * @throws {LockupRegistrationFailed} so a caller can tell local storage trouble from a bad quote.
197
+ *
198
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
199
+ */
200
+ declare function registerLockupContract(contracts: LockupContractWriter, script: InstanceType<typeof VHTLC.ScriptV2>, address: string): Promise<void>;
201
+ /**
202
+ * The stored covenant parameters of a funded lockup — the other half of `rebuildRfqSwap`. The row
203
+ * is the wallet's own copy of the tree (`createContract` refuses params that do not reproduce the
204
+ * script), which is why an RFQ swap record stores no tree parameters.
205
+ *
206
+ * Looked up by script, decoded from the address here, so a bad address fails as such rather than
207
+ * as a missing row.
208
+ *
209
+ * @throws {LockupContractMissing} when there is no row.
210
+ *
211
+ * @deprecated Lockup registration is internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
212
+ */
213
+ declare function lockupContractParams(contracts: LockupContractReader, lockupAddress: string): Promise<Record<string, string>>;
214
+
215
+ export { CLAIM_PACKET_TYPE as C, LockupRegistrationFailed as L, type RestoreIndexer as R, SEALED_CIPHERTEXT_LENGTH as S, type Tx as T, type ClaimPacketShape as a, appendArkadeScript as b, claimPacketShape as c, type ClaimPacketInput as d, LockupContractMissing as e, type LockupContractReader as f, type LockupContractWriter as g, SWAP_LOCKUP_CONTRACT_KIND as h, SWAP_LOCKUP_CONTRACT_LABEL as i, SWAP_LOCKUP_CONTRACT_TYPE as j, type SealedClaimPacket as k, type SpendKind as l, classifyDepositSpend as m, classifySpend as n, lockupContractParams as o, restoreAssetSwaps as p, spendTxidsOf as q, registerLockupContract as r, sealClaimPacket as s };
@@ -59,9 +59,16 @@ var import_node_path2 = require("node:path");
59
59
 
60
60
  // src/repositories/sqlite/repository.ts
61
61
  var import_sqlite = require("@arkade-os/sdk/repositories/sqlite");
62
+ var import_sdk2 = require("@arkade-os/sdk");
62
63
 
63
64
  // src/repository.ts
65
+ var import_sdk = require("@arkade-os/sdk");
64
66
  var marketsCacheKey = (network, registry) => `arkade-intents-markets-${network}-${registry}`;
67
+ function assertRfqSwapPageFilter(filter) {
68
+ if (filter.since !== void 0 && (!Number.isSafeInteger(filter.since) || filter.since < 0)) {
69
+ throw new RangeError("RFQ history since must be non-negative Unix seconds");
70
+ }
71
+ }
65
72
 
66
73
  // src/repositories/sqlite/repository.ts
67
74
  var DEFAULT_PREFIX = "arkade_";
@@ -120,6 +127,13 @@ var SQLiteAssetSwapRepository = class {
120
127
  updated_at INTEGER NOT NULL,
121
128
  data TEXT NOT NULL
122
129
  )`);
130
+ await this.db.run(
131
+ `CREATE INDEX IF NOT EXISTS idx_${this.prefix}rfq_updated ON ${this.rfqSwaps} (updated_at, rfq_id)`
132
+ );
133
+ await this.db.run(
134
+ `CREATE INDEX IF NOT EXISTS idx_${this.prefix}rfq_swaps_history ON ${this.rfqSwaps} (state, updated_at, rfq_id)`
135
+ );
136
+ await this.db.run(`DROP INDEX IF EXISTS idx_${this.prefix}rfq_swaps_page`);
123
137
  await this.db.run(
124
138
  `CREATE INDEX IF NOT EXISTS idx_${this.prefix}rfq_swaps_state ON ${this.rfqSwaps} (state)`
125
139
  );
@@ -157,10 +171,8 @@ var SQLiteAssetSwapRepository = class {
157
171
  );
158
172
  });
159
173
  }
160
- async getAllSwaps() {
161
- await this.ensureInit();
162
- const rows = await this.db.all(`SELECT data FROM ${this.swaps}`);
163
- return rows.map((r) => JSON.parse(r.data));
174
+ async getAssetSwapsPage(page) {
175
+ return this.pageTable(this.swaps, "id", page);
164
176
  }
165
177
  async saveRfqSwap(record) {
166
178
  await this.ensureInit();
@@ -180,10 +192,38 @@ var SQLiteAssetSwapRepository = class {
180
192
  );
181
193
  return row ? JSON.parse(row.data) : void 0;
182
194
  }
183
- async getAllRfqSwaps() {
195
+ async getRfqSwapsPage(filter, page) {
196
+ (0, import_sdk2.assertPageRequest)(page);
197
+ assertRfqSwapPageFilter(filter);
184
198
  await this.ensureInit();
185
- const rows = await this.db.all(`SELECT data FROM ${this.rfqSwaps}`);
186
- return rows.map((r) => JSON.parse(r.data));
199
+ const conditions = [];
200
+ const params = [];
201
+ if (filter.state !== void 0) {
202
+ conditions.push("state = ?");
203
+ params.push(filter.state);
204
+ }
205
+ if (filter.since !== void 0) {
206
+ conditions.push("updated_at >= ?");
207
+ params.push(filter.since);
208
+ }
209
+ if (page.after !== void 0) {
210
+ conditions.push("(updated_at, rfq_id) > (?, ?)");
211
+ params.push(page.after.updatedAt, page.after.rfqId);
212
+ }
213
+ const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "";
214
+ const rows = await this.db.all(
215
+ `SELECT data, updated_at, rfq_id FROM ${this.rfqSwaps}${where}
216
+ ORDER BY updated_at, rfq_id LIMIT ?`,
217
+ [...params, page.limit + 1]
218
+ );
219
+ const result = (0, import_sdk2.pageResult)(rows, page.limit, (row) => ({
220
+ updatedAt: row.updated_at,
221
+ rfqId: row.rfq_id
222
+ }));
223
+ return {
224
+ items: result.items.map((row) => JSON.parse(row.data)),
225
+ ...result.nextCursor === void 0 ? {} : { nextCursor: result.nextCursor }
226
+ };
187
227
  }
188
228
  async removeRfqSwap(rfqId) {
189
229
  await this.ensureInit();
@@ -209,10 +249,21 @@ var SQLiteAssetSwapRepository = class {
209
249
  );
210
250
  return row ? JSON.parse(row.data) : void 0;
211
251
  }
212
- async getAllSwapRecords() {
252
+ async getSwapRecordsPage(page) {
253
+ return this.pageTable(this.swapRecords, "id", page);
254
+ }
255
+ async pageTable(table, key, page) {
256
+ (0, import_sdk2.assertPageRequest)(page);
213
257
  await this.ensureInit();
214
- const rows = await this.db.all(`SELECT data FROM ${this.swapRecords}`);
215
- return rows.map((r) => JSON.parse(r.data));
258
+ const rows = await this.db.all(
259
+ page.after === void 0 ? `SELECT ${key} AS key, data FROM ${table} ORDER BY ${key} LIMIT ?` : `SELECT ${key} AS key, data FROM ${table} WHERE ${key} > ? ORDER BY ${key} LIMIT ?`,
260
+ page.after === void 0 ? [page.limit + 1] : [page.after, page.limit + 1]
261
+ );
262
+ const result = (0, import_sdk2.pageResult)(rows, page.limit, (row) => row.key);
263
+ return {
264
+ items: result.items.map((row) => JSON.parse(row.data)),
265
+ ...result.nextCursor === void 0 ? {} : { nextCursor: result.nextCursor }
266
+ };
216
267
  }
217
268
  async removeSwapRecord(id) {
218
269
  await this.ensureInit();