@arkade-os/swap 0.1.0-rc.9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +261 -252
  2. package/dist/advanced.cjs +6376 -3097
  3. package/dist/advanced.d.cts +325 -282
  4. package/dist/advanced.d.ts +325 -282
  5. package/dist/advanced.js +343 -34
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-FMRAV77W.js +3065 -0
  8. package/dist/{chunk-NS3K6BZG.js → chunk-HRMWBULL.js} +1746 -628
  9. package/dist/chunk-WKJFXXSR.js +3382 -0
  10. package/dist/index.cjs +6809 -3915
  11. package/dist/index.d.cts +71 -243
  12. package/dist/index.d.ts +71 -243
  13. package/dist/index.js +131 -167
  14. package/dist/lockupContract-D7BNjksX.d.ts +148 -0
  15. package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
  16. package/dist/node/index.cjs +61 -10
  17. package/dist/node/index.d.cts +307 -635
  18. package/dist/node/index.d.ts +307 -635
  19. package/dist/node/index.js +65 -10
  20. package/dist/nostr.cjs +427 -49
  21. package/dist/nostr.d.cts +59 -70
  22. package/dist/nostr.d.ts +59 -70
  23. package/dist/nostr.js +268 -36
  24. package/dist/offer-CcJfx5Fj.d.cts +269 -0
  25. package/dist/offer-DdB1M6FZ.d.ts +269 -0
  26. package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
  27. package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
  28. package/dist/protocol.cjs +5650 -4280
  29. package/dist/protocol.d.cts +258 -328
  30. package/dist/protocol.d.ts +258 -328
  31. package/dist/protocol.js +200 -224
  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-DmPzpbd7.d.ts +2342 -0
  41. package/dist/repository-DqdLVrVv.d.cts +2342 -0
  42. package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
  43. package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
  44. package/dist/watch-BonYT9af.d.cts +74 -0
  45. package/dist/watch-CmJQDtsy.d.ts +74 -0
  46. package/package.json +10 -10
  47. package/dist/chunk-JFKGMPMH.js +0 -3456
  48. package/dist/chunk-LLG7RD2T.js +0 -1499
  49. package/dist/chunk-U7VWWTL6.js +0 -66
  50. package/dist/errors-CNISbN0M.d.ts +0 -2218
  51. package/dist/errors-DwNhIP0N.d.cts +0 -2218
  52. package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
  53. package/dist/lockupContract-mIt4syse.d.cts +0 -664
  54. package/dist/repository-CGPLbjBe.d.ts +0 -3489
  55. package/dist/repository-DSGGq0ct.d.cts +0 -3489
  56. package/dist/watch-DWyVqyEN.d.cts +0 -96
  57. package/dist/watch-DmvHNX6T.d.ts +0 -96
package/dist/nostr.js CHANGED
@@ -1,19 +1,154 @@
1
1
  import {
2
2
  expectQuote,
3
3
  pairOf
4
- } from "./chunk-LLG7RD2T.js";
4
+ } from "./chunk-FMRAV77W.js";
5
+ import "./chunk-A3SHHRX4.js";
5
6
 
6
7
  // src/nostr.ts
