@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.
- package/README.md +261 -252
- package/dist/advanced.cjs +6376 -3097
- package/dist/advanced.d.cts +325 -282
- package/dist/advanced.d.ts +325 -282
- package/dist/advanced.js +343 -34
- package/dist/chunk-A3SHHRX4.js +104 -0
- package/dist/chunk-FMRAV77W.js +3065 -0
- package/dist/{chunk-NS3K6BZG.js → chunk-HRMWBULL.js} +1746 -628
- package/dist/chunk-WKJFXXSR.js +3382 -0
- package/dist/index.cjs +6809 -3915
- package/dist/index.d.cts +71 -243
- package/dist/index.d.ts +71 -243
- package/dist/index.js +131 -167
- package/dist/lockupContract-D7BNjksX.d.ts +148 -0
- package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
- package/dist/node/index.cjs +61 -10
- package/dist/node/index.d.cts +307 -635
- package/dist/node/index.d.ts +307 -635
- package/dist/node/index.js +65 -10
- package/dist/nostr.cjs +427 -49
- package/dist/nostr.d.cts +59 -70
- package/dist/nostr.d.ts +59 -70
- package/dist/nostr.js +268 -36
- package/dist/offer-CcJfx5Fj.d.cts +269 -0
- package/dist/offer-DdB1M6FZ.d.ts +269 -0
- package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
- package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
- package/dist/protocol.cjs +5650 -4280
- package/dist/protocol.d.cts +258 -328
- package/dist/protocol.d.ts +258 -328
- package/dist/protocol.js +200 -224
- package/dist/repositories/realm/index.cjs +55 -11
- package/dist/repositories/realm/index.d.cts +18 -30
- package/dist/repositories/realm/index.d.ts +18 -30
- package/dist/repositories/realm/index.js +49 -12
- package/dist/repositories/sqlite/index.cjs +61 -10
- package/dist/repositories/sqlite/index.d.cts +7 -6
- package/dist/repositories/sqlite/index.d.ts +7 -6
- package/dist/repositories/sqlite/index.js +57 -11
- package/dist/repository-DmPzpbd7.d.ts +2342 -0
- package/dist/repository-DqdLVrVv.d.cts +2342 -0
- package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
- package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
- package/dist/watch-BonYT9af.d.cts +74 -0
- package/dist/watch-CmJQDtsy.d.ts +74 -0
- package/package.json +10 -10
- package/dist/chunk-JFKGMPMH.js +0 -3456
- package/dist/chunk-LLG7RD2T.js +0 -1499
- package/dist/chunk-U7VWWTL6.js +0 -66
- package/dist/errors-CNISbN0M.d.ts +0 -2218
- package/dist/errors-DwNhIP0N.d.cts +0 -2218
- package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
- package/dist/lockupContract-mIt4syse.d.cts +0 -664
- package/dist/repository-CGPLbjBe.d.ts +0 -3489
- package/dist/repository-DSGGq0ct.d.cts +0 -3489
- package/dist/watch-DWyVqyEN.d.cts +0 -96
- package/dist/watch-DmvHNX6T.d.ts +0 -96
|
@@ -0,0 +1,3065 @@
|
|
|
1
|
+
import {
|
|
2
|
+
collectAssetSwaps
|
|
3
|
+
} from "./chunk-A3SHHRX4.js";
|
|
4
|
+
|
|
5
|
+
// src/store.ts
|
|
6
|
+
import { hex } from "@scure/base";
|
|
7
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
8
|
+
import { contractPreimage } from "@arkade-os/sdk";
|
|
9
|
+
var BTC_ASSET_ID = "btc";
|
|
10
|
+
var byNewest = (a, b) => b.createdAt - a.createdAt;
|
|
11
|
+
var getAssetSwapsOrThrow = async (repository) => {
|
|
12
|
+
return (await collectAssetSwaps(repository)).filter(
|
|
13
|
+
(s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
|
|
14
|
+
// the payment hash instead — either marks a valid record
|
|
15
|
+
(typeof s.offerHex === "string" || typeof s.paymentHash === "string")
|
|
16
|
+
).sort(byNewest);
|
|
17
|
+
};
|
|
18
|
+
var getAssetSwaps = async (repository) => {
|
|
19
|
+
try {
|
|
20
|
+
return await getAssetSwapsOrThrow(repository);
|
|
21
|
+
} catch {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var saveSwapOrThrow = async (repository, swap) => {
|
|
26
|
+
try {
|
|
27
|
+
await repository.saveSwap(swap);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
30
|
+
throw new Error(`failed to save swap ${swap.id}: ${reason}`);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var addAssetSwap = async (repository, swap) => {
|
|
34
|
+
const swaps = await getAssetSwapsOrThrow(repository);
|
|
35
|
+
if (swaps.some((s) => s.id === swap.id)) return swaps;
|
|
36
|
+
await saveSwapOrThrow(repository, swap);
|
|
37
|
+
const at = swaps.findIndex((s) => byNewest(swap, s) <= 0);
|
|
38
|
+
const merged = [...swaps];
|
|
39
|
+
merged.splice(at === -1 ? merged.length : at, 0, swap);
|
|
40
|
+
return merged;
|
|
41
|
+
};
|
|
42
|
+
var updateAssetSwap = async (repository, id, changes) => {
|
|
43
|
+
const swaps = (await getAssetSwapsOrThrow(repository)).map(
|
|
44
|
+
(s) => s.id === id ? { ...s, ...changes } : s
|
|
45
|
+
);
|
|
46
|
+
const updated = swaps.find((s) => s.id === id);
|
|
47
|
+
if (updated) await saveSwapOrThrow(repository, updated);
|
|
48
|
+
return swaps;
|
|
49
|
+
};
|
|
50
|
+
var updateAssetSwapBestEffort = async (repository, id, changes) => {
|
|
51
|
+
try {
|
|
52
|
+
return { swaps: await updateAssetSwap(repository, id, changes), persisted: true };
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.warn(`[swap] failed to persist update for swap ${id}`, error);
|
|
55
|
+
const swaps = (await getAssetSwaps(repository)).map(
|
|
56
|
+
(s) => s.id === id ? { ...s, ...changes } : s
|
|
57
|
+
);
|
|
58
|
+
return { swaps, persisted: false };
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var swapSecretsToRecord = (secrets) => ({
|
|
62
|
+
signingDescriptor: secrets.descriptor,
|
|
63
|
+
..."mustPersistPreimage" in secrets && secrets.mustPersistPreimage ? { preimageHex: hex.encode(secrets.preimage) } : {},
|
|
64
|
+
..."preimageSalt" in secrets && secrets.preimageSalt ? { preimageSaltHex: hex.encode(secrets.preimageSalt) } : {}
|
|
65
|
+
});
|
|
66
|
+
var decodeHex32 = (value, field) => {
|
|
67
|
+
const bytes = hex.decode(value);
|
|
68
|
+
if (bytes.length !== 32) {
|
|
69
|
+
throw new Error(`${field} must be 32 bytes, got ${bytes.length}`);
|
|
70
|
+
}
|
|
71
|
+
return bytes;
|
|
72
|
+
};
|
|
73
|
+
var PreimageNotRecoverableError = class extends Error {
|
|
74
|
+
constructor(reason, message, options) {
|
|
75
|
+
super(message, options);
|
|
76
|
+
this.reason = reason;
|
|
77
|
+
}
|
|
78
|
+
reason;
|
|
79
|
+
name = "PreimageNotRecoverableError";
|
|
80
|
+
};
|
|
81
|
+
var preimageForSwapRecord = async (wallet, record) => {
|
|
82
|
+
if (!record.signingDescriptor) {
|
|
83
|
+
throw new PreimageNotRecoverableError(
|
|
84
|
+
"no-secrets",
|
|
85
|
+
"this swap record carries no signing descriptor"
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
let stored;
|
|
89
|
+
let salt;
|
|
90
|
+
try {
|
|
91
|
+
stored = record.preimageHex ? decodeHex32(record.preimageHex, "preimageHex") : void 0;
|
|
92
|
+
salt = record.preimageSaltHex ? decodeHex32(record.preimageSaltHex, "preimageSaltHex") : void 0;
|
|
93
|
+
} catch (cause) {
|
|
94
|
+
throw new PreimageNotRecoverableError(
|
|
95
|
+
"malformed-record",
|
|
96
|
+
`this swap record's secrets projection is unreadable: ${String(cause)}`,
|
|
97
|
+
{ cause }
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
let preimage;
|
|
101
|
+
try {
|
|
102
|
+
preimage = await contractPreimage(wallet, record.signingDescriptor, { stored, salt });
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
throw new PreimageNotRecoverableError(
|
|
105
|
+
"not-derivable",
|
|
106
|
+
`this wallet cannot produce the preimage for ${record.signingDescriptor}`,
|
|
107
|
+
{ cause }
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
if (record.paymentHash && hex.encode(sha256(preimage)) !== record.paymentHash.toLowerCase()) {
|
|
111
|
+
throw new PreimageNotRecoverableError(
|
|
112
|
+
"hash-mismatch",
|
|
113
|
+
"the derived preimage does not match this swap's payment hash: wrong wallet, or a tampered salt"
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
return preimage;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// src/rfqCorridor.ts
|
|
120
|
+
var RfqCorridorRegistry = class {
|
|
121
|
+
handlers = /* @__PURE__ */ new Map();
|
|
122
|
+
register(handler) {
|
|
123
|
+
if (this.handlers.has(handler.kind)) {
|
|
124
|
+
throw new Error(
|
|
125
|
+
`RFQ corridor handler for kind '${handler.kind}' is already registered`
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
this.handlers.set(handler.kind, handler);
|
|
129
|
+
}
|
|
130
|
+
/** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
|
|
131
|
+
* `kind` union would read as a check already made. */
|
|
132
|
+
get(kind) {
|
|
133
|
+
return this.handlers.get(kind);
|
|
134
|
+
}
|
|
135
|
+
/** The handler for a kind, or a loud failure naming the registered kinds. */
|
|
136
|
+
getOrThrow(kind) {
|
|
137
|
+
const handler = this.get(kind);
|
|
138
|
+
if (!handler) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
`no RFQ corridor handler registered for kind '${kind}'; registered: ${this.registeredKinds().join(", ") || "none"}`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
return handler;
|
|
144
|
+
}
|
|
145
|
+
registeredKinds() {
|
|
146
|
+
return [...this.handlers.keys()];
|
|
147
|
+
}
|
|
148
|
+
/** Test seam, mirroring the contract registry's. */
|
|
149
|
+
unregister(kind) {
|
|
150
|
+
return this.handlers.delete(kind);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
var rfqCorridorHandlers = new RfqCorridorRegistry();
|
|
154
|
+
|
|
155
|
+
// src/rfqProfileParts.ts
|
|
156
|
+
var rfqSecretsProfile = (secrets, paymentHash) => {
|
|
157
|
+
const { signingDescriptor, ...preimage } = swapSecretsToRecord(secrets);
|
|
158
|
+
return {
|
|
159
|
+
signer: { signingDescriptor },
|
|
160
|
+
...paymentHash ? { hashlock: { paymentHash, ...preimage } } : {}
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
var parseHex32 = (value, field) => {
|
|
164
|
+
if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) {
|
|
165
|
+
throw new Error(`${field} must be 32 bytes of hex, got ${JSON.stringify(value)}`);
|
|
166
|
+
}
|
|
167
|
+
return value.toLowerCase();
|
|
168
|
+
};
|
|
169
|
+
var parseSigner = (value) => {
|
|
170
|
+
const signingDescriptor = value?.signingDescriptor;
|
|
171
|
+
if (typeof signingDescriptor !== "string" || signingDescriptor.length === 0) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
`rfq profile.signer carries no signingDescriptor (got ${JSON.stringify(signingDescriptor)})`
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return { signingDescriptor };
|
|
177
|
+
};
|
|
178
|
+
var parsePayoutAddress = (value, kind) => {
|
|
179
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
`this ${kind} record's claim destination is unusable: expected an Arkade address, got ${JSON.stringify(value)}`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
return value;
|
|
185
|
+
};
|
|
186
|
+
var parseHashlock = (value) => {
|
|
187
|
+
const raw = value ?? {};
|
|
188
|
+
const hashlock = {
|
|
189
|
+
paymentHash: parseHex32(raw.paymentHash, "rfq profile.hashlock.paymentHash")
|
|
190
|
+
};
|
|
191
|
+
if (raw.preimageHex !== void 0) {
|
|
192
|
+
hashlock.preimageHex = parseHex32(raw.preimageHex, "rfq profile.hashlock.preimageHex");
|
|
193
|
+
}
|
|
194
|
+
if (raw.preimageSaltHex !== void 0) {
|
|
195
|
+
hashlock.preimageSaltHex = parseHex32(
|
|
196
|
+
raw.preimageSaltHex,
|
|
197
|
+
"rfq profile.hashlock.preimageSaltHex"
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
return hashlock;
|
|
201
|
+
};
|
|
202
|
+
var hydrateHashlock = (profile) => {
|
|
203
|
+
try {
|
|
204
|
+
return { paymentHash: parseHashlock(profile.hashlock).paymentHash };
|
|
205
|
+
} catch (cause) {
|
|
206
|
+
throw new Error(
|
|
207
|
+
`rfq record carries no usable hashlock; it cannot verify a preimage: ${String(cause)}`,
|
|
208
|
+
{ cause }
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
var rfqSignerOf = (record) => {
|
|
213
|
+
const signer = record.profile.signer;
|
|
214
|
+
if (signer === void 0) return void 0;
|
|
215
|
+
return parseSigner(signer);
|
|
216
|
+
};
|
|
217
|
+
var rfqClaimSecretOf = (record) => {
|
|
218
|
+
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
219
|
+
if (!handler.claimSecret) return void 0;
|
|
220
|
+
try {
|
|
221
|
+
const claim = handler.claimSecret(record.profile);
|
|
222
|
+
return { ...parseSigner(claim), ...parseHashlock(claim) };
|
|
223
|
+
} catch (cause) {
|
|
224
|
+
throw new PreimageNotRecoverableError(
|
|
225
|
+
"malformed-record",
|
|
226
|
+
`this ${record.kind} record's claim secret is unreadable: ${String(cause)}`,
|
|
227
|
+
{ cause }
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
var rfqClaimDestinationOf = (record) => {
|
|
232
|
+
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
233
|
+
if (!handler.claimDestination) return void 0;
|
|
234
|
+
return parsePayoutAddress(handler.claimDestination(record.profile), record.kind);
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// src/offer.ts
|
|
238
|
+
import { hex as hex2 } from "@scure/base";
|
|
239
|
+
import { concatBytes } from "@scure/btc-signer/utils.js";
|
|
240
|
+
import {
|
|
241
|
+
ASSET_CARRIER_SATS as SDK_ASSET_CARRIER_SATS,
|
|
242
|
+
ArkAddress,
|
|
243
|
+
RestArkProvider,
|
|
244
|
+
RestEmulatorProvider,
|
|
245
|
+
RestIndexerProvider,
|
|
246
|
+
arkade,
|
|
247
|
+
asset,
|
|
248
|
+
networkFromArkadeInfo,
|
|
249
|
+
resolveEmulatorPubkey,
|
|
250
|
+
toXOnlySignerHex
|
|
251
|
+
} from "@arkade-os/sdk";
|
|
252
|
+
|
|
253
|
+
// src/swap-want-asset.program.json
|
|
254
|
+
var swap_want_asset_program_default = {
|
|
255
|
+
version: 1,
|
|
256
|
+
name: "banco-btc-to-asset",
|
|
257
|
+
params: [
|
|
258
|
+
{ name: "makerWP", type: "pubkey" },
|
|
259
|
+
{ name: "wantAmount", type: "int" },
|
|
260
|
+
{ name: "wantAssetTxid", type: "bytes32" },
|
|
261
|
+
{ name: "wantAssetGroupIndex", type: "int" },
|
|
262
|
+
{ name: "server", type: "pubkey" },
|
|
263
|
+
{ name: "user", type: "pubkey" }
|
|
264
|
+
],
|
|
265
|
+
functions: {
|
|
266
|
+
fulfill: {
|
|
267
|
+
tapscript: { signers: ["$server"] },
|
|
268
|
+
arkadeScript: {
|
|
269
|
+
asm: [
|
|
270
|
+
0,
|
|
271
|
+
"$wantAssetTxid",
|
|
272
|
+
"$wantAssetGroupIndex",
|
|
273
|
+
"INSPECTOUTASSETLOOKUP",
|
|
274
|
+
"VERIFY",
|
|
275
|
+
"$wantAmount",
|
|
276
|
+
"GREATERTHANOREQUAL",
|
|
277
|
+
"VERIFY",
|
|
278
|
+
0,
|
|
279
|
+
"INSPECTOUTPUTSCRIPTPUBKEY",
|
|
280
|
+
1,
|
|
281
|
+
"EQUALVERIFY",
|
|
282
|
+
"$makerWP",
|
|
283
|
+
"EQUAL"
|
|
284
|
+
]
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
cancel: {
|
|
288
|
+
tapscript: { signers: ["$user", "$server"] }
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// src/swap-want-btc.program.json
|
|
294
|
+
var swap_want_btc_program_default = {
|
|
295
|
+
version: 1,
|
|
296
|
+
name: "banco-asset-to-btc",
|
|
297
|
+
params: [
|
|
298
|
+
{ name: "makerWP", type: "pubkey" },
|
|
299
|
+
{ name: "wantAmount", type: "int" },
|
|
300
|
+
{ name: "server", type: "pubkey" },
|
|
301
|
+
{ name: "user", type: "pubkey" }
|
|
302
|
+
],
|
|
303
|
+
functions: {
|
|
304
|
+
fulfill: {
|
|
305
|
+
tapscript: { signers: ["$server"] },
|
|
306
|
+
arkadeScript: {
|
|
307
|
+
asm: [
|
|
308
|
+
0,
|
|
309
|
+
"INSPECTOUTPUTVALUE",
|
|
310
|
+
"$wantAmount",
|
|
311
|
+
"GREATERTHANOREQUAL",
|
|
312
|
+
"VERIFY",
|
|
313
|
+
0,
|
|
314
|
+
"INSPECTOUTPUTSCRIPTPUBKEY",
|
|
315
|
+
1,
|
|
316
|
+
"EQUALVERIFY",
|
|
317
|
+
"$makerWP",
|
|
318
|
+
"EQUAL"
|
|
319
|
+
]
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
cancel: {
|
|
323
|
+
tapscript: { signers: ["$user", "$server"] }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
// src/coverage.ts
|
|
329
|
+
var RETIRABLE = ["fulfilled", "cancelled"];
|
|
330
|
+
var LOCKUP_RETIRABLE = ["settled", "refunded"];
|
|
331
|
+
var legacyScope = {};
|
|
332
|
+
var issuedByScope = /* @__PURE__ */ new WeakMap();
|
|
333
|
+
function markIssued(script, issued, options) {
|
|
334
|
+
const scope = options.scope ?? legacyScope;
|
|
335
|
+
const issuedAt = issuedByScope.get(scope) ?? /* @__PURE__ */ new Map();
|
|
336
|
+
const outstanding = issuedAt.get(script) ?? { issuedAt: void 0, ids: /* @__PURE__ */ new Set() };
|
|
337
|
+
const id = options.coverageId;
|
|
338
|
+
if (id === void 0) outstanding.issuedAt = issued;
|
|
339
|
+
else outstanding.ids.add(id);
|
|
340
|
+
issuedAt.set(script, outstanding);
|
|
341
|
+
issuedByScope.set(scope, issuedAt);
|
|
342
|
+
}
|
|
343
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
344
|
+
async function serialize(script, task) {
|
|
345
|
+
const previous = inFlight.get(script) ?? Promise.resolve();
|
|
346
|
+
const result = previous.then(task, task);
|
|
347
|
+
const settled = result.then(
|
|
348
|
+
() => {
|
|
349
|
+
},
|
|
350
|
+
() => {
|
|
351
|
+
}
|
|
352
|
+
);
|
|
353
|
+
inFlight.set(script, settled);
|
|
354
|
+
void settled.then(() => {
|
|
355
|
+
if (inFlight.get(script) === settled) inFlight.delete(script);
|
|
356
|
+
});
|
|
357
|
+
return result;
|
|
358
|
+
}
|
|
359
|
+
function addressOutstanding(swaps, script, scope) {
|
|
360
|
+
const issuedAt = issuedByScope.get(scope);
|
|
361
|
+
if (issuedAt === void 0) return false;
|
|
362
|
+
const issued = issuedAt.get(script);
|
|
363
|
+
if (issued === void 0) return false;
|
|
364
|
+
for (const swap of swaps) {
|
|
365
|
+
if (swap.swapPkScript !== script) continue;
|
|
366
|
+
if (swap.id !== void 0) issued.ids.delete(swap.id);
|
|
367
|
+
if (issued.issuedAt !== void 0 && swap.createdAt >= issued.issuedAt) {
|
|
368
|
+
issued.issuedAt = void 0;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (issued.ids.size > 0 || issued.issuedAt !== void 0) return true;
|
|
372
|
+
issuedAt.delete(script);
|
|
373
|
+
return false;
|
|
374
|
+
}
|
|
375
|
+
async function promoteOfferContract(manager, script, issued = Date.now(), options = {}) {
|
|
376
|
+
await serialize(script, async () => {
|
|
377
|
+
await manager.setContractWatchState(script, "watched");
|
|
378
|
+
if (options.restore && options.coverageId !== void 0) return;
|
|
379
|
+
markIssued(script, issued, options);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async function retireOfferContract(manager, swaps, script, options = {}) {
|
|
383
|
+
await serialize(script, async () => {
|
|
384
|
+
const records = typeof swaps === "function" ? await swaps() : swaps;
|
|
385
|
+
const outstanding = addressOutstanding(records, script, options.scope ?? legacyScope);
|
|
386
|
+
if (records.some((s) => s.swapPkScript === script && !RETIRABLE.includes(s.status))) return;
|
|
387
|
+
if (outstanding) return;
|
|
388
|
+
try {
|
|
389
|
+
await manager.setContractWatchState(script, "retained");
|
|
390
|
+
} catch (err) {
|
|
391
|
+
console.warn(`[swap] could not retire offer contract ${script}`, err);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
async function retireSettledOfferContracts(manager, swaps, options = {}) {
|
|
396
|
+
const settled = new Set(
|
|
397
|
+
swaps.filter((s) => RETIRABLE.includes(s.status)).map((s) => s.swapPkScript)
|
|
398
|
+
);
|
|
399
|
+
for (const script of settled) await retireOfferContract(manager, swaps, script, options);
|
|
400
|
+
}
|
|
401
|
+
var registerContractCoverage = async (script, register, options = {}) => serialize(script, async () => {
|
|
402
|
+
const row = await register();
|
|
403
|
+
markIssued(script, Date.now(), options);
|
|
404
|
+
return row;
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
// src/offer.ts
|
|
408
|
+
var swapPrograms = {
|
|
409
|
+
wantAsset: arkade.parseArtifact(swap_want_asset_program_default),
|
|
410
|
+
wantBtc: arkade.parseArtifact(swap_want_btc_program_default)
|
|
411
|
+
};
|
|
412
|
+
function withExitClosure(program, exit) {
|
|
413
|
+
if (!exit) return program;
|
|
414
|
+
return {
|
|
415
|
+
...program,
|
|
416
|
+
// typed params are authoritative: an undeclared `$exitDelay` fails
|
|
417
|
+
// validateProgram instead of compiling against an unbound value
|
|
418
|
+
params: [...program.params ?? [], { name: "exitDelay", type: "int" }],
|
|
419
|
+
functions: {
|
|
420
|
+
...program.functions,
|
|
421
|
+
exit: {
|
|
422
|
+
tapscript: { signers: ["$user"], csv: { type: exit.type, value: "$exitDelay" } }
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
function swapProgramBinding(offer, operatorPubkey) {
|
|
428
|
+
if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
|
|
429
|
+
throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
program: withExitClosure(
|
|
433
|
+
offer.wantAsset ? swapPrograms.wantAsset : swapPrograms.wantBtc,
|
|
434
|
+
offer.exitDelay
|
|
435
|
+
),
|
|
436
|
+
args: {
|
|
437
|
+
makerWP: offer.makerPkScript.subarray(2),
|
|
438
|
+
wantAmount: offer.wantAmount,
|
|
439
|
+
server: operatorPubkey,
|
|
440
|
+
user: offer.makerPublicKey,
|
|
441
|
+
// internal byte order
|
|
442
|
+
...offer.wantAsset && {
|
|
443
|
+
wantAssetTxid: offer.wantAsset.txid.slice().reverse(),
|
|
444
|
+
wantAssetGroupIndex: offer.wantAsset.groupIndex
|
|
445
|
+
},
|
|
446
|
+
...offer.exitDelay && { exitDelay: offer.exitDelay.value }
|
|
447
|
+
},
|
|
448
|
+
keys: {
|
|
449
|
+
serverKey: operatorPubkey,
|
|
450
|
+
userKey: offer.makerPublicKey,
|
|
451
|
+
emulatorKey: offer.emulatorPubkey
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
function offerContract(offer, operatorPubkey) {
|
|
456
|
+
const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
|
|
457
|
+
return new arkade.ArkadeProgramScript(program, args, keys);
|
|
458
|
+
}
|
|
459
|
+
var OFFER_PACKET_TYPE = 3;
|
|
460
|
+
var FIELDS = {
|
|
461
|
+
swapPkScript: { tag: 1, width: 34 },
|
|
462
|
+
wantAmount: { tag: 2, width: 8 },
|
|
463
|
+
wantAsset: { tag: 3, width: void 0 },
|
|
464
|
+
makerPkScript: { tag: 5, width: 34 },
|
|
465
|
+
makerPublicKey: { tag: 7, width: 32 },
|
|
466
|
+
emulatorPubkey: { tag: 8, width: 32 },
|
|
467
|
+
ratioNum: { tag: 9, width: 8 },
|
|
468
|
+
ratioDen: { tag: 10, width: 8 },
|
|
469
|
+
offerAsset: { tag: 11, width: void 0 },
|
|
470
|
+
exitTimelock: { tag: 12, width: 9 }
|
|
471
|
+
};
|
|
472
|
+
var EXIT_TYPES = ["blocks", "seconds"];
|
|
473
|
+
var NAMES = Object.fromEntries(Object.entries(FIELDS).map(([k, f]) => [f.tag, k]));
|
|
474
|
+
function u64(name, value) {
|
|
475
|
+
if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
|
|
476
|
+
throw new Error(`${name} does not fit the offer wire format (u64)`);
|
|
477
|
+
}
|
|
478
|
+
const out = new Uint8Array(FIELDS.wantAmount.width);
|
|
479
|
+
new DataView(out.buffer).setBigUint64(0, value, false);
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
var readU64 = (value) => new DataView(value.buffer, value.byteOffset).getBigUint64(0, false);
|
|
483
|
+
var setRatio = (name, value) => {
|
|
484
|
+
if (value === void 0 || value === BigInt(0)) return void 0;
|
|
485
|
+
if (value < BigInt(0)) throw new Error(`${name} does not fit the offer wire format (u64)`);
|
|
486
|
+
return value;
|
|
487
|
+
};
|
|
488
|
+
function tlv(type, value) {
|
|
489
|
+
if (value.length > 65535) throw new Error("TLV value exceeds the u16 length field");
|
|
490
|
+
return concatBytes(Uint8Array.of(type, value.length >> 8 & 255, value.length & 255), value);
|
|
491
|
+
}
|
|
492
|
+
function encodeOffer(offer) {
|
|
493
|
+
if (Boolean(offer.wantAsset) === Boolean(offer.offerAsset)) {
|
|
494
|
+
throw new Error("offer must carry exactly one of wantAsset or offerAsset");
|
|
495
|
+
}
|
|
496
|
+
for (const name of [
|
|
497
|
+
"swapPkScript",
|
|
498
|
+
"makerPkScript",
|
|
499
|
+
"makerPublicKey",
|
|
500
|
+
"emulatorPubkey"
|
|
501
|
+
]) {
|
|
502
|
+
if (offer[name].length !== FIELDS[name].width) {
|
|
503
|
+
throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const ratioNum = setRatio("ratioNum", offer.ratioNum);
|
|
507
|
+
const ratioDen = setRatio("ratioDen", offer.ratioDen);
|
|
508
|
+
if (ratioNum === void 0 !== (ratioDen === void 0)) {
|
|
509
|
+
throw new Error("offer must carry both ratioNum and ratioDen, or neither");
|
|
510
|
+
}
|
|
511
|
+
const recs = [
|
|
512
|
+
tlv(FIELDS.swapPkScript.tag, offer.swapPkScript),
|
|
513
|
+
tlv(FIELDS.wantAmount.tag, u64("wantAmount", offer.wantAmount))
|
|
514
|
+
];
|
|
515
|
+
if (offer.wantAsset) recs.push(tlv(FIELDS.wantAsset.tag, offer.wantAsset.serialize()));
|
|
516
|
+
if (ratioNum !== void 0) recs.push(tlv(FIELDS.ratioNum.tag, u64("ratioNum", ratioNum)));
|
|
517
|
+
if (ratioDen !== void 0) recs.push(tlv(FIELDS.ratioDen.tag, u64("ratioDen", ratioDen)));
|
|
518
|
+
if (offer.offerAsset) recs.push(tlv(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
|
|
519
|
+
recs.push(
|
|
520
|
+
tlv(FIELDS.makerPkScript.tag, offer.makerPkScript),
|
|
521
|
+
tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
|
|
522
|
+
tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
|
|
523
|
+
);
|
|
524
|
+
if (offer.exitDelay) recs.push(tlv(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
|
|
525
|
+
return concatBytes(...recs);
|
|
526
|
+
}
|
|
527
|
+
function encodeExitDelay(exit) {
|
|
528
|
+
return concatBytes(
|
|
529
|
+
Uint8Array.of(EXIT_TYPES.indexOf(assertExitDelay(exit).type)),
|
|
530
|
+
u64("exitDelay", exit.value)
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
function assertExitDelay(exit) {
|
|
534
|
+
if (EXIT_TYPES.indexOf(exit.type) < 0) {
|
|
535
|
+
throw new Error(`unknown exitDelay locktime type: ${exit.type}`);
|
|
536
|
+
}
|
|
537
|
+
if (exit.value <= BigInt(0)) {
|
|
538
|
+
throw new Error("exitDelay must be a positive relative locktime");
|
|
539
|
+
}
|
|
540
|
+
if (exit.value >> BigInt(32) > BigInt(0)) {
|
|
541
|
+
throw new Error("exitDelay does not fit the locktime field (u32)");
|
|
542
|
+
}
|
|
543
|
+
return exit;
|
|
544
|
+
}
|
|
545
|
+
function decodeOffer(data) {
|
|
546
|
+
const fields = {};
|
|
547
|
+
let off = 0;
|
|
548
|
+
while (off < data.length) {
|
|
549
|
+
if (off + 3 > data.length) throw new Error("truncated TLV header");
|
|
550
|
+
const type = data[off];
|
|
551
|
+
const length = data[off + 1] << 8 | data[off + 2];
|
|
552
|
+
off += 3;
|
|
553
|
+
if (off + length > data.length)
|
|
554
|
+
throw new Error(`truncated TLV value for type 0x${type.toString(16)}`);
|
|
555
|
+
const name = NAMES[type];
|
|
556
|
+
if (!name) throw new Error(`unknown TLV type: 0x${type.toString(16)}`);
|
|
557
|
+
if (fields[name] !== void 0) throw new Error(`duplicate TLV record: ${name}`);
|
|
558
|
+
fields[name] = data.slice(off, off + length);
|
|
559
|
+
off += length;
|
|
560
|
+
}
|
|
561
|
+
for (const name of ["wantAsset", "offerAsset"]) {
|
|
562
|
+
if (fields[name]?.length === 0) throw new Error(`missing/invalid ${name}`);
|
|
563
|
+
}
|
|
564
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
565
|
+
const width = FIELDS[name].width;
|
|
566
|
+
if (width !== void 0 && value.length !== width) {
|
|
567
|
+
throw new Error(`missing/invalid ${name}`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const need = (name) => {
|
|
571
|
+
const v = fields[name];
|
|
572
|
+
if (!v) throw new Error(`missing/invalid ${name}`);
|
|
573
|
+
return v;
|
|
574
|
+
};
|
|
575
|
+
const amount = need("wantAmount");
|
|
576
|
+
if (Boolean(fields.wantAsset) === Boolean(fields.offerAsset)) {
|
|
577
|
+
throw new Error("offer must carry exactly one of wantAsset or offerAsset");
|
|
578
|
+
}
|
|
579
|
+
const readRatio = (name) => {
|
|
580
|
+
const raw = fields[name];
|
|
581
|
+
if (!raw) return void 0;
|
|
582
|
+
const value = readU64(raw);
|
|
583
|
+
if (value === BigInt(0)) throw new Error(`missing/invalid ${name}`);
|
|
584
|
+
return value;
|
|
585
|
+
};
|
|
586
|
+
const ratioNum = readRatio("ratioNum");
|
|
587
|
+
const ratioDen = readRatio("ratioDen");
|
|
588
|
+
if (ratioNum === void 0 !== (ratioDen === void 0)) {
|
|
589
|
+
throw new Error("offer must carry both ratioNum and ratioDen, or neither");
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
swapPkScript: need("swapPkScript"),
|
|
593
|
+
wantAmount: readU64(amount),
|
|
594
|
+
...fields.wantAsset && { wantAsset: asset.AssetId.fromBytes(fields.wantAsset) },
|
|
595
|
+
...fields.offerAsset && { offerAsset: asset.AssetId.fromBytes(fields.offerAsset) },
|
|
596
|
+
makerPkScript: need("makerPkScript"),
|
|
597
|
+
makerPublicKey: need("makerPublicKey"),
|
|
598
|
+
emulatorPubkey: need("emulatorPubkey"),
|
|
599
|
+
...ratioNum !== void 0 && { ratioNum },
|
|
600
|
+
...ratioDen !== void 0 && { ratioDen },
|
|
601
|
+
...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
function decodeExitDelay(value) {
|
|
605
|
+
const type = EXIT_TYPES[value[0]];
|
|
606
|
+
if (!type) throw new Error(`unknown exitDelay locktime type: 0x${value[0].toString(16)}`);
|
|
607
|
+
return { type, value: readU64(value.subarray(1)) };
|
|
608
|
+
}
|
|
609
|
+
var OFFER_CONTRACT_LABEL = "Arkade swap offer";
|
|
610
|
+
var OFFER_CONTRACT_KIND = "asset-swap-offer";
|
|
611
|
+
async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript, options = {}) {
|
|
612
|
+
const contractManager = await wallet.getContractManager();
|
|
613
|
+
const client = await derivingClient(wallet, info, contractManager);
|
|
614
|
+
await contractManager.createContract(
|
|
615
|
+
offerContractParams(client, binding, operatorPubkey, expectedPkScript)
|
|
616
|
+
);
|
|
617
|
+
await promoteOfferContract(contractManager, hex2.encode(expectedPkScript), void 0, {
|
|
618
|
+
...options,
|
|
619
|
+
scope: wallet
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
var derivingClient = (wallet, info, contractManager) => arkade.Arkade.connect({
|
|
623
|
+
arkade: { getInfo: async () => info },
|
|
624
|
+
identity: wallet.identity,
|
|
625
|
+
network: networkFromArkadeInfo(info),
|
|
626
|
+
contractManager
|
|
627
|
+
});
|
|
628
|
+
function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
|
|
629
|
+
const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
|
|
630
|
+
const contract = new arkade.ArkadeContract(client, program, args, keys);
|
|
631
|
+
if (hex2.encode(contract.pkScript) !== hex2.encode(expectedPkScript)) {
|
|
632
|
+
throw new Error("derived covenant does not match the offer's swapPkScript");
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
...contract.toContractParams(),
|
|
636
|
+
label: OFFER_CONTRACT_LABEL,
|
|
637
|
+
metadata: { genericallySpendable: false, kind: OFFER_CONTRACT_KIND }
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
async function restoreOfferCoverage(wallet, swaps) {
|
|
641
|
+
const live = swaps.filter((swap) => !RETIRABLE.includes(swap.status));
|
|
642
|
+
if (live.length === 0) return;
|
|
643
|
+
const [info, contractManager] = await Promise.all([
|
|
644
|
+
wallet.getArkadeInfo({ requireLive: true }),
|
|
645
|
+
wallet.getContractManager()
|
|
646
|
+
]);
|
|
647
|
+
const operatorPubkey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
|
|
648
|
+
const client = await derivingClient(wallet, info, contractManager);
|
|
649
|
+
const rows = await contractManager.getContracts({
|
|
650
|
+
script: live.map((swap) => swap.swapPkScript)
|
|
651
|
+
});
|
|
652
|
+
const fundedKey = new Map(
|
|
653
|
+
rows.filter((row) => row.type === "arkade" && row.params.serverKey).map((row) => [row.script, row.params.serverKey])
|
|
654
|
+
);
|
|
655
|
+
const seen = /* @__PURE__ */ new Set();
|
|
656
|
+
const covenants = [];
|
|
657
|
+
for (const swap of live) {
|
|
658
|
+
if (seen.has(swap.swapPkScript)) continue;
|
|
659
|
+
seen.add(swap.swapPkScript);
|
|
660
|
+
try {
|
|
661
|
+
const { swapPkScript: _, ...binding } = decodeOffer(hex2.decode(swap.offerHex));
|
|
662
|
+
const stored = fundedKey.get(swap.swapPkScript);
|
|
663
|
+
covenants.push({
|
|
664
|
+
script: swap.swapPkScript,
|
|
665
|
+
issued: swap.createdAt,
|
|
666
|
+
coverageId: swap.coverageId,
|
|
667
|
+
params: offerContractParams(
|
|
668
|
+
client,
|
|
669
|
+
binding,
|
|
670
|
+
stored ? hex2.decode(toXOnlySignerHex(stored)) : operatorPubkey,
|
|
671
|
+
hex2.decode(swap.swapPkScript)
|
|
672
|
+
)
|
|
673
|
+
});
|
|
674
|
+
} catch (error) {
|
|
675
|
+
console.warn(`[swap] could not restore coverage for ${swap.swapPkScript}`, error);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
const params = covenants.map((covenant) => covenant.params);
|
|
679
|
+
if (contractManager.createContracts) {
|
|
680
|
+
await contractManager.createContracts(params);
|
|
681
|
+
} else {
|
|
682
|
+
for (const contract of params) await contractManager.createContract(contract);
|
|
683
|
+
}
|
|
684
|
+
for (const covenant of covenants) {
|
|
685
|
+
await promoteOfferContract(contractManager, covenant.script, covenant.issued, {
|
|
686
|
+
coverageId: covenant.coverageId,
|
|
687
|
+
restore: true,
|
|
688
|
+
scope: wallet
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
function serverExitDelay(delay) {
|
|
693
|
+
if (typeof delay !== "bigint" || delay <= BigInt(0)) {
|
|
694
|
+
throw new Error(
|
|
695
|
+
"the server reports no usable unilateralExitDelay; pass `exitDelay` to set the offer's exit closure explicitly, or `noExit: true` to publish without one"
|
|
696
|
+
);
|
|
697
|
+
}
|
|
698
|
+
return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
|
|
699
|
+
}
|
|
700
|
+
async function createOffer(wallet, params, options = {}) {
|
|
701
|
+
const derived = await deriveOffer(wallet, params);
|
|
702
|
+
await registerDerivedOffer(wallet, derived, options);
|
|
703
|
+
return {
|
|
704
|
+
offerHex: derived.offerHex,
|
|
705
|
+
extension: derived.extension,
|
|
706
|
+
address: derived.address,
|
|
707
|
+
swapPkScript: derived.swapPkScript
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
function resolveReceivePkScript(receiveAddress, walletPkScript, hrp, serverPubKey) {
|
|
711
|
+
if (receiveAddress === void 0) return walletPkScript;
|
|
712
|
+
let address;
|
|
713
|
+
try {
|
|
714
|
+
address = ArkAddress.decode(receiveAddress);
|
|
715
|
+
} catch (cause) {
|
|
716
|
+
throw new Error("receiveAddress is not a valid Arkade address", { cause });
|
|
717
|
+
}
|
|
718
|
+
if (address.hrp !== hrp) {
|
|
719
|
+
throw new Error(
|
|
720
|
+
`receiveAddress network ${address.hrp} does not match the server network ${hrp}`
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
if (address.encode() !== receiveAddress) {
|
|
724
|
+
throw new Error("receiveAddress is not in canonical bech32m form");
|
|
725
|
+
}
|
|
726
|
+
if (hex2.encode(address.serverPubKey) !== hex2.encode(serverPubKey)) {
|
|
727
|
+
throw new Error(
|
|
728
|
+
"receiveAddress is bound to a different server public key than the connected server"
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
return address.pkScript;
|
|
732
|
+
}
|
|
733
|
+
async function deriveOffer(wallet, params) {
|
|
734
|
+
if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
|
|
735
|
+
throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
|
|
736
|
+
}
|
|
737
|
+
if (params.wantAmount < BigInt(1)) {
|
|
738
|
+
throw new Error("wantAmount must be positive: a zero want lets anyone take the deposit");
|
|
739
|
+
}
|
|
740
|
+
const [info, maker] = await Promise.all([
|
|
741
|
+
// requireLive: this binds signerPubkey into the covenant, and a snapshot could derive an
|
|
742
|
+
// address the operator no longer co-signs for — fail closed instead
|
|
743
|
+
params.info ?? wallet.getArkadeInfo({ requireLive: true }),
|
|
744
|
+
params.maker ?? (async () => {
|
|
745
|
+
const [address, publicKey] = await Promise.all([
|
|
746
|
+
wallet.getAddress(),
|
|
747
|
+
wallet.identity.xOnlyPublicKey()
|
|
748
|
+
]);
|
|
749
|
+
return { pkScript: ArkAddress.decode(address).pkScript, publicKey };
|
|
750
|
+
})()
|
|
751
|
+
]);
|
|
752
|
+
const operatorPubKey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
|
|
753
|
+
const network = networkFromArkadeInfo(info);
|
|
754
|
+
const emuKey = hex2.decode(
|
|
755
|
+
toXOnlySignerHex(resolveEmulatorPubkey(network, params.emulatorPubkey))
|
|
756
|
+
);
|
|
757
|
+
const binding = Object.freeze({
|
|
758
|
+
wantAmount: params.wantAmount,
|
|
759
|
+
wantAsset: params.wantAsset,
|
|
760
|
+
offerAsset: params.offerAsset,
|
|
761
|
+
makerPkScript: resolveReceivePkScript(
|
|
762
|
+
params.receiveAddress,
|
|
763
|
+
maker.pkScript,
|
|
764
|
+
network.hrp,
|
|
765
|
+
operatorPubKey
|
|
766
|
+
),
|
|
767
|
+
makerPublicKey: maker.publicKey,
|
|
768
|
+
emulatorPubkey: emuKey,
|
|
769
|
+
// checked before registration below. @see assertExitDelay
|
|
770
|
+
exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
|
|
771
|
+
});
|
|
772
|
+
const script = offerContract(binding, operatorPubKey);
|
|
773
|
+
const offer = { ...binding, swapPkScript: script.pkScript };
|
|
774
|
+
const payload = encodeOffer(offer);
|
|
775
|
+
return Object.freeze({
|
|
776
|
+
offerHex: hex2.encode(payload),
|
|
777
|
+
extension: { type: OFFER_PACKET_TYPE, payload },
|
|
778
|
+
// the contract's .address() builds the address; assembling an ArkAddress
|
|
779
|
+
// from tweakedPublicKey here would silently miss any future step it gains
|
|
780
|
+
address: script.address(network.hrp, operatorPubKey).encode(),
|
|
781
|
+
swapPkScript: script.pkScript,
|
|
782
|
+
binding,
|
|
783
|
+
info,
|
|
784
|
+
operatorPubkey: operatorPubKey
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
async function registerDerivedOffer(wallet, derived, options = {}) {
|
|
788
|
+
await registerOfferContract(
|
|
789
|
+
wallet,
|
|
790
|
+
derived.info,
|
|
791
|
+
derived.binding,
|
|
792
|
+
derived.operatorPubkey,
|
|
793
|
+
derived.swapPkScript,
|
|
794
|
+
options
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
async function cancelOffer(wallet, offerHex, opts) {
|
|
798
|
+
const { repository, fundingTxid, fundingOutpoint, swapAddress } = opts;
|
|
799
|
+
const prepared = await prepareOfferCancel(wallet, offerHex, {
|
|
800
|
+
...fundingTxid === void 0 ? {} : { fundingTxid },
|
|
801
|
+
...fundingOutpoint === void 0 ? {} : { fundingOutpoint },
|
|
802
|
+
...swapAddress === void 0 ? {} : { swapAddress }
|
|
803
|
+
});
|
|
804
|
+
const swapId = fundingTxid ?? prepared.vtxo.txid;
|
|
805
|
+
const hasLocalRecord = (await getAssetSwapsOrThrow(repository)).some((s) => s.id === swapId);
|
|
806
|
+
if (hasLocalRecord) await updateAssetSwap(repository, swapId, { status: "cancelling" });
|
|
807
|
+
const txid = await prepared.send();
|
|
808
|
+
if (hasLocalRecord) {
|
|
809
|
+
const { persisted, swaps } = await updateAssetSwapBestEffort(repository, swapId, {
|
|
810
|
+
status: "cancelled",
|
|
811
|
+
spentTxid: txid
|
|
812
|
+
});
|
|
813
|
+
if (persisted) {
|
|
814
|
+
const contractManager = await wallet.getContractManager();
|
|
815
|
+
await retireOfferContract(
|
|
816
|
+
contractManager,
|
|
817
|
+
swaps,
|
|
818
|
+
hex2.encode(prepared.offer.swapPkScript),
|
|
819
|
+
{ scope: wallet }
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return txid;
|
|
824
|
+
}
|
|
825
|
+
var NoSpendableDepositError = class extends Error {
|
|
826
|
+
name = "NoSpendableDepositError";
|
|
827
|
+
constructor(options) {
|
|
828
|
+
super("no spendable VTXO at the swap address", options);
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
var OfferCovenantMismatchError = class extends Error {
|
|
832
|
+
constructor(swapPkScript, options) {
|
|
833
|
+
super(
|
|
834
|
+
"rebuilt covenant does not match the offer's swapPkScript \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt",
|
|
835
|
+
options
|
|
836
|
+
);
|
|
837
|
+
this.swapPkScript = swapPkScript;
|
|
838
|
+
}
|
|
839
|
+
swapPkScript;
|
|
840
|
+
name = "OfferCovenantMismatchError";
|
|
841
|
+
};
|
|
842
|
+
async function prepareOfferCancel(wallet, offerHex, opts) {
|
|
843
|
+
const { fundingTxid, fundingOutpoint, swapAddress } = opts;
|
|
844
|
+
const offer = decodeOffer(hex2.decode(offerHex));
|
|
845
|
+
const [contractManager, info, reader, broadcaster] = await Promise.all([
|
|
846
|
+
wallet.getContractManager(),
|
|
847
|
+
wallet.getArkadeInfo({ requireLive: true }),
|
|
848
|
+
wallet.getArkadeReader(),
|
|
849
|
+
wallet.getArkadeBroadcaster()
|
|
850
|
+
]);
|
|
851
|
+
const client = await arkade.Arkade.connect({
|
|
852
|
+
arkade: { getInfo: async () => info, ...broadcaster },
|
|
853
|
+
indexer: reader,
|
|
854
|
+
identity: wallet.identity,
|
|
855
|
+
// registered offers resolve VTXOs from the contract repository; the indexer is the fallback
|
|
856
|
+
// for offers created before registration existed
|
|
857
|
+
contractManager
|
|
858
|
+
// no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
|
|
859
|
+
});
|
|
860
|
+
const operatorPubkey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
|
|
861
|
+
const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
|
|
862
|
+
let rebuilt;
|
|
863
|
+
try {
|
|
864
|
+
rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
|
|
865
|
+
} catch (cause) {
|
|
866
|
+
throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript), { cause });
|
|
867
|
+
}
|
|
868
|
+
if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
|
|
869
|
+
throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript));
|
|
870
|
+
}
|
|
871
|
+
const contract = new arkade.ArkadeContract(client, program, args, keys);
|
|
872
|
+
const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
|
|
873
|
+
const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
|
|
874
|
+
const makerPkScript = ArkAddress.decode(makerAddress).pkScript;
|
|
875
|
+
const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
|
|
876
|
+
for (const a of vtxo.assets ?? []) {
|
|
877
|
+
cancel.withAsset({
|
|
878
|
+
assetId: a.assetId,
|
|
879
|
+
inputs: [{ vin: 0, amount: BigInt(a.amount) }],
|
|
880
|
+
outputs: [{ vout: 0, amount: BigInt(a.amount) }]
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
return {
|
|
884
|
+
offer,
|
|
885
|
+
vtxo: { txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value },
|
|
886
|
+
send: async () => (await cancel.send()).txid
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
var ASSET_CARRIER_SATS = BigInt(SDK_ASSET_CARRIER_SATS);
|
|
890
|
+
async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
|
|
891
|
+
const {
|
|
892
|
+
fund,
|
|
893
|
+
payoutScript,
|
|
894
|
+
fundingTxid,
|
|
895
|
+
fundingOutpoint,
|
|
896
|
+
swapAddress,
|
|
897
|
+
assetCarrierSats = ASSET_CARRIER_SATS,
|
|
898
|
+
emulator,
|
|
899
|
+
emulatorPubkey
|
|
900
|
+
} = opts;
|
|
901
|
+
const offer = decodeOffer(hex2.decode(offerHex));
|
|
902
|
+
const contract = await connectFillContract(wallet, arkServerUrl, offer, {
|
|
903
|
+
swapAddress,
|
|
904
|
+
emulator,
|
|
905
|
+
emulatorPubkey
|
|
906
|
+
});
|
|
907
|
+
const [vtxos, takerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
|
|
908
|
+
const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
|
|
909
|
+
const fill = contract.functions.fulfill();
|
|
910
|
+
assembleOfferFill(fill, {
|
|
911
|
+
offer,
|
|
912
|
+
vtxo,
|
|
913
|
+
solverFund: fund,
|
|
914
|
+
solverPayout: payoutScript ?? ArkAddress.decode(takerAddress).pkScript,
|
|
915
|
+
assetCarrierSats
|
|
916
|
+
});
|
|
917
|
+
const { txid } = await fill.send();
|
|
918
|
+
return txid;
|
|
919
|
+
}
|
|
920
|
+
async function connectFillContract(wallet, arkServerUrl, offer, opts = {}) {
|
|
921
|
+
const { swapAddress, emulator, emulatorPubkey } = opts;
|
|
922
|
+
const contractManager = await wallet.getContractManager();
|
|
923
|
+
const client = await arkade.Arkade.connect({
|
|
924
|
+
arkade: new RestArkProvider(arkServerUrl),
|
|
925
|
+
indexer: new RestIndexerProvider(arkServerUrl),
|
|
926
|
+
identity: wallet.identity,
|
|
927
|
+
contractManager,
|
|
928
|
+
...emulator !== void 0 ? {
|
|
929
|
+
emulator: typeof emulator === "string" ? new RestEmulatorProvider(emulator) : emulator
|
|
930
|
+
} : {},
|
|
931
|
+
...emulatorPubkey ? { emulatorPubkey } : {}
|
|
932
|
+
});
|
|
933
|
+
const serverKey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
|
|
934
|
+
const { program, args, keys } = swapProgramBinding(offer, serverKey);
|
|
935
|
+
const rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
|
|
936
|
+
if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
|
|
937
|
+
throw new Error(
|
|
938
|
+
"rebuilt covenant does not match the offer's swapPkScript \u2014 the server signing key has likely rotated since funding; pass swapAddress (the funded address) to pin the original key"
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
return new arkade.ArkadeContract(client, program, args, keys);
|
|
942
|
+
}
|
|
943
|
+
function resolveDeposit(vtxos, sel) {
|
|
944
|
+
const { fundingTxid, fundingOutpoint } = sel;
|
|
945
|
+
if (fundingOutpoint !== void 0) {
|
|
946
|
+
const txid = parseHex32(fundingOutpoint.txid, "fundingOutpoint.txid");
|
|
947
|
+
const vout = assertVout(fundingOutpoint.vout, "fundingOutpoint.vout");
|
|
948
|
+
if (fundingTxid !== void 0 && fundingTxid.toLowerCase() !== txid) {
|
|
949
|
+
throw new Error(
|
|
950
|
+
`fundingTxid ${fundingTxid} does not match fundingOutpoint ${txid}:${vout} \u2014 pass one deposit reference`
|
|
951
|
+
);
|
|
952
|
+
}
|
|
953
|
+
const vtxo2 = vtxos.find((v) => v.txid.toLowerCase() === txid && v.vout === vout);
|
|
954
|
+
if (!vtxo2) throw new NoSpendableDepositError();
|
|
955
|
+
return vtxo2;
|
|
956
|
+
}
|
|
957
|
+
if (fundingTxid !== void 0) {
|
|
958
|
+
const txid = parseHex32(fundingTxid, "fundingTxid");
|
|
959
|
+
const matches = vtxos.filter((v) => v.txid.toLowerCase() === txid);
|
|
960
|
+
if (matches.length > 1) {
|
|
961
|
+
throw new Error(
|
|
962
|
+
`multiple spendable deposits share fundingTxid ${txid} \u2014 pass fundingOutpoint to select one`
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
const [vtxo2] = matches;
|
|
966
|
+
if (!vtxo2) throw new NoSpendableDepositError();
|
|
967
|
+
return vtxo2;
|
|
968
|
+
}
|
|
969
|
+
if (vtxos.length > 1) {
|
|
970
|
+
throw new Error(
|
|
971
|
+
"multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
|
|
972
|
+
);
|
|
973
|
+
}
|
|
974
|
+
const [vtxo] = vtxos;
|
|
975
|
+
if (!vtxo) throw new NoSpendableDepositError();
|
|
976
|
+
return vtxo;
|
|
977
|
+
}
|
|
978
|
+
function assembleOfferFill(fill, args) {
|
|
979
|
+
const {
|
|
980
|
+
offer,
|
|
981
|
+
vtxo,
|
|
982
|
+
solverFund,
|
|
983
|
+
solverPayout,
|
|
984
|
+
assetCarrierSats = ASSET_CARRIER_SATS,
|
|
985
|
+
sponsor
|
|
986
|
+
} = args;
|
|
987
|
+
const wantedAssetId = offer.wantAsset?.toString();
|
|
988
|
+
if (solverFund.length === 0) {
|
|
989
|
+
throw new Error("fillOffer needs coins to pay wantAmount with \u2014 `fund` is empty");
|
|
990
|
+
}
|
|
991
|
+
solverFund.forEach((coin, i) => assertFillCoin(coin, `fund[${i}]`));
|
|
992
|
+
assertScript(solverPayout, "payoutScript");
|
|
993
|
+
toAmount(vtxo.value, "deposit.value", "sats", BigInt(1));
|
|
994
|
+
assertAssetEntries(vtxo.assets, "deposit");
|
|
995
|
+
const carrier = toAmount(assetCarrierSats, "assetCarrierSats", "sats", BigInt(1));
|
|
996
|
+
let sponsorFund = [];
|
|
997
|
+
let sponsorChange = BigInt(0);
|
|
998
|
+
let fareAsset = "";
|
|
999
|
+
let fareAmount = BigInt(0);
|
|
1000
|
+
let fareSats = BigInt(0);
|
|
1001
|
+
let combineSatsFareWithChange = false;
|
|
1002
|
+
if (sponsor !== void 0) {
|
|
1003
|
+
if (sponsor.fund.length === 0) {
|
|
1004
|
+
throw new Error("sponsor needs coins to contribute with \u2014 `sponsor.fund` is empty");
|
|
1005
|
+
}
|
|
1006
|
+
sponsor.fund.forEach((coin, i) => {
|
|
1007
|
+
assertFillCoin(coin, `sponsor.fund[${i}]`);
|
|
1008
|
+
if ((coin.assets?.length ?? 0) > 0) {
|
|
1009
|
+
throw new Error(`sponsor.fund[${i}] carries assets \u2014 sponsor funding is sats-only`);
|
|
1010
|
+
}
|
|
1011
|
+
});
|
|
1012
|
+
assertScript(sponsor.changeScript, "sponsor.changeScript");
|
|
1013
|
+
const contribution = toAmount(
|
|
1014
|
+
sponsor.netContributionSats,
|
|
1015
|
+
"sponsor.netContributionSats",
|
|
1016
|
+
"sats"
|
|
1017
|
+
);
|
|
1018
|
+
if (contribution <= BigInt(0)) {
|
|
1019
|
+
throw new Error("sponsor.netContributionSats must be a positive amount of sats");
|
|
1020
|
+
}
|
|
1021
|
+
if (sponsor.combineSatsFareWithChange !== void 0 && typeof sponsor.combineSatsFareWithChange !== "boolean") {
|
|
1022
|
+
throw new Error("sponsor.combineSatsFareWithChange must be a boolean");
|
|
1023
|
+
}
|
|
1024
|
+
combineSatsFareWithChange = sponsor.combineSatsFareWithChange === true;
|
|
1025
|
+
if (combineSatsFareWithChange && sponsor.fare === void 0) {
|
|
1026
|
+
throw new Error("sponsor.combineSatsFareWithChange requires a fare");
|
|
1027
|
+
}
|
|
1028
|
+
if (sponsor.fare !== void 0) {
|
|
1029
|
+
const { assetId, amount } = sponsor.fare;
|
|
1030
|
+
if (assetId === void 0 !== (amount === void 0)) {
|
|
1031
|
+
throw new Error(
|
|
1032
|
+
"sponsor.fare needs assetId and amount together, or neither for a sats fare"
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
if (assetId !== void 0) {
|
|
1036
|
+
fareAsset = assertAssetId(assetId, "sponsor.fare.assetId");
|
|
1037
|
+
fareAmount = toAmount(amount, "sponsor.fare.amount", "asset units");
|
|
1038
|
+
if (fareAmount <= BigInt(0)) {
|
|
1039
|
+
throw new Error("sponsor.fare.amount must be a positive amount of asset units");
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
assertScript(sponsor.fare.script, "sponsor.fare.script");
|
|
1043
|
+
fareSats = toAmount(sponsor.fare.sats, "sponsor.fare.sats", "sats", BigInt(1));
|
|
1044
|
+
if (combineSatsFareWithChange) {
|
|
1045
|
+
if (assetId !== void 0) {
|
|
1046
|
+
throw new Error("sponsor.combineSatsFareWithChange requires a sats-only fare");
|
|
1047
|
+
}
|
|
1048
|
+
if (hex2.encode(sponsor.fare.script) !== hex2.encode(sponsor.changeScript)) {
|
|
1049
|
+
throw new Error(
|
|
1050
|
+
"sponsor.combineSatsFareWithChange requires fare and change to use the same script"
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
const sponsorInputs = sponsor.fund.reduce((s, c) => s + BigInt(c.value), BigInt(0));
|
|
1056
|
+
if (contribution > sponsorInputs) {
|
|
1057
|
+
throw new Error(
|
|
1058
|
+
`sponsor.netContributionSats ${contribution} exceeds the sponsor inputs ${sponsorInputs}`
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
sponsorFund = sponsor.fund;
|
|
1062
|
+
const baseSponsorChange = sponsorInputs - contribution;
|
|
1063
|
+
sponsorChange = combineSatsFareWithChange ? toAmount(baseSponsorChange + fareSats, "combined sponsor change", "sats", BigInt(1)) : baseSponsorChange;
|
|
1064
|
+
}
|
|
1065
|
+
if (wantedAssetId !== void 0) {
|
|
1066
|
+
const required = offer.wantAmount + (sponsor?.fare !== void 0 && fareAsset === wantedAssetId ? fareAmount : BigInt(0));
|
|
1067
|
+
const supplied = solverFund.reduce(
|
|
1068
|
+
(sum, coin) => sum + amountOfAsset(coin.assets, wantedAssetId),
|
|
1069
|
+
BigInt(0)
|
|
1070
|
+
);
|
|
1071
|
+
if (supplied < required) {
|
|
1072
|
+
throw new Error(
|
|
1073
|
+
`fillOffer needs ${required} of ${wantedAssetId} to pay the maker, but \`fund\` declares ${supplied} \u2014 pass coins carrying it, and declare their assets`
|
|
1074
|
+
);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
if (offer.offerAsset) {
|
|
1078
|
+
const offered = offer.offerAsset.toString();
|
|
1079
|
+
const deposited = amountOfAsset(vtxo.assets, offered);
|
|
1080
|
+
if (deposited <= BigInt(0)) {
|
|
1081
|
+
throw new Error(
|
|
1082
|
+
`the deposit at the swap address carries no ${offered}, which this offer sells \u2014 filling it would pay wantAmount for nothing. The indexer may be behind, or the offer may not be backed by what it advertises`
|
|
1083
|
+
);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1087
|
+
const claim = (txid, vout, what) => {
|
|
1088
|
+
const key = `${txid.toLowerCase()}:${vout}`;
|
|
1089
|
+
if (seen.has(key)) throw new Error(`duplicate fill input ${key} (${what})`);
|
|
1090
|
+
seen.add(key);
|
|
1091
|
+
};
|
|
1092
|
+
claim(parseHex32(vtxo.txid, "deposit.txid"), assertVout(vtxo.vout, "deposit.vout"), "deposit");
|
|
1093
|
+
solverFund.forEach((coin, i) => claim(coin.txid, coin.vout, `fund[${i}]`));
|
|
1094
|
+
sponsorFund.forEach((coin, i) => claim(coin.txid, coin.vout, `sponsor.fund[${i}]`));
|
|
1095
|
+
const makerSats = wantedAssetId === void 0 ? toAmount(offer.wantAmount, "offer.wantAmount", "sats") : carrier;
|
|
1096
|
+
const outputs = [
|
|
1097
|
+
{ role: "receiver", script: offer.makerPkScript, sats: makerSats }
|
|
1098
|
+
];
|
|
1099
|
+
const fareVout = outputs.length;
|
|
1100
|
+
if (sponsor?.fare !== void 0 && !combineSatsFareWithChange) {
|
|
1101
|
+
outputs.push({ role: "sponsor-fare", script: sponsor.fare.script, sats: fareSats });
|
|
1102
|
+
}
|
|
1103
|
+
if (sponsor !== void 0 && sponsorChange > BigInt(0)) {
|
|
1104
|
+
outputs.push({ role: "sponsor-change", script: sponsor.changeScript, sats: sponsorChange });
|
|
1105
|
+
}
|
|
1106
|
+
const solverVout = outputs.length;
|
|
1107
|
+
fill.from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).fund(sponsorFund.length > 0 ? [...solverFund, ...sponsorFund] : solverFund).to(offer.makerPkScript, makerSats);
|
|
1108
|
+
if (sponsor?.fare !== void 0 && !combineSatsFareWithChange)
|
|
1109
|
+
fill.to(sponsor.fare.script, fareSats);
|
|
1110
|
+
if (sponsor !== void 0 && sponsorChange > BigInt(0))
|
|
1111
|
+
fill.to(sponsor.changeScript, sponsorChange);
|
|
1112
|
+
fill.change(solverPayout);
|
|
1113
|
+
const held = /* @__PURE__ */ new Map();
|
|
1114
|
+
const hold = (vin, assets) => {
|
|
1115
|
+
for (const a of assets ?? []) {
|
|
1116
|
+
const amount = BigInt(a.amount);
|
|
1117
|
+
if (amount <= BigInt(0)) continue;
|
|
1118
|
+
held.set(a.assetId, [...held.get(a.assetId) ?? [], { vin, amount }]);
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
hold(0, vtxo.assets);
|
|
1122
|
+
solverFund.forEach((coin, i) => hold(i + 1, coin.assets));
|
|
1123
|
+
sponsorFund.forEach((coin, i) => hold(1 + solverFund.length + i, coin.assets));
|
|
1124
|
+
const explicitSats = outputs.reduce((s, o) => s + o.sats, BigInt(0));
|
|
1125
|
+
const inputsSum = BigInt(vtxo.value) + solverFund.reduce((s, c) => s + BigInt(c.value), BigInt(0)) + sponsorFund.reduce((s, c) => s + BigInt(c.value), BigInt(0));
|
|
1126
|
+
if (inputsSum > MAX_SAFE_SATS) {
|
|
1127
|
+
throw new Error(`fill inputs total ${inputsSum} sats exceeds the safe integer domain`);
|
|
1128
|
+
}
|
|
1129
|
+
if (explicitSats > MAX_SAFE_SATS) {
|
|
1130
|
+
throw new Error(`fill outputs total ${explicitSats} sats exceeds the safe integer domain`);
|
|
1131
|
+
}
|
|
1132
|
+
if (explicitSats > inputsSum) {
|
|
1133
|
+
throw new Error(
|
|
1134
|
+
`fill outputs total ${explicitSats} sats but the inputs carry ${inputsSum} \u2014 increase solver or sponsor funding`
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
const hasPayoutOutput = inputsSum > explicitSats;
|
|
1138
|
+
if (sponsor?.fare !== void 0 && fareAsset !== "") {
|
|
1139
|
+
const carried = (held.get(fareAsset) ?? []).reduce((s, i) => s + i.amount, BigInt(0));
|
|
1140
|
+
if (carried < fareAmount) {
|
|
1141
|
+
throw new Error(
|
|
1142
|
+
`sponsor fare needs ${fareAmount} of ${fareAsset} but the inputs carry ${carried}`
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
const stranded = (assetId, amount) => new Error(
|
|
1147
|
+
`fillOffer has ${amount} of ${assetId} to return but no payout output \u2014 fund with more sats than the maker's output takes`
|
|
1148
|
+
);
|
|
1149
|
+
if (wantedAssetId !== void 0) {
|
|
1150
|
+
const supplying = held.get(wantedAssetId) ?? [];
|
|
1151
|
+
const supplied = supplying.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1152
|
+
const group = [{ vout: 0, amount: offer.wantAmount }];
|
|
1153
|
+
const farePart = sponsor?.fare !== void 0 && fareAsset === wantedAssetId ? fareAmount : BigInt(0);
|
|
1154
|
+
if (farePart > BigInt(0)) group.push({ vout: fareVout, amount: farePart });
|
|
1155
|
+
const surplus = supplied - offer.wantAmount - farePart;
|
|
1156
|
+
if (surplus > BigInt(0)) {
|
|
1157
|
+
if (!hasPayoutOutput) throw stranded(wantedAssetId, surplus);
|
|
1158
|
+
group.push({ vout: solverVout, amount: surplus });
|
|
1159
|
+
}
|
|
1160
|
+
fill.withAsset({ assetId: wantedAssetId, inputs: supplying, outputs: group });
|
|
1161
|
+
held.delete(wantedAssetId);
|
|
1162
|
+
}
|
|
1163
|
+
if (sponsor?.fare !== void 0 && fareAsset !== "" && fareAsset !== wantedAssetId) {
|
|
1164
|
+
const supplying = held.get(fareAsset) ?? [];
|
|
1165
|
+
const carried = supplying.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1166
|
+
const group = [{ vout: fareVout, amount: fareAmount }];
|
|
1167
|
+
const remainder = carried - fareAmount;
|
|
1168
|
+
if (remainder > BigInt(0)) {
|
|
1169
|
+
if (!hasPayoutOutput) throw stranded(fareAsset, remainder);
|
|
1170
|
+
group.push({ vout: solverVout, amount: remainder });
|
|
1171
|
+
}
|
|
1172
|
+
fill.withAsset({ assetId: fareAsset, inputs: supplying, outputs: group });
|
|
1173
|
+
held.delete(fareAsset);
|
|
1174
|
+
}
|
|
1175
|
+
for (const [assetId, inputs] of held) {
|
|
1176
|
+
const amount = inputs.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1177
|
+
if (!hasPayoutOutput) throw stranded(assetId, amount);
|
|
1178
|
+
fill.withAsset({ assetId, inputs, outputs: [{ vout: solverVout, amount }] });
|
|
1179
|
+
}
|
|
1180
|
+
if (hasPayoutOutput) {
|
|
1181
|
+
outputs.push({ role: "solver", script: solverPayout, sats: inputsSum - explicitSats });
|
|
1182
|
+
}
|
|
1183
|
+
return {
|
|
1184
|
+
inputs: [
|
|
1185
|
+
{ owner: null, txid: vtxo.txid.toLowerCase(), vout: vtxo.vout },
|
|
1186
|
+
...solverFund.map((coin) => ({
|
|
1187
|
+
owner: "solver",
|
|
1188
|
+
txid: coin.txid.toLowerCase(),
|
|
1189
|
+
vout: coin.vout
|
|
1190
|
+
})),
|
|
1191
|
+
...sponsorFund.map((coin) => ({
|
|
1192
|
+
owner: "sponsor",
|
|
1193
|
+
txid: coin.txid.toLowerCase(),
|
|
1194
|
+
vout: coin.vout
|
|
1195
|
+
}))
|
|
1196
|
+
],
|
|
1197
|
+
outputs
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
var amountOfAsset = (assets, assetId) => {
|
|
1201
|
+
let total = BigInt(0);
|
|
1202
|
+
for (const a of assets ?? []) {
|
|
1203
|
+
if (a.assetId === assetId) total += BigInt(a.amount);
|
|
1204
|
+
}
|
|
1205
|
+
return total;
|
|
1206
|
+
};
|
|
1207
|
+
var U64_MAX = (BigInt(1) << BigInt(64)) - BigInt(1);
|
|
1208
|
+
var MAX_SAFE_SATS = BigInt(Number.MAX_SAFE_INTEGER);
|
|
1209
|
+
function assertVout(vout, what) {
|
|
1210
|
+
if (typeof vout !== "number" || !Number.isSafeInteger(vout) || vout < 0 || vout > 4294967295) {
|
|
1211
|
+
throw new Error(`${what} must be a non-negative output index`);
|
|
1212
|
+
}
|
|
1213
|
+
return vout;
|
|
1214
|
+
}
|
|
1215
|
+
function toAmount(value, what, unit, min = BigInt(0)) {
|
|
1216
|
+
const max = unit === "sats" ? MAX_SAFE_SATS : U64_MAX;
|
|
1217
|
+
let amount;
|
|
1218
|
+
if (typeof value === "bigint") {
|
|
1219
|
+
if (value >= BigInt(0) && value <= max) amount = value;
|
|
1220
|
+
} else if (typeof value === "number") {
|
|
1221
|
+
if (Number.isSafeInteger(value) && value >= 0) amount = BigInt(value);
|
|
1222
|
+
}
|
|
1223
|
+
if (amount === void 0) {
|
|
1224
|
+
throw new Error(`${what} must be a safe integer amount of ${unit} (0 to ${max})`);
|
|
1225
|
+
}
|
|
1226
|
+
if (amount < min) {
|
|
1227
|
+
throw new Error(`${what} must be a positive amount of ${unit}`);
|
|
1228
|
+
}
|
|
1229
|
+
return amount;
|
|
1230
|
+
}
|
|
1231
|
+
function assertScript(script, what) {
|
|
1232
|
+
if (!(script instanceof Uint8Array) || script.length === 0) {
|
|
1233
|
+
throw new Error(`${what} must be a non-empty output script`);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
function assertAssetId(assetId, what) {
|
|
1237
|
+
if (typeof assetId !== "string") throw new Error(`${what} must be an asset id string`);
|
|
1238
|
+
try {
|
|
1239
|
+
return asset.AssetId.fromString(assetId).toString();
|
|
1240
|
+
} catch {
|
|
1241
|
+
throw new Error(`${what} is not a valid asset id`);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
function assertAssetEntries(assets, what) {
|
|
1245
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1246
|
+
for (const [i, a] of (assets ?? []).entries()) {
|
|
1247
|
+
const id = assertAssetId(a.assetId, `${what}.assets[${i}].assetId`);
|
|
1248
|
+
if (seen.has(id)) {
|
|
1249
|
+
throw new Error(`${what} declares ${id} twice \u2014 merge the entries instead`);
|
|
1250
|
+
}
|
|
1251
|
+
seen.add(id);
|
|
1252
|
+
toAmount(a.amount, `${what}.assets[${i}].amount`, "asset units");
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
function assertFillCoin(coin, what) {
|
|
1256
|
+
parseHex32(coin.txid, `${what}.txid`);
|
|
1257
|
+
assertVout(coin.vout, `${what}.vout`);
|
|
1258
|
+
toAmount(coin.value, `${what}.value`, "sats", BigInt(1));
|
|
1259
|
+
assertAssetEntries(coin.assets, what);
|
|
1260
|
+
}
|
|
1261
|
+
var offerVtxoScript = offerContract;
|
|
1262
|
+
|
|
1263
|
+
// src/lockupContract.ts
|
|
1264
|
+
import { hex as hex3 } from "@scure/base";
|
|
1265
|
+
import {
|
|
1266
|
+
ArkAddress as ArkAddress2,
|
|
1267
|
+
VHTLCV2ContractHandler
|
|
1268
|
+
} from "@arkade-os/sdk";
|
|
1269
|
+
var SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
|
|
1270
|
+
var SWAP_LOCKUP_CONTRACT_LABEL = "Arkade RFQ swap lockup";
|
|
1271
|
+
var SWAP_LOCKUP_CONTRACT_KIND = "rfq-swap-lockup";
|
|
1272
|
+
var LockupContractMissing = class extends Error {
|
|
1273
|
+
/** The lockup whose row is absent. */
|
|
1274
|
+
address;
|
|
1275
|
+
/** Its pkScript hex — the key the row would have been under. */
|
|
1276
|
+
script;
|
|
1277
|
+
constructor(address, script) {
|
|
1278
|
+
super(
|
|
1279
|
+
`no contract row for lockup ${address} (script ${script}); its covenant cannot be rebuilt from this wallet's contract store`
|
|
1280
|
+
);
|
|
1281
|
+
this.name = "LockupContractMissing";
|
|
1282
|
+
this.address = address;
|
|
1283
|
+
this.script = script;
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
var LockupRegistrationFailed = class extends Error {
|
|
1287
|
+
/** The lockup address that was never registered — never fund it: nothing
|
|
1288
|
+
* is watching it. */
|
|
1289
|
+
address;
|
|
1290
|
+
/** The covenant the row would have been written from, so the write is retryable without a
|
|
1291
|
+
* quote. */
|
|
1292
|
+
script;
|
|
1293
|
+
constructor(script, address, cause) {
|
|
1294
|
+
super(`failed to register the lockup contract for ${address}`, { cause });
|
|
1295
|
+
this.name = "LockupRegistrationFailed";
|
|
1296
|
+
this.address = address;
|
|
1297
|
+
this.script = script;
|
|
1298
|
+
}
|
|
1299
|
+
};
|
|
1300
|
+
async function registerLockupContract(contracts, script, address, options = {}) {
|
|
1301
|
+
try {
|
|
1302
|
+
await registerContractCoverage(
|
|
1303
|
+
hex3.encode(script.pkScript),
|
|
1304
|
+
() => contracts.createContract({
|
|
1305
|
+
type: SWAP_LOCKUP_CONTRACT_TYPE,
|
|
1306
|
+
params: VHTLCV2ContractHandler.serializeParams(script.options),
|
|
1307
|
+
script: hex3.encode(script.pkScript),
|
|
1308
|
+
address,
|
|
1309
|
+
label: SWAP_LOCKUP_CONTRACT_LABEL,
|
|
1310
|
+
metadata: { genericallySpendable: false, kind: SWAP_LOCKUP_CONTRACT_KIND }
|
|
1311
|
+
}),
|
|
1312
|
+
options
|
|
1313
|
+
);
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
throw new LockupRegistrationFailed(script, address, error);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
async function lockupContractParams(contracts, lockupAddress) {
|
|
1319
|
+
const script = hex3.encode(ArkAddress2.decode(lockupAddress).pkScript);
|
|
1320
|
+
const [row] = await contracts.getContracts({ script });
|
|
1321
|
+
if (!row) throw new LockupContractMissing(lockupAddress, script);
|
|
1322
|
+
return row.params;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
// src/onchainHtlc.ts
|
|
1326
|
+
import { hex as hex4 } from "@scure/base";
|
|
1327
|
+
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
1328
|
+
import { ripemd160 } from "@noble/hashes/legacy.js";
|
|
1329
|
+
import * as btc from "@scure/btc-signer";
|
|
1330
|
+
import { assertTimerMs } from "@arkade-os/sdk";
|
|
1331
|
+
var ONCHAIN_ORDER_MARGIN_SECONDS = 2 * 60 * 60;
|
|
1332
|
+
var ONCHAIN_CLAIM_MARGIN_SECONDS = 90 * 60;
|
|
1333
|
+
var ONCHAIN_CLAIM_BUMP_SECONDS = 20 * 60;
|
|
1334
|
+
var MAX_MIN_CONFIRMATIONS = 6;
|
|
1335
|
+
var LOCKTIME_THRESHOLD = 5e8;
|
|
1336
|
+
var ONCHAIN_SECONDS_PER_BLOCK = 600;
|
|
1337
|
+
var ONCHAIN_DUST_SATS = BigInt(330);
|
|
1338
|
+
var ONCHAIN_CLAIM_VSIZE = 152;
|
|
1339
|
+
var newPreimage = () => crypto.getRandomValues(new Uint8Array(32));
|
|
1340
|
+
var paymentHashOf = (preimage) => hex4.encode(sha2562(preimage));
|
|
1341
|
+
var h160FromPaymentHash = (paymentHash) => ripemd160(hex4.decode(paymentHash));
|
|
1342
|
+
var assertPreimageMatches = (preimage, preimageHash) => {
|
|
1343
|
+
if (hex4.encode(ripemd160(sha2562(preimage))) !== hex4.encode(preimageHash)) {
|
|
1344
|
+
throw new Error("preimage does not match the covenant's payment hash");
|
|
1345
|
+
}
|
|
1346
|
+
};
|
|
1347
|
+
var gateError = (reason, message) => {
|
|
1348
|
+
const error = new Error(message);
|
|
1349
|
+
error.reason = reason;
|
|
1350
|
+
return error;
|
|
1351
|
+
};
|
|
1352
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1353
|
+
async function pollUntil(probe, options, reason, message) {
|
|
1354
|
+
const pollMs = options.pollMs ?? 5e3;
|
|
1355
|
+
assertTimerMs("pollMs", pollMs);
|
|
1356
|
+
for (; ; ) {
|
|
1357
|
+
const value = await probe();
|
|
1358
|
+
if (value !== void 0) return value;
|
|
1359
|
+
if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
|
|
1360
|
+
throw gateError(reason, message);
|
|
1361
|
+
}
|
|
1362
|
+
await sleep(pollMs);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
var L1_NETWORKS = {
|
|
1366
|
+
bitcoin: btc.NETWORK,
|
|
1367
|
+
testnet: btc.TEST_NETWORK,
|
|
1368
|
+
regtest: { ...btc.TEST_NETWORK, bech32: "bcrt" }
|
|
1369
|
+
};
|
|
1370
|
+
var l1ScriptForAddress = (address, network) => btc.OutScript.encode(btc.Address(L1_NETWORKS[network]).decode(address));
|
|
1371
|
+
function onchainHtlcScript(params, network) {
|
|
1372
|
+
if (params.claimKey.length !== 32 || params.refundKey.length !== 32) {
|
|
1373
|
+
throw new Error("claimKey and refundKey must be 32-byte x-only keys");
|
|
1374
|
+
}
|
|
1375
|
+
if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0) {
|
|
1376
|
+
throw new Error(
|
|
1377
|
+
`refundLocktime must be a positive unix timestamp, got ${params.refundLocktime}`
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
if (params.refundLocktime < LOCKTIME_THRESHOLD) {
|
|
1381
|
+
throw new Error(
|
|
1382
|
+
`refundLocktime ${params.refundLocktime} is below LOCKTIME_THRESHOLD (${LOCKTIME_THRESHOLD}) and would be interpreted as a block height`
|
|
1383
|
+
);
|
|
1384
|
+
}
|
|
1385
|
+
if (!Object.hasOwn(L1_NETWORKS, network)) {
|
|
1386
|
+
throw new Error(
|
|
1387
|
+
`unknown L1 network '${String(network)}' \u2014 expected one of ${Object.keys(L1_NETWORKS).join(", ")}`
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
const h160 = h160FromPaymentHash(params.paymentHash);
|
|
1391
|
+
const claim = btc.Script.encode([
|
|
1392
|
+
"SIZE",
|
|
1393
|
+
32,
|
|
1394
|
+
"EQUALVERIFY",
|
|
1395
|
+
"HASH160",
|
|
1396
|
+
h160,
|
|
1397
|
+
"EQUALVERIFY",
|
|
1398
|
+
params.claimKey,
|
|
1399
|
+
"CHECKSIG"
|
|
1400
|
+
]);
|
|
1401
|
+
const refund = btc.Script.encode([
|
|
1402
|
+
btc.ScriptNum().encode(BigInt(params.refundLocktime)),
|
|
1403
|
+
"CHECKLOCKTIMEVERIFY",
|
|
1404
|
+
"DROP",
|
|
1405
|
+
params.refundKey,
|
|
1406
|
+
"CHECKSIG"
|
|
1407
|
+
]);
|
|
1408
|
+
const payment = btc.p2tr(
|
|
1409
|
+
btc.taprootNumsKey(),
|
|
1410
|
+
btc.taprootListToTree([{ script: claim }, { script: refund }]),
|
|
1411
|
+
L1_NETWORKS[network],
|
|
1412
|
+
true
|
|
1413
|
+
);
|
|
1414
|
+
const controlBlockFor = (leaf) => {
|
|
1415
|
+
for (const [block, script] of payment.tapLeafScript ?? []) {
|
|
1416
|
+
if (script.length - 1 === leaf.length && hex4.encode(script.subarray(0, leaf.length)) === hex4.encode(leaf)) {
|
|
1417
|
+
return btc.TaprootControlBlock.encode(block);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
throw new Error("leaf missing from compiled taproot tree");
|
|
1421
|
+
};
|
|
1422
|
+
return {
|
|
1423
|
+
address: payment.address,
|
|
1424
|
+
pkScript: payment.script,
|
|
1425
|
+
leaves: { claim, refund },
|
|
1426
|
+
controlBlocks: { claim: controlBlockFor(claim), refund: controlBlockFor(refund) },
|
|
1427
|
+
paymentHash: params.paymentHash,
|
|
1428
|
+
refundLocktime: params.refundLocktime
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
var buildLeafSpend = async (input) => {
|
|
1432
|
+
if (!Number.isFinite(input.feeRateSatVb) || input.feeRateSatVb <= 0) {
|
|
1433
|
+
throw new Error(`feeRateSatVb must be positive, got ${input.feeRateSatVb}`);
|
|
1434
|
+
}
|
|
1435
|
+
const assemble = (payout2) => {
|
|
1436
|
+
const tx2 = new btc.Transaction({ lockTime: input.lockTime ?? 0 });
|
|
1437
|
+
tx2.addInput({
|
|
1438
|
+
txid: input.utxo.txid,
|
|
1439
|
+
index: input.utxo.vout,
|
|
1440
|
+
witnessUtxo: { script: input.htlc.pkScript, amount: input.utxo.amount },
|
|
1441
|
+
sequence: input.sequence
|
|
1442
|
+
});
|
|
1443
|
+
tx2.addOutput({ script: input.payoutPkScript, amount: payout2 });
|
|
1444
|
+
return tx2;
|
|
1445
|
+
};
|
|
1446
|
+
const witness = (sig2) => [
|
|
1447
|
+
sig2,
|
|
1448
|
+
...input.stackAboveSig,
|
|
1449
|
+
input.leaf,
|
|
1450
|
+
input.controlBlock
|
|
1451
|
+
];
|
|
1452
|
+
const sizing = assemble(input.utxo.amount);
|
|
1453
|
+
sizing.updateInput(0, { finalScriptWitness: witness(new Uint8Array(64)) }, true);
|
|
1454
|
+
const fee = BigInt(Math.ceil(sizing.vsize * input.feeRateSatVb));
|
|
1455
|
+
const payout = input.utxo.amount - fee;
|
|
1456
|
+
if (payout < ONCHAIN_DUST_SATS) {
|
|
1457
|
+
throw new Error(
|
|
1458
|
+
`fee ${fee} leaves ${payout} sats from a ${input.utxo.amount} sat HTLC \u2014 below the ${ONCHAIN_DUST_SATS} sat dust limit`
|
|
1459
|
+
);
|
|
1460
|
+
}
|
|
1461
|
+
const tx = assemble(payout);
|
|
1462
|
+
const sighash = tx.preimageWitnessV1(
|
|
1463
|
+
0,
|
|
1464
|
+
[input.htlc.pkScript],
|
|
1465
|
+
btc.SigHash.DEFAULT,
|
|
1466
|
+
[input.utxo.amount],
|
|
1467
|
+
void 0,
|
|
1468
|
+
input.leaf,
|
|
1469
|
+
192
|
|
1470
|
+
);
|
|
1471
|
+
const sig = await input.sign(sighash);
|
|
1472
|
+
if (sig.length !== 64)
|
|
1473
|
+
throw new Error(`sign() must return a 64-byte BIP340 signature, got ${sig.length}`);
|
|
1474
|
+
tx.updateInput(0, { finalScriptWitness: witness(sig) }, true);
|
|
1475
|
+
return { txHex: tx.hex, txid: tx.id, payoutAmount: payout };
|
|
1476
|
+
};
|
|
1477
|
+
var buildHtlcClaim = async (input) => {
|
|
1478
|
+
if (paymentHashOf(input.preimage) !== input.htlc.paymentHash) {
|
|
1479
|
+
throw new Error("preimage does not hash to the HTLC's payment hash");
|
|
1480
|
+
}
|
|
1481
|
+
return buildLeafSpend({
|
|
1482
|
+
htlc: input.htlc,
|
|
1483
|
+
utxo: input.utxo,
|
|
1484
|
+
leaf: input.htlc.leaves.claim,
|
|
1485
|
+
controlBlock: input.htlc.controlBlocks.claim,
|
|
1486
|
+
stackAboveSig: [input.preimage],
|
|
1487
|
+
payoutPkScript: input.payoutPkScript,
|
|
1488
|
+
feeRateSatVb: input.feeRateSatVb,
|
|
1489
|
+
sign: input.sign,
|
|
1490
|
+
sequence: 4294967293
|
|
1491
|
+
});
|
|
1492
|
+
};
|
|
1493
|
+
var buildHtlcRefund = (input) => buildLeafSpend({
|
|
1494
|
+
htlc: input.htlc,
|
|
1495
|
+
utxo: input.utxo,
|
|
1496
|
+
leaf: input.htlc.leaves.refund,
|
|
1497
|
+
controlBlock: input.htlc.controlBlocks.refund,
|
|
1498
|
+
stackAboveSig: [],
|
|
1499
|
+
payoutPkScript: input.payoutPkScript,
|
|
1500
|
+
feeRateSatVb: input.feeRateSatVb,
|
|
1501
|
+
sign: input.sign,
|
|
1502
|
+
lockTime: input.htlc.refundLocktime,
|
|
1503
|
+
// any value below 0xffffffff enables nLockTime enforcement
|
|
1504
|
+
sequence: 4294967294
|
|
1505
|
+
});
|
|
1506
|
+
function nextClaimFeeRate(input) {
|
|
1507
|
+
const last = input.lastSatVb;
|
|
1508
|
+
const estimate = Number.isFinite(input.estimateSatVb) ? input.estimateSatVb : 0;
|
|
1509
|
+
const wanted = last === void 0 ? Math.max(input.configuredSatVb, estimate) : input.bump ? Math.max(Math.ceil(last * 1.5), last + 1, estimate) : Math.max(last, estimate);
|
|
1510
|
+
const affordable = Number((input.utxoAmount - ONCHAIN_DUST_SATS) / BigInt(ONCHAIN_CLAIM_VSIZE));
|
|
1511
|
+
return Math.max(last ?? input.configuredSatVb, Math.min(wanted, affordable));
|
|
1512
|
+
}
|
|
1513
|
+
function extractPreimage(txHex, paymentHash) {
|
|
1514
|
+
let raw;
|
|
1515
|
+
try {
|
|
1516
|
+
raw = btc.RawTx.decode(hex4.decode(txHex));
|
|
1517
|
+
} catch {
|
|
1518
|
+
return null;
|
|
1519
|
+
}
|
|
1520
|
+
for (const stack of raw.witnesses ?? []) {
|
|
1521
|
+
for (const item of stack) {
|
|
1522
|
+
if (item.length === 32 && hex4.encode(sha2562(item)) === paymentHash) return item;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
return null;
|
|
1526
|
+
}
|
|
1527
|
+
async function awaitOnchainFill(chain, htlc, minConfirmations, options = {}) {
|
|
1528
|
+
return pollUntil(
|
|
1529
|
+
async () => {
|
|
1530
|
+
const utxos = await chain.getScriptUtxos(htlc.pkScript);
|
|
1531
|
+
return utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
|
|
1532
|
+
},
|
|
1533
|
+
options,
|
|
1534
|
+
"fill_timeout",
|
|
1535
|
+
"HTLC was not filled before the deadline"
|
|
1536
|
+
);
|
|
1537
|
+
}
|
|
1538
|
+
async function claimOnchainFill(chain, input) {
|
|
1539
|
+
const now = input.now ?? Math.floor(Date.now() / 1e3);
|
|
1540
|
+
if (!input.republish && input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
|
|
1541
|
+
throw gateError(
|
|
1542
|
+
"claim_window_closed",
|
|
1543
|
+
"refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
const spend = await buildHtlcClaim(input);
|
|
1547
|
+
const txid = await chain.broadcast(spend.txHex);
|
|
1548
|
+
return { txid, payoutAmount: spend.payoutAmount };
|
|
1549
|
+
}
|
|
1550
|
+
async function classifyOnchainHtlc(chain, input) {
|
|
1551
|
+
const utxos = await chain.getScriptUtxos(input.htlc.pkScript);
|
|
1552
|
+
const best = utxos.sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
|
|
1553
|
+
if (!best) {
|
|
1554
|
+
if (!input.funding) return { phase: "unfunded" };
|
|
1555
|
+
const spend = await chain.getSpendingTx(
|
|
1556
|
+
input.funding.txid,
|
|
1557
|
+
input.funding.vout,
|
|
1558
|
+
input.htlc.pkScript
|
|
1559
|
+
);
|
|
1560
|
+
if (!spend) return { phase: "unfunded" };
|
|
1561
|
+
const preimage = extractPreimage(spend.txHex, input.htlc.paymentHash);
|
|
1562
|
+
const txid = btc.Transaction.fromRaw(hex4.decode(spend.txHex), {
|
|
1563
|
+
allowUnknownInputs: true,
|
|
1564
|
+
allowUnknownOutputs: true
|
|
1565
|
+
}).id;
|
|
1566
|
+
return preimage ? { phase: "claimed", txid, preimage } : { phase: "swept", txid };
|
|
1567
|
+
}
|
|
1568
|
+
if (best.confirmations < input.minConfirmations)
|
|
1569
|
+
return { phase: "awaiting_confirmations", utxo: best };
|
|
1570
|
+
const mtp = await chain.getMtp();
|
|
1571
|
+
if (mtp >= input.htlc.refundLocktime) return { phase: "refundable", utxo: best };
|
|
1572
|
+
return { phase: "claimable", utxo: best };
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
// src/claimPacket.ts
|
|
1576
|
+
import { base64 } from "@scure/base";
|
|
1577
|
+
import { concatBytes as concatBytes2 } from "@scure/btc-signer/utils.js";
|
|
1578
|
+
import { gcm } from "@noble/ciphers/aes.js";
|
|
1579
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
1580
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
1581
|
+
import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
|
|
1582
|
+
var HKDF_INFO = new TextEncoder().encode("covclaimd/preimage/v1");
|
|
1583
|
+
async function sealClaimPacket(input) {
|
|
1584
|
+
return sealWithEntropy(
|
|
1585
|
+
input,
|
|
1586
|
+
secp256k1.utils.randomSecretKey(),
|
|
1587
|
+
crypto.getRandomValues(new Uint8Array(12))
|
|
1588
|
+
);
|
|
1589
|
+
}
|
|
1590
|
+
async function sealWithEntropy(input, ephemeralKey, nonce) {
|
|
1591
|
+
if (input.preimage.length !== 32) throw new Error("preimage must be 32 bytes");
|
|
1592
|
+
if (input.covclaimdPubkey.length !== 33) {
|
|
1593
|
+
throw new Error("covclaimd pubkey must be 33-byte compressed");
|
|
1594
|
+
}
|
|
1595
|
+
const { minAmount } = input;
|
|
1596
|
+
if (minAmount !== void 0 && (typeof minAmount !== "bigint" || minAmount < 1n || minAmount >= 1n << 64n)) {
|
|
1597
|
+
throw new Error("minAmount must be a bigint in [1, 2^64-1]");
|
|
1598
|
+
}
|
|
1599
|
+
const ephemeralPub = secp256k1.getPublicKey(ephemeralKey, true);
|
|
1600
|
+
const sharedX = secp256k1.getSharedSecret(ephemeralKey, input.covclaimdPubkey, true).subarray(1);
|
|
1601
|
+
const key = hkdf(sha2563, sharedX, ephemeralPub, HKDF_INFO, 32);
|
|
1602
|
+
if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
|
|
1603
|
+
const amount = new Uint8Array(8);
|
|
1604
|
+
if (minAmount !== void 0) new DataView(amount.buffer).setBigUint64(0, minAmount, false);
|
|
1605
|
+
const additionalData = minAmount === void 0 ? ephemeralPub : concatBytes2(ephemeralPub, amount);
|
|
1606
|
+
const sealed = gcm(key, nonce, additionalData).encrypt(input.preimage);
|
|
1607
|
+
const ciphertext = concatBytes2(ephemeralPub, nonce, sealed);
|
|
1608
|
+
return {
|
|
1609
|
+
ciphertext: base64.encode(ciphertext),
|
|
1610
|
+
packet: base64.encode(
|
|
1611
|
+
concatBytes2(
|
|
1612
|
+
tlv2(TLV_CIPHERTEXT, ciphertext),
|
|
1613
|
+
tlv2(TLV_COVCLAIMD_PUBKEY, input.covclaimdPubkey),
|
|
1614
|
+
minAmount === void 0 ? new Uint8Array() : tlv2(TLV_MIN_AMOUNT, amount)
|
|
1615
|
+
)
|
|
1616
|
+
)
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1619
|
+
var TLV_CIPHERTEXT = 1;
|
|
1620
|
+
var TLV_ARKADE_SCRIPT = 2;
|
|
1621
|
+
var TLV_COVCLAIMD_PUBKEY = 3;
|
|
1622
|
+
var TLV_MIN_AMOUNT = 4;
|
|
1623
|
+
var COMPRESSED_PUBKEY_LENGTH = 33;
|
|
1624
|
+
var SEALED_CIPHERTEXT_LENGTH = 93;
|
|
1625
|
+
var CLAIM_PACKET_TYPE = 4;
|
|
1626
|
+
var tlv2 = (type, value) => Uint8Array.from([type, value.length >> 8 & 255, value.length & 255, ...value]);
|
|
1627
|
+
var appendArkadeScript = (body, arkadeScript) => Uint8Array.from([...body, ...tlv2(TLV_ARKADE_SCRIPT, arkadeScript)]);
|
|
1628
|
+
var parseTlv = (data) => {
|
|
1629
|
+
let ciphertextLength;
|
|
1630
|
+
let hasArkadeScript = false;
|
|
1631
|
+
let pubkey;
|
|
1632
|
+
let offset = 0;
|
|
1633
|
+
while (offset < data.length) {
|
|
1634
|
+
if (offset + 3 > data.length) throw new Error("truncated TLV header");
|
|
1635
|
+
const type = data[offset];
|
|
1636
|
+
const length = data[offset + 1] << 8 | data[offset + 2];
|
|
1637
|
+
offset += 3;
|
|
1638
|
+
if (offset + length > data.length) {
|
|
1639
|
+
throw new Error(`TLV type 0x${type.toString(16)} overruns the buffer`);
|
|
1640
|
+
}
|
|
1641
|
+
const value = data.subarray(offset, offset + length);
|
|
1642
|
+
offset += length;
|
|
1643
|
+
if (type === TLV_CIPHERTEXT) ciphertextLength = value.length;
|
|
1644
|
+
else if (type === TLV_ARKADE_SCRIPT) hasArkadeScript = true;
|
|
1645
|
+
else if (type === TLV_COVCLAIMD_PUBKEY) {
|
|
1646
|
+
if (value.length !== COMPRESSED_PUBKEY_LENGTH) {
|
|
1647
|
+
throw new Error(
|
|
1648
|
+
`covclaimd_pub_key TLV is ${value.length} bytes, want ${COMPRESSED_PUBKEY_LENGTH}`
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1651
|
+
pubkey = value;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
return { ciphertextLength, hasArkadeScript, pubkey };
|
|
1655
|
+
};
|
|
1656
|
+
var claimPacketShape = (b64) => {
|
|
1657
|
+
try {
|
|
1658
|
+
const raw = base64.decode(b64);
|
|
1659
|
+
if (raw.length === SEALED_CIPHERTEXT_LENGTH) return { kind: "ciphertext" };
|
|
1660
|
+
const { ciphertextLength, hasArkadeScript, pubkey } = parseTlv(raw);
|
|
1661
|
+
if (ciphertextLength !== SEALED_CIPHERTEXT_LENGTH || pubkey === void 0) {
|
|
1662
|
+
return { kind: "ciphertext" };
|
|
1663
|
+
}
|
|
1664
|
+
return {
|
|
1665
|
+
kind: "packet",
|
|
1666
|
+
body: raw,
|
|
1667
|
+
needsArkadeScript: !hasArkadeScript,
|
|
1668
|
+
covclaimdPubkey: pubkey
|
|
1669
|
+
};
|
|
1670
|
+
} catch {
|
|
1671
|
+
return { kind: "ciphertext" };
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
// src/rfq.ts
|
|
1676
|
+
import { hex as hex5 } from "@scure/base";
|
|
1677
|
+
import { isAmount } from "@arkade-os/solver-discovery";
|
|
1678
|
+
import { ripemd160 as ripemd1602 } from "@noble/hashes/legacy.js";
|
|
1679
|
+
import {
|
|
1680
|
+
ArkAddress as ArkAddress3,
|
|
1681
|
+
assertTimerMs as assertTimerMs2,
|
|
1682
|
+
VHTLC,
|
|
1683
|
+
networkFromArkadeInfo as networkFromArkadeInfo2,
|
|
1684
|
+
resolveEmulatorPubkey as resolveEmulatorPubkey2,
|
|
1685
|
+
toXOnly
|
|
1686
|
+
} from "@arkade-os/sdk";
|
|
1687
|
+
import {
|
|
1688
|
+
provisionClaimSecret,
|
|
1689
|
+
provisionRefundKey
|
|
1690
|
+
} from "@arkade-os/sdk";
|
|
1691
|
+
|
|
1692
|
+
// src/claimAmountGate.ts
|
|
1693
|
+
var bindsClaimAmount = () => false;
|
|
1694
|
+
|
|
1695
|
+
// src/rfq.ts
|
|
1696
|
+
var solverHex = (value, field) => {
|
|
1697
|
+
try {
|
|
1698
|
+
return hex5.decode(value);
|
|
1699
|
+
} catch {
|
|
1700
|
+
throw new Error(`solver sent malformed hex for ${field}`);
|
|
1701
|
+
}
|
|
1702
|
+
};
|
|
1703
|
+
var quoteSats = (value, field) => {
|
|
1704
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
1705
|
+
throw new Error(`HTLC quote carries a non-sats ${field}: ${String(value)}`);
|
|
1706
|
+
}
|
|
1707
|
+
return value;
|
|
1708
|
+
};
|
|
1709
|
+
var quoteAmountSats = (value, field) => {
|
|
1710
|
+
if (typeof value === "string" && isAmount(value)) return BigInt(value);
|
|
1711
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value);
|
|
1712
|
+
throw new Error(`HTLC quote carries an unreadable ${field}: ${String(value)}`);
|
|
1713
|
+
};
|
|
1714
|
+
var quoteExpectedSats = (value, field) => {
|
|
1715
|
+
const sats = quoteAmountSats(value, field);
|
|
1716
|
+
if (sats <= 0n || sats > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
1717
|
+
throw new Error(`HTLC quote carries an unusable ${field}: ${String(value)}`);
|
|
1718
|
+
}
|
|
1719
|
+
return Number(sats);
|
|
1720
|
+
};
|
|
1721
|
+
var ARKADE_BTC = "arkade:BTC";
|
|
1722
|
+
var LIGHTNING_BTC = "lightning:BTC";
|
|
1723
|
+
var ONCHAIN_BTC = "onchain:BTC";
|
|
1724
|
+
var arkadeAssetLeg = (id) => `arkade:${id.toString()}`;
|
|
1725
|
+
var rfqPair = (from, to) => `${from}->${to}`;
|
|
1726
|
+
var LIGHTNING_SEND_PAIR = rfqPair(ARKADE_BTC, LIGHTNING_BTC);
|
|
1727
|
+
var LIGHTNING_RECEIVE_PAIR = rfqPair(LIGHTNING_BTC, ARKADE_BTC);
|
|
1728
|
+
var ONCHAIN_SEND_PAIR = rfqPair(ARKADE_BTC, ONCHAIN_BTC);
|
|
1729
|
+
var ONCHAIN_RECEIVE_PAIR = rfqPair(ONCHAIN_BTC, ARKADE_BTC);
|
|
1730
|
+
var RFQ_TERMINAL_STATES = ["settled", "refused", "expired", "refunded", "stuck"];
|
|
1731
|
+
var RFQ_REFUSAL_ERROR_CODES = [
|
|
1732
|
+
"amount_side_unsupported",
|
|
1733
|
+
"exact_out_unsupported",
|
|
1734
|
+
"invalid_amount",
|
|
1735
|
+
"invalid_payout_address",
|
|
1736
|
+
"invalid_refund_address",
|
|
1737
|
+
"invoice_amount_mismatch",
|
|
1738
|
+
"invoice_cltv_too_large",
|
|
1739
|
+
"invoice_malformed",
|
|
1740
|
+
"invoice_missing_amount",
|
|
1741
|
+
"invoice_missing_network",
|
|
1742
|
+
"invoice_missing_payment_hash",
|
|
1743
|
+
"invoice_missing_timestamp",
|
|
1744
|
+
"invoice_mixed_case",
|
|
1745
|
+
"invoice_sub_satoshi_amount",
|
|
1746
|
+
"invoice_too_long",
|
|
1747
|
+
"invoice_wrong_network"
|
|
1748
|
+
];
|
|
1749
|
+
var isRfqRefusalErrorCode = (value) => typeof value === "string" && RFQ_REFUSAL_ERROR_CODES.includes(value);
|
|
1750
|
+
var REFUSAL_FIELDS = /* @__PURE__ */ new Set([
|
|
1751
|
+
"amount",
|
|
1752
|
+
"amount_side",
|
|
1753
|
+
"profile.invoice",
|
|
1754
|
+
"profile.payout_address",
|
|
1755
|
+
"profile.refund_address"
|
|
1756
|
+
]);
|
|
1757
|
+
var REFUSAL_UNITS = /* @__PURE__ */ new Set(["blocks", "characters", "sats"]);
|
|
1758
|
+
var safeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
1759
|
+
var safeRefusalDetail = (detail) => {
|
|
1760
|
+
if (!isRfqRefusalErrorCode(detail.errorCode)) return {};
|
|
1761
|
+
return {
|
|
1762
|
+
errorCode: detail.errorCode,
|
|
1763
|
+
field: typeof detail.field === "string" && REFUSAL_FIELDS.has(detail.field) ? detail.field : void 0,
|
|
1764
|
+
actual: safeInteger(detail.actual),
|
|
1765
|
+
expected: safeInteger(detail.expected),
|
|
1766
|
+
limit: safeInteger(detail.limit),
|
|
1767
|
+
unit: typeof detail.unit === "string" && REFUSAL_UNITS.has(detail.unit) ? detail.unit : void 0
|
|
1768
|
+
};
|
|
1769
|
+
};
|
|
1770
|
+
var refusalMessage = (reason, detail) => {
|
|
1771
|
+
if (!detail.errorCode) return `solver refused: ${reason}`;
|
|
1772
|
+
const where = detail.field ? ` at ${detail.field}` : "";
|
|
1773
|
+
const unit = detail.unit ? ` ${detail.unit}` : "";
|
|
1774
|
+
if (detail.actual !== void 0 && detail.limit !== void 0) {
|
|
1775
|
+
return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, limit ${detail.limit})`;
|
|
1776
|
+
}
|
|
1777
|
+
if (detail.actual !== void 0 && detail.expected !== void 0) {
|
|
1778
|
+
return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, expected ${detail.expected})`;
|
|
1779
|
+
}
|
|
1780
|
+
return `solver refused: ${reason} (${detail.errorCode}${where})`;
|
|
1781
|
+
};
|
|
1782
|
+
var SwapRefusal = class extends Error {
|
|
1783
|
+
/** Literal-typed so the v2 error taxonomy's union discriminates on `name`
|
|
1784
|
+
* — a `string` here collapses the discriminant for every member. */
|
|
1785
|
+
name = "SwapRefusal";
|
|
1786
|
+
reason;
|
|
1787
|
+
rfqId;
|
|
1788
|
+
errorCode;
|
|
1789
|
+
field;
|
|
1790
|
+
actual;
|
|
1791
|
+
expected;
|
|
1792
|
+
limit;
|
|
1793
|
+
unit;
|
|
1794
|
+
constructor(reason, rfqId, detail = {}) {
|
|
1795
|
+
const safeDetail = safeRefusalDetail(detail);
|
|
1796
|
+
super(refusalMessage(reason, safeDetail));
|
|
1797
|
+
this.reason = reason;
|
|
1798
|
+
this.rfqId = rfqId;
|
|
1799
|
+
this.errorCode = safeDetail.errorCode;
|
|
1800
|
+
this.field = safeDetail.field;
|
|
1801
|
+
this.actual = safeDetail.actual;
|
|
1802
|
+
this.expected = safeDetail.expected;
|
|
1803
|
+
this.limit = safeDetail.limit;
|
|
1804
|
+
this.unit = safeDetail.unit;
|
|
1805
|
+
}
|
|
1806
|
+
};
|
|
1807
|
+
var AddressMismatch = class extends Error {
|
|
1808
|
+
derived;
|
|
1809
|
+
quoted;
|
|
1810
|
+
constructor(derived, quoted) {
|
|
1811
|
+
super("solver lockup address does not match local derivation \u2014 refusing to fund");
|
|
1812
|
+
this.name = "AddressMismatch";
|
|
1813
|
+
this.derived = derived;
|
|
1814
|
+
this.quoted = quoted;
|
|
1815
|
+
}
|
|
1816
|
+
};
|
|
1817
|
+
var newRfqId = () => hex5.encode(crypto.getRandomValues(new Uint8Array(32)));
|
|
1818
|
+
var lightningSendRequest = (input) => ({
|
|
1819
|
+
v: 1,
|
|
1820
|
+
type: "rfq_request",
|
|
1821
|
+
rfq_id: input.rfqId,
|
|
1822
|
+
pair: LIGHTNING_SEND_PAIR,
|
|
1823
|
+
amount_side: "to",
|
|
1824
|
+
profile: {
|
|
1825
|
+
invoice: input.invoice,
|
|
1826
|
+
refund_address: input.refundAddress,
|
|
1827
|
+
client_refund_pubkey: hex5.encode(input.senderPubkey)
|
|
1828
|
+
}
|
|
1829
|
+
});
|
|
1830
|
+
var arkadeSwapRequest = (input) => {
|
|
1831
|
+
if (!input.wantAsset && !input.offerAsset) {
|
|
1832
|
+
throw new Error(
|
|
1833
|
+
"set at least one of wantAsset or offerAsset \u2014 with neither set both legs are BTC, which is not a swap"
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
const pair = rfqPair(
|
|
1837
|
+
input.offerAsset ? arkadeAssetLeg(input.offerAsset) : ARKADE_BTC,
|
|
1838
|
+
input.wantAsset ? arkadeAssetLeg(input.wantAsset) : ARKADE_BTC
|
|
1839
|
+
);
|
|
1840
|
+
assertPairLength(pair);
|
|
1841
|
+
return {
|
|
1842
|
+
v: 1,
|
|
1843
|
+
type: "rfq_request",
|
|
1844
|
+
rfq_id: input.rfqId,
|
|
1845
|
+
pair,
|
|
1846
|
+
amount_side: input.amountSide ?? "from",
|
|
1847
|
+
amount: canonicalAssetAmount(input.amount),
|
|
1848
|
+
// The solver's `.strict()` schema refuses any undeclared key as `unsupported_payload`.
|
|
1849
|
+
profile: {
|
|
1850
|
+
maker_pk_script: normalizeMakerPkScript(input.makerPkScript),
|
|
1851
|
+
maker_public_key: normalizeMakerPublicKey(input.makerPublicKey)
|
|
1852
|
+
}
|
|
1853
|
+
};
|
|
1854
|
+
};
|
|
1855
|
+
var canonicalAssetAmount = (amount) => {
|
|
1856
|
+
if (typeof amount === "bigint") {
|
|
1857
|
+
if (amount <= 0n) throw new Error(`amount must be positive, got ${amount}`);
|
|
1858
|
+
return amount.toString();
|
|
1859
|
+
}
|
|
1860
|
+
if (typeof amount === "number") {
|
|
1861
|
+
if (!Number.isSafeInteger(amount) || amount <= 0) {
|
|
1862
|
+
throw new Error(`amount must be a positive safe integer, got ${amount}`);
|
|
1863
|
+
}
|
|
1864
|
+
return String(amount);
|
|
1865
|
+
}
|
|
1866
|
+
if (!/^(0|[1-9][0-9]*)$/.test(amount) || BigInt(amount) <= 0n) {
|
|
1867
|
+
throw new Error(`amount must be a canonical decimal string of atomic units, got ${amount}`);
|
|
1868
|
+
}
|
|
1869
|
+
return amount;
|
|
1870
|
+
};
|
|
1871
|
+
var normalizeHexBytes = (value, expectedBytes, label) => {
|
|
1872
|
+
if (value === void 0 || value === null) {
|
|
1873
|
+
throw new Error(`${label} is required`);
|
|
1874
|
+
}
|
|
1875
|
+
const bytes = typeof value === "string" ? solverHex(value, label) : value;
|
|
1876
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== expectedBytes) {
|
|
1877
|
+
const got = bytes instanceof Uint8Array ? bytes.length : typeof bytes;
|
|
1878
|
+
throw new Error(`${label} must be ${expectedBytes} bytes, got ${got}`);
|
|
1879
|
+
}
|
|
1880
|
+
return hex5.encode(bytes);
|
|
1881
|
+
};
|
|
1882
|
+
var normalizeMakerPkScript = (value) => {
|
|
1883
|
+
const encoded = normalizeHexBytes(value, 34, "maker_pk_script");
|
|
1884
|
+
if (!encoded.startsWith("5100") && !encoded.startsWith("5120")) {
|
|
1885
|
+
throw new Error("maker_pk_script must be a taproot scriptPubKey (OP_1 <32-byte program>)");
|
|
1886
|
+
}
|
|
1887
|
+
return encoded;
|
|
1888
|
+
};
|
|
1889
|
+
var normalizeMakerPublicKey = (value) => {
|
|
1890
|
+
const raw = typeof value === "string" ? value : hex5.encode(value);
|
|
1891
|
+
const bytes = solverHex(raw, "maker_public_key");
|
|
1892
|
+
if (bytes.length === 33) {
|
|
1893
|
+
throw new Error("maker_public_key must be x-only (32 bytes), not compressed (33 bytes)");
|
|
1894
|
+
}
|
|
1895
|
+
return normalizeHexBytes(bytes, 32, "maker_public_key");
|
|
1896
|
+
};
|
|
1897
|
+
var MIN_HEADROOM_SECONDS = 90 * 60;
|
|
1898
|
+
var assertFinite = (value, reason, label) => {
|
|
1899
|
+
if (value !== void 0 && !Number.isFinite(value)) {
|
|
1900
|
+
throw gateError(reason, `${label} is not a finite number (${String(value)})`);
|
|
1901
|
+
}
|
|
1902
|
+
};
|
|
1903
|
+
var MAX_PAIR_LENGTH = 158;
|
|
1904
|
+
var assertPairLength = (pair) => {
|
|
1905
|
+
if (pair.length > MAX_PAIR_LENGTH) {
|
|
1906
|
+
throw new Error(
|
|
1907
|
+
`pair is ${pair.length} characters, over the wire's ${MAX_PAIR_LENGTH}-character limit`
|
|
1908
|
+
);
|
|
1909
|
+
}
|
|
1910
|
+
};
|
|
1911
|
+
var verifyLockupAddress = (quote, derivedAddress) => {
|
|
1912
|
+
const quoted = quote.profile?.lockup_address;
|
|
1913
|
+
const candidates = Array.isArray(derivedAddress) ? derivedAddress : [derivedAddress];
|
|
1914
|
+
const matched = candidates.find((address) => address === quoted);
|
|
1915
|
+
if (matched === void 0) throw new AddressMismatch(candidates, quoted);
|
|
1916
|
+
return matched;
|
|
1917
|
+
};
|
|
1918
|
+
var LOCKUP_SHAPE_VARIANTS = [void 0, "preTimelockedRefund"];
|
|
1919
|
+
var matchQuotedLockup = (quote, hrp, serverPubkey, build) => {
|
|
1920
|
+
const candidates = LOCKUP_SHAPE_VARIANTS.map((legacy) => {
|
|
1921
|
+
const script = build(legacy);
|
|
1922
|
+
return { script, address: script.address(hrp, serverPubkey).encode(), legacy };
|
|
1923
|
+
});
|
|
1924
|
+
const matchedAddress = verifyLockupAddress(
|
|
1925
|
+
quote,
|
|
1926
|
+
candidates.map((candidate) => candidate.address)
|
|
1927
|
+
);
|
|
1928
|
+
return candidates.find((candidate) => candidate.address === matchedAddress);
|
|
1929
|
+
};
|
|
1930
|
+
var assertFundable = (input) => {
|
|
1931
|
+
const fail = (reason, message) => {
|
|
1932
|
+
throw gateError(reason, message);
|
|
1933
|
+
};
|
|
1934
|
+
if (input.quote.pair.split("->").some((leg) => leg.startsWith("ethereum:"))) {
|
|
1935
|
+
fail(
|
|
1936
|
+
"evm_funding_unavailable",
|
|
1937
|
+
"EVM funding is unavailable until local contract, finality, and deadline verification is implemented"
|
|
1938
|
+
);
|
|
1939
|
+
}
|
|
1940
|
+
if (input.quote.valid_until === void 0) {
|
|
1941
|
+
fail("quote_malformed", "quote carries no valid_until");
|
|
1942
|
+
}
|
|
1943
|
+
assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
|
|
1944
|
+
if (input.invoiceExpiresAt !== void 0 && input.now >= input.invoiceExpiresAt) {
|
|
1945
|
+
fail("invoice_expired", "invoice expired");
|
|
1946
|
+
}
|
|
1947
|
+
if (input.now >= input.quote.valid_until)
|
|
1948
|
+
fail("quote_expired", "quote expired \u2014 request a fresh one");
|
|
1949
|
+
if (quoteAmountSats(input.quote.from_amount, "from_amount") <= 0n || quoteAmountSats(input.quote.to_amount, "to_amount") <= 0n) {
|
|
1950
|
+
fail("non_positive_amount", "quote carries a non-positive amount");
|
|
1951
|
+
}
|
|
1952
|
+
if (input.quote.refund_locktime !== void 0 && input.quote.refund_locktime - input.now < MIN_HEADROOM_SECONDS) {
|
|
1953
|
+
fail("insufficient_headroom", "refund deadline headroom below 90 minutes");
|
|
1954
|
+
}
|
|
1955
|
+
if (input.maxFee) {
|
|
1956
|
+
const { bps, sats, referenceRate } = input.maxFee;
|
|
1957
|
+
if (bps === void 0 && sats === void 0) {
|
|
1958
|
+
fail("max_fee_unbounded", "maxFee names neither bps nor sats");
|
|
1959
|
+
}
|
|
1960
|
+
if (bps !== void 0 && (!Number.isInteger(bps) || bps < 0 || bps > 1e4)) {
|
|
1961
|
+
fail("max_fee_out_of_range", `maxFee.bps must be an integer in 0..10000, got ${bps}`);
|
|
1962
|
+
}
|
|
1963
|
+
if (sats !== void 0 && (!Number.isInteger(sats) || sats < 0)) {
|
|
1964
|
+
fail("max_fee_out_of_range", `maxFee.sats must be a non-negative integer, got ${sats}`);
|
|
1965
|
+
}
|
|
1966
|
+
const legs = input.quote.pair.split("->");
|
|
1967
|
+
const assetOf = (leg) => leg.slice(leg.indexOf(":") + 1);
|
|
1968
|
+
const sameAsset = legs.length === 2 && assetOf(legs[0]) === assetOf(legs[1]);
|
|
1969
|
+
if (!sameAsset && referenceRate === void 0) {
|
|
1970
|
+
fail(
|
|
1971
|
+
"fee_gate_unavailable",
|
|
1972
|
+
`maxFee cannot gate ${input.quote.pair}: its legs name different assets, so from_amount - to_amount is not a fee. Supply maxFee.referenceRate (to-units per from-unit) from a source of your OWN \u2014 reading it off the solver's published feed would check the solver against its own number`
|
|
1973
|
+
);
|
|
1974
|
+
}
|
|
1975
|
+
if (!sameAsset && (!Number.isFinite(referenceRate) || referenceRate <= 0)) {
|
|
1976
|
+
fail(
|
|
1977
|
+
"max_fee_out_of_range",
|
|
1978
|
+
`maxFee.referenceRate must be a positive finite number, got ${referenceRate}`
|
|
1979
|
+
);
|
|
1980
|
+
}
|
|
1981
|
+
const fromSats = quoteSats(input.quote.from_amount, "from_amount");
|
|
1982
|
+
const toSats = quoteSats(input.quote.to_amount, "to_amount");
|
|
1983
|
+
const fee = sameAsset ? fromSats - toSats : Math.ceil(
|
|
1984
|
+
(fromSats * referenceRate - toSats) / referenceRate
|
|
1985
|
+
);
|
|
1986
|
+
const allowed = Math.max(sats ?? 0, Math.floor(fromSats * (bps ?? 0) / 1e4));
|
|
1987
|
+
if (fee > allowed) {
|
|
1988
|
+
fail("fee_too_high", `fee ${fee} exceeds the ${allowed} this client allows`);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
if (input.onchain) {
|
|
1992
|
+
const { htlcLocktime, minConfirmations, direction } = input.onchain;
|
|
1993
|
+
if (!Number.isInteger(minConfirmations) || minConfirmations < 1 || minConfirmations > MAX_MIN_CONFIRMATIONS) {
|
|
1994
|
+
fail(
|
|
1995
|
+
"confirmations_out_of_range",
|
|
1996
|
+
`min_confirmations must be 1..${MAX_MIN_CONFIRMATIONS}, got ${minConfirmations}`
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
const needed = minConfirmations * ONCHAIN_SECONDS_PER_BLOCK + ONCHAIN_CLAIM_MARGIN_SECONDS;
|
|
2000
|
+
if (htlcLocktime - input.now <= needed) {
|
|
2001
|
+
fail("claim_window_too_short", "L1 HTLC locktime leaves no safe claim window");
|
|
2002
|
+
}
|
|
2003
|
+
if (direction === "send") {
|
|
2004
|
+
if (input.quote.refund_locktime === void 0 || htlcLocktime + ONCHAIN_ORDER_MARGIN_SECONDS > input.quote.refund_locktime) {
|
|
2005
|
+
fail(
|
|
2006
|
+
"timelock_order",
|
|
2007
|
+
"L1 HTLC locktime + margin must fall before the Arkade refund locktime"
|
|
2008
|
+
);
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
var expectQuote = (payload, rfqId, requestedPair) => {
|
|
2014
|
+
const p = payload;
|
|
2015
|
+
if (p?.type === "rfq_refusal") {
|
|
2016
|
+
throw new SwapRefusal(p.reason ?? "unknown", p.rfq_id ?? rfqId, {
|
|
2017
|
+
errorCode: p.error_code,
|
|
2018
|
+
field: p.field,
|
|
2019
|
+
actual: p.actual,
|
|
2020
|
+
expected: p.expected,
|
|
2021
|
+
limit: p.limit,
|
|
2022
|
+
unit: p.unit
|
|
2023
|
+
});
|
|
2024
|
+
}
|
|
2025
|
+
if (p?.type !== "rfq_quote" || p.rfq_id !== rfqId) {
|
|
2026
|
+
throw new Error(`unexpected reply: ${p?.type ?? "no payload"}`);
|
|
2027
|
+
}
|
|
2028
|
+
if (requestedPair !== void 0 && p.pair !== requestedPair) {
|
|
2029
|
+
throw new Error(
|
|
2030
|
+
`solver quoted ${JSON.stringify(p.pair)}, not the requested ${requestedPair}`
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
return payload;
|
|
2034
|
+
};
|
|
2035
|
+
var pairOf = (payload) => typeof payload.pair === "string" ? payload.pair : void 0;
|
|
2036
|
+
var httpTransport = (baseUrl, options = {}) => {
|
|
2037
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
2038
|
+
const readJson = async (response, what) => {
|
|
2039
|
+
const body = await response.text();
|
|
2040
|
+
try {
|
|
2041
|
+
return JSON.parse(body);
|
|
2042
|
+
} catch {
|
|
2043
|
+
throw new Error(
|
|
2044
|
+
`${what} returned HTTP ${response.status} with a non-JSON body: ${body.slice(0, 200)}`
|
|
2045
|
+
);
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
return {
|
|
2049
|
+
async requestQuote(payload) {
|
|
2050
|
+
const response = await fetchImpl(`${baseUrl}/v1/swap`, {
|
|
2051
|
+
method: "POST",
|
|
2052
|
+
headers: { "content-type": "application/json" },
|
|
2053
|
+
body: JSON.stringify(payload)
|
|
2054
|
+
});
|
|
2055
|
+
return expectQuote(
|
|
2056
|
+
await readJson(response, "quote request"),
|
|
2057
|
+
String(payload.rfq_id),
|
|
2058
|
+
pairOf(payload)
|
|
2059
|
+
);
|
|
2060
|
+
},
|
|
2061
|
+
async status(rfqId) {
|
|
2062
|
+
const response = await fetchImpl(`${baseUrl}/v1/rfq/${rfqId}`, { method: "GET" });
|
|
2063
|
+
if (response.status === 404) return null;
|
|
2064
|
+
const payload = await readJson(response, "status request");
|
|
2065
|
+
return payload?.type === "rfq_status" ? payload : null;
|
|
2066
|
+
},
|
|
2067
|
+
async close() {
|
|
2068
|
+
}
|
|
2069
|
+
};
|
|
2070
|
+
};
|
|
2071
|
+
var relayTransport = (relayUrl, options) => {
|
|
2072
|
+
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
2073
|
+
assertTimerMs2("timeoutMs", timeoutMs);
|
|
2074
|
+
const Ctor = options.WebSocketCtor ?? WebSocket;
|
|
2075
|
+
const pending = /* @__PURE__ */ new Map();
|
|
2076
|
+
let sequence = 0;
|
|
2077
|
+
const socketReady = new Promise((resolve, reject) => {
|
|
2078
|
+
const ws = new Ctor(relayUrl);
|
|
2079
|
+
ws.addEventListener("open", () => {
|
|
2080
|
+
ws.send(
|
|
2081
|
+
JSON.stringify({
|
|
2082
|
+
op: "sub",
|
|
2083
|
+
id: "s1",
|
|
2084
|
+
filter: { recipient: options.clientPubkey }
|
|
2085
|
+
})
|
|
2086
|
+
);
|
|
2087
|
+
resolve(ws);
|
|
2088
|
+
});
|
|
2089
|
+
ws.addEventListener("error", () => reject(new Error("relay connection failed")));
|
|
2090
|
+
ws.addEventListener("message", (event) => {
|
|
2091
|
+
let frame;
|
|
2092
|
+
try {
|
|
2093
|
+
frame = JSON.parse(String(event.data));
|
|
2094
|
+
} catch {
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
2097
|
+
if (frame.op !== "event") return;
|
|
2098
|
+
const payload = frame.event?.payload;
|
|
2099
|
+
const rfqId = payload?.rfq_id;
|
|
2100
|
+
const settle = rfqId !== void 0 ? pending.get(rfqId) : void 0;
|
|
2101
|
+
if (settle && rfqId !== void 0) {
|
|
2102
|
+
pending.delete(rfqId);
|
|
2103
|
+
settle(payload);
|
|
2104
|
+
}
|
|
2105
|
+
});
|
|
2106
|
+
});
|
|
2107
|
+
const roundTrip = async (payload, rfqId) => {
|
|
2108
|
+
const ws = await socketReady;
|
|
2109
|
+
const reply = new Promise((resolve, reject) => {
|
|
2110
|
+
const timer = setTimeout(() => {
|
|
2111
|
+
pending.delete(rfqId);
|
|
2112
|
+
reject(new Error(`no reply within ${timeoutMs}ms`));
|
|
2113
|
+
}, timeoutMs);
|
|
2114
|
+
pending.set(rfqId, (p) => {
|
|
2115
|
+
clearTimeout(timer);
|
|
2116
|
+
resolve(p);
|
|
2117
|
+
});
|
|
2118
|
+
});
|
|
2119
|
+
ws.send(
|
|
2120
|
+
JSON.stringify({
|
|
2121
|
+
op: "event",
|
|
2122
|
+
event: {
|
|
2123
|
+
id: `${options.clientPubkey}:${sequence += 1}`,
|
|
2124
|
+
author: options.clientPubkey,
|
|
2125
|
+
recipient: options.solverPubkey,
|
|
2126
|
+
createdAtMs: Date.now(),
|
|
2127
|
+
payload
|
|
2128
|
+
}
|
|
2129
|
+
})
|
|
2130
|
+
);
|
|
2131
|
+
return reply;
|
|
2132
|
+
};
|
|
2133
|
+
return {
|
|
2134
|
+
async requestQuote(payload) {
|
|
2135
|
+
return expectQuote(
|
|
2136
|
+
await roundTrip(payload, String(payload.rfq_id)),
|
|
2137
|
+
String(payload.rfq_id),
|
|
2138
|
+
pairOf(payload)
|
|
2139
|
+
);
|
|
2140
|
+
},
|
|
2141
|
+
async status(rfqId) {
|
|
2142
|
+
const payload = await roundTrip(
|
|
2143
|
+
{ v: 1, type: "rfq_status_request", rfq_id: rfqId },
|
|
2144
|
+
rfqId
|
|
2145
|
+
);
|
|
2146
|
+
return payload?.type === "rfq_status" ? payload : null;
|
|
2147
|
+
},
|
|
2148
|
+
async close() {
|
|
2149
|
+
try {
|
|
2150
|
+
(await socketReady).close();
|
|
2151
|
+
} catch {
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
};
|
|
2156
|
+
var SEQUENCE_GRANULARITY_SECONDS = 512;
|
|
2157
|
+
var SOLO_REFUND_HEADROOM_SECONDS = 8 * SEQUENCE_GRANULARITY_SECONDS;
|
|
2158
|
+
var unilateralClaimDelay = (operatorExitDelaySeconds) => {
|
|
2159
|
+
if (!Number.isFinite(operatorExitDelaySeconds) || operatorExitDelaySeconds < SEQUENCE_GRANULARITY_SECONDS) {
|
|
2160
|
+
throw new Error(
|
|
2161
|
+
`operator exit delay must be at least ${SEQUENCE_GRANULARITY_SECONDS}s of seconds, got ${operatorExitDelaySeconds}`
|
|
2162
|
+
);
|
|
2163
|
+
}
|
|
2164
|
+
if (operatorExitDelaySeconds > 65535 * SEQUENCE_GRANULARITY_SECONDS - SOLO_REFUND_HEADROOM_SECONDS) {
|
|
2165
|
+
throw new Error(
|
|
2166
|
+
`operator exit delay ${operatorExitDelaySeconds}s exceeds what BIP68 can encode once the solo refund's headroom is stacked above it`
|
|
2167
|
+
);
|
|
2168
|
+
}
|
|
2169
|
+
return Math.ceil(operatorExitDelaySeconds / SEQUENCE_GRANULARITY_SECONDS) * SEQUENCE_GRANULARITY_SECONDS;
|
|
2170
|
+
};
|
|
2171
|
+
var unilateralRefundDelay = (claimDelay) => claimDelay;
|
|
2172
|
+
var unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
|
|
2173
|
+
var seconds = (value) => ({
|
|
2174
|
+
type: "seconds",
|
|
2175
|
+
value: BigInt(value)
|
|
2176
|
+
});
|
|
2177
|
+
var suiteVhtlc = (params, roles) => new VHTLC.ScriptV2({
|
|
2178
|
+
sender: roles.sender,
|
|
2179
|
+
receiver: roles.receiver,
|
|
2180
|
+
server: params.operatorPubkey,
|
|
2181
|
+
preimageHash: ripemd1602(hex5.decode(params.paymentHash)),
|
|
2182
|
+
refundLocktime: BigInt(params.refundLocktime),
|
|
2183
|
+
unilateralClaimDelay: seconds(params.claimDelay),
|
|
2184
|
+
unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
|
|
2185
|
+
unilateralRefundWithoutReceiverDelay: seconds(
|
|
2186
|
+
roles.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
|
|
2187
|
+
),
|
|
2188
|
+
nonInteractiveParameters: {
|
|
2189
|
+
receiverPkScript: roles.receiverPkScript,
|
|
2190
|
+
senderPkScript: roles.senderPkScript,
|
|
2191
|
+
emulatorPubkey: params.emulatorPubkey,
|
|
2192
|
+
...params.legacy !== void 0 && { legacy: params.legacy }
|
|
2193
|
+
}
|
|
2194
|
+
});
|
|
2195
|
+
function lightningSendContract(params) {
|
|
2196
|
+
return suiteVhtlc(params, {
|
|
2197
|
+
sender: params.senderPubkey,
|
|
2198
|
+
receiver: params.solverPubkey,
|
|
2199
|
+
senderPkScript: params.refundPkScript,
|
|
2200
|
+
receiverPkScript: params.receiverPkScript,
|
|
2201
|
+
refundWithoutReceiverDelay: params.refundWithoutReceiverDelay
|
|
2202
|
+
});
|
|
2203
|
+
}
|
|
2204
|
+
var quotedSoloRefundDelay = (quote, claimDelay, corridor) => {
|
|
2205
|
+
const delay = quote.profile?.refund_without_receiver_delay;
|
|
2206
|
+
if (delay === void 0) return void 0;
|
|
2207
|
+
if (!Number.isSafeInteger(delay) || delay < claimDelay || delay % SEQUENCE_GRANULARITY_SECONDS !== 0 || delay > 65535 * SEQUENCE_GRANULARITY_SECONDS) {
|
|
2208
|
+
throw new Error(`${corridor} quote carries an invalid refund_without_receiver_delay`);
|
|
2209
|
+
}
|
|
2210
|
+
return delay;
|
|
2211
|
+
};
|
|
2212
|
+
function deriveLightningSend(input) {
|
|
2213
|
+
const { quote } = input;
|
|
2214
|
+
if (quote.refund_locktime === void 0) {
|
|
2215
|
+
throw new Error("lightning-send quote is missing refund_locktime");
|
|
2216
|
+
}
|
|
2217
|
+
const refundWithoutReceiverDelay = quotedSoloRefundDelay(
|
|
2218
|
+
quote,
|
|
2219
|
+
input.claimDelay,
|
|
2220
|
+
"lightning-send"
|
|
2221
|
+
);
|
|
2222
|
+
if (refundWithoutReceiverDelay === void 0) {
|
|
2223
|
+
throw new Error("lightning-send quote is missing profile.refund_without_receiver_delay");
|
|
2224
|
+
}
|
|
2225
|
+
if (refundWithoutReceiverDelay < quote.refund_locktime - input.now) {
|
|
2226
|
+
throw new Error("lightning-send quote lets the solo refund open before refund_locktime");
|
|
2227
|
+
}
|
|
2228
|
+
const receiverPkScriptHex = quote.profile?.receiver_pk_script;
|
|
2229
|
+
if (receiverPkScriptHex === void 0) {
|
|
2230
|
+
throw new Error("lightning-send quote is missing profile.receiver_pk_script");
|
|
2231
|
+
}
|
|
2232
|
+
const contractParams = {
|
|
2233
|
+
solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
|
|
2234
|
+
refundLocktime: quote.refund_locktime,
|
|
2235
|
+
operatorPubkey: input.operatorPubkey,
|
|
2236
|
+
paymentHash: input.paymentHash,
|
|
2237
|
+
claimDelay: input.claimDelay,
|
|
2238
|
+
refundWithoutReceiverDelay,
|
|
2239
|
+
emulatorPubkey: input.emulatorPubkey,
|
|
2240
|
+
senderPubkey: input.senderPubkey,
|
|
2241
|
+
receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
|
|
2242
|
+
refundPkScript: input.refundPkScript
|
|
2243
|
+
};
|
|
2244
|
+
const matched = matchQuotedLockup(
|
|
2245
|
+
quote,
|
|
2246
|
+
input.hrp,
|
|
2247
|
+
input.operatorPubkey,
|
|
2248
|
+
(legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
2249
|
+
);
|
|
2250
|
+
return {
|
|
2251
|
+
address: matched.address,
|
|
2252
|
+
swapPkScript: matched.script.pkScript,
|
|
2253
|
+
script: matched.script,
|
|
2254
|
+
contractParams: {
|
|
2255
|
+
...contractParams,
|
|
2256
|
+
...matched.legacy !== void 0 && { legacy: matched.legacy }
|
|
2257
|
+
},
|
|
2258
|
+
refundLocktime: quote.refund_locktime
|
|
2259
|
+
};
|
|
2260
|
+
}
|
|
2261
|
+
async function requestLightningSend(wallet, transport, params) {
|
|
2262
|
+
const rfqId = params.rfqId ?? newRfqId();
|
|
2263
|
+
const secrets = await provisionRefundKey(wallet);
|
|
2264
|
+
const senderPubkey = secrets.pubkey;
|
|
2265
|
+
const refundAddress = secrets.address;
|
|
2266
|
+
const info = await wallet.getArkadeInfo({ requireLive: true });
|
|
2267
|
+
const quote = await transport.requestQuote(
|
|
2268
|
+
lightningSendRequest({ rfqId, invoice: params.invoice.raw, refundAddress, senderPubkey })
|
|
2269
|
+
);
|
|
2270
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
2271
|
+
const claimDelay = unilateralClaimDelay(Number(info.unilateralExitDelay));
|
|
2272
|
+
if (quoteSats(quote.to_amount, "to_amount") !== params.invoice.amountSats) {
|
|
2273
|
+
throw new Error(
|
|
2274
|
+
`quote to_amount ${quote.to_amount} does not match the invoice's ${params.invoice.amountSats}`
|
|
2275
|
+
);
|
|
2276
|
+
}
|
|
2277
|
+
if (quoteSats(quote.from_amount, "from_amount") < quoteSats(quote.to_amount, "to_amount")) {
|
|
2278
|
+
throw new Error(
|
|
2279
|
+
`quote from_amount ${quote.from_amount} is below the invoice amount \u2014 a negative spread is not a quote`
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
const operatorPubkey = toXOnly(hex5.decode(info.signerPubkey), "ark signer key");
|
|
2283
|
+
const network = networkFromArkadeInfo2(info);
|
|
2284
|
+
const derived = deriveLightningSend({
|
|
2285
|
+
quote,
|
|
2286
|
+
paymentHash: params.invoice.paymentHash,
|
|
2287
|
+
senderPubkey,
|
|
2288
|
+
refundPkScript: secrets.pkScript,
|
|
2289
|
+
operatorPubkey,
|
|
2290
|
+
emulatorPubkey: toXOnly(
|
|
2291
|
+
hex5.decode(resolveEmulatorPubkey2(network, params.emulatorPubkey)),
|
|
2292
|
+
"emulator signer key"
|
|
2293
|
+
),
|
|
2294
|
+
claimDelay,
|
|
2295
|
+
hrp: network.hrp,
|
|
2296
|
+
now
|
|
2297
|
+
});
|
|
2298
|
+
const { address, script, contractParams } = derived;
|
|
2299
|
+
assertFundable({
|
|
2300
|
+
quote,
|
|
2301
|
+
invoiceExpiresAt: params.invoice.expiresAt,
|
|
2302
|
+
now
|
|
2303
|
+
});
|
|
2304
|
+
await registerLockupContract(await wallet.getContractManager(), script, address, {
|
|
2305
|
+
scope: wallet
|
|
2306
|
+
});
|
|
2307
|
+
return {
|
|
2308
|
+
rfqId,
|
|
2309
|
+
quote,
|
|
2310
|
+
address,
|
|
2311
|
+
fundAmount: quoteSats(quote.from_amount, "from_amount"),
|
|
2312
|
+
swapPkScript: derived.swapPkScript,
|
|
2313
|
+
script,
|
|
2314
|
+
refundAddress,
|
|
2315
|
+
senderPubkey,
|
|
2316
|
+
secrets,
|
|
2317
|
+
contractParams
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
var offerTermsFromQuote = (quote, assets) => {
|
|
2321
|
+
if (!assets.wantAsset && !assets.offerAsset) {
|
|
2322
|
+
throw new Error("set at least one of wantAsset or offerAsset");
|
|
2323
|
+
}
|
|
2324
|
+
const wantAmount = BigInt(quote.to_amount);
|
|
2325
|
+
if (assets.wantAsset) return { wantAmount, wantAsset: assets.wantAsset };
|
|
2326
|
+
return { wantAmount, offerAsset: assets.offerAsset };
|
|
2327
|
+
};
|
|
2328
|
+
var verifyOfferAddress = (quote, derived) => {
|
|
2329
|
+
const quotedAddress = quote.profile?.offer_address;
|
|
2330
|
+
const quotedScript = quote.profile?.offer_pk_script;
|
|
2331
|
+
const derivedScript = hex5.encode(derived.swapPkScript);
|
|
2332
|
+
if (quotedAddress !== derived.address || quotedScript !== derivedScript) {
|
|
2333
|
+
throw new AddressMismatch([derived.address], quotedAddress);
|
|
2334
|
+
}
|
|
2335
|
+
return derived;
|
|
2336
|
+
};
|
|
2337
|
+
var assertArkadeFundable = (input) => {
|
|
2338
|
+
const now = input.now ?? Math.floor(Date.now() / 1e3);
|
|
2339
|
+
if (!Number.isSafeInteger(input.quote.valid_until)) {
|
|
2340
|
+
throw gateError("quote_expired", "quote carries no valid_until");
|
|
2341
|
+
}
|
|
2342
|
+
if (now >= input.quote.valid_until) {
|
|
2343
|
+
throw gateError("quote_expired", `quote lapsed at ${input.quote.valid_until} (now ${now})`);
|
|
2344
|
+
}
|
|
2345
|
+
if (BigInt(input.quote.from_amount) <= 0n || BigInt(input.quote.to_amount) <= 0n) {
|
|
2346
|
+
throw gateError("quote_expired", "quote carries a non-positive amount");
|
|
2347
|
+
}
|
|
2348
|
+
};
|
|
2349
|
+
var quoteCarrierSats = (quote) => {
|
|
2350
|
+
const raw = quote.carrier_sats;
|
|
2351
|
+
if (raw === void 0) return ASSET_CARRIER_SATS;
|
|
2352
|
+
const canonical = typeof raw === "number" ? Number.isSafeInteger(raw) && raw >= 0 : /^(0|[1-9][0-9]*)$/.test(raw);
|
|
2353
|
+
if (!canonical) {
|
|
2354
|
+
throw gateError(
|
|
2355
|
+
"carrier_malformed",
|
|
2356
|
+
`quote carrier_sats ${String(raw)} is not a non-negative integer`
|
|
2357
|
+
);
|
|
2358
|
+
}
|
|
2359
|
+
const published = BigInt(raw);
|
|
2360
|
+
return published > 0n ? published : ASSET_CARRIER_SATS;
|
|
2361
|
+
};
|
|
2362
|
+
async function requestArkadeSwap(wallet, transport, params) {
|
|
2363
|
+
if (!params.wantAsset && !params.offerAsset) {
|
|
2364
|
+
throw new Error("set at least one of wantAsset or offerAsset; BTC-to-BTC is not a swap");
|
|
2365
|
+
}
|
|
2366
|
+
const rfqId = params.rfqId ?? newRfqId();
|
|
2367
|
+
const amountSide = params.amountSide ?? "from";
|
|
2368
|
+
const receiveAddress = params.receiveAddress;
|
|
2369
|
+
const [makerAddress, makerPublicKey] = await Promise.all([
|
|
2370
|
+
wallet.getAddress(),
|
|
2371
|
+
wallet.identity.xOnlyPublicKey()
|
|
2372
|
+
]);
|
|
2373
|
+
const ownPkScript = ArkAddress3.decode(makerAddress).pkScript;
|
|
2374
|
+
const info = receiveAddress === void 0 ? void 0 : await wallet.getArkadeInfo({ requireLive: true });
|
|
2375
|
+
const makerPkScript = info === void 0 ? ownPkScript : resolveReceivePkScript(
|
|
2376
|
+
receiveAddress,
|
|
2377
|
+
ownPkScript,
|
|
2378
|
+
networkFromArkadeInfo2(info).hrp,
|
|
2379
|
+
toXOnly(hex5.decode(info.signerPubkey), "ark signer key")
|
|
2380
|
+
);
|
|
2381
|
+
const pair = rfqPair(
|
|
2382
|
+
params.offerAsset ? arkadeAssetLeg(params.offerAsset) : ARKADE_BTC,
|
|
2383
|
+
params.wantAsset ? arkadeAssetLeg(params.wantAsset) : ARKADE_BTC
|
|
2384
|
+
);
|
|
2385
|
+
const quote = await transport.requestQuote(
|
|
2386
|
+
arkadeSwapRequest({
|
|
2387
|
+
rfqId,
|
|
2388
|
+
...params.offerAsset !== void 0 ? { offerAsset: params.offerAsset } : {},
|
|
2389
|
+
...params.wantAsset !== void 0 ? { wantAsset: params.wantAsset } : {},
|
|
2390
|
+
amount: params.amount,
|
|
2391
|
+
amountSide,
|
|
2392
|
+
makerPkScript,
|
|
2393
|
+
makerPublicKey
|
|
2394
|
+
})
|
|
2395
|
+
);
|
|
2396
|
+
if (quote.pair !== pair) {
|
|
2397
|
+
throw new Error(`solver quoted ${JSON.stringify(quote.pair)}, not the requested ${pair}`);
|
|
2398
|
+
}
|
|
2399
|
+
assertArkadeFundable({ quote, ...params.now !== void 0 ? { now: params.now } : {} });
|
|
2400
|
+
const terms = offerTermsFromQuote(quote, {
|
|
2401
|
+
...params.offerAsset !== void 0 ? { offerAsset: params.offerAsset } : {},
|
|
2402
|
+
...params.wantAsset !== void 0 ? { wantAsset: params.wantAsset } : {}
|
|
2403
|
+
});
|
|
2404
|
+
const quoted = amountSide === "from" ? quote.from_amount : quote.to_amount;
|
|
2405
|
+
if (BigInt(quoted).toString() !== canonicalAssetAmount(params.amount)) {
|
|
2406
|
+
throw new Error(
|
|
2407
|
+
`quote ${amountSide}_amount ${quoted} does not match the requested ${canonicalAssetAmount(params.amount)}`
|
|
2408
|
+
);
|
|
2409
|
+
}
|
|
2410
|
+
if (params.maxFromAmount !== void 0) {
|
|
2411
|
+
const cap = BigInt(canonicalAssetAmount(params.maxFromAmount));
|
|
2412
|
+
if (BigInt(quote.from_amount) > cap) {
|
|
2413
|
+
throw gateError(
|
|
2414
|
+
"quote_amount_rejected",
|
|
2415
|
+
`quote from_amount ${quote.from_amount} exceeds maxFromAmount ${cap}`
|
|
2416
|
+
);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
if (params.minToAmount !== void 0) {
|
|
2420
|
+
const floorAmount = BigInt(canonicalAssetAmount(params.minToAmount));
|
|
2421
|
+
if (BigInt(quote.to_amount) < floorAmount) {
|
|
2422
|
+
throw gateError(
|
|
2423
|
+
"quote_amount_rejected",
|
|
2424
|
+
`quote to_amount ${quote.to_amount} is under minToAmount ${floorAmount}`
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
const offer = await createOffer(wallet, {
|
|
2429
|
+
maker: { pkScript: ownPkScript, publicKey: makerPublicKey },
|
|
2430
|
+
...info === void 0 ? {} : { info },
|
|
2431
|
+
...receiveAddress === void 0 ? {} : { receiveAddress },
|
|
2432
|
+
wantAmount: terms.wantAmount,
|
|
2433
|
+
...terms.wantAsset !== void 0 ? { wantAsset: terms.wantAsset } : {},
|
|
2434
|
+
...terms.offerAsset !== void 0 ? { offerAsset: terms.offerAsset } : {},
|
|
2435
|
+
...params.emulatorPubkey !== void 0 ? { emulatorPubkey: params.emulatorPubkey } : {}
|
|
2436
|
+
});
|
|
2437
|
+
verifyOfferAddress(quote, offer);
|
|
2438
|
+
const fundAmount = BigInt(quote.from_amount);
|
|
2439
|
+
return {
|
|
2440
|
+
rfqId,
|
|
2441
|
+
quote,
|
|
2442
|
+
pair,
|
|
2443
|
+
address: offer.address,
|
|
2444
|
+
fundAmount,
|
|
2445
|
+
carrierSats: params.offerAsset !== void 0 ? quoteCarrierSats(quote) : 0n,
|
|
2446
|
+
swapPkScript: offer.swapPkScript,
|
|
2447
|
+
offerHex: offer.offerHex,
|
|
2448
|
+
extension: offer.extension
|
|
2449
|
+
};
|
|
2450
|
+
}
|
|
2451
|
+
var l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
|
|
2452
|
+
var serverTerms = (info, emulatorPubkey) => {
|
|
2453
|
+
const network = networkFromArkadeInfo2(info);
|
|
2454
|
+
return {
|
|
2455
|
+
operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
|
|
2456
|
+
emulatorPubkey: toXOnly(
|
|
2457
|
+
hex5.decode(resolveEmulatorPubkey2(network, emulatorPubkey)),
|
|
2458
|
+
"emulator signer key"
|
|
2459
|
+
),
|
|
2460
|
+
claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
|
|
2461
|
+
hrp: network.hrp
|
|
2462
|
+
};
|
|
2463
|
+
};
|
|
2464
|
+
var onchainSendRequest = (input) => ({
|
|
2465
|
+
v: 1,
|
|
2466
|
+
type: "rfq_request",
|
|
2467
|
+
rfq_id: input.rfqId,
|
|
2468
|
+
pair: ONCHAIN_SEND_PAIR,
|
|
2469
|
+
amount_side: input.amountSide,
|
|
2470
|
+
amount: input.amount,
|
|
2471
|
+
profile: {
|
|
2472
|
+
payment_hash: input.paymentHash,
|
|
2473
|
+
payout_pubkey: hex5.encode(input.payoutPubkey),
|
|
2474
|
+
refund_address: input.refundAddress,
|
|
2475
|
+
client_refund_pubkey: hex5.encode(input.senderPubkey)
|
|
2476
|
+
}
|
|
2477
|
+
});
|
|
2478
|
+
var lightningReceiveRequest = (input) => ({
|
|
2479
|
+
v: 1,
|
|
2480
|
+
type: "rfq_request",
|
|
2481
|
+
rfq_id: input.rfqId,
|
|
2482
|
+
pair: LIGHTNING_RECEIVE_PAIR,
|
|
2483
|
+
amount_side: input.amountSide,
|
|
2484
|
+
amount: input.amount,
|
|
2485
|
+
profile: {
|
|
2486
|
+
payment_hash: input.paymentHash,
|
|
2487
|
+
payout_address: input.payoutAddress,
|
|
2488
|
+
payout_pubkey: hex5.encode(input.payoutPubkey),
|
|
2489
|
+
...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket }
|
|
2490
|
+
}
|
|
2491
|
+
});
|
|
2492
|
+
var onchainReceiveRequest = (input) => ({
|
|
2493
|
+
v: 1,
|
|
2494
|
+
type: "rfq_request",
|
|
2495
|
+
rfq_id: input.rfqId,
|
|
2496
|
+
pair: ONCHAIN_RECEIVE_PAIR,
|
|
2497
|
+
amount_side: input.amountSide,
|
|
2498
|
+
amount: input.amount,
|
|
2499
|
+
profile: {
|
|
2500
|
+
payment_hash: input.paymentHash,
|
|
2501
|
+
...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket },
|
|
2502
|
+
refund_pubkey: hex5.encode(input.refundPubkey),
|
|
2503
|
+
payout_address: input.payoutAddress,
|
|
2504
|
+
payout_pubkey: hex5.encode(input.payoutPubkey)
|
|
2505
|
+
}
|
|
2506
|
+
});
|
|
2507
|
+
function deriveOnchainSend(input) {
|
|
2508
|
+
const { quote } = input;
|
|
2509
|
+
const profile = quote.profile ?? {};
|
|
2510
|
+
const refundLocktime = quote.refund_locktime ?? profile.refund_locktime;
|
|
2511
|
+
const htlcPubkey = profile.htlc_pubkey;
|
|
2512
|
+
const htlcLocktime = profile.htlc_locktime;
|
|
2513
|
+
const htlcAddress = profile.htlc_address;
|
|
2514
|
+
const minConfirmations = profile.min_confirmations;
|
|
2515
|
+
const receiverPkScriptHex = profile.receiver_pk_script;
|
|
2516
|
+
if (refundLocktime === void 0 || htlcPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || receiverPkScriptHex === void 0) {
|
|
2517
|
+
throw new Error("onchain-send quote is missing a binding field");
|
|
2518
|
+
}
|
|
2519
|
+
const refundWithoutReceiverDelay = quotedSoloRefundDelay(
|
|
2520
|
+
quote,
|
|
2521
|
+
input.claimDelay,
|
|
2522
|
+
"onchain-send"
|
|
2523
|
+
);
|
|
2524
|
+
const contractParams = {
|
|
2525
|
+
solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
|
|
2526
|
+
refundLocktime,
|
|
2527
|
+
operatorPubkey: input.operatorPubkey,
|
|
2528
|
+
paymentHash: input.paymentHash,
|
|
2529
|
+
claimDelay: input.claimDelay,
|
|
2530
|
+
refundWithoutReceiverDelay,
|
|
2531
|
+
emulatorPubkey: input.emulatorPubkey,
|
|
2532
|
+
senderPubkey: input.senderPubkey,
|
|
2533
|
+
receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
|
|
2534
|
+
refundPkScript: ArkAddress3.decode(input.refundAddress).pkScript
|
|
2535
|
+
};
|
|
2536
|
+
const { script, address } = matchQuotedLockup(
|
|
2537
|
+
quote,
|
|
2538
|
+
input.hrp,
|
|
2539
|
+
input.operatorPubkey,
|
|
2540
|
+
(legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
2541
|
+
);
|
|
2542
|
+
const htlcParams = {
|
|
2543
|
+
paymentHash: input.paymentHash,
|
|
2544
|
+
claimKey: input.payoutPubkey,
|
|
2545
|
+
refundKey: toXOnly(hex5.decode(htlcPubkey), "solver L1 htlc key"),
|
|
2546
|
+
refundLocktime: htlcLocktime
|
|
2547
|
+
};
|
|
2548
|
+
const htlc = onchainHtlcScript(htlcParams, input.l1Network);
|
|
2549
|
+
if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
|
|
2550
|
+
return {
|
|
2551
|
+
address,
|
|
2552
|
+
swapPkScript: script.pkScript,
|
|
2553
|
+
script,
|
|
2554
|
+
htlc,
|
|
2555
|
+
htlcParams,
|
|
2556
|
+
l1Network: input.l1Network,
|
|
2557
|
+
refundLocktime,
|
|
2558
|
+
refundWithoutReceiverDelay,
|
|
2559
|
+
htlcLocktime,
|
|
2560
|
+
minConfirmations,
|
|
2561
|
+
expectedAmount: quoteExpectedSats(quote.to_amount, "to_amount")
|
|
2562
|
+
};
|
|
2563
|
+
}
|
|
2564
|
+
async function requestOnchainSend(wallet, transport, params) {
|
|
2565
|
+
const rfqId = params.rfqId ?? newRfqId();
|
|
2566
|
+
const secrets = await provisionClaimSecret(wallet, { preimage: params.preimage });
|
|
2567
|
+
if (secrets.mustPersistPreimage) {
|
|
2568
|
+
console.warn(
|
|
2569
|
+
"[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
|
|
2570
|
+
);
|
|
2571
|
+
}
|
|
2572
|
+
const paymentHash = hex5.encode(secrets.paymentHash);
|
|
2573
|
+
const senderPubkey = secrets.pubkey;
|
|
2574
|
+
const [info, refundAddress] = await Promise.all([
|
|
2575
|
+
wallet.getArkadeInfo({ requireLive: true }),
|
|
2576
|
+
wallet.getAddress()
|
|
2577
|
+
]);
|
|
2578
|
+
const quote = await transport.requestQuote(
|
|
2579
|
+
onchainSendRequest({
|
|
2580
|
+
rfqId,
|
|
2581
|
+
paymentHash,
|
|
2582
|
+
payoutPubkey: params.payoutPubkey,
|
|
2583
|
+
refundAddress,
|
|
2584
|
+
senderPubkey,
|
|
2585
|
+
amount: params.amount,
|
|
2586
|
+
amountSide: params.amountSide
|
|
2587
|
+
})
|
|
2588
|
+
);
|
|
2589
|
+
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
2590
|
+
const derived = deriveOnchainSend({
|
|
2591
|
+
quote,
|
|
2592
|
+
paymentHash,
|
|
2593
|
+
payoutPubkey: params.payoutPubkey,
|
|
2594
|
+
...serverTerms(info, params.emulatorPubkey),
|
|
2595
|
+
l1Network: l1NetworkFromArk(info.network),
|
|
2596
|
+
refundAddress,
|
|
2597
|
+
senderPubkey
|
|
2598
|
+
});
|
|
2599
|
+
assertFundable({
|
|
2600
|
+
quote,
|
|
2601
|
+
now: Math.floor(Date.now() / 1e3),
|
|
2602
|
+
onchain: {
|
|
2603
|
+
htlcLocktime: derived.htlcLocktime,
|
|
2604
|
+
minConfirmations: derived.minConfirmations,
|
|
2605
|
+
direction: "send"
|
|
2606
|
+
}
|
|
2607
|
+
});
|
|
2608
|
+
await registerLockupContract(
|
|
2609
|
+
await wallet.getContractManager(),
|
|
2610
|
+
derived.script,
|
|
2611
|
+
derived.address,
|
|
2612
|
+
{ scope: wallet }
|
|
2613
|
+
);
|
|
2614
|
+
return {
|
|
2615
|
+
rfqId,
|
|
2616
|
+
quote,
|
|
2617
|
+
address: derived.address,
|
|
2618
|
+
fundAmount: quoteSats(quote.from_amount, "from_amount"),
|
|
2619
|
+
expectedAmount: quoteSats(quote.to_amount, "to_amount"),
|
|
2620
|
+
swapPkScript: derived.swapPkScript,
|
|
2621
|
+
script: derived.script,
|
|
2622
|
+
refundAddress,
|
|
2623
|
+
htlc: derived.htlc,
|
|
2624
|
+
htlcParams: derived.htlcParams,
|
|
2625
|
+
l1Network: derived.l1Network,
|
|
2626
|
+
minConfirmations: derived.minConfirmations,
|
|
2627
|
+
refundLocktime: derived.refundLocktime,
|
|
2628
|
+
senderPubkey,
|
|
2629
|
+
secrets
|
|
2630
|
+
};
|
|
2631
|
+
}
|
|
2632
|
+
var assertQuotedAmount = (quote, amountSide, amount) => {
|
|
2633
|
+
const quoted = amountSide === "from" ? quoteSats(quote.from_amount, "from_amount") : quoteSats(quote.to_amount, "to_amount");
|
|
2634
|
+
if (quoted !== amount) {
|
|
2635
|
+
throw new Error(
|
|
2636
|
+
`quote ${amountSide === "from" ? "from_amount" : "to_amount"} ${quoted} does not match the requested ${amount} \u2014 not this trade's quote`
|
|
2637
|
+
);
|
|
2638
|
+
}
|
|
2639
|
+
if (quote.to_amount > quote.from_amount) {
|
|
2640
|
+
throw new Error("quote pays out more than it takes in \u2014 not a quote to fund");
|
|
2641
|
+
}
|
|
2642
|
+
};
|
|
2643
|
+
var MIN_CLAIM_WINDOW_SECONDS = 30 * 60;
|
|
2644
|
+
var verifyReceiveInvoice = (input) => {
|
|
2645
|
+
let decoded;
|
|
2646
|
+
try {
|
|
2647
|
+
decoded = input.decode(input.invoice);
|
|
2648
|
+
} catch (error) {
|
|
2649
|
+
throw gateError(
|
|
2650
|
+
"invoice_undecodable",
|
|
2651
|
+
`solver sent an undecodable invoice: ${error instanceof Error ? error.message : String(error)}`
|
|
2652
|
+
);
|
|
2653
|
+
}
|
|
2654
|
+
assertFinite(decoded.expiresAt, "invoice_undecodable", "the decoded invoice expiry");
|
|
2655
|
+
assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
|
|
2656
|
+
if (decoded.paymentHash !== input.paymentHash) {
|
|
2657
|
+
throw gateError(
|
|
2658
|
+
"invoice_hash_mismatch",
|
|
2659
|
+
`solver's invoice pays ${decoded.paymentHash}, not this swap's ${input.paymentHash}`
|
|
2660
|
+
);
|
|
2661
|
+
}
|
|
2662
|
+
if (decoded.amountSats <= 0) {
|
|
2663
|
+
throw gateError("invoice_amount_mismatch", "solver's invoice names no amount");
|
|
2664
|
+
}
|
|
2665
|
+
if (decoded.amountSats !== input.quote.from_amount) {
|
|
2666
|
+
throw gateError(
|
|
2667
|
+
"invoice_amount_mismatch",
|
|
2668
|
+
`solver's invoice asks for ${decoded.amountSats}, not the quoted from_amount ${input.quote.from_amount}`
|
|
2669
|
+
);
|
|
2670
|
+
}
|
|
2671
|
+
return { payDeadline: Math.min(decoded.expiresAt, input.quote.valid_until) };
|
|
2672
|
+
};
|
|
2673
|
+
var assertReceivable = (input) => {
|
|
2674
|
+
assertFinite(input.payDeadline, "quote_malformed", "payDeadline");
|
|
2675
|
+
assertFinite(input.now, "invalid_gate_input", "now");
|
|
2676
|
+
assertFinite(input.minClaimWindowSeconds, "invalid_gate_input", "minClaimWindowSeconds");
|
|
2677
|
+
assertFinite(input.maxPayAmount, "invalid_gate_input", "maxPayAmount");
|
|
2678
|
+
const minClaimWindow = input.minClaimWindowSeconds ?? MIN_CLAIM_WINDOW_SECONDS;
|
|
2679
|
+
if (input.now >= input.payDeadline) {
|
|
2680
|
+
throw gateError("quote_expired", "quote or invoice already expired \u2014 request a fresh one");
|
|
2681
|
+
}
|
|
2682
|
+
if (input.quote.refund_locktime === void 0) {
|
|
2683
|
+
throw gateError("missing_refund_locktime", "receive quote carries no refund_locktime");
|
|
2684
|
+
}
|
|
2685
|
+
assertFinite(input.quote.refund_locktime, "quote_malformed", "quote refund_locktime");
|
|
2686
|
+
if (input.quote.refund_locktime - input.payDeadline < minClaimWindow) {
|
|
2687
|
+
throw gateError(
|
|
2688
|
+
"claim_window_too_short",
|
|
2689
|
+
`a payment at the deadline would leave under ${minClaimWindow}s to claim before the solver's refund opens`
|
|
2690
|
+
);
|
|
2691
|
+
}
|
|
2692
|
+
if (input.maxPayAmount !== void 0 && quoteSats(input.quote.from_amount, "from_amount") > input.maxPayAmount) {
|
|
2693
|
+
throw gateError(
|
|
2694
|
+
"price_too_high",
|
|
2695
|
+
`quote asks ${input.quote.from_amount} sats, above the ${input.maxPayAmount} ceiling`
|
|
2696
|
+
);
|
|
2697
|
+
}
|
|
2698
|
+
};
|
|
2699
|
+
function lightningReceiveContract(params) {
|
|
2700
|
+
return suiteVhtlc(params, {
|
|
2701
|
+
sender: params.solverPubkey,
|
|
2702
|
+
receiver: params.payoutPubkey,
|
|
2703
|
+
senderPkScript: params.solverRefundPkScript,
|
|
2704
|
+
receiverPkScript: params.payoutPkScript
|
|
2705
|
+
});
|
|
2706
|
+
}
|
|
2707
|
+
var matchReceiveLockup = (input, refundLocktime, solverRefundPkScriptHex) => {
|
|
2708
|
+
const contractParams = {
|
|
2709
|
+
solverPubkey: toXOnly(hex5.decode(input.quote.solver_pubkey), "solver key"),
|
|
2710
|
+
refundLocktime,
|
|
2711
|
+
operatorPubkey: input.operatorPubkey,
|
|
2712
|
+
paymentHash: input.paymentHash,
|
|
2713
|
+
claimDelay: input.claimDelay,
|
|
2714
|
+
emulatorPubkey: input.emulatorPubkey,
|
|
2715
|
+
solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
|
|
2716
|
+
payoutPubkey: input.payoutPubkey,
|
|
2717
|
+
payoutPkScript: ArkAddress3.decode(input.payoutAddress).pkScript
|
|
2718
|
+
};
|
|
2719
|
+
const matched = matchQuotedLockup(
|
|
2720
|
+
input.quote,
|
|
2721
|
+
input.hrp,
|
|
2722
|
+
input.operatorPubkey,
|
|
2723
|
+
(legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
2724
|
+
);
|
|
2725
|
+
return { contractParams, matched };
|
|
2726
|
+
};
|
|
2727
|
+
function deriveLightningReceive(input) {
|
|
2728
|
+
const { quote } = input;
|
|
2729
|
+
const profile = quote.profile ?? {};
|
|
2730
|
+
const refundLocktime = quote.refund_locktime;
|
|
2731
|
+
const invoice = profile.invoice;
|
|
2732
|
+
const solverRefundPkScriptHex = profile.solver_refund_pk_script;
|
|
2733
|
+
if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
|
|
2734
|
+
throw new Error("lightning-receive quote is missing a binding field");
|
|
2735
|
+
}
|
|
2736
|
+
const { contractParams, matched } = matchReceiveLockup(
|
|
2737
|
+
input,
|
|
2738
|
+
refundLocktime,
|
|
2739
|
+
solverRefundPkScriptHex
|
|
2740
|
+
);
|
|
2741
|
+
return {
|
|
2742
|
+
address: matched.address,
|
|
2743
|
+
swapPkScript: matched.script.pkScript,
|
|
2744
|
+
script: matched.script,
|
|
2745
|
+
invoice,
|
|
2746
|
+
refundLocktime,
|
|
2747
|
+
contractParams: {
|
|
2748
|
+
...contractParams,
|
|
2749
|
+
...matched.legacy !== void 0 && { legacy: matched.legacy }
|
|
2750
|
+
}
|
|
2751
|
+
};
|
|
2752
|
+
}
|
|
2753
|
+
var provisionReceive = async (wallet, params, persistBefore) => {
|
|
2754
|
+
const secrets = await provisionClaimSecret(wallet);
|
|
2755
|
+
if (secrets.mustPersistPreimage) {
|
|
2756
|
+
console.warn(
|
|
2757
|
+
`[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before ${persistBefore}`
|
|
2758
|
+
);
|
|
2759
|
+
}
|
|
2760
|
+
const preimage = secrets.preimage;
|
|
2761
|
+
const paymentHash = hex5.encode(secrets.paymentHash);
|
|
2762
|
+
const payoutPubkey = secrets.pubkey;
|
|
2763
|
+
const [info, payoutAddress] = await Promise.all([
|
|
2764
|
+
wallet.getArkadeInfo({ requireLive: true }),
|
|
2765
|
+
wallet.getAddress()
|
|
2766
|
+
]);
|
|
2767
|
+
const binds = bindsClaimAmount();
|
|
2768
|
+
const claimPacket = params.covclaimdPubkey && (!binds || params.amountSide === "to") ? await sealClaimPacket({
|
|
2769
|
+
preimage,
|
|
2770
|
+
covclaimdPubkey: params.covclaimdPubkey,
|
|
2771
|
+
minAmount: binds ? BigInt(params.amount) : void 0
|
|
2772
|
+
}) : void 0;
|
|
2773
|
+
return { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket };
|
|
2774
|
+
};
|
|
2775
|
+
var quoteReceive = async (wallet, transport, params, persistBefore, request) => {
|
|
2776
|
+
for (let attempt = 0; ; attempt++) {
|
|
2777
|
+
const provisioned = await provisionReceive(wallet, params, persistBefore);
|
|
2778
|
+
try {
|
|
2779
|
+
return { ...provisioned, quote: await transport.requestQuote(request(provisioned)) };
|
|
2780
|
+
} catch (error) {
|
|
2781
|
+
const conflict = error instanceof SwapRefusal && error.reason === "quote_conflict";
|
|
2782
|
+
if (!conflict || attempt >= 1) throw error;
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
};
|
|
2786
|
+
async function requestLightningReceive(wallet, transport, params) {
|
|
2787
|
+
const rfqId = params.rfqId ?? newRfqId();
|
|
2788
|
+
const { secrets, paymentHash, payoutPubkey, info, payoutAddress, quote } = await quoteReceive(
|
|
2789
|
+
wallet,
|
|
2790
|
+
transport,
|
|
2791
|
+
params,
|
|
2792
|
+
"paying",
|
|
2793
|
+
({ paymentHash: paymentHash2, payoutAddress: payoutAddress2, payoutPubkey: payoutPubkey2, claimPacket }) => lightningReceiveRequest({
|
|
2794
|
+
rfqId,
|
|
2795
|
+
paymentHash: paymentHash2,
|
|
2796
|
+
payoutAddress: payoutAddress2,
|
|
2797
|
+
payoutPubkey: payoutPubkey2,
|
|
2798
|
+
claimPacket: claimPacket?.packet,
|
|
2799
|
+
amount: params.amount,
|
|
2800
|
+
amountSide: params.amountSide
|
|
2801
|
+
})
|
|
2802
|
+
);
|
|
2803
|
+
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
2804
|
+
const derived = deriveLightningReceive({
|
|
2805
|
+
quote,
|
|
2806
|
+
paymentHash,
|
|
2807
|
+
payoutPubkey,
|
|
2808
|
+
payoutAddress,
|
|
2809
|
+
...serverTerms(info, params.emulatorPubkey)
|
|
2810
|
+
});
|
|
2811
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
2812
|
+
const { payDeadline } = verifyReceiveInvoice({
|
|
2813
|
+
invoice: derived.invoice,
|
|
2814
|
+
decode: params.decodeInvoice,
|
|
2815
|
+
paymentHash,
|
|
2816
|
+
quote
|
|
2817
|
+
});
|
|
2818
|
+
assertReceivable({ quote, payDeadline, now, maxPayAmount: params.maxPayAmount });
|
|
2819
|
+
await registerLockupContract(
|
|
2820
|
+
await wallet.getContractManager(),
|
|
2821
|
+
derived.script,
|
|
2822
|
+
derived.address,
|
|
2823
|
+
{ scope: wallet }
|
|
2824
|
+
);
|
|
2825
|
+
return {
|
|
2826
|
+
rfqId,
|
|
2827
|
+
quote,
|
|
2828
|
+
invoice: derived.invoice,
|
|
2829
|
+
payAmount: quoteSats(quote.from_amount, "from_amount"),
|
|
2830
|
+
expectedAmount: quoteSats(quote.to_amount, "to_amount"),
|
|
2831
|
+
invoiceExpiresAt: payDeadline,
|
|
2832
|
+
address: derived.address,
|
|
2833
|
+
swapPkScript: derived.swapPkScript,
|
|
2834
|
+
script: derived.script,
|
|
2835
|
+
payoutAddress,
|
|
2836
|
+
payoutPubkey,
|
|
2837
|
+
secrets,
|
|
2838
|
+
contractParams: derived.contractParams
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
function deriveOnchainReceive(input) {
|
|
2842
|
+
const { quote } = input;
|
|
2843
|
+
const profile = quote.profile ?? {};
|
|
2844
|
+
const refundLocktime = quote.refund_locktime;
|
|
2845
|
+
const claimPubkey = profile.claim_pubkey;
|
|
2846
|
+
const htlcLocktime = profile.htlc_locktime;
|
|
2847
|
+
const htlcAddress = profile.htlc_address;
|
|
2848
|
+
const minConfirmations = profile.min_confirmations;
|
|
2849
|
+
const solverRefundPkScriptHex = profile.solver_refund_pk_script;
|
|
2850
|
+
if (refundLocktime === void 0 || claimPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || solverRefundPkScriptHex === void 0) {
|
|
2851
|
+
throw new Error("onchain-receive quote is missing a binding field");
|
|
2852
|
+
}
|
|
2853
|
+
const { script, address } = matchReceiveLockup(
|
|
2854
|
+
input,
|
|
2855
|
+
refundLocktime,
|
|
2856
|
+
solverRefundPkScriptHex
|
|
2857
|
+
).matched;
|
|
2858
|
+
const htlcParams = {
|
|
2859
|
+
paymentHash: input.paymentHash,
|
|
2860
|
+
claimKey: toXOnly(hex5.decode(claimPubkey), "solver L1 claim key"),
|
|
2861
|
+
refundKey: input.refundPubkey,
|
|
2862
|
+
refundLocktime: htlcLocktime
|
|
2863
|
+
};
|
|
2864
|
+
const htlc = onchainHtlcScript(htlcParams, input.l1Network);
|
|
2865
|
+
if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
|
|
2866
|
+
return {
|
|
2867
|
+
address,
|
|
2868
|
+
swapPkScript: script.pkScript,
|
|
2869
|
+
script,
|
|
2870
|
+
htlc,
|
|
2871
|
+
htlcParams,
|
|
2872
|
+
refundLocktime,
|
|
2873
|
+
htlcLocktime,
|
|
2874
|
+
minConfirmations
|
|
2875
|
+
};
|
|
2876
|
+
}
|
|
2877
|
+
async function requestOnchainReceive(wallet, transport, params) {
|
|
2878
|
+
const rfqId = params.rfqId ?? newRfqId();
|
|
2879
|
+
const { secrets, paymentHash, payoutPubkey, info, payoutAddress, quote } = await quoteReceive(
|
|
2880
|
+
wallet,
|
|
2881
|
+
transport,
|
|
2882
|
+
params,
|
|
2883
|
+
"funding",
|
|
2884
|
+
({ paymentHash: paymentHash2, payoutAddress: payoutAddress2, payoutPubkey: payoutPubkey2, claimPacket }) => onchainReceiveRequest({
|
|
2885
|
+
rfqId,
|
|
2886
|
+
paymentHash: paymentHash2,
|
|
2887
|
+
payoutAddress: payoutAddress2,
|
|
2888
|
+
payoutPubkey: payoutPubkey2,
|
|
2889
|
+
refundPubkey: params.refundPubkey,
|
|
2890
|
+
claimPacket: claimPacket?.packet,
|
|
2891
|
+
amount: params.amount,
|
|
2892
|
+
amountSide: params.amountSide
|
|
2893
|
+
})
|
|
2894
|
+
);
|
|
2895
|
+
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
2896
|
+
const derived = deriveOnchainReceive({
|
|
2897
|
+
quote,
|
|
2898
|
+
paymentHash,
|
|
2899
|
+
payoutPubkey,
|
|
2900
|
+
payoutAddress,
|
|
2901
|
+
refundPubkey: params.refundPubkey,
|
|
2902
|
+
...serverTerms(info, params.emulatorPubkey),
|
|
2903
|
+
l1Network: l1NetworkFromArk(info.network)
|
|
2904
|
+
});
|
|
2905
|
+
assertFundable({
|
|
2906
|
+
quote,
|
|
2907
|
+
now: Math.floor(Date.now() / 1e3),
|
|
2908
|
+
onchain: {
|
|
2909
|
+
htlcLocktime: derived.htlcLocktime,
|
|
2910
|
+
minConfirmations: derived.minConfirmations,
|
|
2911
|
+
direction: "receive"
|
|
2912
|
+
}
|
|
2913
|
+
});
|
|
2914
|
+
await registerLockupContract(
|
|
2915
|
+
await wallet.getContractManager(),
|
|
2916
|
+
derived.script,
|
|
2917
|
+
derived.address,
|
|
2918
|
+
{ scope: wallet }
|
|
2919
|
+
);
|
|
2920
|
+
return {
|
|
2921
|
+
rfqId,
|
|
2922
|
+
quote,
|
|
2923
|
+
address: derived.address,
|
|
2924
|
+
fundAmount: quoteSats(quote.from_amount, "from_amount"),
|
|
2925
|
+
expectedAmount: quoteSats(quote.to_amount, "to_amount"),
|
|
2926
|
+
swapPkScript: derived.swapPkScript,
|
|
2927
|
+
script: derived.script,
|
|
2928
|
+
htlc: derived.htlc,
|
|
2929
|
+
payoutAddress,
|
|
2930
|
+
payoutPubkey,
|
|
2931
|
+
secrets
|
|
2932
|
+
};
|
|
2933
|
+
}
|
|
2934
|
+
|
|
2935
|
+
export {
|
|
2936
|
+
RETIRABLE,
|
|
2937
|
+
LOCKUP_RETIRABLE,
|
|
2938
|
+
promoteOfferContract,
|
|
2939
|
+
retireOfferContract,
|
|
2940
|
+
retireSettledOfferContracts,
|
|
2941
|
+
rfqCorridorHandlers,
|
|
2942
|
+
BTC_ASSET_ID,
|
|
2943
|
+
getAssetSwaps,
|
|
2944
|
+
addAssetSwap,
|
|
2945
|
+
updateAssetSwap,
|
|
2946
|
+
updateAssetSwapBestEffort,
|
|
2947
|
+
swapSecretsToRecord,
|
|
2948
|
+
PreimageNotRecoverableError,
|
|
2949
|
+
preimageForSwapRecord,
|
|
2950
|
+
rfqSecretsProfile,
|
|
2951
|
+
hydrateHashlock,
|
|
2952
|
+
rfqSignerOf,
|
|
2953
|
+
rfqClaimSecretOf,
|
|
2954
|
+
rfqClaimDestinationOf,
|
|
2955
|
+
swapPrograms,
|
|
2956
|
+
withExitClosure,
|
|
2957
|
+
offerContract,
|
|
2958
|
+
OFFER_PACKET_TYPE,
|
|
2959
|
+
encodeOffer,
|
|
2960
|
+
decodeOffer,
|
|
2961
|
+
OFFER_CONTRACT_KIND,
|
|
2962
|
+
restoreOfferCoverage,
|
|
2963
|
+
createOffer,
|
|
2964
|
+
resolveReceivePkScript,
|
|
2965
|
+
deriveOffer,
|
|
2966
|
+
registerDerivedOffer,
|
|
2967
|
+
cancelOffer,
|
|
2968
|
+
NoSpendableDepositError,
|
|
2969
|
+
OfferCovenantMismatchError,
|
|
2970
|
+
prepareOfferCancel,
|
|
2971
|
+
ASSET_CARRIER_SATS,
|
|
2972
|
+
fillOffer,
|
|
2973
|
+
connectFillContract,
|
|
2974
|
+
resolveDeposit,
|
|
2975
|
+
assembleOfferFill,
|
|
2976
|
+
offerVtxoScript,
|
|
2977
|
+
SWAP_LOCKUP_CONTRACT_TYPE,
|
|
2978
|
+
SWAP_LOCKUP_CONTRACT_LABEL,
|
|
2979
|
+
SWAP_LOCKUP_CONTRACT_KIND,
|
|
2980
|
+
LockupContractMissing,
|
|
2981
|
+
LockupRegistrationFailed,
|
|
2982
|
+
registerLockupContract,
|
|
2983
|
+
lockupContractParams,
|
|
2984
|
+
ONCHAIN_ORDER_MARGIN_SECONDS,
|
|
2985
|
+
ONCHAIN_CLAIM_MARGIN_SECONDS,
|
|
2986
|
+
ONCHAIN_CLAIM_BUMP_SECONDS,
|
|
2987
|
+
MAX_MIN_CONFIRMATIONS,
|
|
2988
|
+
LOCKTIME_THRESHOLD,
|
|
2989
|
+
ONCHAIN_SECONDS_PER_BLOCK,
|
|
2990
|
+
ONCHAIN_DUST_SATS,
|
|
2991
|
+
ONCHAIN_CLAIM_VSIZE,
|
|
2992
|
+
newPreimage,
|
|
2993
|
+
paymentHashOf,
|
|
2994
|
+
assertPreimageMatches,
|
|
2995
|
+
gateError,
|
|
2996
|
+
pollUntil,
|
|
2997
|
+
L1_NETWORKS,
|
|
2998
|
+
l1ScriptForAddress,
|
|
2999
|
+
onchainHtlcScript,
|
|
3000
|
+
buildHtlcClaim,
|
|
3001
|
+
buildHtlcRefund,
|
|
3002
|
+
nextClaimFeeRate,
|
|
3003
|
+
extractPreimage,
|
|
3004
|
+
awaitOnchainFill,
|
|
3005
|
+
claimOnchainFill,
|
|
3006
|
+
classifyOnchainHtlc,
|
|
3007
|
+
bindsClaimAmount,
|
|
3008
|
+
sealClaimPacket,
|
|
3009
|
+
SEALED_CIPHERTEXT_LENGTH,
|
|
3010
|
+
CLAIM_PACKET_TYPE,
|
|
3011
|
+
appendArkadeScript,
|
|
3012
|
+
claimPacketShape,
|
|
3013
|
+
ARKADE_BTC,
|
|
3014
|
+
LIGHTNING_BTC,
|
|
3015
|
+
ONCHAIN_BTC,
|
|
3016
|
+
arkadeAssetLeg,
|
|
3017
|
+
rfqPair,
|
|
3018
|
+
LIGHTNING_SEND_PAIR,
|
|
3019
|
+
LIGHTNING_RECEIVE_PAIR,
|
|
3020
|
+
ONCHAIN_SEND_PAIR,
|
|
3021
|
+
ONCHAIN_RECEIVE_PAIR,
|
|
3022
|
+
RFQ_TERMINAL_STATES,
|
|
3023
|
+
RFQ_REFUSAL_ERROR_CODES,
|
|
3024
|
+
isRfqRefusalErrorCode,
|
|
3025
|
+
SwapRefusal,
|
|
3026
|
+
AddressMismatch,
|
|
3027
|
+
newRfqId,
|
|
3028
|
+
lightningSendRequest,
|
|
3029
|
+
arkadeSwapRequest,
|
|
3030
|
+
canonicalAssetAmount,
|
|
3031
|
+
normalizeMakerPkScript,
|
|
3032
|
+
normalizeMakerPublicKey,
|
|
3033
|
+
assertPairLength,
|
|
3034
|
+
verifyLockupAddress,
|
|
3035
|
+
assertFundable,
|
|
3036
|
+
expectQuote,
|
|
3037
|
+
pairOf,
|
|
3038
|
+
httpTransport,
|
|
3039
|
+
relayTransport,
|
|
3040
|
+
unilateralClaimDelay,
|
|
3041
|
+
unilateralRefundDelay,
|
|
3042
|
+
unilateralRefundWithoutReceiverDelay,
|
|
3043
|
+
lightningSendContract,
|
|
3044
|
+
deriveLightningSend,
|
|
3045
|
+
requestLightningSend,
|
|
3046
|
+
offerTermsFromQuote,
|
|
3047
|
+
verifyOfferAddress,
|
|
3048
|
+
assertArkadeFundable,
|
|
3049
|
+
quoteCarrierSats,
|
|
3050
|
+
requestArkadeSwap,
|
|
3051
|
+
l1NetworkFromArk,
|
|
3052
|
+
onchainSendRequest,
|
|
3053
|
+
lightningReceiveRequest,
|
|
3054
|
+
onchainReceiveRequest,
|
|
3055
|
+
deriveOnchainSend,
|
|
3056
|
+
requestOnchainSend,
|
|
3057
|
+
MIN_CLAIM_WINDOW_SECONDS,
|
|
3058
|
+
verifyReceiveInvoice,
|
|
3059
|
+
assertReceivable,
|
|
3060
|
+
lightningReceiveContract,
|
|
3061
|
+
deriveLightningReceive,
|
|
3062
|
+
requestLightningReceive,
|
|
3063
|
+
deriveOnchainReceive,
|
|
3064
|
+
requestOnchainReceive
|
|
3065
|
+
};
|