8
+ import {
9
+ SOLVER_CARD_KIND
10
+ } from "@arkade-os/solver-discovery";
11
+
12
+ // src/nostrPool.ts
13
+ import { SimplePool } from "nostr-tools";
14
+ import { normalizeURL } from "nostr-tools/utils";
15
+
16
+ // src/closeOnceWebSocket.ts
17
+ var CloseOnceWebSocket = typeof WebSocket === "undefined" ? void 0 : class CloseOnceWebSocket2 extends WebSocket {
18
+ #closed = false;
19
+ close(code, reason) {
20
+ if (this.#closed) return;
21
+ this.#closed = true;
22
+ super.close(code, reason);
23
+ }
24
+ };
25
+
26
+ // src/nostrPool.ts
27
+ var shared;
28
+ var IDLE_CLOSE_MS = 3e4;
29
+ var NEVER_IDLE_MS = 2 ** 31 - 1;
30
+ var PUBLISH_TIMED_OUT = "publish timed out";
31
+ var POOL_DESTROYED = "nostr pool destroyed";
32
+ var urlKey = (url) => {
33
+ try {
34
+ return normalizeURL(url);
35
+ } catch {
36
+ return url;
37
+ }
38
+ };
39
+ var SharedPool = class extends SimplePool {
40
+ #users = /* @__PURE__ */ new Map();
41
+ #idle = /* @__PURE__ */ new Map();
42
+ #destroyed = false;
43
+ /** Count one user on each relay; the returned release is idempotent. */
44
+ #hold(urls) {
45
+ const held = [...new Set(urls.map(urlKey))];
46
+ for (const url of held) {
47
+ clearTimeout(this.#idle.get(url));
48
+ this.#idle.delete(url);
49
+ this.#users.set(url, (this.#users.get(url) ?? 0) + 1);
50
+ }
51
+ let released = false;
52
+ return () => {
53
+ if (released) return;
54
+ released = true;
55
+ for (const url of held) {
56
+ const left = (this.#users.get(url) ?? 1) - 1;
57
+ if (left > 0) {
58
+ this.#users.set(url, left);
59
+ continue;
60
+ }
61
+ this.#users.delete(url);
62
+ const timer = setTimeout(() => {
63
+ this.#idle.delete(url);
64
+ if (!this.#users.has(url)) this.close([url]);
65
+ }, IDLE_CLOSE_MS);
66
+ timer.unref?.();
67
+ this.#idle.set(url, timer);
68
+ }
69
+ };
70
+ }
71
+ /**
72
+ * A destroyed pool would otherwise reconnect for anyone still holding it (a transport that
73
+ * outlived closeSharedNostrPool()), opening a socket no one can close. Refused here, a
74
+ * subscription reports every relay lost and a publish a connection failure.
75
+ */
76
+ async ensureRelay(...args) {
77
+ if (this.#destroyed) throw new Error(POOL_DESTROYED);
78
+ return super.ensureRelay(...args);
79
+ }
80
+ subscribeMap(...[requests, params]) {
81
+ const release = this.#hold(requests.map((request) => request.url));
82
+ const closer = super.subscribeMap(requests, {
83
+ ...params,
84
+ // Every relay dropped it: nothing is left to hold the sockets for.
85
+ onclose: (reasons) => {
86
+ release();
87
+ params.onclose?.(reasons);
88
+ }
89
+ });
90
+ let closed = false;
91
+ return {
92
+ close: (reason) => {
93
+ if (closed) return;
94
+ closed = true;
95
+ release();
96
+ closer.close(reason);
97
+ }
98
+ };
99
+ }
100
+ publish(...[relays, event, params]) {
101
+ const release = this.#hold(relays);
102
+ const sent = super.publish(relays, event, params);
103
+ sent.forEach((publish, i) => {
104
+ publish.catch((error) => {
105
+ if (error instanceof Error && error.message === PUBLISH_TIMED_OUT)
106
+ this.close([relays[i]]);
107
+ });
108
+ });
109
+ void Promise.allSettled(sent).then(release);
110
+ return sent;
111
+ }
112
+ destroy() {
113
+ this.#destroyed = true;
114
+ for (const timer of this.#idle.values()) clearTimeout(timer);
115
+ this.#idle.clear();
116
+ this.#users.clear();
117
+ super.destroy();
118
+ }
119
+ };
120
+ var createNostrPool = () => (
121
+ // SimplePool forwards every option at runtime; its declared options just omit most of them.
122
+ new SharedPool({
123
+ enablePing: true,
124
+ idleTimeout: NEVER_IDLE_MS,
125
+ ...CloseOnceWebSocket ? { websocketImplementation: CloseOnceWebSocket } : {}
126
+ })
127
+ );
128
+ var sharedNostrPool = () => shared ??= createNostrPool();
129
+ var closeSharedNostrPool = () => {
130
+ const pool = shared;
131
+ shared = void 0;
132
+ if (!pool) return;
133
+ try {
134
+ pool.destroy();
135
+ } catch {
136
+ }
137
+ };
138
+
139
+ // src/nostr.ts
140
+ import { assertTimerMs } from "@arkade-os/sdk";
7
141
  import {
8
142
  finalizeEvent,
9
143
  generateSecretKey,
10
144
  getPublicKey,
11
145
  nip44,
12
- SimplePool
146
+ verifyEvent
13
147
  } from "nostr-tools";
14
148
  var RFQ_DIRECTED_KIND = 24859;
15
- var RFQ_AD_KIND = 38859;
16
149
  var DEFAULT_TIMEOUT_MS = 3e4;
150
+ var CONNECTION_FAILURE = "connection failure";
151
+ var CARD_FETCH_TIMEOUT_MS = 5e3;
17
152
  var RelayUnavailable = class extends Error {
18
153
  reasons;
19
154
  constructor(reasons) {
@@ -34,15 +169,16 @@ var closeReasons = (raw) => raw.map((entry) => {
34
169
  return url ? `${url}: ${reason ?? "closed"}` : reason ?? "closed";
35
170
  });
36
171
  var nostrRfqTransport = (options) => {
172
+ assertTimerMs("timeoutMs", options.timeoutMs);
37
173
  const relays = options.relays;
38
174
  const solverPubkey = options.solverPubkey;
39
175
  const secretKey = options.secretKey ?? generateSecretKey();
40
176
  const pubkey = getPublicKey(secretKey);
41
- const pool = options.pool ?? new SimplePool();
42
- const ownsPool = !options.pool;
177
+ const pool = options.pool ?? sharedNostrPool();
43
178
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
44
179
  const conversationKey = nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
45
180
  let closed = false;
181
+ let lost;
46
182
  const waiters = /* @__PURE__ */ new Map();
47
183
  const subscription = pool.subscribeMany(
48
184
  relays,
@@ -59,12 +195,11 @@ var nostrRfqTransport = (options) => {
59
195
  if (!rfqId) return;
60
196
  waiters.get(rfqId)?.resolve(payload);
61
197
  },
62
- // subscribeMany calls this once every relay has closed. Nothing will
63
- // arrive after it, so failing now beats waiting out the timeout — and
64
- // it names the real cause instead of implicating the solver.
198
+ // Called once every relay has closed: fail now with the real cause, not at timeout.
65
199
  onclose(reasons) {
66
200
  if (closed) return;
67
201
  const error = new RelayUnavailable(closeReasons(reasons));
202
+ lost = error;
68
203
  for (const waiter of waiters.values()) waiter.reject(error);
69
204
  waiters.clear();
70
205
  }
@@ -81,55 +216,152 @@ var nostrRfqTransport = (options) => {
81
216
  secretKey
82
217
  );
83
218
  const results = await Promise.allSettled(pool.publish(relays, event));
84
- if (!results.some((r) => r.status === "fulfilled")) {
85
- throw new Error("no relay accepted the RFQ message");
86
- }
219
+ const reasons = results.map(
220
+ (r) => r.status === "rejected" ? String(r.reason) : String(r.value)
221
+ );
222
+ const accepted = results.some(
223
+ (r) => r.status === "fulfilled" && !String(r.value).startsWith(CONNECTION_FAILURE)
224
+ );
225
+ if (!accepted) throw new Error(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
87
226
  };
88
- const awaitReply = (rfqId) => new Promise((resolve, reject) => {
89
- const timer = setTimeout(() => {
90
- waiters.delete(rfqId);
91
- reject(new Error(`no solver reply within ${timeoutMs}ms`));
92
- }, timeoutMs);
93
- waiters.set(rfqId, {
94
- resolve: (payload) => {
95
- clearTimeout(timer);
96
- waiters.delete(rfqId);
97
- resolve(payload);
98
- },
99
- reject: (error) => {
100
- clearTimeout(timer);
227
+ const awaitReply = (rfqId) => {
228
+ const reply = new Promise((resolve, reject) => {
229
+ const timer = setTimeout(() => {
101
230
  waiters.delete(rfqId);
102
- reject(error);
103
- }
231
+ reject(new Error(`no solver reply within ${timeoutMs}ms`));
232
+ }, timeoutMs);
233
+ waiters.set(rfqId, {
234
+ resolve: (payload) => {
235
+ clearTimeout(timer);
236
+ waiters.delete(rfqId);
237
+ resolve(payload);
238
+ },
239
+ reject: (error) => {
240
+ clearTimeout(timer);
241
+ waiters.delete(rfqId);
242
+ reject(error);
243
+ }
244
+ });
104
245
  });
105
- });
246
+ reply.catch(() => {
247
+ });
248
+ return reply;
249
+ };
250
+ const ask = async (rfqId, payload) => {
251
+ if (closed) throw new TransportClosed();
252
+ if (lost) throw lost;
253
+ const reply = awaitReply(rfqId);
254
+ try {
255
+ await send(payload);
256
+ } catch (error) {
257
+ waiters.get(rfqId)?.reject(error);
258
+ throw error;
259
+ }
260
+ return reply;
261
+ };
106
262
  return {
107
263
  async requestQuote(payload) {
108
264
  const rfqId = String(payload.rfq_id);
109
- const reply = awaitReply(rfqId);
110
- await send(payload);
111
- return expectQuote(await reply, rfqId, pairOf(payload));
265
+ return expectQuote(await ask(rfqId, payload), rfqId, pairOf(payload));
112
266
  },
113
267
  async status(rfqId) {
114
- const reply = awaitReply(rfqId);
115
- await send({ v: 1, type: "rfq_status_request", rfq_id: rfqId });
268
+ const reply = ask(rfqId, { v: 1, type: "rfq_status_request", rfq_id: rfqId });
116
269
  const payload = await reply;
117
270
  if (payload?.type !== "rfq_status") return null;
118
271
  return payload;
119
272
  },
120
273
  async close() {
274
+ if (closed) return;
121
275
  closed = true;
122
276
  for (const waiter of waiters.values()) waiter.reject(new TransportClosed());
123
277
  waiters.clear();
124
- if (ownsPool) pool.close(relays);
125
- else subscription.close();
278
+ subscription.close();
279
+ }
280
+ };
281
+ };
282
+ var isNewer = (event, held) => !held || event.created_at > held.created_at || event.created_at === held.created_at && event.id < held.id;
283
+ var nostrCardFetcher = (options = {}) => {
284
+ assertTimerMs("timeoutMs", options.timeoutMs);
285
+ if (options.timeoutMs === 0) throw new Error("timeoutMs must be positive");
286
+ const seen = /* @__PURE__ */ new Map();
287
+ const inflight = /* @__PURE__ */ new Map();
288
+ return {
289
+ async fetch(solvers, network) {
290
+ const asked = new Set(solvers.map((solver) => solver.discovery_pubkey));
291
+ const authors = [...asked];
292
+ const relays = [
293
+ ...new Set(solvers.flatMap((solver) => solver.transports?.nostr?.relays ?? []))
294
+ ];
295
+ if (authors.length === 0 || relays.length === 0) return [];
296
+ const key = `${network}:${[...asked].sort().join(",")}@${[...relays].sort().join(",")}`;
297
+ const pending = inflight.get(key);
298
+ if (pending) return pending;
299
+ const task = (async () => {
300
+ const timeoutMs = options.timeoutMs ?? CARD_FETCH_TIMEOUT_MS;
301
+ const pool = options.pool ?? sharedNostrPool();
302
+ const latest = /* @__PURE__ */ new Map();
303
+ let subscription;
304
+ let timer;
305
+ try {
306
+ await new Promise((resolve) => {
307
+ timer = setTimeout(resolve, timeoutMs);
308
+ subscription = pool.subscribeMany(
309
+ relays,
310
+ { kinds: [SOLVER_CARD_KIND], authors, "#d": [network] },
311
+ {
312
+ // Relays are untrusted: re-check the filter and the signature, so a stray
313
+ // or forged later event cannot shadow the real card.
314
+ onevent(event) {
315
+ if (event.kind !== SOLVER_CARD_KIND || !asked.has(event.pubkey))
316
+ return;
317
+ if (!verifyEvent(event)) return;
318
+ if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
319
+ return;
320
+ if (isNewer(event, latest.get(event.pubkey)))
321
+ latest.set(event.pubkey, event);
322
+ },
323
+ oneose: () => resolve(),
324
+ onclose: () => resolve()
325
+ }
326
+ );
327
+ });
328
+ } finally {
329
+ clearTimeout(timer);
330
+ subscription?.close();
331
+ }
332
+ for (const author of authors) {
333
+ const seenKey = `${network}:${author}`;
334
+ const event = latest.get(author);
335
+ if (event && isNewer(event, seen.get(seenKey))) seen.set(seenKey, event);
336
+ const best = seen.get(seenKey);
337
+ if (best) latest.set(author, best);
338
+ }
339
+ const cards = [];
340
+ for (const event of latest.values()) {
341
+ try {
342
+ const card = JSON.parse(event.content);
343
+ cards.push({ pubkey: event.pubkey, createdAt: event.created_at, card });
344
+ } catch {
345
+ }
346
+ }
347
+ return cards;
348
+ })();
349
+ inflight.set(key, task);
350
+ try {
351
+ return await task;
352
+ } finally {
353
+ if (inflight.get(key) === task) inflight.delete(key);
354
+ }
126
355
  }
127
356
  };
128
357
  };
129
358
  export {
130
- RFQ_AD_KIND,
131
359
  RFQ_DIRECTED_KIND,
132
360
  RelayUnavailable,
133
361
  TransportClosed,
134
- nostrRfqTransport
362
+ closeSharedNostrPool,
363
+ createNostrPool,
364
+ nostrCardFetcher,
365
+ nostrRfqTransport,
366
+ sharedNostrPool
135
367
  };
@@ -0,0 +1,269 @@
1
+ import { asset, RelativeTimelock, ArkadeInfo, ArkTxInput, Outpoint, IWallet, EmulatorProvider, arkade } from '@arkade-os/sdk';
2
+ import { d as AssetSwapRepository } from './repository-DqdLVrVv.cjs';
3
+
4
+ /**
5
+ * Coverage: whether an offer's script is in the wallet's watched set. `createOffer` promotes; the
6
+ * watcher and restore consumer retire. Identical offers share one script, so a late demotion would
7
+ * unwatch an address the user was just told to fund. Guards: per-script serialization (the watch
8
+ * state is a read-modify-write), and an issuance mark for created-but-unfunded offers, which have no
9
+ * record yet. The mark is per process; the restore scan backstops other contexts and restarts.
10
+ */
11
+
12
+ interface CoverageRegistrationOptions {
13
+ readonly coverageId?: string;
14
+ /** Use the wallet object: a worker can return a fresh manager proxy on every call. */
15
+ readonly scope?: object;
16
+ }
17
+
18
+ /**
19
+ * The contracts, one per WANT side — pure data, shared verbatim with any other implementation.
20
+ *
21
+ * An offer carrying an exit delay compiles a third closure that is in neither file (see
22
+ * {@link withExitClosure}); the golden in `offer.test.ts` pins the artifact it produces.
23
+ *
24
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
25
+ */
26
+ declare const swapPrograms: Record<"wantAsset" | "wantBtc", ReturnType<typeof arkade.parseArtifact>>;
27
+ /** A full-fill offer. Exactly one field names an asset: `wantAsset` = the fill must deliver that
28
+ * asset (the deposit is whatever the funding vtxo holds); `offerAsset` = the user deposits that
29
+ * asset and wants sats.
30
+ *
31
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
32
+ */
33
+ interface Offer {
34
+ /** The scriptPubKey of the swap contract. */
35
+ swapPkScript: Uint8Array;
36
+ /** Amount the user wants (asset units, or sats when wanting BTC). */
37
+ wantAmount: bigint;
38
+ /** The asset the user wants. Omitted when wanting BTC. */
39
+ wantAsset?: asset.AssetId;
40
+ /** The asset the user deposits. Omitted when depositing BTC. */
41
+ offerAsset?: asset.AssetId;
42
+ /** Maker's taproot scriptPubKey (34 bytes) — where the fill must pay. */
43
+ makerPkScript: Uint8Array;
44
+ /** Maker's x-only key (32 bytes) — the cancel path's `user` signer. */
45
+ makerPublicKey: Uint8Array;
46
+ /** Covenant co-signer (emulator) x-only key (32 bytes). */
47
+ emulatorPubkey: Uint8Array;
48
+ /** Partial-fill numerator. Reserved wire space in V1: carried through the
49
+ * codec so an offer that sets it decodes, never interpreted here. */
50
+ ratioNum?: bigint;
51
+ /** Partial-fill denominator. Set with {@link Offer.ratioNum} or not at all. */
52
+ ratioDen?: bigint;
53
+ /** The maker's unilateral exit path. Present adds a third closure to the
54
+ * taproot tree, so it changes `swapPkScript` — see {@link offerVtxoScript}. */
55
+ exitDelay?: RelativeTimelock;
56
+ }
57
+ /** Compile the offer's contract: program + args -> taproot tree.
58
+ *
59
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
60
+ */
61
+ declare function offerContract(offer: Omit<Offer, "swapPkScript">, operatorPubkey: Uint8Array): InstanceType<typeof arkade.ArkadeProgramScript>;
62
+ /** Extension packet type tag for Arkade Intents offers.
63
+ *
64
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
65
+ */
66
+ declare const OFFER_PACKET_TYPE = 3;
67
+ /** Serialize an offer to TLV bytes (the packet payload).
68
+ *
69
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
70
+ */
71
+ declare function encodeOffer(offer: Offer): Uint8Array;
72
+ /** Parse TLV bytes into an offer. Throws on malformed or unknown records.
73
+ *
74
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
75
+ */
76
+ declare function decodeOffer(data: Uint8Array): Offer;
77
+ /**
78
+ * Build a new offer for `wallet` (the user). Fund `address` with the side
79
+ * you deposit, embedding the returned extension, and the solver does the rest:
80
+ *
81
+ * // BTC -> asset
82
+ * const o = await createOffer(wallet, { wantAmount: 1000n, wantAsset })
83
+ * await wallet.send({ address: o.address, amount: 1000, extensions: [o.extension] })
84
+ *
85
+ * // asset -> BTC (the sats are the VTXO carrier for the asset)
86
+ * const o = await createOffer(wallet, { wantAmount: 1000n, offerAsset })
87
+ * await wallet.send({ address: o.address, amount: 500,
88
+ * assets: [{ assetId, amount: 1000n }],
89
+ * extensions: [o.extension] })
90
+ *
91
+ * Broadcasts nothing, but registers the covenant before returning the address: a failure now is
92
+ * retryable, whereas after `wallet.send` it would leave a funded deposit unwatched. The unilateral
93
+ * exit closure is built by default (server's `unilateralExitDelay`, as solverd does); without it only
94
+ * the server-co-signed `cancel` gets the deposit out, and an offer never expires.
95
+ *
96
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
97
+ */
98
+ declare function createOffer(wallet: IWallet, params: OfferParams, options?: CoverageRegistrationOptions): Promise<{
99
+ /** The encoded offer, hex. **Persist this** — it is the only input `cancelOffer` needs to
100
+ * rebuild the covenant. */
101
+ offerHex: string;
102
+ /** Ready for `wallet.send`'s `extensions` — the caller never handles the packet type. */
103
+ extension: {
104
+ type: number;
105
+ payload: Uint8Array;
106
+ };
107
+ /** The swap address to fund. Identical offers derive an identical address, so the funding
108
+ * txid — not the address — identifies one deposit. */
109
+ address: string;
110
+ /** The covenant's scriptPubKey: the key an indexer watches to spot the
111
+ * deposit and its later spend (`AssetSwap.swapPkScript`). */
112
+ swapPkScript: Uint8Array;
113
+ }>;
114
+ interface OfferParams {
115
+ receiveAddress?: string;
116
+ wantAmount: bigint;
117
+ wantAsset?: asset.AssetId;
118
+ offerAsset?: asset.AssetId;
119
+ /** Co-signer key override (33-byte compressed hex); see
120
+ * {@link resolveEmulatorPubkey}. */
121
+ emulatorPubkey?: string;
122
+ /** Override the exit closure's delay. Defaults to the server's own
123
+ * `unilateralExitDelay`, which is the delay solverd uses too. */
124
+ exitDelay?: RelativeTimelock;
125
+ /** Publish without the exit closure, leaving `cancel` — which needs the
126
+ * server — as the only way back out. See the note on {@link createOffer}. */
127
+ noExit?: boolean;
128
+ /**
129
+ * A live `getArkadeInfo` the caller already made.
130
+ *
131
+ * Passing it is what lets one live read bind both the derivation and the
132
+ * registration that follows it; omitting it makes the read here. It must be
133
+ * live for the reason {@link createOffer} reads live — the info's
134
+ * `signerPubkey` ends up in a covenant leaf.
135
+ */
136
+ info?: ArkadeInfo;
137
+ /**
138
+ * The maker position, when the caller already read it.
139
+ *
140
+ * The RFQ path reads it BEFORE it sends the request — the profile commits
141
+ * to this script and this key — so re-reading it here would let an address
142
+ * rotation between the two reads derive a covenant the solver never quoted.
143
+ */
144
+ maker?: {
145
+ pkScript: Uint8Array;
146
+ publicKey: Uint8Array;
147
+ };
148
+ }
149
+ /**
150
+ * Everything an offer commits to, derived and encoded, with nothing written.
151
+ *
152
+ * The split exists because `quote()` must derive the covenant it verifies the
153
+ * solver's `offer_address` against while persisting and registering nothing,
154
+ * and `accept()` must register **that** derivation rather than a second one
155
+ * built from the same terms. So the tree's own parameters travel on this value:
156
+ * two derivations that can disagree is the failure the hand-off deletes.
157
+ */
158
+ interface DerivedOffer {
159
+ readonly offerHex: string;
160
+ readonly extension: {
161
+ readonly type: number;
162
+ readonly payload: Uint8Array;
163
+ };
164
+ readonly address: string;
165
+ readonly swapPkScript: Uint8Array;
166
+ /** The covenant's parameters — {@link registerDerivedOffer}'s only input. */
167
+ readonly binding: Readonly<Omit<Offer, "swapPkScript">>;
168
+ /** The live info this covenant is bound to. */
169
+ readonly info: ArkadeInfo;
170
+ readonly operatorPubkey: Uint8Array;
171
+ }
172
+ /**
173
+ * Cancel an offer: spend the swap VTXO back to the user. Returns the ark txid. No path is on a
174
+ * deadline, so an unfilled deposit stays at the swap address until the user cancels.
175
+ *
176
+ * Routes out: `fulfill` (server alone, but constrained to pay `makerWP` at least `wantAmount`),
177
+ * `cancel` (user+server 2-of-2, no solver involved), `exit` (user alone after a CSV unless `noExit`;
178
+ * reached by unrolling onchain, not here).
179
+ *
180
+ * Cancel races a fill: if `fulfill` spent first this throws "no spendable VTXO at the swap address",
181
+ * which means the swap completed (`classifySpend` tells the spends apart by leaf). The escrow marker
182
+ * gates implicit coin selection only; cancel names its input explicitly.
183
+ *
184
+ * `fundingTxid` selects the deposit (identical offers share an address); without it the address must
185
+ * hold exactly one. `swapAddress` pins the funding-time operator key across a signer rotation. When
186
+ * `repository` holds the record, this writes `cancelling` (crash marker) then `cancelled`, so the
187
+ * watcher has nothing to decide for our own cancels; otherwise the watcher/restore scan classifies.
188
+ *
189
+ * @deprecated Use `client.cancel()`. Moved off the package root to `@arkade-os/swap/protocol`.
190
+ */
191
+ declare function cancelOffer(wallet: IWallet, offerHex: string, opts: {
192
+ repository: AssetSwapRepository;
193
+ fundingTxid?: string;
194
+ fundingOutpoint?: FillOutpoint;
195
+ swapAddress?: string;
196
+ }): Promise<string>;
197
+ /**
198
+ * No deposit left to cancel at the swap address — almost always the fill winning the race. Typed so
199
+ * the v2 client's `cancel()` reconciles by `instanceof` (see `client/cancel.ts`); message is v1's.
200
+ *
201
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
202
+ */
203
+ declare class NoSpendableDepositError extends Error {
204
+ readonly name = "NoSpendableDepositError";
205
+ constructor(options?: ErrorOptions);
206
+ }
207
+ /**
208
+ * The rebuilt covenant disagrees with the offer's `swapPkScript`: the pinned operator key is not the
209
+ * one the covenant was funded with (rotated signer, a wrong `swapAddress`, or a corrupt record).
210
+ * Fires before any broadcast.
211
+ *
212
+ * @deprecated Internal to `accept()`; no replacement. Moved off the package root to `@arkade-os/swap/protocol`.
213
+ */
214
+ declare class OfferCovenantMismatchError extends Error {
215
+ readonly swapPkScript: string;
216
+ readonly name = "OfferCovenantMismatchError";
217
+ constructor(swapPkScript: string, options?: ErrorOptions);
218
+ }
219
+ /** Sats carried by output 0 when the maker is paid in an ASSET: the covenant checks the asset, and
220
+ * the output still needs its own carrier. Overridable per fill via `assetCarrierSats`.
221
+ *
222
+ * @deprecated Read it from `@arkade-os/sdk`, which owns the constant. Moved off the package root to `@arkade-os/swap/protocol`.
223
+ */
224
+ declare const ASSET_CARRIER_SATS: bigint;
225
+ /**
226
+ * A coin the taker supplies, plus the assets it carries. `ArkTxInput` is sats-only, and **arkd
227
+ * refuses a spend whose asset packet omits an asset one of its inputs owns** (`ASSET_NOT_FOUND`), so
228
+ * every asset on a funding coin must be declared. A wallet's own coins already carry this shape.
229
+ */
230
+ type FillFunding = ArkTxInput & {
231
+ assets?: readonly {
232
+ assetId: string;
233
+ amount: bigint | number;
234
+ }[];
235
+ };
236
+ /** @deprecated Use `Outpoint` from `@arkade-os/sdk`. */
237
+ type FillOutpoint = Outpoint;
238
+ type FillInputOwner = "solver" | "sponsor";
239
+ /**
240
+ * Fill an offer — the TAKER's side, and the counterpart to {@link createOffer}. Composes the
241
+ * `fulfill` spend; it does not weaken or reinterpret the covenant.
242
+ *
243
+ * For an ASSET want the covenant reads output 0 through `OP_INSPECTOUTASSETLOOKUP` with
244
+ * `lookup_index = 0`, so the wanted asset must be the FIRST group in the packet (groups keep insertion
245
+ * order) and output 0 carries only a dust carrier ({@link ASSET_CARRIER_SATS}). Every other asset in
246
+ * the spend goes to the taker's payout; see {@link FillFunding}.
247
+ *
248
+ * Writes NO local swap record: the maker learns the outcome from the chain (RFQ protocol § 7.2).
249
+ * `fund` is explicit because only the caller knows which coins are reserved (e.g. a corridor's
250
+ * float). Racing a cancel is NORMAL: "no spendable VTXO at the swap address" means the offer is gone.
251
+ *
252
+ * @deprecated The v2 client has no taker-side fill, so there is no replacement:
253
+ * `accept()` funds a covenant of your own; it does not spend someone else's
254
+ * offer through its `fulfill` leaf. Moved off the package root to `@arkade-os/swap/protocol`.
255
+ */
256
+ declare function fillOffer(wallet: IWallet, arkServerUrl: string, offerHex: string, opts: {
257
+ fund: FillFunding[];
258
+ payoutScript?: Uint8Array;
259
+ fundingTxid?: string;
260
+ fundingOutpoint?: FillOutpoint;
261
+ swapAddress?: string;
262
+ assetCarrierSats?: bigint;
263
+ emulator: EmulatorProvider | string;
264
+ emulatorPubkey?: string;
265
+ }): Promise<string>;
266
+ /** @deprecated Use `offerContract` from `@arkade-os/swap/protocol`. */
267
+ declare const offerVtxoScript: typeof offerContract;
268
+
269
+ export { ASSET_CARRIER_SATS as A, type CoverageRegistrationOptions as C, type DerivedOffer as D, type FillFunding as F, NoSpendableDepositError as N, type Offer as O, type FillOutpoint as a, type FillInputOwner as b, OFFER_PACKET_TYPE as c, OfferCovenantMismatchError as d, cancelOffer as e, createOffer as f, decodeOffer as g, encodeOffer as h, fillOffer as i, offerVtxoScript as j, offerContract as o, swapPrograms as s };