@arkade-os/swap 0.1.0-rc.24 → 0.1.0-rc.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/advanced.cjs +1858 -651
- package/dist/advanced.d.cts +9 -8
- package/dist/advanced.d.ts +9 -8
- package/dist/advanced.js +41 -23
- package/dist/{chunk-J6MXF4GQ.js → chunk-6O3L4AVI.js} +579 -295
- package/dist/{chunk-UFJEO4VV.js → chunk-DHFKCTER.js} +567 -99
- package/dist/{chunk-MSVRO7ZS.js → chunk-XBMWEK43.js} +551 -136
- package/dist/index.cjs +1869 -664
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +29 -13
- package/dist/{lockupContract-5r5RlgOJ.d.cts → lockupContract-BTCE7g83.d.ts} +8 -1
- package/dist/{lockupContract-5r5RlgOJ.d.ts → lockupContract-BTCGwjRH.d.cts} +8 -1
- package/dist/node/index.d.cts +39 -22
- package/dist/node/index.d.ts +39 -22
- package/dist/nostr.cjs +38 -0
- package/dist/nostr.d.cts +1 -1
- package/dist/nostr.d.ts +1 -1
- package/dist/nostr.js +1 -1
- package/dist/{offer-N2oXLfLX.d.cts → offer-CsXgroM0.d.cts} +26 -18
- package/dist/{offer-cE8qJmbC.d.ts → offer-DYCiKDm6.d.ts} +26 -18
- package/dist/{errors-ByFSFU1B.d.ts → offerFillPlan-BQnzburi.d.ts} +56 -7
- package/dist/{errors-C0agdsz-.d.cts → offerFillPlan-CFT8qgTV.d.cts} +56 -7
- package/dist/protocol.cjs +711 -334
- package/dist/protocol.d.cts +8 -8
- package/dist/protocol.d.ts +8 -8
- package/dist/protocol.js +8 -6
- package/dist/repositories/realm/index.d.cts +2 -2
- package/dist/repositories/realm/index.d.ts +2 -2
- package/dist/repositories/sqlite/index.d.cts +2 -2
- package/dist/repositories/sqlite/index.d.ts +2 -2
- package/dist/{repository-DITDhUdX.d.ts → repository-Bgn0apiL.d.cts} +75 -25
- package/dist/{repository-yN-i_u-0.d.cts → repository-CSJXRd5N.d.ts} +75 -25
- package/dist/{rfq-BgdgO9OO.d.cts → rfq-m9tCbQx7.d.cts} +2 -0
- package/dist/{rfq-BgdgO9OO.d.ts → rfq-m9tCbQx7.d.ts} +2 -0
- package/dist/{watch-Bws1mS0R.d.cts → watch-CLJXFpMq.d.cts} +1 -1
- package/dist/{watch-G0Z7yJZb.d.ts → watch-D0R7YhYg.d.ts} +1 -1
- package/package.json +2 -2
package/dist/advanced.cjs
CHANGED
|
@@ -121,6 +121,16 @@ var init_swap_want_btc_program = __esm({
|
|
|
121
121
|
});
|
|
122
122
|
|
|
123
123
|
// src/coverage.ts
|
|
124
|
+
function markIssued(script, issued, options) {
|
|
125
|
+
const scope = options.scope ?? legacyScope;
|
|
126
|
+
const issuedAt = issuedByScope.get(scope) ?? /* @__PURE__ */ new Map();
|
|
127
|
+
const outstanding = issuedAt.get(script) ?? { issuedAt: void 0, ids: /* @__PURE__ */ new Set() };
|
|
128
|
+
const id = options.coverageId;
|
|
129
|
+
if (id === void 0) outstanding.issuedAt = issued;
|
|
130
|
+
else outstanding.ids.add(id);
|
|
131
|
+
issuedAt.set(script, outstanding);
|
|
132
|
+
issuedByScope.set(scope, issuedAt);
|
|
133
|
+
}
|
|
124
134
|
async function serialize(script, task) {
|
|
125
135
|
const previous = inFlight.get(script) ?? Promise.resolve();
|
|
126
136
|
const result = previous.then(task, task);
|
|
@@ -136,25 +146,35 @@ async function serialize(script, task) {
|
|
|
136
146
|
});
|
|
137
147
|
return result;
|
|
138
148
|
}
|
|
139
|
-
function addressOutstanding(swaps, script) {
|
|
149
|
+
function addressOutstanding(swaps, script, scope) {
|
|
150
|
+
const issuedAt = issuedByScope.get(scope);
|
|
151
|
+
if (issuedAt === void 0) return false;
|
|
140
152
|
const issued = issuedAt.get(script);
|
|
141
153
|
if (issued === void 0) return false;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
154
|
+
for (const swap of swaps) {
|
|
155
|
+
if (swap.swapPkScript !== script) continue;
|
|
156
|
+
if (swap.id !== void 0) issued.ids.delete(swap.id);
|
|
157
|
+
if (issued.issuedAt !== void 0 && swap.createdAt >= issued.issuedAt) {
|
|
158
|
+
issued.issuedAt = void 0;
|
|
159
|
+
}
|
|
145
160
|
}
|
|
146
|
-
return true;
|
|
161
|
+
if (issued.ids.size > 0 || issued.issuedAt !== void 0) return true;
|
|
162
|
+
issuedAt.delete(script);
|
|
163
|
+
return false;
|
|
147
164
|
}
|
|
148
|
-
async function promoteOfferContract(manager, script, issued = Date.now()) {
|
|
165
|
+
async function promoteOfferContract(manager, script, issued = Date.now(), options = {}) {
|
|
149
166
|
await serialize(script, async () => {
|
|
150
167
|
await manager.setContractWatchState(script, "watched");
|
|
151
|
-
|
|
168
|
+
if (options.restore && options.coverageId !== void 0) return;
|
|
169
|
+
markIssued(script, issued, options);
|
|
152
170
|
});
|
|
153
171
|
}
|
|
154
|
-
async function retireOfferContract(manager, swaps, script) {
|
|
172
|
+
async function retireOfferContract(manager, swaps, script, options = {}) {
|
|
155
173
|
await serialize(script, async () => {
|
|
156
|
-
|
|
157
|
-
|
|
174
|
+
const records = typeof swaps === "function" ? await swaps() : swaps;
|
|
175
|
+
const outstanding = addressOutstanding(records, script, options.scope ?? legacyScope);
|
|
176
|
+
if (records.some((s) => s.swapPkScript === script && !RETIRABLE.includes(s.status))) return;
|
|
177
|
+
if (outstanding) return;
|
|
158
178
|
try {
|
|
159
179
|
await manager.setContractWatchState(script, "retained");
|
|
160
180
|
} catch (err) {
|
|
@@ -162,20 +182,68 @@ async function retireOfferContract(manager, swaps, script) {
|
|
|
162
182
|
}
|
|
163
183
|
});
|
|
164
184
|
}
|
|
165
|
-
async function retireSettledOfferContracts(manager, swaps) {
|
|
185
|
+
async function retireSettledOfferContracts(manager, swaps, options = {}) {
|
|
166
186
|
const settled = new Set(
|
|
167
187
|
swaps.filter((s) => RETIRABLE.includes(s.status)).map((s) => s.swapPkScript)
|
|
168
188
|
);
|
|
169
|
-
for (const script of settled) await retireOfferContract(manager, swaps, script);
|
|
189
|
+
for (const script of settled) await retireOfferContract(manager, swaps, script, options);
|
|
170
190
|
}
|
|
171
|
-
var RETIRABLE, LOCKUP_RETIRABLE,
|
|
191
|
+
var RETIRABLE, LOCKUP_RETIRABLE, legacyScope, issuedByScope, inFlight, registerContractCoverage;
|
|
172
192
|
var init_coverage = __esm({
|
|
173
193
|
"src/coverage.ts"() {
|
|
174
194
|
"use strict";
|
|
175
195
|
RETIRABLE = ["fulfilled", "cancelled"];
|
|
176
196
|
LOCKUP_RETIRABLE = ["settled", "refunded"];
|
|
177
|
-
|
|
197
|
+
legacyScope = {};
|
|
198
|
+
issuedByScope = /* @__PURE__ */ new WeakMap();
|
|
178
199
|
inFlight = /* @__PURE__ */ new Map();
|
|
200
|
+
registerContractCoverage = async (script, register, options = {}) => serialize(script, async () => {
|
|
201
|
+
const row = await register();
|
|
202
|
+
markIssued(script, Date.now(), options);
|
|
203
|
+
return row;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// src/rfqCorridor.ts
|
|
209
|
+
var RfqCorridorRegistry, rfqCorridorHandlers;
|
|
210
|
+
var init_rfqCorridor = __esm({
|
|
211
|
+
"src/rfqCorridor.ts"() {
|
|
212
|
+
"use strict";
|
|
213
|
+
RfqCorridorRegistry = class {
|
|
214
|
+
handlers = /* @__PURE__ */ new Map();
|
|
215
|
+
register(handler) {
|
|
216
|
+
if (this.handlers.has(handler.kind)) {
|
|
217
|
+
throw new Error(
|
|
218
|
+
`RFQ corridor handler for kind '${handler.kind}' is already registered`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
this.handlers.set(handler.kind, handler);
|
|
222
|
+
}
|
|
223
|
+
/** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
|
|
224
|
+
* `kind` union would read as a check already made. */
|
|
225
|
+
get(kind) {
|
|
226
|
+
return this.handlers.get(kind);
|
|
227
|
+
}
|
|
228
|
+
/** The handler for a kind, or a loud failure naming the registered kinds. */
|
|
229
|
+
getOrThrow(kind) {
|
|
230
|
+
const handler = this.get(kind);
|
|
231
|
+
if (!handler) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
`no RFQ corridor handler registered for kind '${kind}'; registered: ${this.registeredKinds().join(", ") || "none"}`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
return handler;
|
|
237
|
+
}
|
|
238
|
+
registeredKinds() {
|
|
239
|
+
return [...this.handlers.keys()];
|
|
240
|
+
}
|
|
241
|
+
/** Test seam, mirroring the contract registry's. */
|
|
242
|
+
unregister(kind) {
|
|
243
|
+
return this.handlers.delete(kind);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
rfqCorridorHandlers = new RfqCorridorRegistry();
|
|
179
247
|
}
|
|
180
248
|
});
|
|
181
249
|
|
|
@@ -310,6 +378,96 @@ var init_store = __esm({
|
|
|
310
378
|
}
|
|
311
379
|
});
|
|
312
380
|
|
|
381
|
+
// src/rfqProfileParts.ts
|
|
382
|
+
var rfqSecretsProfile, parseHex32, parseSigner, parsePayoutAddress, parseHashlock, hydrateHashlock, rfqSignerOf, rfqClaimSecretOf, rfqClaimDestinationOf;
|
|
383
|
+
var init_rfqProfileParts = __esm({
|
|
384
|
+
"src/rfqProfileParts.ts"() {
|
|
385
|
+
"use strict";
|
|
386
|
+
init_rfqCorridor();
|
|
387
|
+
init_store();
|
|
388
|
+
rfqSecretsProfile = (secrets, paymentHash) => {
|
|
389
|
+
const { signingDescriptor, ...preimage } = swapSecretsToRecord(secrets);
|
|
390
|
+
return {
|
|
391
|
+
signer: { signingDescriptor },
|
|
392
|
+
...paymentHash ? { hashlock: { paymentHash, ...preimage } } : {}
|
|
393
|
+
};
|
|
394
|
+
};
|
|
395
|
+
parseHex32 = (value, field) => {
|
|
396
|
+
if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) {
|
|
397
|
+
throw new Error(`${field} must be 32 bytes of hex, got ${JSON.stringify(value)}`);
|
|
398
|
+
}
|
|
399
|
+
return value.toLowerCase();
|
|
400
|
+
};
|
|
401
|
+
parseSigner = (value) => {
|
|
402
|
+
const signingDescriptor = value?.signingDescriptor;
|
|
403
|
+
if (typeof signingDescriptor !== "string" || signingDescriptor.length === 0) {
|
|
404
|
+
throw new Error(
|
|
405
|
+
`rfq profile.signer carries no signingDescriptor (got ${JSON.stringify(signingDescriptor)})`
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
return { signingDescriptor };
|
|
409
|
+
};
|
|
410
|
+
parsePayoutAddress = (value, kind) => {
|
|
411
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
412
|
+
throw new Error(
|
|
413
|
+
`this ${kind} record's claim destination is unusable: expected an Arkade address, got ${JSON.stringify(value)}`
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return value;
|
|
417
|
+
};
|
|
418
|
+
parseHashlock = (value) => {
|
|
419
|
+
const raw = value ?? {};
|
|
420
|
+
const hashlock = {
|
|
421
|
+
paymentHash: parseHex32(raw.paymentHash, "rfq profile.hashlock.paymentHash")
|
|
422
|
+
};
|
|
423
|
+
if (raw.preimageHex !== void 0) {
|
|
424
|
+
hashlock.preimageHex = parseHex32(raw.preimageHex, "rfq profile.hashlock.preimageHex");
|
|
425
|
+
}
|
|
426
|
+
if (raw.preimageSaltHex !== void 0) {
|
|
427
|
+
hashlock.preimageSaltHex = parseHex32(
|
|
428
|
+
raw.preimageSaltHex,
|
|
429
|
+
"rfq profile.hashlock.preimageSaltHex"
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
return hashlock;
|
|
433
|
+
};
|
|
434
|
+
hydrateHashlock = (profile) => {
|
|
435
|
+
try {
|
|
436
|
+
return { paymentHash: parseHashlock(profile.hashlock).paymentHash };
|
|
437
|
+
} catch (cause) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
`rfq record carries no usable hashlock; it cannot verify a preimage: ${String(cause)}`,
|
|
440
|
+
{ cause }
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
rfqSignerOf = (record) => {
|
|
445
|
+
const signer = record.profile.signer;
|
|
446
|
+
if (signer === void 0) return void 0;
|
|
447
|
+
return parseSigner(signer);
|
|
448
|
+
};
|
|
449
|
+
rfqClaimSecretOf = (record) => {
|
|
450
|
+
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
451
|
+
if (!handler.claimSecret) return void 0;
|
|
452
|
+
try {
|
|
453
|
+
const claim = handler.claimSecret(record.profile);
|
|
454
|
+
return { ...parseSigner(claim), ...parseHashlock(claim) };
|
|
455
|
+
} catch (cause) {
|
|
456
|
+
throw new PreimageNotRecoverableError(
|
|
457
|
+
"malformed-record",
|
|
458
|
+
`this ${record.kind} record's claim secret is unreadable: ${String(cause)}`,
|
|
459
|
+
{ cause }
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
rfqClaimDestinationOf = (record) => {
|
|
464
|
+
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
465
|
+
if (!handler.claimDestination) return void 0;
|
|
466
|
+
return parsePayoutAddress(handler.claimDestination(record.profile), record.kind);
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
|
|
313
471
|
// src/offer.ts
|
|
314
472
|
function withExitClosure(program, exit) {
|
|
315
473
|
if (!exit) return program;
|
|
@@ -487,13 +645,16 @@ function decodeExitDelay(value) {
|
|
|
487
645
|
if (!type) throw new Error(`unknown exitDelay locktime type: 0x${value[0].toString(16)}`);
|
|
488
646
|
return { type, value: readU64(value.subarray(1)) };
|
|
489
647
|
}
|
|
490
|
-
async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
|
|
648
|
+
async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript, options = {}) {
|
|
491
649
|
const contractManager = await wallet.getContractManager();
|
|
492
650
|
const client = await derivingClient(wallet, info, contractManager);
|
|
493
651
|
await contractManager.createContract(
|
|
494
652
|
offerContractParams(client, binding, operatorPubkey, expectedPkScript)
|
|
495
653
|
);
|
|
496
|
-
await promoteOfferContract(contractManager, import_base2.hex.encode(expectedPkScript)
|
|
654
|
+
await promoteOfferContract(contractManager, import_base2.hex.encode(expectedPkScript), void 0, {
|
|
655
|
+
...options,
|
|
656
|
+
scope: wallet
|
|
657
|
+
});
|
|
497
658
|
}
|
|
498
659
|
function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
|
|
499
660
|
const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
|
|
@@ -526,6 +687,7 @@ async function restoreOfferCoverage(wallet, swaps) {
|
|
|
526
687
|
covenants.push({
|
|
527
688
|
script: swap.swapPkScript,
|
|
528
689
|
issued: swap.createdAt,
|
|
690
|
+
coverageId: swap.coverageId,
|
|
529
691
|
params: offerContractParams(
|
|
530
692
|
client,
|
|
531
693
|
binding,
|
|
@@ -544,7 +706,11 @@ async function restoreOfferCoverage(wallet, swaps) {
|
|
|
544
706
|
for (const contract of params) await contractManager.createContract(contract);
|
|
545
707
|
}
|
|
546
708
|
for (const covenant of covenants) {
|
|
547
|
-
await promoteOfferContract(contractManager, covenant.script, covenant.issued
|
|
709
|
+
await promoteOfferContract(contractManager, covenant.script, covenant.issued, {
|
|
710
|
+
coverageId: covenant.coverageId,
|
|
711
|
+
restore: true,
|
|
712
|
+
scope: wallet
|
|
713
|
+
});
|
|
548
714
|
}
|
|
549
715
|
}
|
|
550
716
|
function serverExitDelay(delay) {
|
|
@@ -555,9 +721,9 @@ function serverExitDelay(delay) {
|
|
|
555
721
|
}
|
|
556
722
|
return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
|
|
557
723
|
}
|
|
558
|
-
async function createOffer(wallet, params) {
|
|
724
|
+
async function createOffer(wallet, params, options = {}) {
|
|
559
725
|
const derived = await deriveOffer(wallet, params);
|
|
560
|
-
await registerDerivedOffer(wallet, derived);
|
|
726
|
+
await registerDerivedOffer(wallet, derived, options);
|
|
561
727
|
return {
|
|
562
728
|
offerHex: derived.offerHex,
|
|
563
729
|
extension: derived.extension,
|
|
@@ -565,6 +731,29 @@ async function createOffer(wallet, params) {
|
|
|
565
731
|
swapPkScript: derived.swapPkScript
|
|
566
732
|
};
|
|
567
733
|
}
|
|
734
|
+
function resolveReceivePkScript(receiveAddress, walletPkScript, hrp, serverPubKey) {
|
|
735
|
+
if (receiveAddress === void 0) return walletPkScript;
|
|
736
|
+
let address;
|
|
737
|
+
try {
|
|
738
|
+
address = import_sdk3.ArkAddress.decode(receiveAddress);
|
|
739
|
+
} catch (cause) {
|
|
740
|
+
throw new Error("receiveAddress is not a valid Arkade address", { cause });
|
|
741
|
+
}
|
|
742
|
+
if (address.hrp !== hrp) {
|
|
743
|
+
throw new Error(
|
|
744
|
+
`receiveAddress network ${address.hrp} does not match the server network ${hrp}`
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
if (address.encode() !== receiveAddress) {
|
|
748
|
+
throw new Error("receiveAddress is not in canonical bech32m form");
|
|
749
|
+
}
|
|
750
|
+
if (import_base2.hex.encode(address.serverPubKey) !== import_base2.hex.encode(serverPubKey)) {
|
|
751
|
+
throw new Error(
|
|
752
|
+
"receiveAddress is bound to a different server public key than the connected server"
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
return address.pkScript;
|
|
756
|
+
}
|
|
568
757
|
async function deriveOffer(wallet, params) {
|
|
569
758
|
if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
|
|
570
759
|
throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
|
|
@@ -593,7 +782,12 @@ async function deriveOffer(wallet, params) {
|
|
|
593
782
|
wantAmount: params.wantAmount,
|
|
594
783
|
wantAsset: params.wantAsset,
|
|
595
784
|
offerAsset: params.offerAsset,
|
|
596
|
-
makerPkScript:
|
|
785
|
+
makerPkScript: resolveReceivePkScript(
|
|
786
|
+
params.receiveAddress,
|
|
787
|
+
maker.pkScript,
|
|
788
|
+
network.hrp,
|
|
789
|
+
operatorPubKey
|
|
790
|
+
),
|
|
597
791
|
makerPublicKey: maker.publicKey,
|
|
598
792
|
emulatorPubkey: emuKey,
|
|
599
793
|
// checked before registration below. @see assertExitDelay
|
|
@@ -614,17 +808,18 @@ async function deriveOffer(wallet, params) {
|
|
|
614
808
|
operatorPubkey: operatorPubKey
|
|
615
809
|
});
|
|
616
810
|
}
|
|
617
|
-
async function registerDerivedOffer(wallet, derived) {
|
|
811
|
+
async function registerDerivedOffer(wallet, derived, options = {}) {
|
|
618
812
|
await registerOfferContract(
|
|
619
813
|
wallet,
|
|
620
814
|
derived.info,
|
|
621
815
|
derived.binding,
|
|
622
816
|
derived.operatorPubkey,
|
|
623
|
-
derived.swapPkScript
|
|
817
|
+
derived.swapPkScript,
|
|
818
|
+
options
|
|
624
819
|
);
|
|
625
820
|
}
|
|
626
821
|
async function prepareOfferCancel(wallet, offerHex, opts) {
|
|
627
|
-
const { fundingTxid, swapAddress } = opts;
|
|
822
|
+
const { fundingTxid, fundingOutpoint, swapAddress } = opts;
|
|
628
823
|
const offer = decodeOffer(import_base2.hex.decode(offerHex));
|
|
629
824
|
const [contractManager, info, reader, broadcaster] = await Promise.all([
|
|
630
825
|
wallet.getContractManager(),
|
|
@@ -654,13 +849,7 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
|
|
|
654
849
|
}
|
|
655
850
|
const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
|
|
656
851
|
const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
|
|
657
|
-
|
|
658
|
-
throw new Error(
|
|
659
|
-
"multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
|
-
const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
|
|
663
|
-
if (!vtxo) throw new NoSpendableDepositError();
|
|
852
|
+
const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
|
|
664
853
|
const makerPkScript = import_sdk3.ArkAddress.decode(makerAddress).pkScript;
|
|
665
854
|
const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
|
|
666
855
|
for (const a of vtxo.assets ?? []) {
|
|
@@ -676,7 +865,339 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
|
|
|
676
865
|
send: async () => (await cancel.send()).txid
|
|
677
866
|
};
|
|
678
867
|
}
|
|
679
|
-
|
|
868
|
+
async function connectFillContract(wallet, arkServerUrl, offer, opts = {}) {
|
|
869
|
+
const { swapAddress, emulator, emulatorPubkey } = opts;
|
|
870
|
+
const contractManager = await wallet.getContractManager();
|
|
871
|
+
const client = await import_sdk3.arkade.Arkade.connect({
|
|
872
|
+
arkade: new import_sdk3.RestArkProvider(arkServerUrl),
|
|
873
|
+
indexer: new import_sdk3.RestIndexerProvider(arkServerUrl),
|
|
874
|
+
identity: wallet.identity,
|
|
875
|
+
contractManager,
|
|
876
|
+
...emulator !== void 0 ? {
|
|
877
|
+
emulator: typeof emulator === "string" ? new import_sdk3.RestEmulatorProvider(emulator) : emulator
|
|
878
|
+
} : {},
|
|
879
|
+
...emulatorPubkey ? { emulatorPubkey } : {}
|
|
880
|
+
});
|
|
881
|
+
const serverKey = swapAddress ? import_sdk3.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
|
|
882
|
+
const { program, args, keys } = swapProgramBinding(offer, serverKey);
|
|
883
|
+
const rebuilt = new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
|
|
884
|
+
if (import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(offer.swapPkScript)) {
|
|
885
|
+
throw new Error(
|
|
886
|
+
"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"
|
|
887
|
+
);
|
|
888
|
+
}
|
|
889
|
+
return new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
|
|
890
|
+
}
|
|
891
|
+
function resolveDeposit(vtxos, sel) {
|
|
892
|
+
const { fundingTxid, fundingOutpoint } = sel;
|
|
893
|
+
if (fundingOutpoint !== void 0) {
|
|
894
|
+
const txid = parseHex32(fundingOutpoint.txid, "fundingOutpoint.txid");
|
|
895
|
+
const vout = assertVout(fundingOutpoint.vout, "fundingOutpoint.vout");
|
|
896
|
+
if (fundingTxid !== void 0 && fundingTxid.toLowerCase() !== txid) {
|
|
897
|
+
throw new Error(
|
|
898
|
+
`fundingTxid ${fundingTxid} does not match fundingOutpoint ${txid}:${vout} \u2014 pass one deposit reference`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
const vtxo2 = vtxos.find((v) => v.txid.toLowerCase() === txid && v.vout === vout);
|
|
902
|
+
if (!vtxo2) throw new NoSpendableDepositError();
|
|
903
|
+
return vtxo2;
|
|
904
|
+
}
|
|
905
|
+
if (fundingTxid !== void 0) {
|
|
906
|
+
const txid = parseHex32(fundingTxid, "fundingTxid");
|
|
907
|
+
const matches = vtxos.filter((v) => v.txid.toLowerCase() === txid);
|
|
908
|
+
if (matches.length > 1) {
|
|
909
|
+
throw new Error(
|
|
910
|
+
`multiple spendable deposits share fundingTxid ${txid} \u2014 pass fundingOutpoint to select one`
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
const [vtxo2] = matches;
|
|
914
|
+
if (!vtxo2) throw new NoSpendableDepositError();
|
|
915
|
+
return vtxo2;
|
|
916
|
+
}
|
|
917
|
+
if (vtxos.length > 1) {
|
|
918
|
+
throw new Error(
|
|
919
|
+
"multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
const [vtxo] = vtxos;
|
|
923
|
+
if (!vtxo) throw new NoSpendableDepositError();
|
|
924
|
+
return vtxo;
|
|
925
|
+
}
|
|
926
|
+
function assembleOfferFill(fill, args) {
|
|
927
|
+
const {
|
|
928
|
+
offer,
|
|
929
|
+
vtxo,
|
|
930
|
+
solverFund,
|
|
931
|
+
solverPayout,
|
|
932
|
+
assetCarrierSats = ASSET_CARRIER_SATS,
|
|
933
|
+
sponsor
|
|
934
|
+
} = args;
|
|
935
|
+
const wantedAssetId = offer.wantAsset?.toString();
|
|
936
|
+
if (solverFund.length === 0) {
|
|
937
|
+
throw new Error("fillOffer needs coins to pay wantAmount with \u2014 `fund` is empty");
|
|
938
|
+
}
|
|
939
|
+
solverFund.forEach((coin, i) => assertFillCoin(coin, `fund[${i}]`));
|
|
940
|
+
assertScript(solverPayout, "payoutScript");
|
|
941
|
+
toAmount(vtxo.value, "deposit.value", "sats", BigInt(1));
|
|
942
|
+
assertAssetEntries(vtxo.assets, "deposit");
|
|
943
|
+
const carrier = toAmount(assetCarrierSats, "assetCarrierSats", "sats", BigInt(1));
|
|
944
|
+
let sponsorFund = [];
|
|
945
|
+
let sponsorChange = BigInt(0);
|
|
946
|
+
let fareAsset = "";
|
|
947
|
+
let fareAmount = BigInt(0);
|
|
948
|
+
let fareSats = BigInt(0);
|
|
949
|
+
let combineSatsFareWithChange = false;
|
|
950
|
+
if (sponsor !== void 0) {
|
|
951
|
+
if (sponsor.fund.length === 0) {
|
|
952
|
+
throw new Error("sponsor needs coins to contribute with \u2014 `sponsor.fund` is empty");
|
|
953
|
+
}
|
|
954
|
+
sponsor.fund.forEach((coin, i) => {
|
|
955
|
+
assertFillCoin(coin, `sponsor.fund[${i}]`);
|
|
956
|
+
if ((coin.assets?.length ?? 0) > 0) {
|
|
957
|
+
throw new Error(`sponsor.fund[${i}] carries assets \u2014 sponsor funding is sats-only`);
|
|
958
|
+
}
|
|
959
|
+
});
|
|
960
|
+
assertScript(sponsor.changeScript, "sponsor.changeScript");
|
|
961
|
+
const contribution = toAmount(
|
|
962
|
+
sponsor.netContributionSats,
|
|
963
|
+
"sponsor.netContributionSats",
|
|
964
|
+
"sats"
|
|
965
|
+
);
|
|
966
|
+
if (contribution <= BigInt(0)) {
|
|
967
|
+
throw new Error("sponsor.netContributionSats must be a positive amount of sats");
|
|
968
|
+
}
|
|
969
|
+
if (sponsor.combineSatsFareWithChange !== void 0 && typeof sponsor.combineSatsFareWithChange !== "boolean") {
|
|
970
|
+
throw new Error("sponsor.combineSatsFareWithChange must be a boolean");
|
|
971
|
+
}
|
|
972
|
+
combineSatsFareWithChange = sponsor.combineSatsFareWithChange === true;
|
|
973
|
+
if (combineSatsFareWithChange && sponsor.fare === void 0) {
|
|
974
|
+
throw new Error("sponsor.combineSatsFareWithChange requires a fare");
|
|
975
|
+
}
|
|
976
|
+
if (sponsor.fare !== void 0) {
|
|
977
|
+
const { assetId, amount } = sponsor.fare;
|
|
978
|
+
if (assetId === void 0 !== (amount === void 0)) {
|
|
979
|
+
throw new Error(
|
|
980
|
+
"sponsor.fare needs assetId and amount together, or neither for a sats fare"
|
|
981
|
+
);
|
|
982
|
+
}
|
|
983
|
+
if (assetId !== void 0) {
|
|
984
|
+
fareAsset = assertAssetId(assetId, "sponsor.fare.assetId");
|
|
985
|
+
fareAmount = toAmount(amount, "sponsor.fare.amount", "asset units");
|
|
986
|
+
if (fareAmount <= BigInt(0)) {
|
|
987
|
+
throw new Error("sponsor.fare.amount must be a positive amount of asset units");
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
assertScript(sponsor.fare.script, "sponsor.fare.script");
|
|
991
|
+
fareSats = toAmount(sponsor.fare.sats, "sponsor.fare.sats", "sats", BigInt(1));
|
|
992
|
+
if (combineSatsFareWithChange) {
|
|
993
|
+
if (assetId !== void 0) {
|
|
994
|
+
throw new Error("sponsor.combineSatsFareWithChange requires a sats-only fare");
|
|
995
|
+
}
|
|
996
|
+
if (import_base2.hex.encode(sponsor.fare.script) !== import_base2.hex.encode(sponsor.changeScript)) {
|
|
997
|
+
throw new Error(
|
|
998
|
+
"sponsor.combineSatsFareWithChange requires fare and change to use the same script"
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const sponsorInputs = sponsor.fund.reduce((s, c) => s + BigInt(c.value), BigInt(0));
|
|
1004
|
+
if (contribution > sponsorInputs) {
|
|
1005
|
+
throw new Error(
|
|
1006
|
+
`sponsor.netContributionSats ${contribution} exceeds the sponsor inputs ${sponsorInputs}`
|
|
1007
|
+
);
|
|
1008
|
+
}
|
|
1009
|
+
sponsorFund = sponsor.fund;
|
|
1010
|
+
const baseSponsorChange = sponsorInputs - contribution;
|
|
1011
|
+
sponsorChange = combineSatsFareWithChange ? toAmount(baseSponsorChange + fareSats, "combined sponsor change", "sats", BigInt(1)) : baseSponsorChange;
|
|
1012
|
+
}
|
|
1013
|
+
if (wantedAssetId !== void 0) {
|
|
1014
|
+
const required = offer.wantAmount + (sponsor?.fare !== void 0 && fareAsset === wantedAssetId ? fareAmount : BigInt(0));
|
|
1015
|
+
const supplied = solverFund.reduce(
|
|
1016
|
+
(sum, coin) => sum + amountOfAsset(coin.assets, wantedAssetId),
|
|
1017
|
+
BigInt(0)
|
|
1018
|
+
);
|
|
1019
|
+
if (supplied < required) {
|
|
1020
|
+
throw new Error(
|
|
1021
|
+
`fillOffer needs ${required} of ${wantedAssetId} to pay the maker, but \`fund\` declares ${supplied} \u2014 pass coins carrying it, and declare their assets`
|
|
1022
|
+
);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
if (offer.offerAsset) {
|
|
1026
|
+
const offered = offer.offerAsset.toString();
|
|
1027
|
+
const deposited = amountOfAsset(vtxo.assets, offered);
|
|
1028
|
+
if (deposited <= BigInt(0)) {
|
|
1029
|
+
throw new Error(
|
|
1030
|
+
`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`
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1035
|
+
const claim = (txid, vout, what) => {
|
|
1036
|
+
const key = `${txid.toLowerCase()}:${vout}`;
|
|
1037
|
+
if (seen.has(key)) throw new Error(`duplicate fill input ${key} (${what})`);
|
|
1038
|
+
seen.add(key);
|
|
1039
|
+
};
|
|
1040
|
+
claim(parseHex32(vtxo.txid, "deposit.txid"), assertVout(vtxo.vout, "deposit.vout"), "deposit");
|
|
1041
|
+
solverFund.forEach((coin, i) => claim(coin.txid, coin.vout, `fund[${i}]`));
|
|
1042
|
+
sponsorFund.forEach((coin, i) => claim(coin.txid, coin.vout, `sponsor.fund[${i}]`));
|
|
1043
|
+
const makerSats = wantedAssetId === void 0 ? toAmount(offer.wantAmount, "offer.wantAmount", "sats") : carrier;
|
|
1044
|
+
const outputs = [
|
|
1045
|
+
{ role: "receiver", script: offer.makerPkScript, sats: makerSats }
|
|
1046
|
+
];
|
|
1047
|
+
const fareVout = outputs.length;
|
|
1048
|
+
if (sponsor?.fare !== void 0 && !combineSatsFareWithChange) {
|
|
1049
|
+
outputs.push({ role: "sponsor-fare", script: sponsor.fare.script, sats: fareSats });
|
|
1050
|
+
}
|
|
1051
|
+
if (sponsor !== void 0 && sponsorChange > BigInt(0)) {
|
|
1052
|
+
outputs.push({ role: "sponsor-change", script: sponsor.changeScript, sats: sponsorChange });
|
|
1053
|
+
}
|
|
1054
|
+
const solverVout = outputs.length;
|
|
1055
|
+
fill.from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).fund(sponsorFund.length > 0 ? [...solverFund, ...sponsorFund] : solverFund).to(offer.makerPkScript, makerSats);
|
|
1056
|
+
if (sponsor?.fare !== void 0 && !combineSatsFareWithChange)
|
|
1057
|
+
fill.to(sponsor.fare.script, fareSats);
|
|
1058
|
+
if (sponsor !== void 0 && sponsorChange > BigInt(0))
|
|
1059
|
+
fill.to(sponsor.changeScript, sponsorChange);
|
|
1060
|
+
fill.change(solverPayout);
|
|
1061
|
+
const held = /* @__PURE__ */ new Map();
|
|
1062
|
+
const hold = (vin, assets) => {
|
|
1063
|
+
for (const a of assets ?? []) {
|
|
1064
|
+
const amount = BigInt(a.amount);
|
|
1065
|
+
if (amount <= BigInt(0)) continue;
|
|
1066
|
+
held.set(a.assetId, [...held.get(a.assetId) ?? [], { vin, amount }]);
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
hold(0, vtxo.assets);
|
|
1070
|
+
solverFund.forEach((coin, i) => hold(i + 1, coin.assets));
|
|
1071
|
+
sponsorFund.forEach((coin, i) => hold(1 + solverFund.length + i, coin.assets));
|
|
1072
|
+
const explicitSats = outputs.reduce((s, o) => s + o.sats, BigInt(0));
|
|
1073
|
+
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));
|
|
1074
|
+
if (inputsSum > MAX_SAFE_SATS) {
|
|
1075
|
+
throw new Error(`fill inputs total ${inputsSum} sats exceeds the safe integer domain`);
|
|
1076
|
+
}
|
|
1077
|
+
if (explicitSats > MAX_SAFE_SATS) {
|
|
1078
|
+
throw new Error(`fill outputs total ${explicitSats} sats exceeds the safe integer domain`);
|
|
1079
|
+
}
|
|
1080
|
+
if (explicitSats > inputsSum) {
|
|
1081
|
+
throw new Error(
|
|
1082
|
+
`fill outputs total ${explicitSats} sats but the inputs carry ${inputsSum} \u2014 increase solver or sponsor funding`
|
|
1083
|
+
);
|
|
1084
|
+
}
|
|
1085
|
+
const hasPayoutOutput = inputsSum > explicitSats;
|
|
1086
|
+
if (sponsor?.fare !== void 0 && fareAsset !== "") {
|
|
1087
|
+
const carried = (held.get(fareAsset) ?? []).reduce((s, i) => s + i.amount, BigInt(0));
|
|
1088
|
+
if (carried < fareAmount) {
|
|
1089
|
+
throw new Error(
|
|
1090
|
+
`sponsor fare needs ${fareAmount} of ${fareAsset} but the inputs carry ${carried}`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const stranded = (assetId, amount) => new Error(
|
|
1095
|
+
`fillOffer has ${amount} of ${assetId} to return but no payout output \u2014 fund with more sats than the maker's output takes`
|
|
1096
|
+
);
|
|
1097
|
+
if (wantedAssetId !== void 0) {
|
|
1098
|
+
const supplying = held.get(wantedAssetId) ?? [];
|
|
1099
|
+
const supplied = supplying.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1100
|
+
const group = [{ vout: 0, amount: offer.wantAmount }];
|
|
1101
|
+
const farePart = sponsor?.fare !== void 0 && fareAsset === wantedAssetId ? fareAmount : BigInt(0);
|
|
1102
|
+
if (farePart > BigInt(0)) group.push({ vout: fareVout, amount: farePart });
|
|
1103
|
+
const surplus = supplied - offer.wantAmount - farePart;
|
|
1104
|
+
if (surplus > BigInt(0)) {
|
|
1105
|
+
if (!hasPayoutOutput) throw stranded(wantedAssetId, surplus);
|
|
1106
|
+
group.push({ vout: solverVout, amount: surplus });
|
|
1107
|
+
}
|
|
1108
|
+
fill.withAsset({ assetId: wantedAssetId, inputs: supplying, outputs: group });
|
|
1109
|
+
held.delete(wantedAssetId);
|
|
1110
|
+
}
|
|
1111
|
+
if (sponsor?.fare !== void 0 && fareAsset !== "" && fareAsset !== wantedAssetId) {
|
|
1112
|
+
const supplying = held.get(fareAsset) ?? [];
|
|
1113
|
+
const carried = supplying.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1114
|
+
const group = [{ vout: fareVout, amount: fareAmount }];
|
|
1115
|
+
const remainder = carried - fareAmount;
|
|
1116
|
+
if (remainder > BigInt(0)) {
|
|
1117
|
+
if (!hasPayoutOutput) throw stranded(fareAsset, remainder);
|
|
1118
|
+
group.push({ vout: solverVout, amount: remainder });
|
|
1119
|
+
}
|
|
1120
|
+
fill.withAsset({ assetId: fareAsset, inputs: supplying, outputs: group });
|
|
1121
|
+
held.delete(fareAsset);
|
|
1122
|
+
}
|
|
1123
|
+
for (const [assetId, inputs] of held) {
|
|
1124
|
+
const amount = inputs.reduce((s, i) => s + i.amount, BigInt(0));
|
|
1125
|
+
if (!hasPayoutOutput) throw stranded(assetId, amount);
|
|
1126
|
+
fill.withAsset({ assetId, inputs, outputs: [{ vout: solverVout, amount }] });
|
|
1127
|
+
}
|
|
1128
|
+
if (hasPayoutOutput) {
|
|
1129
|
+
outputs.push({ role: "solver", script: solverPayout, sats: inputsSum - explicitSats });
|
|
1130
|
+
}
|
|
1131
|
+
return {
|
|
1132
|
+
inputs: [
|
|
1133
|
+
{ owner: null, txid: vtxo.txid.toLowerCase(), vout: vtxo.vout },
|
|
1134
|
+
...solverFund.map((coin) => ({
|
|
1135
|
+
owner: "solver",
|
|
1136
|
+
txid: coin.txid.toLowerCase(),
|
|
1137
|
+
vout: coin.vout
|
|
1138
|
+
})),
|
|
1139
|
+
...sponsorFund.map((coin) => ({
|
|
1140
|
+
owner: "sponsor",
|
|
1141
|
+
txid: coin.txid.toLowerCase(),
|
|
1142
|
+
vout: coin.vout
|
|
1143
|
+
}))
|
|
1144
|
+
],
|
|
1145
|
+
outputs
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
function assertVout(vout, what) {
|
|
1149
|
+
if (typeof vout !== "number" || !Number.isSafeInteger(vout) || vout < 0 || vout > 4294967295) {
|
|
1150
|
+
throw new Error(`${what} must be a non-negative output index`);
|
|
1151
|
+
}
|
|
1152
|
+
return vout;
|
|
1153
|
+
}
|
|
1154
|
+
function toAmount(value, what, unit, min = BigInt(0)) {
|
|
1155
|
+
const max = unit === "sats" ? MAX_SAFE_SATS : U64_MAX;
|
|
1156
|
+
let amount;
|
|
1157
|
+
if (typeof value === "bigint") {
|
|
1158
|
+
if (value >= BigInt(0) && value <= max) amount = value;
|
|
1159
|
+
} else if (typeof value === "number") {
|
|
1160
|
+
if (Number.isSafeInteger(value) && value >= 0) amount = BigInt(value);
|
|
1161
|
+
}
|
|
1162
|
+
if (amount === void 0) {
|
|
1163
|
+
throw new Error(`${what} must be a safe integer amount of ${unit} (0 to ${max})`);
|
|
1164
|
+
}
|
|
1165
|
+
if (amount < min) {
|
|
1166
|
+
throw new Error(`${what} must be a positive amount of ${unit}`);
|
|
1167
|
+
}
|
|
1168
|
+
return amount;
|
|
1169
|
+
}
|
|
1170
|
+
function assertScript(script, what) {
|
|
1171
|
+
if (!(script instanceof Uint8Array) || script.length === 0) {
|
|
1172
|
+
throw new Error(`${what} must be a non-empty output script`);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
function assertAssetId(assetId, what) {
|
|
1176
|
+
if (typeof assetId !== "string") throw new Error(`${what} must be an asset id string`);
|
|
1177
|
+
try {
|
|
1178
|
+
return import_sdk3.asset.AssetId.fromString(assetId).toString();
|
|
1179
|
+
} catch {
|
|
1180
|
+
throw new Error(`${what} is not a valid asset id`);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
function assertAssetEntries(assets, what) {
|
|
1184
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1185
|
+
for (const [i, a] of (assets ?? []).entries()) {
|
|
1186
|
+
const id = assertAssetId(a.assetId, `${what}.assets[${i}].assetId`);
|
|
1187
|
+
if (seen.has(id)) {
|
|
1188
|
+
throw new Error(`${what} declares ${id} twice \u2014 merge the entries instead`);
|
|
1189
|
+
}
|
|
1190
|
+
seen.add(id);
|
|
1191
|
+
toAmount(a.amount, `${what}.assets[${i}].amount`, "asset units");
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
function assertFillCoin(coin, what) {
|
|
1195
|
+
parseHex32(coin.txid, `${what}.txid`);
|
|
1196
|
+
assertVout(coin.vout, `${what}.vout`);
|
|
1197
|
+
toAmount(coin.value, `${what}.value`, "sats", BigInt(1));
|
|
1198
|
+
assertAssetEntries(coin.assets, what);
|
|
1199
|
+
}
|
|
1200
|
+
var import_base2, import_utils, import_sdk3, swapPrograms, OFFER_PACKET_TYPE, FIELDS, EXIT_TYPES, NAMES, readU64, setRatio, OFFER_CONTRACT_LABEL, OFFER_CONTRACT_KIND, derivingClient, NoSpendableDepositError, OfferCovenantMismatchError, ASSET_CARRIER_SATS, amountOfAsset, U64_MAX, MAX_SAFE_SATS;
|
|
680
1201
|
var init_offer = __esm({
|
|
681
1202
|
"src/offer.ts"() {
|
|
682
1203
|
"use strict";
|
|
@@ -686,6 +1207,7 @@ var init_offer = __esm({
|
|
|
686
1207
|
init_swap_want_asset_program();
|
|
687
1208
|
init_swap_want_btc_program();
|
|
688
1209
|
init_coverage();
|
|
1210
|
+
init_rfqProfileParts();
|
|
689
1211
|
init_store();
|
|
690
1212
|
swapPrograms = {
|
|
691
1213
|
wantAsset: import_sdk3.arkade.parseArtifact(swap_want_asset_program_default),
|
|
@@ -738,20 +1260,33 @@ var init_offer = __esm({
|
|
|
738
1260
|
name = "OfferCovenantMismatchError";
|
|
739
1261
|
};
|
|
740
1262
|
ASSET_CARRIER_SATS = BigInt(import_sdk3.ASSET_CARRIER_SATS);
|
|
1263
|
+
amountOfAsset = (assets, assetId) => {
|
|
1264
|
+
let total = BigInt(0);
|
|
1265
|
+
for (const a of assets ?? []) {
|
|
1266
|
+
if (a.assetId === assetId) total += BigInt(a.amount);
|
|
1267
|
+
}
|
|
1268
|
+
return total;
|
|
1269
|
+
};
|
|
1270
|
+
U64_MAX = (BigInt(1) << BigInt(64)) - BigInt(1);
|
|
1271
|
+
MAX_SAFE_SATS = BigInt(Number.MAX_SAFE_INTEGER);
|
|
741
1272
|
}
|
|
742
1273
|
});
|
|
743
1274
|
|
|
744
1275
|
// src/lockupContract.ts
|
|
745
|
-
async function registerLockupContract(contracts, script, address) {
|
|
1276
|
+
async function registerLockupContract(contracts, script, address, options = {}) {
|
|
746
1277
|
try {
|
|
747
|
-
await
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
1278
|
+
await registerContractCoverage(
|
|
1279
|
+
import_base3.hex.encode(script.pkScript),
|
|
1280
|
+
() => contracts.createContract({
|
|
1281
|
+
type: SWAP_LOCKUP_CONTRACT_TYPE,
|
|
1282
|
+
params: import_sdk4.VHTLCV2ContractHandler.serializeParams(script.options),
|
|
1283
|
+
script: import_base3.hex.encode(script.pkScript),
|
|
1284
|
+
address,
|
|
1285
|
+
label: SWAP_LOCKUP_CONTRACT_LABEL,
|
|
1286
|
+
metadata: { genericallySpendable: false, kind: SWAP_LOCKUP_CONTRACT_KIND }
|
|
1287
|
+
}),
|
|
1288
|
+
options
|
|
1289
|
+
);
|
|
755
1290
|
} catch (error) {
|
|
756
1291
|
throw new LockupRegistrationFailed(script, address, error);
|
|
757
1292
|
}
|
|
@@ -766,6 +1301,7 @@ var import_base3, import_sdk4, SWAP_LOCKUP_CONTRACT_TYPE, SWAP_LOCKUP_CONTRACT_L
|
|
|
766
1301
|
var init_lockupContract = __esm({
|
|
767
1302
|
"src/lockupContract.ts"() {
|
|
768
1303
|
"use strict";
|
|
1304
|
+
init_coverage();
|
|
769
1305
|
import_base3 = require("@scure/base");
|
|
770
1306
|
import_sdk4 = require("@arkade-os/sdk");
|
|
771
1307
|
SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
|
|
@@ -1790,14 +2326,14 @@ __export(nostr_exports, {
|
|
|
1790
2326
|
nostrCardFetcher: () => nostrCardFetcher,
|
|
1791
2327
|
nostrRfqTransport: () => nostrRfqTransport
|
|
1792
2328
|
});
|
|
1793
|
-
var
|
|
2329
|
+
var import_solver_discovery7, import_sdk19, import_nostr_tools, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CARD_FETCH_TIMEOUT_MS, newPool, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
|
|
1794
2330
|
var init_nostr = __esm({
|
|
1795
2331
|
"src/nostr.ts"() {
|
|
1796
2332
|
"use strict";
|
|
1797
|
-
|
|
2333
|
+
import_solver_discovery7 = require("@arkade-os/solver-discovery");
|
|
1798
2334
|
init_rfq();
|
|
1799
2335
|
init_closeOnceWebSocket();
|
|
1800
|
-
|
|
2336
|
+
import_sdk19 = require("@arkade-os/sdk");
|
|
1801
2337
|
import_nostr_tools = require("nostr-tools");
|
|
1802
2338
|
RFQ_DIRECTED_KIND = 24859;
|
|
1803
2339
|
DEFAULT_TIMEOUT_MS = 3e4;
|
|
@@ -1825,7 +2361,7 @@ var init_nostr = __esm({
|
|
|
1825
2361
|
return url ? `${url}: ${reason ?? "closed"}` : reason ?? "closed";
|
|
1826
2362
|
});
|
|
1827
2363
|
nostrRfqTransport = (options) => {
|
|
1828
|
-
(0,
|
|
2364
|
+
(0, import_sdk19.assertTimerMs)("timeoutMs", options.timeoutMs);
|
|
1829
2365
|
const relays = options.relays;
|
|
1830
2366
|
const solverPubkey = options.solverPubkey;
|
|
1831
2367
|
const secretKey = options.secretKey ?? (0, import_nostr_tools.generateSecretKey)();
|
|
@@ -1918,7 +2454,7 @@ var init_nostr = __esm({
|
|
|
1918
2454
|
};
|
|
1919
2455
|
isNewer = (event, held) => !held || event.created_at > held.created_at || event.created_at === held.created_at && event.id < held.id;
|
|
1920
2456
|
nostrCardFetcher = (options = {}) => {
|
|
1921
|
-
(0,
|
|
2457
|
+
(0, import_sdk19.assertTimerMs)("timeoutMs", options.timeoutMs);
|
|
1922
2458
|
if (options.timeoutMs === 0) throw new Error("timeoutMs must be positive");
|
|
1923
2459
|
const seen = /* @__PURE__ */ new Map();
|
|
1924
2460
|
return {
|
|
@@ -1939,12 +2475,12 @@ var init_nostr = __esm({
|
|
|
1939
2475
|
timer = setTimeout(resolve, timeoutMs);
|
|
1940
2476
|
subscription = pool.subscribeMany(
|
|
1941
2477
|
relays,
|
|
1942
|
-
{ kinds: [
|
|
2478
|
+
{ kinds: [import_solver_discovery7.SOLVER_CARD_KIND], authors, "#d": [network] },
|
|
1943
2479
|
{
|
|
1944
2480
|
// Relays are untrusted: re-check the filter and the signature, so a stray
|
|
1945
2481
|
// or forged later event cannot shadow the real card.
|
|
1946
2482
|
onevent(event) {
|
|
1947
|
-
if (event.kind !==
|
|
2483
|
+
if (event.kind !== import_solver_discovery7.SOLVER_CARD_KIND || !asked.has(event.pubkey))
|
|
1948
2484
|
return;
|
|
1949
2485
|
if (!(0, import_nostr_tools.verifyEvent)(event)) return;
|
|
1950
2486
|
if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
|
|
@@ -2017,6 +2553,8 @@ __export(advanced_exports, {
|
|
|
2017
2553
|
MaxFeeExceeded: () => MaxFeeExceeded,
|
|
2018
2554
|
MissingCorridorDep: () => MissingCorridorDep,
|
|
2019
2555
|
NotCancellable: () => NotCancellable,
|
|
2556
|
+
OFFER_FILL_OWNERS: () => OFFER_FILL_OWNERS,
|
|
2557
|
+
OFFER_FILL_TEMPLATE: () => OFFER_FILL_TEMPLATE,
|
|
2020
2558
|
OFFER_SWAP_ID_PREFIX: () => OFFER_SWAP_ID_PREFIX,
|
|
2021
2559
|
ONCHAIN_CLAIM_FEE_RATE_SATVB: () => ONCHAIN_CLAIM_FEE_RATE_SATVB,
|
|
2022
2560
|
ONCHAIN_DRIVE: () => ONCHAIN_DRIVE,
|
|
@@ -2043,6 +2581,7 @@ __export(advanced_exports, {
|
|
|
2043
2581
|
bitcoinNetworkOf: () => bitcoinNetworkOf,
|
|
2044
2582
|
btcAssetPart: () => btcAssetPart,
|
|
2045
2583
|
btcOn: () => btcOn,
|
|
2584
|
+
buildOfferFillPlan: () => buildOfferFillPlan,
|
|
2046
2585
|
cancelSwap: () => cancelSwap,
|
|
2047
2586
|
canonicalAssetId: () => canonicalAssetId,
|
|
2048
2587
|
cardMarketOf: () => cardMarketOf,
|
|
@@ -2058,6 +2597,8 @@ __export(advanced_exports, {
|
|
|
2058
2597
|
createSwapDrive: () => createSwapDrive,
|
|
2059
2598
|
decodeBolt11: () => decodeBolt11,
|
|
2060
2599
|
decodeRfqAmount: () => decodeRfqAmount,
|
|
2600
|
+
deepFreeze: () => deepFreeze,
|
|
2601
|
+
digestJointGraph: () => digestJointGraph,
|
|
2061
2602
|
discoveryIndex: () => discoveryIndex,
|
|
2062
2603
|
eligibleMarkets: () => eligibleMarkets,
|
|
2063
2604
|
encodeRfqAmount: () => encodeRfqAmount,
|
|
@@ -2083,6 +2624,7 @@ __export(advanced_exports, {
|
|
|
2083
2624
|
formatAssetId: () => formatAssetId,
|
|
2084
2625
|
fromAtomicDecimal: () => fromAtomicDecimal,
|
|
2085
2626
|
fromRfqAmountSide: () => fromRfqAmountSide,
|
|
2627
|
+
fundingWasNotSubmitted: () => fundingWasNotSubmitted,
|
|
2086
2628
|
fundsFromWallet: () => fundsFromWallet,
|
|
2087
2629
|
instrumentOf: () => instrumentOf,
|
|
2088
2630
|
isAddressable: () => isAddressable,
|
|
@@ -2148,9 +2690,12 @@ __export(advanced_exports, {
|
|
|
2148
2690
|
toDiscoveryLeg: () => toDiscoveryLeg,
|
|
2149
2691
|
toRfqAmountSide: () => toRfqAmountSide,
|
|
2150
2692
|
toSafeNumber: () => toSafeNumber,
|
|
2693
|
+
unsignedPsbtBytes: () => unsignedPsbtBytes,
|
|
2151
2694
|
usableMarkets: () => usableMarkets,
|
|
2152
2695
|
verifiedCarrierSats: () => verifiedCarrierSats,
|
|
2153
2696
|
verifyCrossAssetAmount: () => verifyCrossAssetAmount,
|
|
2697
|
+
verifyJointGraph: () => verifyJointGraph,
|
|
2698
|
+
verifyOfferFillPlan: () => verifyOfferFillPlan,
|
|
2154
2699
|
verifyPair: () => verifyPair,
|
|
2155
2700
|
verifyPlanLegs: () => verifyPlanLegs,
|
|
2156
2701
|
verifyQuoteTtl: () => verifyQuoteTtl,
|
|
@@ -2170,134 +2715,17 @@ __export(advanced_exports, {
|
|
|
2170
2715
|
module.exports = __toCommonJS(advanced_exports);
|
|
2171
2716
|
|
|
2172
2717
|
// src/client/accept.ts
|
|
2173
|
-
var
|
|
2174
|
-
var
|
|
2718
|
+
var import_base9 = require("@scure/base");
|
|
2719
|
+
var import_solver_discovery6 = require("@arkade-os/solver-discovery");
|
|
2720
|
+
var import_sdk13 = require("@arkade-os/sdk");
|
|
2175
2721
|
init_offer();
|
|
2722
|
+
init_coverage();
|
|
2176
2723
|
init_lockupContract();
|
|
2177
2724
|
|
|
2178
2725
|
// src/rfqCorridors.ts
|
|
2179
2726
|
var import_base5 = require("@scure/base");
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
var RfqCorridorRegistry = class {
|
|
2183
|
-
handlers = /* @__PURE__ */ new Map();
|
|
2184
|
-
register(handler) {
|
|
2185
|
-
if (this.handlers.has(handler.kind)) {
|
|
2186
|
-
throw new Error(
|
|
2187
|
-
`RFQ corridor handler for kind '${handler.kind}' is already registered`
|
|
2188
|
-
);
|
|
2189
|
-
}
|
|
2190
|
-
this.handlers.set(handler.kind, handler);
|
|
2191
|
-
}
|
|
2192
|
-
/** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
|
|
2193
|
-
* `kind` union would read as a check already made. */
|
|
2194
|
-
get(kind) {
|
|
2195
|
-
return this.handlers.get(kind);
|
|
2196
|
-
}
|
|
2197
|
-
/** The handler for a kind, or a loud failure naming the registered kinds. */
|
|
2198
|
-
getOrThrow(kind) {
|
|
2199
|
-
const handler = this.get(kind);
|
|
2200
|
-
if (!handler) {
|
|
2201
|
-
throw new Error(
|
|
2202
|
-
`no RFQ corridor handler registered for kind '${kind}'; registered: ${this.registeredKinds().join(", ") || "none"}`
|
|
2203
|
-
);
|
|
2204
|
-
}
|
|
2205
|
-
return handler;
|
|
2206
|
-
}
|
|
2207
|
-
registeredKinds() {
|
|
2208
|
-
return [...this.handlers.keys()];
|
|
2209
|
-
}
|
|
2210
|
-
/** Test seam, mirroring the contract registry's. */
|
|
2211
|
-
unregister(kind) {
|
|
2212
|
-
return this.handlers.delete(kind);
|
|
2213
|
-
}
|
|
2214
|
-
};
|
|
2215
|
-
var rfqCorridorHandlers = new RfqCorridorRegistry();
|
|
2216
|
-
|
|
2217
|
-
// src/rfqProfileParts.ts
|
|
2218
|
-
init_store();
|
|
2219
|
-
var rfqSecretsProfile = (secrets, paymentHash) => {
|
|
2220
|
-
const { signingDescriptor, ...preimage } = swapSecretsToRecord(secrets);
|
|
2221
|
-
return {
|
|
2222
|
-
signer: { signingDescriptor },
|
|
2223
|
-
...paymentHash ? { hashlock: { paymentHash, ...preimage } } : {}
|
|
2224
|
-
};
|
|
2225
|
-
};
|
|
2226
|
-
var parseHex32 = (value, field) => {
|
|
2227
|
-
if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) {
|
|
2228
|
-
throw new Error(`${field} must be 32 bytes of hex, got ${JSON.stringify(value)}`);
|
|
2229
|
-
}
|
|
2230
|
-
return value.toLowerCase();
|
|
2231
|
-
};
|
|
2232
|
-
var parseSigner = (value) => {
|
|
2233
|
-
const signingDescriptor = value?.signingDescriptor;
|
|
2234
|
-
if (typeof signingDescriptor !== "string" || signingDescriptor.length === 0) {
|
|
2235
|
-
throw new Error(
|
|
2236
|
-
`rfq profile.signer carries no signingDescriptor (got ${JSON.stringify(signingDescriptor)})`
|
|
2237
|
-
);
|
|
2238
|
-
}
|
|
2239
|
-
return { signingDescriptor };
|
|
2240
|
-
};
|
|
2241
|
-
var parsePayoutAddress = (value, kind) => {
|
|
2242
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
2243
|
-
throw new Error(
|
|
2244
|
-
`this ${kind} record's claim destination is unusable: expected an Arkade address, got ${JSON.stringify(value)}`
|
|
2245
|
-
);
|
|
2246
|
-
}
|
|
2247
|
-
return value;
|
|
2248
|
-
};
|
|
2249
|
-
var parseHashlock = (value) => {
|
|
2250
|
-
const raw = value ?? {};
|
|
2251
|
-
const hashlock = {
|
|
2252
|
-
paymentHash: parseHex32(raw.paymentHash, "rfq profile.hashlock.paymentHash")
|
|
2253
|
-
};
|
|
2254
|
-
if (raw.preimageHex !== void 0) {
|
|
2255
|
-
hashlock.preimageHex = parseHex32(raw.preimageHex, "rfq profile.hashlock.preimageHex");
|
|
2256
|
-
}
|
|
2257
|
-
if (raw.preimageSaltHex !== void 0) {
|
|
2258
|
-
hashlock.preimageSaltHex = parseHex32(
|
|
2259
|
-
raw.preimageSaltHex,
|
|
2260
|
-
"rfq profile.hashlock.preimageSaltHex"
|
|
2261
|
-
);
|
|
2262
|
-
}
|
|
2263
|
-
return hashlock;
|
|
2264
|
-
};
|
|
2265
|
-
var hydrateHashlock = (profile) => {
|
|
2266
|
-
try {
|
|
2267
|
-
return { paymentHash: parseHashlock(profile.hashlock).paymentHash };
|
|
2268
|
-
} catch (cause) {
|
|
2269
|
-
throw new Error(
|
|
2270
|
-
`rfq record carries no usable hashlock; it cannot verify a preimage: ${String(cause)}`,
|
|
2271
|
-
{ cause }
|
|
2272
|
-
);
|
|
2273
|
-
}
|
|
2274
|
-
};
|
|
2275
|
-
var rfqSignerOf = (record) => {
|
|
2276
|
-
const signer = record.profile.signer;
|
|
2277
|
-
if (signer === void 0) return void 0;
|
|
2278
|
-
return parseSigner(signer);
|
|
2279
|
-
};
|
|
2280
|
-
var rfqClaimSecretOf = (record) => {
|
|
2281
|
-
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
2282
|
-
if (!handler.claimSecret) return void 0;
|
|
2283
|
-
try {
|
|
2284
|
-
const claim = handler.claimSecret(record.profile);
|
|
2285
|
-
return { ...parseSigner(claim), ...parseHashlock(claim) };
|
|
2286
|
-
} catch (cause) {
|
|
2287
|
-
throw new PreimageNotRecoverableError(
|
|
2288
|
-
"malformed-record",
|
|
2289
|
-
`this ${record.kind} record's claim secret is unreadable: ${String(cause)}`,
|
|
2290
|
-
{ cause }
|
|
2291
|
-
);
|
|
2292
|
-
}
|
|
2293
|
-
};
|
|
2294
|
-
var rfqClaimDestinationOf = (record) => {
|
|
2295
|
-
const handler = rfqCorridorHandlers.getOrThrow(record.kind);
|
|
2296
|
-
if (!handler.claimDestination) return void 0;
|
|
2297
|
-
return parsePayoutAddress(handler.claimDestination(record.profile), record.kind);
|
|
2298
|
-
};
|
|
2299
|
-
|
|
2300
|
-
// src/rfqCorridors.ts
|
|
2727
|
+
init_rfqCorridor();
|
|
2728
|
+
init_rfqProfileParts();
|
|
2301
2729
|
init_onchainHtlc();
|
|
2302
2730
|
var LightningSendCorridor = {
|
|
2303
2731
|
kind: "lightning_send",
|
|
@@ -2482,6 +2910,7 @@ rfqCorridorHandlers.register(OnchainSendCorridor);
|
|
|
2482
2910
|
rfqCorridorHandlers.register(OnchainReceiveCorridor);
|
|
2483
2911
|
|
|
2484
2912
|
// src/client/accept.ts
|
|
2913
|
+
init_rfqProfileParts();
|
|
2485
2914
|
init_store();
|
|
2486
2915
|
|
|
2487
2916
|
// src/client/assetId.ts
|
|
@@ -2713,10 +3142,10 @@ var QuoteExpired = class extends Error {
|
|
|
2713
3142
|
name = "QuoteExpired";
|
|
2714
3143
|
};
|
|
2715
3144
|
var MaxFeeExceeded = class extends Error {
|
|
2716
|
-
constructor(quoteId,
|
|
2717
|
-
super(`fee ${fee} of ${
|
|
3145
|
+
constructor(quoteId, asset8, fee, maxFee) {
|
|
3146
|
+
super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
|
|
2718
3147
|
this.quoteId = quoteId;
|
|
2719
|
-
this.asset =
|
|
3148
|
+
this.asset = asset8;
|
|
2720
3149
|
this.fee = fee;
|
|
2721
3150
|
this.maxFee = maxFee;
|
|
2722
3151
|
}
|
|
@@ -2727,11 +3156,11 @@ var MaxFeeExceeded = class extends Error {
|
|
|
2727
3156
|
name = "MaxFeeExceeded";
|
|
2728
3157
|
};
|
|
2729
3158
|
var InsufficientFunds = class extends Error {
|
|
2730
|
-
constructor(
|
|
3159
|
+
constructor(asset8, required, available) {
|
|
2731
3160
|
super(
|
|
2732
|
-
`funding needs ${required} of ${
|
|
3161
|
+
`funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
|
|
2733
3162
|
);
|
|
2734
|
-
this.asset =
|
|
3163
|
+
this.asset = asset8;
|
|
2735
3164
|
this.required = required;
|
|
2736
3165
|
this.available = available;
|
|
2737
3166
|
}
|
|
@@ -2769,9 +3198,9 @@ var NotCancellable = class extends Error {
|
|
|
2769
3198
|
name = "NotCancellable";
|
|
2770
3199
|
};
|
|
2771
3200
|
var InconsistentRoute = class extends Error {
|
|
2772
|
-
constructor(
|
|
2773
|
-
super(`destination ${JSON.stringify(destination)} is not on ${
|
|
2774
|
-
this.asset =
|
|
3201
|
+
constructor(asset8, destination) {
|
|
3202
|
+
super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
|
|
3203
|
+
this.asset = asset8;
|
|
2775
3204
|
this.destination = destination;
|
|
2776
3205
|
}
|
|
2777
3206
|
asset;
|
|
@@ -2824,9 +3253,9 @@ function isSwapError(e, name) {
|
|
|
2824
3253
|
// src/client/aliases.ts
|
|
2825
3254
|
var toDiscoveryLeg = (id) => {
|
|
2826
3255
|
const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
|
|
2827
|
-
const
|
|
3256
|
+
const asset8 = `${assetNamespace}:${assetReference}`;
|
|
2828
3257
|
const isBtc = isBtcAsset(id);
|
|
2829
|
-
if (!isBtc && rail !== "eip155" && (
|
|
3258
|
+
if (!isBtc && rail !== "eip155" && (asset8 === "slip44:0" || asset8 === "slip44:1")) {
|
|
2830
3259
|
const expected = btcOn(rail, reference);
|
|
2831
3260
|
throw new UnsupportedRoute(`${id} is not BTC on ${reference}: BTC there is ${expected}`);
|
|
2832
3261
|
}
|
|
@@ -2835,15 +3264,15 @@ var toDiscoveryLeg = (id) => {
|
|
|
2835
3264
|
if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
|
|
2836
3265
|
return { corridor: "arkade", assetId: assetReference, marketId: id };
|
|
2837
3266
|
}
|
|
2838
|
-
throw new UnsupportedRoute(`the arkade corridor has no ${
|
|
3267
|
+
throw new UnsupportedRoute(`the arkade corridor has no ${asset8}`);
|
|
2839
3268
|
}
|
|
2840
3269
|
if (rail === "bolt11") {
|
|
2841
3270
|
if (isBtc) return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
|
|
2842
|
-
throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${
|
|
3271
|
+
throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset8}`);
|
|
2843
3272
|
}
|
|
2844
3273
|
if (rail === "bitcoin") {
|
|
2845
3274
|
if (isBtc) return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
|
|
2846
|
-
throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${
|
|
3275
|
+
throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset8}`);
|
|
2847
3276
|
}
|
|
2848
3277
|
throw new UnsupportedRoute(`no corridor serves ${id}`);
|
|
2849
3278
|
};
|
|
@@ -2874,20 +3303,543 @@ var canonicalAssetId = (input, table) => {
|
|
|
2874
3303
|
return matches[0].id;
|
|
2875
3304
|
};
|
|
2876
3305
|
|
|
2877
|
-
// src/client/
|
|
3306
|
+
// src/client/assetPayment.ts
|
|
2878
3307
|
var import_sdk9 = require("@arkade-os/sdk");
|
|
2879
|
-
var
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
var
|
|
2886
|
-
|
|
2887
|
-
|
|
3308
|
+
var import_solver_discovery3 = require("@arkade-os/solver-discovery");
|
|
3309
|
+
var DECIMAL = /^(0|[1-9][0-9]*)$/;
|
|
3310
|
+
var MAX_SATS = 2100000000000000n;
|
|
3311
|
+
var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
3312
|
+
var CARRIER_QUOTE_ID_MAX = 128;
|
|
3313
|
+
var CARRIER_TAXI_URL_MAX = 512;
|
|
3314
|
+
var XONLY_HEX = /^[0-9a-f]{64}$/;
|
|
3315
|
+
var MAX_BITCOIN_SATS_DECIMAL = MAX_SATS.toString();
|
|
3316
|
+
var parseSatsField = (value, field) => {
|
|
3317
|
+
if (typeof value !== "string" || !DECIMAL.test(value)) {
|
|
3318
|
+
throw new Error("carrier echo " + field + " must be a canonical decimal string");
|
|
3319
|
+
}
|
|
3320
|
+
if (value.length > MAX_BITCOIN_SATS_DECIMAL.length || value.length === MAX_BITCOIN_SATS_DECIMAL.length && value > MAX_BITCOIN_SATS_DECIMAL) {
|
|
3321
|
+
throw new Error("carrier echo " + field + " exceeds the Bitcoin supply");
|
|
3322
|
+
}
|
|
3323
|
+
return BigInt(value);
|
|
2888
3324
|
};
|
|
2889
|
-
var
|
|
2890
|
-
|
|
3325
|
+
var parseTopLevelCarrierSats = (value) => {
|
|
3326
|
+
if (typeof value === "number") {
|
|
3327
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
3328
|
+
throw new Error("top-level carrier_sats must be a non-negative safe integer");
|
|
3329
|
+
}
|
|
3330
|
+
if (value > Number(MAX_SATS)) {
|
|
3331
|
+
throw new Error("top-level carrier_sats exceeds the Bitcoin supply");
|
|
3332
|
+
}
|
|
3333
|
+
return BigInt(value);
|
|
3334
|
+
}
|
|
3335
|
+
return parseSatsField(value, "top-level carrier_sats");
|
|
3336
|
+
};
|
|
3337
|
+
var parseExpiresAt = (value) => {
|
|
3338
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
|
|
3339
|
+
throw new Error("carrier echo expires_at must be a safe positive unix time");
|
|
3340
|
+
}
|
|
3341
|
+
return value;
|
|
3342
|
+
};
|
|
3343
|
+
function validateReceiverPaidQuoteShape(q) {
|
|
3344
|
+
if (!q || typeof q !== "object") throw new Error("carrier receiver-paid quote is required");
|
|
3345
|
+
if (typeof q.quoteId !== "string" || !q.quoteId.length || q.quoteId.length > CARRIER_QUOTE_ID_MAX) {
|
|
3346
|
+
throw new Error("carrier receiver-paid quoteId must be 1..128 chars");
|
|
3347
|
+
}
|
|
3348
|
+
if (typeof q.receiveAddress !== "string" || !q.receiveAddress.length) {
|
|
3349
|
+
throw new Error("carrier receiver-paid quote needs a receiveAddress");
|
|
3350
|
+
}
|
|
3351
|
+
if (typeof q.senderKey !== "string" || !XONLY_HEX.test(q.senderKey)) {
|
|
3352
|
+
throw new Error("carrier receiver-paid quote senderKey must be lowercase x-only hex");
|
|
3353
|
+
}
|
|
3354
|
+
if (typeof q.assetId !== "string" || !q.assetId.length) {
|
|
3355
|
+
throw new Error("carrier receiver-paid quote needs an assetId");
|
|
3356
|
+
}
|
|
3357
|
+
try {
|
|
3358
|
+
import_sdk9.asset.AssetId.fromString(q.assetId);
|
|
3359
|
+
} catch {
|
|
3360
|
+
throw new Error("carrier receiver-paid quote assetId is not a valid SDK asset id");
|
|
3361
|
+
}
|
|
3362
|
+
const amounts = [
|
|
3363
|
+
["physicalSats", q.physicalSats],
|
|
3364
|
+
["loanSats", q.loanSats]
|
|
3365
|
+
];
|
|
3366
|
+
for (const [name, v] of amounts) {
|
|
3367
|
+
if (typeof v !== "bigint" || v < 0n) {
|
|
3368
|
+
throw new Error(
|
|
3369
|
+
"carrier receiver-paid quote " + name + " must be a non-negative bigint"
|
|
3370
|
+
);
|
|
3371
|
+
}
|
|
3372
|
+
if (v > MAX_SATS) {
|
|
3373
|
+
throw new Error("carrier receiver-paid quote " + name + " exceeds the Bitcoin supply");
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
if (q.physicalSats <= 0n)
|
|
3377
|
+
throw new Error("carrier receiver-paid quote physicalSats must be positive");
|
|
3378
|
+
if (q.loanSats !== q.physicalSats) {
|
|
3379
|
+
throw new Error("carrier receiver-paid quote loanSats must equal physical");
|
|
3380
|
+
}
|
|
3381
|
+
if (!Number.isSafeInteger(q.expiresAt) || q.expiresAt <= 0) {
|
|
3382
|
+
throw new Error("carrier receiver-paid quote expiresAt must be safe positive unix time");
|
|
3383
|
+
}
|
|
3384
|
+
}
|
|
3385
|
+
function encodeCarrierRequest(choice) {
|
|
3386
|
+
if (!asRecord(choice)) throw new Error("carrier request must be an object");
|
|
3387
|
+
if (choice.mode !== "purchase" && choice.mode !== "recycle_receiver") {
|
|
3388
|
+
throw new Error("carrier request mode must be purchase or recycle_receiver");
|
|
3389
|
+
}
|
|
3390
|
+
const allowed = choice.mode === "purchase" ? /* @__PURE__ */ new Set(["mode"]) : /* @__PURE__ */ new Set(["mode", "quoteId", "taxiUrl", "taxiKey"]);
|
|
3391
|
+
for (const key of Object.keys(choice)) {
|
|
3392
|
+
if (!allowed.has(key)) throw new Error("carrier request carries unknown field " + key);
|
|
3393
|
+
}
|
|
3394
|
+
if (choice.mode === "purchase") return { mode: "purchase" };
|
|
3395
|
+
if (typeof choice.quoteId !== "string" || !choice.quoteId.length || choice.quoteId.length > CARRIER_QUOTE_ID_MAX) {
|
|
3396
|
+
throw new Error(`carrier ${choice.mode} quoteId must be 1..128 chars`);
|
|
3397
|
+
}
|
|
3398
|
+
if (typeof choice.taxiUrl !== "string" || !choice.taxiUrl.length || choice.taxiUrl.length > CARRIER_TAXI_URL_MAX) {
|
|
3399
|
+
throw new Error("carrier recycle_receiver taxiUrl must be 1..512 chars");
|
|
3400
|
+
}
|
|
3401
|
+
if (typeof choice.taxiKey !== "string" || !XONLY_HEX.test(choice.taxiKey)) {
|
|
3402
|
+
throw new Error("carrier recycle_receiver taxiKey must be 64 lowercase hex chars");
|
|
3403
|
+
}
|
|
3404
|
+
return {
|
|
3405
|
+
mode: "recycle_receiver",
|
|
3406
|
+
quote_id: choice.quoteId,
|
|
3407
|
+
taxi_url: choice.taxiUrl,
|
|
3408
|
+
taxi_key: choice.taxiKey
|
|
3409
|
+
};
|
|
3410
|
+
}
|
|
3411
|
+
function parseCarrierEcho(raw, expected) {
|
|
3412
|
+
const r = asRecord(raw);
|
|
3413
|
+
if (!r) throw new Error("carrier echo must be an object");
|
|
3414
|
+
if (r.mode !== expected.mode) throw new Error("carrier echo mode differs from the request");
|
|
3415
|
+
const keys = new Set(Object.keys(r));
|
|
3416
|
+
const base = /* @__PURE__ */ new Set([
|
|
3417
|
+
"mode",
|
|
3418
|
+
"physical_sats",
|
|
3419
|
+
"loan_sats",
|
|
3420
|
+
"receipt_sats",
|
|
3421
|
+
"service_fare_sats",
|
|
3422
|
+
"priced_sats",
|
|
3423
|
+
"expires_at"
|
|
3424
|
+
]);
|
|
3425
|
+
const allowed = expected.mode === "recycle_receiver" ? /* @__PURE__ */ new Set([...base, "quote_id", "taxi_url", "taxi_key"]) : base;
|
|
3426
|
+
for (const k of keys) {
|
|
3427
|
+
if (!allowed.has(k)) throw new Error("carrier echo carries unknown field " + k);
|
|
3428
|
+
}
|
|
3429
|
+
for (const k of allowed) {
|
|
3430
|
+
if (!keys.has(k)) throw new Error("carrier echo is missing " + k);
|
|
3431
|
+
}
|
|
3432
|
+
let quoteId;
|
|
3433
|
+
if (expected.mode === "recycle_receiver") {
|
|
3434
|
+
const qid = r.quote_id;
|
|
3435
|
+
if (typeof qid !== "string" || !qid.length || qid.length > CARRIER_QUOTE_ID_MAX) {
|
|
3436
|
+
throw new Error("carrier echo quote_id must be 1..128 chars");
|
|
3437
|
+
}
|
|
3438
|
+
if (qid !== expected.quoteId)
|
|
3439
|
+
throw new Error("carrier echo quote_id differs from the request");
|
|
3440
|
+
quoteId = qid;
|
|
3441
|
+
const taxiUrl = r.taxi_url;
|
|
3442
|
+
if (typeof taxiUrl !== "string" || !taxiUrl.length || taxiUrl.length > CARRIER_TAXI_URL_MAX) {
|
|
3443
|
+
throw new Error("carrier echo taxi_url must be 1..512 chars");
|
|
3444
|
+
}
|
|
3445
|
+
if (taxiUrl !== expected.taxiUrl)
|
|
3446
|
+
throw new Error("carrier echo taxi_url differs from the request");
|
|
3447
|
+
const taxiKey = r.taxi_key;
|
|
3448
|
+
if (typeof taxiKey !== "string" || !XONLY_HEX.test(taxiKey)) {
|
|
3449
|
+
throw new Error("carrier echo taxi_key must be 64 lowercase hex chars");
|
|
3450
|
+
}
|
|
3451
|
+
if (taxiKey !== expected.taxiKey)
|
|
3452
|
+
throw new Error("carrier echo taxi_key differs from the request");
|
|
3453
|
+
}
|
|
3454
|
+
const physical = parseSatsField(r.physical_sats, "physical_sats");
|
|
3455
|
+
const loan = parseSatsField(r.loan_sats, "loan_sats");
|
|
3456
|
+
const receipt = parseSatsField(r.receipt_sats, "receipt_sats");
|
|
3457
|
+
const serviceFare = parseSatsField(r.service_fare_sats, "service_fare_sats");
|
|
3458
|
+
const priced = parseSatsField(r.priced_sats, "priced_sats");
|
|
3459
|
+
const expiresAt = parseExpiresAt(r.expires_at);
|
|
3460
|
+
if (physical <= 0n) throw new Error("carrier echo physical_sats must be positive");
|
|
3461
|
+
if (expected.mode === "purchase") {
|
|
3462
|
+
if (loan !== 0n || receipt !== 0n || serviceFare !== 0n) {
|
|
3463
|
+
throw new Error("carrier purchase echo must carry zero loan/receipt/fare");
|
|
3464
|
+
}
|
|
3465
|
+
if (priced !== physical) throw new Error("carrier purchase priced must equal physical");
|
|
3466
|
+
} else {
|
|
3467
|
+
if (loan !== physical) {
|
|
3468
|
+
throw new Error("carrier receiver-paid echo loan must equal physical");
|
|
3469
|
+
}
|
|
3470
|
+
if (receipt !== 0n) {
|
|
3471
|
+
throw new Error("carrier receiver-paid echo must carry a zero receipt");
|
|
3472
|
+
}
|
|
3473
|
+
if (serviceFare !== 0n) {
|
|
3474
|
+
throw new Error("carrier receiver-paid echo must carry a zero service fare");
|
|
3475
|
+
}
|
|
3476
|
+
if (priced !== 0n) {
|
|
3477
|
+
throw new Error("carrier receiver-paid echo must carry a zero priced_sats");
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
return {
|
|
3481
|
+
mode: expected.mode,
|
|
3482
|
+
physicalSats: physical,
|
|
3483
|
+
loanSats: loan,
|
|
3484
|
+
receiptSats: receipt,
|
|
3485
|
+
serviceFareSats: serviceFare,
|
|
3486
|
+
pricedSats: priced,
|
|
3487
|
+
expiresAt,
|
|
3488
|
+
...quoteId !== void 0 ? { quoteId, taxiUrl: r.taxi_url, taxiKey: r.taxi_key } : {}
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
function assertReceiverPaidEchoMatchesExpected(echo, expected) {
|
|
3492
|
+
if (echo.mode !== "recycle_receiver" || echo.quoteId !== expected.quoteId) {
|
|
3493
|
+
throw new Error("carrier echo quote differs from the expected descriptor");
|
|
3494
|
+
}
|
|
3495
|
+
if (echo.physicalSats !== expected.physicalSats || echo.loanSats !== expected.loanSats || echo.receiptSats !== 0n || echo.serviceFareSats !== 0n || echo.pricedSats !== 0n) {
|
|
3496
|
+
throw new Error("carrier echo amounts differ from the expected descriptor");
|
|
3497
|
+
}
|
|
3498
|
+
if (echo.expiresAt > expected.expiresAt) {
|
|
3499
|
+
throw new Error("carrier echo must not extend the expected expiry");
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
var captureAssetPayment = (input) => {
|
|
3503
|
+
if (input === void 0) return void 0;
|
|
3504
|
+
const receiveAddress = input.receiveAddress;
|
|
3505
|
+
const carrier = input.carrier;
|
|
3506
|
+
if (receiveAddress !== void 0 && (typeof receiveAddress !== "string" || receiveAddress.length === 0))
|
|
3507
|
+
throw new Error("receiveAddress must be an Arkade address");
|
|
3508
|
+
if (carrier === void 0) return { receiveAddress };
|
|
3509
|
+
if (carrier.mode === "purchase") return { receiveAddress, carrier: { mode: "purchase" } };
|
|
3510
|
+
if (carrier.mode !== "recycleReceiver")
|
|
3511
|
+
throw new Error("carrier request mode must be purchase or recycleReceiver");
|
|
3512
|
+
const quote = { ...carrier.quote };
|
|
3513
|
+
validateReceiverPaidQuoteShape(quote);
|
|
3514
|
+
const taxi = { ...carrier.taxi };
|
|
3515
|
+
encodeCarrierRequest({
|
|
3516
|
+
mode: "recycle_receiver",
|
|
3517
|
+
quoteId: quote.quoteId,
|
|
3518
|
+
taxiUrl: taxi.url,
|
|
3519
|
+
taxiKey: taxi.operatorKey
|
|
3520
|
+
});
|
|
3521
|
+
if (receiveAddress !== void 0 && receiveAddress !== quote.receiveAddress)
|
|
3522
|
+
throw new Error("receiveAddress must match the carrier quote receiveAddress");
|
|
3523
|
+
const inputExpiryFloor = carrier.inputExpiryFloor === void 0 ? void 0 : { ...carrier.inputExpiryFloor };
|
|
3524
|
+
if (inputExpiryFloor === void 0 || inputExpiryFloor.kind !== "time" && inputExpiryFloor.kind !== "height" || typeof inputExpiryFloor.value !== "bigint" || inputExpiryFloor.value <= 0n)
|
|
3525
|
+
throw new Error("invalid carrier inputExpiryFloor");
|
|
3526
|
+
return {
|
|
3527
|
+
receiveAddress: quote.receiveAddress,
|
|
3528
|
+
carrier: {
|
|
3529
|
+
mode: "recycleReceiver",
|
|
3530
|
+
quote,
|
|
3531
|
+
taxi,
|
|
3532
|
+
inputExpiryFloor
|
|
3533
|
+
}
|
|
3534
|
+
};
|
|
3535
|
+
};
|
|
3536
|
+
var recordAssetPayment = (terms) => {
|
|
3537
|
+
const { carrier, inputExpiryFloor, ...rest } = terms;
|
|
3538
|
+
return {
|
|
3539
|
+
...rest,
|
|
3540
|
+
...carrier === void 0 ? {} : {
|
|
3541
|
+
carrier: {
|
|
3542
|
+
...carrier,
|
|
3543
|
+
physicalSats: carrier.physicalSats.toString(),
|
|
3544
|
+
loanSats: carrier.loanSats.toString(),
|
|
3545
|
+
receiptSats: carrier.receiptSats.toString(),
|
|
3546
|
+
serviceFareSats: carrier.serviceFareSats.toString(),
|
|
3547
|
+
pricedSats: carrier.pricedSats.toString()
|
|
3548
|
+
}
|
|
3549
|
+
},
|
|
3550
|
+
...inputExpiryFloor === void 0 ? {} : {
|
|
3551
|
+
inputExpiryFloor: {
|
|
3552
|
+
kind: inputExpiryFloor.kind,
|
|
3553
|
+
value: inputExpiryFloor.value.toString()
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
};
|
|
3557
|
+
};
|
|
3558
|
+
var storedFundingBounds = (stored, quoteExpiry) => {
|
|
3559
|
+
if (stored === void 0) return {};
|
|
3560
|
+
if (!Number.isSafeInteger(stored.validUntil) || stored.validUntil <= 0 || stored.validUntil > quoteExpiry)
|
|
3561
|
+
throw new Error("invalid stored asset payment funding deadline");
|
|
3562
|
+
const floor = stored.inputExpiryFloor;
|
|
3563
|
+
if (stored.carrier?.mode === "recycle_receiver" && floor === void 0)
|
|
3564
|
+
throw new Error("stored receiver carrier has no inputExpiryFloor");
|
|
3565
|
+
if (floor !== void 0 && (floor.kind !== "time" && floor.kind !== "height" || typeof floor.value !== "string" || !/^(0|[1-9][0-9]*)$/.test(floor.value) || floor.value === "0"))
|
|
3566
|
+
throw new Error("invalid stored asset payment inputExpiryFloor");
|
|
3567
|
+
return {
|
|
3568
|
+
validUntil: stored.validUntil,
|
|
3569
|
+
...floor === void 0 ? {} : { inputExpiryFloor: { kind: floor.kind, value: BigInt(floor.value) } }
|
|
3570
|
+
};
|
|
3571
|
+
};
|
|
3572
|
+
var assetPaymentFacts = (terms) => {
|
|
3573
|
+
if (terms === void 0) return void 0;
|
|
3574
|
+
const { validUntil, ...facts } = terms;
|
|
3575
|
+
return (0, import_solver_discovery3.stableStringify)(facts);
|
|
3576
|
+
};
|
|
3577
|
+
var assetPaymentOf = (stored, quoteExpiry) => {
|
|
3578
|
+
const bounds = storedFundingBounds(stored, quoteExpiry);
|
|
3579
|
+
const { carrier, inputExpiryFloor, ...rest } = stored;
|
|
3580
|
+
return {
|
|
3581
|
+
...rest,
|
|
3582
|
+
...bounds.inputExpiryFloor === void 0 ? {} : { inputExpiryFloor: bounds.inputExpiryFloor },
|
|
3583
|
+
...carrier === void 0 ? {} : {
|
|
3584
|
+
carrier: {
|
|
3585
|
+
...carrier,
|
|
3586
|
+
physicalSats: parseSatsField(carrier.physicalSats, "physicalSats"),
|
|
3587
|
+
loanSats: parseSatsField(carrier.loanSats, "loanSats"),
|
|
3588
|
+
receiptSats: parseSatsField(carrier.receiptSats, "receiptSats"),
|
|
3589
|
+
serviceFareSats: parseSatsField(carrier.serviceFareSats, "serviceFareSats"),
|
|
3590
|
+
pricedSats: parseSatsField(carrier.pricedSats, "pricedSats")
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
};
|
|
3594
|
+
};
|
|
3595
|
+
|
|
3596
|
+
// src/client/fundingNotSubmitted.ts
|
|
3597
|
+
var import_sdk10 = require("@arkade-os/sdk");
|
|
3598
|
+
var import_base8 = require("@scure/base");
|
|
3599
|
+
init_coverage();
|
|
3600
|
+
init_repository();
|
|
3601
|
+
|
|
3602
|
+
// src/client/amount.ts
|
|
3603
|
+
var import_solver_discovery4 = require("@arkade-os/solver-discovery");
|
|
3604
|
+
var AmountFormatError = class extends Error {
|
|
3605
|
+
constructor(reason, message) {
|
|
3606
|
+
super(message);
|
|
3607
|
+
this.reason = reason;
|
|
3608
|
+
}
|
|
3609
|
+
reason;
|
|
3610
|
+
name = "AmountFormatError";
|
|
3611
|
+
};
|
|
3612
|
+
var SCALED_DECIMAL = /^([0-9]+)(?:\.([0-9]+))?$/;
|
|
3613
|
+
var ATOMIC_CEILING = 10n ** 30n;
|
|
3614
|
+
var MAX_SIGNIFICANT_DIGITS = 64;
|
|
3615
|
+
var assertDecimals = (decimals) => {
|
|
3616
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > import_solver_discovery4.MAX_ASSET_DECIMALS) {
|
|
3617
|
+
throw new AmountFormatError(
|
|
3618
|
+
"invalid_decimals",
|
|
3619
|
+
`decimals must be an integer in [0, ${import_solver_discovery4.MAX_ASSET_DECIMALS}], got ${decimals}`
|
|
3620
|
+
);
|
|
3621
|
+
}
|
|
3622
|
+
};
|
|
3623
|
+
var assertRepresentable = (value, what) => {
|
|
3624
|
+
if (value >= ATOMIC_CEILING) {
|
|
3625
|
+
throw new AmountFormatError(
|
|
3626
|
+
"too_large",
|
|
3627
|
+
`${what} does not fit the canonical 30-digit encoding`
|
|
3628
|
+
);
|
|
3629
|
+
}
|
|
3630
|
+
};
|
|
3631
|
+
var Amount = {
|
|
3632
|
+
/**
|
|
3633
|
+
* A human decimal into atomic units.
|
|
3634
|
+
*
|
|
3635
|
+
* `string` only, no exponent: a `number` makes `100000` ambiguous between sats and BTC, and the
|
|
3636
|
+
* ambiguity resolves only after funding. Refuses rather than rounds input finer than the asset
|
|
3637
|
+
* (a truncated amount is a swap for the wrong size), and refuses results that would not survive
|
|
3638
|
+
* the record boundary.
|
|
3639
|
+
*/
|
|
3640
|
+
parse(display, asset8) {
|
|
3641
|
+
assertDecimals(asset8.decimals);
|
|
3642
|
+
const parts = SCALED_DECIMAL.exec(display);
|
|
3643
|
+
if (!parts) {
|
|
3644
|
+
throw new AmountFormatError(
|
|
3645
|
+
"not_decimal",
|
|
3646
|
+
`not an unsigned decimal amount: ${JSON.stringify(display)} (write 0.5, not .5; no sign, exponent, separator or space)`
|
|
3647
|
+
);
|
|
3648
|
+
}
|
|
3649
|
+
const [, whole, fraction = ""] = parts;
|
|
3650
|
+
if (fraction.length > asset8.decimals) {
|
|
3651
|
+
throw new AmountFormatError(
|
|
3652
|
+
"too_precise",
|
|
3653
|
+
`${display} has more precision than ${asset8.decimals} decimals allow`
|
|
3654
|
+
);
|
|
3655
|
+
}
|
|
3656
|
+
if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
|
|
3657
|
+
throw new AmountFormatError("too_large", `${display} has too many digits`);
|
|
3658
|
+
}
|
|
3659
|
+
const value = (0, import_solver_discovery4.toAtomic)(display, asset8.decimals);
|
|
3660
|
+
assertRepresentable(value, `${display} at ${asset8.decimals} decimals`);
|
|
3661
|
+
return value;
|
|
3662
|
+
},
|
|
3663
|
+
/** Atomic units into a human decimal, trailing zeros trimmed. Refuses a negative: every amount
|
|
3664
|
+
* here is an obligation, so a negative one is an upstream defect. */
|
|
3665
|
+
format(value, asset8) {
|
|
3666
|
+
assertDecimals(asset8.decimals);
|
|
3667
|
+
if (value < 0n) {
|
|
3668
|
+
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
3669
|
+
}
|
|
3670
|
+
assertRepresentable(value, `${value}`);
|
|
3671
|
+
return (0, import_solver_discovery4.fromAtomic)(value, asset8.decimals);
|
|
3672
|
+
}
|
|
3673
|
+
};
|
|
3674
|
+
var toAtomicDecimal = (value) => {
|
|
3675
|
+
if (value < 0n) {
|
|
3676
|
+
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
3677
|
+
}
|
|
3678
|
+
assertRepresentable(value, `${value}`);
|
|
3679
|
+
return value.toString();
|
|
3680
|
+
};
|
|
3681
|
+
var fromAtomicDecimal = (text) => {
|
|
3682
|
+
if (!(0, import_solver_discovery4.isAmount)(text)) {
|
|
3683
|
+
throw new AmountFormatError(
|
|
3684
|
+
"not_canonical",
|
|
3685
|
+
`not a canonical atomic amount: ${JSON.stringify(text)}`
|
|
3686
|
+
);
|
|
3687
|
+
}
|
|
3688
|
+
return BigInt(text);
|
|
3689
|
+
};
|
|
3690
|
+
var isAtomicDecimal = (value) => typeof value === "string" && import_solver_discovery4.AMOUNT_PATTERN.test(value);
|
|
3691
|
+
|
|
3692
|
+
// src/client/record.ts
|
|
3693
|
+
var assetSwapIdOf = (family, quoteId) => `${family}:${quoteId}`;
|
|
3694
|
+
var OFFER_SWAP_ID_PREFIX = "offer:";
|
|
3695
|
+
var RFQ_SWAP_ID_PREFIX = "rfq:";
|
|
3696
|
+
var familyOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? "offer" : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? "rfq" : void 0;
|
|
3697
|
+
var quoteIdOfSwapId = (swapId) => {
|
|
3698
|
+
const family = familyOfSwapId(swapId);
|
|
3699
|
+
return family === void 0 ? swapId : swapId.slice(`${family}:`.length);
|
|
3700
|
+
};
|
|
3701
|
+
var recordEndpoint = (endpoint2) => ({
|
|
3702
|
+
corridor: endpoint2.corridor,
|
|
3703
|
+
asset: endpoint2.asset,
|
|
3704
|
+
instrument: recordInstrument(endpoint2.instrument)
|
|
3705
|
+
});
|
|
3706
|
+
var recordInstrument = (instrument) => {
|
|
3707
|
+
switch (instrument.kind) {
|
|
3708
|
+
case "wallet":
|
|
3709
|
+
return { kind: "wallet" };
|
|
3710
|
+
case "address":
|
|
3711
|
+
return { kind: "address", address: instrument.address };
|
|
3712
|
+
case "invoice":
|
|
3713
|
+
return {
|
|
3714
|
+
kind: "invoice",
|
|
3715
|
+
bolt11: instrument.bolt11,
|
|
3716
|
+
paymentHash: instrument.paymentHash,
|
|
3717
|
+
...instrument.amount === void 0 ? {} : { amount: toAtomicDecimal(instrument.amount) },
|
|
3718
|
+
expiresAt: instrument.expiresAt
|
|
3719
|
+
};
|
|
3720
|
+
}
|
|
3721
|
+
};
|
|
3722
|
+
var instrumentOf = (instrument) => {
|
|
3723
|
+
switch (instrument.kind) {
|
|
3724
|
+
case "wallet":
|
|
3725
|
+
return { kind: "wallet" };
|
|
3726
|
+
case "address":
|
|
3727
|
+
return { kind: "address", address: instrument.address };
|
|
3728
|
+
case "invoice":
|
|
3729
|
+
return {
|
|
3730
|
+
kind: "invoice",
|
|
3731
|
+
bolt11: instrument.bolt11,
|
|
3732
|
+
paymentHash: instrument.paymentHash,
|
|
3733
|
+
...instrument.amount === void 0 ? {} : { amount: fromAtomicDecimal(instrument.amount) },
|
|
3734
|
+
expiresAt: instrument.expiresAt
|
|
3735
|
+
};
|
|
3736
|
+
}
|
|
3737
|
+
};
|
|
3738
|
+
var recordArtifact = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
3739
|
+
kind: "deposit",
|
|
3740
|
+
corridor: artifact.corridor,
|
|
3741
|
+
address: artifact.address,
|
|
3742
|
+
asset: artifact.asset,
|
|
3743
|
+
amount: toAtomicDecimal(artifact.amount),
|
|
3744
|
+
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
3745
|
+
};
|
|
3746
|
+
var artifactOf = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
3747
|
+
kind: "deposit",
|
|
3748
|
+
corridor: artifact.corridor,
|
|
3749
|
+
address: artifact.address,
|
|
3750
|
+
asset: artifact.asset,
|
|
3751
|
+
amount: fromAtomicDecimal(artifact.amount),
|
|
3752
|
+
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
3753
|
+
};
|
|
3754
|
+
var recordLeg = (leg) => ({
|
|
3755
|
+
asset: leg.asset,
|
|
3756
|
+
amount: toAtomicDecimal(leg.amount)
|
|
3757
|
+
});
|
|
3758
|
+
var legOf = (leg) => ({
|
|
3759
|
+
asset: leg.asset,
|
|
3760
|
+
amount: fromAtomicDecimal(leg.amount)
|
|
3761
|
+
});
|
|
3762
|
+
var swapOf = (record, outcome) => ({
|
|
3763
|
+
id: assetSwapIdOf(record.family, record.id),
|
|
3764
|
+
...record.assetPayment === void 0 ? {} : { assetPayment: assetPaymentOf(record.assetPayment, record.expiresAt) },
|
|
3765
|
+
family: record.family,
|
|
3766
|
+
outcome,
|
|
3767
|
+
route: {
|
|
3768
|
+
give: {
|
|
3769
|
+
corridor: record.route.give.corridor,
|
|
3770
|
+
asset: record.route.give.asset,
|
|
3771
|
+
instrument: instrumentOf(record.route.give.instrument)
|
|
3772
|
+
},
|
|
3773
|
+
take: {
|
|
3774
|
+
corridor: record.route.take.corridor,
|
|
3775
|
+
asset: record.route.take.asset,
|
|
3776
|
+
instrument: instrumentOf(record.route.take.instrument)
|
|
3777
|
+
}
|
|
3778
|
+
},
|
|
3779
|
+
give: legOf(record.give),
|
|
3780
|
+
take: legOf(record.take),
|
|
3781
|
+
fee: legOf(record.fee),
|
|
3782
|
+
market: record.market,
|
|
3783
|
+
...record.solver === void 0 ? {} : { solver: record.solver },
|
|
3784
|
+
...record.family === "rfq" ? { lock: record.lock, refundLocktime: record.refundLocktime } : {},
|
|
3785
|
+
...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
|
|
3786
|
+
expiresAt: record.expiresAt,
|
|
3787
|
+
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
3788
|
+
...record.failure === void 0 ? {} : { failure: record.failure },
|
|
3789
|
+
...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason },
|
|
3790
|
+
createdAt: record.createdAt,
|
|
3791
|
+
updatedAt: record.updatedAt
|
|
3792
|
+
});
|
|
3793
|
+
var fundsFromWallet = (route) => route.give.instrument.kind === "wallet";
|
|
3794
|
+
var fundingWasNotSubmitted = (record) => {
|
|
3795
|
+
const proof = record.fundingNotSubmitted;
|
|
3796
|
+
return proof?.reason === "send_deadline" && Number.isSafeInteger(proof.validUntil) && proof.validUntil > 0 && Number.isSafeInteger(record.expiresAt) && proof.validUntil <= record.expiresAt && record.fundingTxid === void 0 && record.route?.give?.instrument?.kind === "wallet" && (record.family === "offer" ? record.status === "cancelled" : record.state === "failed");
|
|
3797
|
+
};
|
|
3798
|
+
|
|
3799
|
+
// src/client/fundingNotSubmitted.ts
|
|
3800
|
+
var retireUnsubmittedFunding = async (wallet, repository, record, contracts) => {
|
|
3801
|
+
if (!fundingWasNotSubmitted(record)) return;
|
|
3802
|
+
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
3803
|
+
try {
|
|
3804
|
+
await retireOfferContract(
|
|
3805
|
+
contracts ?? await wallet.getContractManager(),
|
|
3806
|
+
async () => {
|
|
3807
|
+
const records = await collectSwapRecords(repository);
|
|
3808
|
+
const native = records.map((row) => ({
|
|
3809
|
+
id: row.id,
|
|
3810
|
+
swapPkScript: row.family === "offer" ? row.swapPkScript : row.lockupPkScript,
|
|
3811
|
+
createdAt: row.createdAt * 1e3,
|
|
3812
|
+
status: row.family === "offer" ? row.status : fundingWasNotSubmitted(row) ? "cancelled" : row.state === "settled" || row.state === "refunded" ? "fulfilled" : "pending"
|
|
3813
|
+
}));
|
|
3814
|
+
const legacy = (await collectRfqSwaps(repository)).map((row) => ({
|
|
3815
|
+
swapPkScript: import_base8.hex.encode(import_sdk10.ArkAddress.decode(row.lockupAddress).pkScript),
|
|
3816
|
+
createdAt: row.createdAt * 1e3,
|
|
3817
|
+
status: row.state === "settled" || row.state === "refunded" ? "fulfilled" : "pending"
|
|
3818
|
+
}));
|
|
3819
|
+
return [...native, ...legacy];
|
|
3820
|
+
},
|
|
3821
|
+
script,
|
|
3822
|
+
{ scope: wallet }
|
|
3823
|
+
);
|
|
3824
|
+
} catch (error) {
|
|
3825
|
+
console.warn(`[swap] could not retire unsent funding for ${record.id}`, error);
|
|
3826
|
+
}
|
|
3827
|
+
};
|
|
3828
|
+
|
|
3829
|
+
// src/client/corridors/lightning.ts
|
|
3830
|
+
var import_sdk11 = require("@arkade-os/sdk");
|
|
3831
|
+
var INVOICE_HRPS = [
|
|
3832
|
+
["lnbcrt", ["regtest"]],
|
|
3833
|
+
["lntbs", ["signet", "mutinynet"]],
|
|
3834
|
+
["lnbc", ["bitcoin"]],
|
|
3835
|
+
["lntb", ["testnet"]]
|
|
3836
|
+
];
|
|
3837
|
+
var networksOfInvoiceHrp = (raw) => {
|
|
3838
|
+
const lower = raw.toLowerCase();
|
|
3839
|
+
return INVOICE_HRPS.find(([hrp]) => lower.startsWith(hrp))?.[1];
|
|
3840
|
+
};
|
|
3841
|
+
var PAYMENT_HASH = /^[0-9a-f]{64}$/;
|
|
3842
|
+
var LIGHTNING_DRIVE = {
|
|
2891
3843
|
give: {
|
|
2892
3844
|
lockups: [{ covenant: "arkade_lockup", owner: "solver", deadline: "refund_locktime" }],
|
|
2893
3845
|
actions: ["claimLockup"],
|
|
@@ -2905,7 +3857,7 @@ var lightningCorridor = Object.assign(
|
|
|
2905
3857
|
deps,
|
|
2906
3858
|
drive: LIGHTNING_DRIVE,
|
|
2907
3859
|
matches(raw) {
|
|
2908
|
-
const invoice = (0,
|
|
3860
|
+
const invoice = (0, import_sdk11.invoiceTarget)(raw);
|
|
2909
3861
|
if (invoice === void 0) return void 0;
|
|
2910
3862
|
const networks2 = networksOfInvoiceHrp(invoice);
|
|
2911
3863
|
if (networks2 === void 0) {
|
|
@@ -2951,11 +3903,11 @@ var lightningCorridor = Object.assign(
|
|
|
2951
3903
|
};
|
|
2952
3904
|
}
|
|
2953
3905
|
}),
|
|
2954
|
-
{ target:
|
|
3906
|
+
{ target: import_sdk11.invoiceTarget }
|
|
2955
3907
|
);
|
|
2956
3908
|
|
|
2957
3909
|
// src/client/corridors/onchain.ts
|
|
2958
|
-
var
|
|
3910
|
+
var import_sdk12 = require("@arkade-os/sdk");
|
|
2959
3911
|
var btc2 = __toESM(require("@scure/btc-signer"), 1);
|
|
2960
3912
|
init_onchainHtlc();
|
|
2961
3913
|
init_rfq();
|
|
@@ -2985,14 +3937,14 @@ var onchainCorridor = Object.assign(
|
|
|
2985
3937
|
deps,
|
|
2986
3938
|
drive: ONCHAIN_DRIVE,
|
|
2987
3939
|
matches(raw) {
|
|
2988
|
-
const target = (0,
|
|
3940
|
+
const target = (0, import_sdk12.btcTarget)(raw);
|
|
2989
3941
|
if (target === void 0) return void 0;
|
|
2990
3942
|
try {
|
|
2991
3943
|
btc2.Address(L1_NETWORKS[l1]).decode(target);
|
|
2992
3944
|
} catch {
|
|
2993
3945
|
return { refused: `this is not a ${l1} address` };
|
|
2994
3946
|
}
|
|
2995
|
-
const amount =
|
|
3947
|
+
const amount = import_sdk12.BIP21.amountSats(raw);
|
|
2996
3948
|
return {
|
|
2997
3949
|
claimed: {
|
|
2998
3950
|
kind: "address",
|
|
@@ -3003,7 +3955,7 @@ var onchainCorridor = Object.assign(
|
|
|
3003
3955
|
}
|
|
3004
3956
|
};
|
|
3005
3957
|
},
|
|
3006
|
-
{ target:
|
|
3958
|
+
{ target: import_sdk12.btcTarget }
|
|
3007
3959
|
);
|
|
3008
3960
|
|
|
3009
3961
|
// src/client/outcome.ts
|
|
@@ -3060,6 +4012,8 @@ var OFFER_OUTCOME = {
|
|
|
3060
4012
|
};
|
|
3061
4013
|
var offerOutcome = (status) => OFFER_OUTCOME[status];
|
|
3062
4014
|
var recordOutcome = (record) => {
|
|
4015
|
+
if (record.route !== void 0 && fundingWasNotSubmitted(record))
|
|
4016
|
+
return "cancelled";
|
|
3063
4017
|
if (record.fundingTxid === void 0) return "accepted";
|
|
3064
4018
|
if (record.family === "rfq") return "funding";
|
|
3065
4019
|
return record.status === void 0 ? "funding" : offerOutcome(record.status);
|
|
@@ -3083,98 +4037,8 @@ var ACTIVITY_TOKEN = {
|
|
|
3083
4037
|
failed: "failed"
|
|
3084
4038
|
};
|
|
3085
4039
|
|
|
3086
|
-
// src/client/amount.ts
|
|
3087
|
-
var import_solver_discovery3 = require("@arkade-os/solver-discovery");
|
|
3088
|
-
var AmountFormatError = class extends Error {
|
|
3089
|
-
constructor(reason, message) {
|
|
3090
|
-
super(message);
|
|
3091
|
-
this.reason = reason;
|
|
3092
|
-
}
|
|
3093
|
-
reason;
|
|
3094
|
-
name = "AmountFormatError";
|
|
3095
|
-
};
|
|
3096
|
-
var SCALED_DECIMAL = /^([0-9]+)(?:\.([0-9]+))?$/;
|
|
3097
|
-
var ATOMIC_CEILING = 10n ** 30n;
|
|
3098
|
-
var MAX_SIGNIFICANT_DIGITS = 64;
|
|
3099
|
-
var assertDecimals = (decimals) => {
|
|
3100
|
-
if (!Number.isInteger(decimals) || decimals < 0 || decimals > import_solver_discovery3.MAX_ASSET_DECIMALS) {
|
|
3101
|
-
throw new AmountFormatError(
|
|
3102
|
-
"invalid_decimals",
|
|
3103
|
-
`decimals must be an integer in [0, ${import_solver_discovery3.MAX_ASSET_DECIMALS}], got ${decimals}`
|
|
3104
|
-
);
|
|
3105
|
-
}
|
|
3106
|
-
};
|
|
3107
|
-
var assertRepresentable = (value, what) => {
|
|
3108
|
-
if (value >= ATOMIC_CEILING) {
|
|
3109
|
-
throw new AmountFormatError(
|
|
3110
|
-
"too_large",
|
|
3111
|
-
`${what} does not fit the canonical 30-digit encoding`
|
|
3112
|
-
);
|
|
3113
|
-
}
|
|
3114
|
-
};
|
|
3115
|
-
var Amount = {
|
|
3116
|
-
/**
|
|
3117
|
-
* A human decimal into atomic units.
|
|
3118
|
-
*
|
|
3119
|
-
* `string` only, no exponent: a `number` makes `100000` ambiguous between sats and BTC, and the
|
|
3120
|
-
* ambiguity resolves only after funding. Refuses rather than rounds input finer than the asset
|
|
3121
|
-
* (a truncated amount is a swap for the wrong size), and refuses results that would not survive
|
|
3122
|
-
* the record boundary.
|
|
3123
|
-
*/
|
|
3124
|
-
parse(display, asset7) {
|
|
3125
|
-
assertDecimals(asset7.decimals);
|
|
3126
|
-
const parts = SCALED_DECIMAL.exec(display);
|
|
3127
|
-
if (!parts) {
|
|
3128
|
-
throw new AmountFormatError(
|
|
3129
|
-
"not_decimal",
|
|
3130
|
-
`not an unsigned decimal amount: ${JSON.stringify(display)} (write 0.5, not .5; no sign, exponent, separator or space)`
|
|
3131
|
-
);
|
|
3132
|
-
}
|
|
3133
|
-
const [, whole, fraction = ""] = parts;
|
|
3134
|
-
if (fraction.length > asset7.decimals) {
|
|
3135
|
-
throw new AmountFormatError(
|
|
3136
|
-
"too_precise",
|
|
3137
|
-
`${display} has more precision than ${asset7.decimals} decimals allow`
|
|
3138
|
-
);
|
|
3139
|
-
}
|
|
3140
|
-
if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
|
|
3141
|
-
throw new AmountFormatError("too_large", `${display} has too many digits`);
|
|
3142
|
-
}
|
|
3143
|
-
const value = (0, import_solver_discovery3.toAtomic)(display, asset7.decimals);
|
|
3144
|
-
assertRepresentable(value, `${display} at ${asset7.decimals} decimals`);
|
|
3145
|
-
return value;
|
|
3146
|
-
},
|
|
3147
|
-
/** Atomic units into a human decimal, trailing zeros trimmed. Refuses a negative: every amount
|
|
3148
|
-
* here is an obligation, so a negative one is an upstream defect. */
|
|
3149
|
-
format(value, asset7) {
|
|
3150
|
-
assertDecimals(asset7.decimals);
|
|
3151
|
-
if (value < 0n) {
|
|
3152
|
-
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
3153
|
-
}
|
|
3154
|
-
assertRepresentable(value, `${value}`);
|
|
3155
|
-
return (0, import_solver_discovery3.fromAtomic)(value, asset7.decimals);
|
|
3156
|
-
}
|
|
3157
|
-
};
|
|
3158
|
-
var toAtomicDecimal = (value) => {
|
|
3159
|
-
if (value < 0n) {
|
|
3160
|
-
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
3161
|
-
}
|
|
3162
|
-
assertRepresentable(value, `${value}`);
|
|
3163
|
-
return value.toString();
|
|
3164
|
-
};
|
|
3165
|
-
var fromAtomicDecimal = (text) => {
|
|
3166
|
-
if (!(0, import_solver_discovery3.isAmount)(text)) {
|
|
3167
|
-
throw new AmountFormatError(
|
|
3168
|
-
"not_canonical",
|
|
3169
|
-
`not a canonical atomic amount: ${JSON.stringify(text)}`
|
|
3170
|
-
);
|
|
3171
|
-
}
|
|
3172
|
-
return BigInt(text);
|
|
3173
|
-
};
|
|
3174
|
-
var isAtomicDecimal = (value) => typeof value === "string" && import_solver_discovery3.AMOUNT_PATTERN.test(value);
|
|
3175
|
-
|
|
3176
4040
|
// src/client/rfqAmount.ts
|
|
3177
|
-
var
|
|
4041
|
+
var import_solver_discovery5 = require("@arkade-os/solver-discovery");
|
|
3178
4042
|
var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
|
|
3179
4043
|
var fromRfqAmountSide = (side) => side === "from" ? "give" : "take";
|
|
3180
4044
|
var encodeRfqAmount = (value, field) => {
|
|
@@ -3188,146 +4052,44 @@ var encodeRfqAmount = (value, field) => {
|
|
|
3188
4052
|
{ cause }
|
|
3189
4053
|
);
|
|
3190
4054
|
}
|
|
3191
|
-
};
|
|
3192
|
-
var decodeRfqAmount = (raw, field) => {
|
|
3193
|
-
if (typeof raw === "string") {
|
|
3194
|
-
if (!(0,
|
|
3195
|
-
throw new AmountEncodingUnsupported(
|
|
3196
|
-
field,
|
|
3197
|
-
raw,
|
|
3198
|
-
"not a canonical decimal amount (unsigned, no leading zeros, 30 digits)"
|
|
3199
|
-
);
|
|
3200
|
-
}
|
|
3201
|
-
return BigInt(raw);
|
|
3202
|
-
}
|
|
3203
|
-
if (typeof raw === "number") {
|
|
3204
|
-
if (!Number.isSafeInteger(raw) || raw < 0) {
|
|
3205
|
-
throw new AmountEncodingUnsupported(
|
|
3206
|
-
field,
|
|
3207
|
-
`${raw}`,
|
|
3208
|
-
"a JSON number amount is only readable as a non-negative safe integer"
|
|
3209
|
-
);
|
|
3210
|
-
}
|
|
3211
|
-
return BigInt(raw);
|
|
3212
|
-
}
|
|
3213
|
-
throw new AmountEncodingUnsupported(
|
|
3214
|
-
field,
|
|
3215
|
-
typeof raw === "bigint" || typeof raw === "boolean" ? `${raw}` : String(raw),
|
|
3216
|
-
`expected a decimal string, got ${typeof raw}`
|
|
3217
|
-
);
|
|
3218
|
-
};
|
|
3219
|
-
var toSafeNumber = (value, field) => {
|
|
3220
|
-
if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
3221
|
-
throw new AmountEncodingUnsupported(
|
|
3222
|
-
field,
|
|
3223
|
-
`${value}`,
|
|
3224
|
-
"does not fit a non-negative safe integer"
|
|
3225
|
-
);
|
|
3226
|
-
}
|
|
3227
|
-
return Number(value);
|
|
3228
|
-
};
|
|
3229
|
-
|
|
3230
|
-
// src/client/record.ts
|
|
3231
|
-
var assetSwapIdOf = (family, quoteId) => `${family}:${quoteId}`;
|
|
3232
|
-
var OFFER_SWAP_ID_PREFIX = "offer:";
|
|
3233
|
-
var RFQ_SWAP_ID_PREFIX = "rfq:";
|
|
3234
|
-
var familyOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? "offer" : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? "rfq" : void 0;
|
|
3235
|
-
var quoteIdOfSwapId = (swapId) => {
|
|
3236
|
-
const family = familyOfSwapId(swapId);
|
|
3237
|
-
return family === void 0 ? swapId : swapId.slice(`${family}:`.length);
|
|
3238
|
-
};
|
|
3239
|
-
var recordEndpoint = (endpoint2) => ({
|
|
3240
|
-
corridor: endpoint2.corridor,
|
|
3241
|
-
asset: endpoint2.asset,
|
|
3242
|
-
instrument: recordInstrument(endpoint2.instrument)
|
|
3243
|
-
});
|
|
3244
|
-
var recordInstrument = (instrument) => {
|
|
3245
|
-
switch (instrument.kind) {
|
|
3246
|
-
case "wallet":
|
|
3247
|
-
return { kind: "wallet" };
|
|
3248
|
-
case "address":
|
|
3249
|
-
return { kind: "address", address: instrument.address };
|
|
3250
|
-
case "invoice":
|
|
3251
|
-
return {
|
|
3252
|
-
kind: "invoice",
|
|
3253
|
-
bolt11: instrument.bolt11,
|
|
3254
|
-
paymentHash: instrument.paymentHash,
|
|
3255
|
-
...instrument.amount === void 0 ? {} : { amount: toAtomicDecimal(instrument.amount) },
|
|
3256
|
-
expiresAt: instrument.expiresAt
|
|
3257
|
-
};
|
|
3258
|
-
}
|
|
3259
|
-
};
|
|
3260
|
-
var instrumentOf = (instrument) => {
|
|
3261
|
-
switch (instrument.kind) {
|
|
3262
|
-
case "wallet":
|
|
3263
|
-
return { kind: "wallet" };
|
|
3264
|
-
case "address":
|
|
3265
|
-
return { kind: "address", address: instrument.address };
|
|
3266
|
-
case "invoice":
|
|
3267
|
-
return {
|
|
3268
|
-
kind: "invoice",
|
|
3269
|
-
bolt11: instrument.bolt11,
|
|
3270
|
-
paymentHash: instrument.paymentHash,
|
|
3271
|
-
...instrument.amount === void 0 ? {} : { amount: fromAtomicDecimal(instrument.amount) },
|
|
3272
|
-
expiresAt: instrument.expiresAt
|
|
3273
|
-
};
|
|
3274
|
-
}
|
|
3275
|
-
};
|
|
3276
|
-
var recordArtifact = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
3277
|
-
kind: "deposit",
|
|
3278
|
-
corridor: artifact.corridor,
|
|
3279
|
-
address: artifact.address,
|
|
3280
|
-
asset: artifact.asset,
|
|
3281
|
-
amount: toAtomicDecimal(artifact.amount),
|
|
3282
|
-
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
3283
|
-
};
|
|
3284
|
-
var artifactOf = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
3285
|
-
kind: "deposit",
|
|
3286
|
-
corridor: artifact.corridor,
|
|
3287
|
-
address: artifact.address,
|
|
3288
|
-
asset: artifact.asset,
|
|
3289
|
-
amount: fromAtomicDecimal(artifact.amount),
|
|
3290
|
-
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
3291
|
-
};
|
|
3292
|
-
var recordLeg = (leg) => ({
|
|
3293
|
-
asset: leg.asset,
|
|
3294
|
-
amount: toAtomicDecimal(leg.amount)
|
|
3295
|
-
});
|
|
3296
|
-
var legOf = (leg) => ({
|
|
3297
|
-
asset: leg.asset,
|
|
3298
|
-
amount: fromAtomicDecimal(leg.amount)
|
|
3299
|
-
});
|
|
3300
|
-
var swapOf = (record, outcome) => ({
|
|
3301
|
-
id: assetSwapIdOf(record.family, record.id),
|
|
3302
|
-
family: record.family,
|
|
3303
|
-
outcome,
|
|
3304
|
-
route: {
|
|
3305
|
-
give: {
|
|
3306
|
-
corridor: record.route.give.corridor,
|
|
3307
|
-
asset: record.route.give.asset,
|
|
3308
|
-
instrument: instrumentOf(record.route.give.instrument)
|
|
3309
|
-
},
|
|
3310
|
-
take: {
|
|
3311
|
-
corridor: record.route.take.corridor,
|
|
3312
|
-
asset: record.route.take.asset,
|
|
3313
|
-
instrument: instrumentOf(record.route.take.instrument)
|
|
4055
|
+
};
|
|
4056
|
+
var decodeRfqAmount = (raw, field) => {
|
|
4057
|
+
if (typeof raw === "string") {
|
|
4058
|
+
if (!(0, import_solver_discovery5.isAmount)(raw)) {
|
|
4059
|
+
throw new AmountEncodingUnsupported(
|
|
4060
|
+
field,
|
|
4061
|
+
raw,
|
|
4062
|
+
"not a canonical decimal amount (unsigned, no leading zeros, 30 digits)"
|
|
4063
|
+
);
|
|
3314
4064
|
}
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
})
|
|
3330
|
-
|
|
4065
|
+
return BigInt(raw);
|
|
4066
|
+
}
|
|
4067
|
+
if (typeof raw === "number") {
|
|
4068
|
+
if (!Number.isSafeInteger(raw) || raw < 0) {
|
|
4069
|
+
throw new AmountEncodingUnsupported(
|
|
4070
|
+
field,
|
|
4071
|
+
`${raw}`,
|
|
4072
|
+
"a JSON number amount is only readable as a non-negative safe integer"
|
|
4073
|
+
);
|
|
4074
|
+
}
|
|
4075
|
+
return BigInt(raw);
|
|
4076
|
+
}
|
|
4077
|
+
throw new AmountEncodingUnsupported(
|
|
4078
|
+
field,
|
|
4079
|
+
typeof raw === "bigint" || typeof raw === "boolean" ? `${raw}` : String(raw),
|
|
4080
|
+
`expected a decimal string, got ${typeof raw}`
|
|
4081
|
+
);
|
|
4082
|
+
};
|
|
4083
|
+
var toSafeNumber = (value, field) => {
|
|
4084
|
+
if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
4085
|
+
throw new AmountEncodingUnsupported(
|
|
4086
|
+
field,
|
|
4087
|
+
`${value}`,
|
|
4088
|
+
"does not fit a non-negative safe integer"
|
|
4089
|
+
);
|
|
4090
|
+
}
|
|
4091
|
+
return Number(value);
|
|
4092
|
+
};
|
|
3331
4093
|
|
|
3332
4094
|
// src/client/accept.ts
|
|
3333
4095
|
var acceptLocks = /* @__PURE__ */ new Map();
|
|
@@ -3364,6 +4126,7 @@ var conflictingFields = (record, quote) => {
|
|
|
3364
4126
|
const incoming = recordedFacts(quote);
|
|
3365
4127
|
const stored = {
|
|
3366
4128
|
"route.pair": `${record.route.give.corridor}->${record.route.take.corridor}`,
|
|
4129
|
+
assetPayment: assetPaymentFacts(record.assetPayment),
|
|
3367
4130
|
"give.asset": record.route.give.asset,
|
|
3368
4131
|
"take.asset": record.route.take.asset,
|
|
3369
4132
|
"give.amount": record.give.amount,
|
|
@@ -3387,6 +4150,9 @@ var conflictingFields = (record, quote) => {
|
|
|
3387
4150
|
};
|
|
3388
4151
|
var recordedFacts = (quote) => ({
|
|
3389
4152
|
"route.pair": `${quote.route.give.corridor}->${quote.route.take.corridor}`,
|
|
4153
|
+
assetPayment: assetPaymentFacts(
|
|
4154
|
+
quote.assetPayment === void 0 ? void 0 : recordAssetPayment(quote.assetPayment)
|
|
4155
|
+
),
|
|
3390
4156
|
"give.asset": quote.route.give.asset,
|
|
3391
4157
|
"take.asset": quote.route.take.asset,
|
|
3392
4158
|
"give.amount": recordLeg(quote.give).amount,
|
|
@@ -3409,6 +4175,7 @@ var assertFundable2 = async (wallet, quote) => {
|
|
|
3409
4175
|
};
|
|
3410
4176
|
var commonOf = (quote, now) => ({
|
|
3411
4177
|
id: quote.id,
|
|
4178
|
+
...quote.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(quote.assetPayment) },
|
|
3412
4179
|
route: {
|
|
3413
4180
|
give: recordEndpoint(quote.route.give),
|
|
3414
4181
|
take: recordEndpoint(quote.route.take)
|
|
@@ -3434,7 +4201,7 @@ var corridorRecord = (quote, preparation, now) => {
|
|
|
3434
4201
|
kind: KIND_OF[preparation.route],
|
|
3435
4202
|
rfqId: preparation.rfqId,
|
|
3436
4203
|
lockupAddress: preparation.lockup.address,
|
|
3437
|
-
lockupPkScript:
|
|
4204
|
+
lockupPkScript: import_base9.hex.encode(preparation.lockup.pkScript),
|
|
3438
4205
|
lock: { hash: quote.lock.hash },
|
|
3439
4206
|
refundLocktime: quote.refundLocktime,
|
|
3440
4207
|
profile: profileOf(preparation, quote.lock.hash)
|
|
@@ -3497,6 +4264,7 @@ var acceptQuoteBody = async (input) => {
|
|
|
3497
4264
|
if (fields.length > 0) {
|
|
3498
4265
|
throw new AcceptConflict(quote.id, stored.id, fields);
|
|
3499
4266
|
}
|
|
4267
|
+
if (fundingWasNotSubmitted(stored)) return answer(stored);
|
|
3500
4268
|
if (stored.fundingTxid !== void 0) return answer(stored);
|
|
3501
4269
|
if (!fundsFromWallet(stored.route)) return answer(stored);
|
|
3502
4270
|
const found = await reconcileFunding({ wallet }, stored);
|
|
@@ -3504,7 +4272,13 @@ var acceptQuoteBody = async (input) => {
|
|
|
3504
4272
|
return answer(await stampFunding(repository, stored, found, now));
|
|
3505
4273
|
}
|
|
3506
4274
|
if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
|
|
3507
|
-
return answer(
|
|
4275
|
+
return answer(
|
|
4276
|
+
await fundAndStamp(
|
|
4277
|
+
{ wallet, now, validUntil: input.validUntil, drive: input.drive },
|
|
4278
|
+
stored,
|
|
4279
|
+
repository
|
|
4280
|
+
)
|
|
4281
|
+
);
|
|
3508
4282
|
}
|
|
3509
4283
|
if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
|
|
3510
4284
|
const preparation = input.preparation;
|
|
@@ -3518,48 +4292,114 @@ var acceptQuoteBody = async (input) => {
|
|
|
3518
4292
|
const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
|
|
3519
4293
|
await repository.saveSwapRecord(record);
|
|
3520
4294
|
if (!funds) return answer(record);
|
|
3521
|
-
return answer(
|
|
4295
|
+
return answer(
|
|
4296
|
+
await fundAndStamp(
|
|
4297
|
+
{
|
|
4298
|
+
wallet,
|
|
4299
|
+
now,
|
|
4300
|
+
validUntil: input.validUntil,
|
|
4301
|
+
drive: input.drive,
|
|
4302
|
+
firstFundingAttempt: true
|
|
4303
|
+
},
|
|
4304
|
+
record,
|
|
4305
|
+
repository
|
|
4306
|
+
)
|
|
4307
|
+
);
|
|
3522
4308
|
};
|
|
3523
4309
|
var registeredOfferRecord = async (input, preparation) => {
|
|
3524
4310
|
const { quote, wallet, corridors, now } = input;
|
|
3525
4311
|
const { plan } = preparation;
|
|
3526
4312
|
const arkade2 = corridors.get("arkade").deps;
|
|
3527
4313
|
const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
|
|
3528
|
-
const offer = await createOffer(
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
4314
|
+
const offer = await createOffer(
|
|
4315
|
+
wallet,
|
|
4316
|
+
{
|
|
4317
|
+
// Keyed on the receive side: the covenant binds what the fill delivers.
|
|
4318
|
+
wantAmount: plan.receive.atomic,
|
|
4319
|
+
...receiveIsBtc ? { offerAsset: import_sdk13.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk13.asset.AssetId.fromString(plan.receive.asset.id) },
|
|
4320
|
+
emulatorPubkey: arkade2.emulatorPubkey
|
|
4321
|
+
},
|
|
4322
|
+
{ coverageId: quote.id }
|
|
4323
|
+
);
|
|
3534
4324
|
return {
|
|
3535
4325
|
...commonOf(quote, now),
|
|
3536
4326
|
family: "offer",
|
|
3537
4327
|
status: "pending",
|
|
3538
4328
|
offerHex: offer.offerHex,
|
|
3539
4329
|
swapAddress: offer.address,
|
|
3540
|
-
swapPkScript:
|
|
4330
|
+
swapPkScript: import_base9.hex.encode(offer.swapPkScript)
|
|
3541
4331
|
};
|
|
3542
4332
|
};
|
|
3543
4333
|
var registeredAssetRecord = async (input, preparation) => {
|
|
3544
|
-
|
|
4334
|
+
if ((0, import_solver_discovery6.stableStringify)(
|
|
4335
|
+
input.quote.assetPayment === void 0 ? void 0 : recordAssetPayment(input.quote.assetPayment)
|
|
4336
|
+
) !== (0, import_solver_discovery6.stableStringify)(
|
|
4337
|
+
preparation.assetPayment === void 0 ? void 0 : recordAssetPayment(preparation.assetPayment)
|
|
4338
|
+
))
|
|
4339
|
+
throw new Error("asset payment differs from verified quote preparation");
|
|
4340
|
+
if (preparation.assetPaymentRecipient !== void 0 && (0, import_solver_discovery6.stableStringify)(input.quote.route.take.instrument) !== (0, import_solver_discovery6.stableStringify)(preparation.assetPaymentRecipient))
|
|
4341
|
+
throw new Error("asset payment recipient differs from verified quote preparation");
|
|
4342
|
+
await registerDerivedOffer(input.wallet, preparation.offer, { coverageId: input.quote.id });
|
|
3545
4343
|
return {
|
|
3546
4344
|
...commonOf(input.quote, input.now),
|
|
4345
|
+
...preparation.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(preparation.assetPayment) },
|
|
3547
4346
|
family: "offer",
|
|
3548
4347
|
status: "pending",
|
|
3549
4348
|
offerHex: preparation.offer.offerHex,
|
|
3550
4349
|
swapAddress: preparation.offer.address,
|
|
3551
|
-
swapPkScript:
|
|
4350
|
+
swapPkScript: import_base9.hex.encode(preparation.offer.swapPkScript),
|
|
3552
4351
|
...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
|
|
3553
4352
|
};
|
|
3554
4353
|
};
|
|
3555
4354
|
var registeredCorridorRecord = async (input, preparation) => {
|
|
3556
4355
|
const contracts = await input.wallet.getContractManager();
|
|
3557
|
-
await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address
|
|
4356
|
+
await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address, {
|
|
4357
|
+
coverageId: input.quote.id,
|
|
4358
|
+
scope: input.wallet
|
|
4359
|
+
});
|
|
4360
|
+
await promoteOfferContract(
|
|
4361
|
+
contracts,
|
|
4362
|
+
import_base9.hex.encode(preparation.lockup.script.pkScript),
|
|
4363
|
+
void 0,
|
|
4364
|
+
{
|
|
4365
|
+
coverageId: input.quote.id,
|
|
4366
|
+
scope: input.wallet
|
|
4367
|
+
}
|
|
4368
|
+
);
|
|
3558
4369
|
return corridorRecord(input.quote, preparation, input.now);
|
|
3559
4370
|
};
|
|
3560
4371
|
var fundAndStamp = async (input, record, repository) => {
|
|
3561
|
-
const
|
|
3562
|
-
|
|
4372
|
+
const bounds = storedFundingBounds(record.assetPayment, record.expiresAt);
|
|
4373
|
+
const cap = input.validUntil === void 0 ? bounds.validUntil : Math.min(input.validUntil, bounds.validUntil ?? record.expiresAt);
|
|
4374
|
+
const validUntil = cap === void 0 ? void 0 : Math.min(cap, record.expiresAt);
|
|
4375
|
+
if (input.firstFundingAttempt && record.assetPayment !== void 0 && validUntil !== void 0 && validUntil < record.assetPayment.validUntil) {
|
|
4376
|
+
record = { ...record, assetPayment: { ...record.assetPayment, validUntil } };
|
|
4377
|
+
await repository.saveSwapRecord(record);
|
|
4378
|
+
}
|
|
4379
|
+
try {
|
|
4380
|
+
const txid = await fund({ ...input, ...bounds, validUntil }, record);
|
|
4381
|
+
return stampFunding(repository, record, txid, input.now);
|
|
4382
|
+
} catch (error) {
|
|
4383
|
+
if (input.firstFundingAttempt && validUntil !== void 0 && error instanceof import_sdk13.SendDeadlineExceededError) {
|
|
4384
|
+
const stopped = {
|
|
4385
|
+
...record,
|
|
4386
|
+
...record.family === "offer" ? { status: "cancelled" } : { state: "failed" },
|
|
4387
|
+
fundingNotSubmitted: { reason: "send_deadline", validUntil },
|
|
4388
|
+
updatedAt: Math.floor(Date.now() / 1e3)
|
|
4389
|
+
};
|
|
4390
|
+
try {
|
|
4391
|
+
await repository.saveSwapRecord(stopped);
|
|
4392
|
+
input.drive?.ingest(stopped);
|
|
4393
|
+
await retireUnsubmittedFunding(input.wallet, repository, stopped);
|
|
4394
|
+
} catch (cause) {
|
|
4395
|
+
console.warn(
|
|
4396
|
+
`[swap] could not finish unsent funding cleanup for ${record.id}`,
|
|
4397
|
+
cause
|
|
4398
|
+
);
|
|
4399
|
+
}
|
|
4400
|
+
}
|
|
4401
|
+
throw error;
|
|
4402
|
+
}
|
|
3563
4403
|
};
|
|
3564
4404
|
var stampFunding = async (repository, record, fundingTxid, now) => {
|
|
3565
4405
|
const stamped = { ...record, fundingTxid, updatedAt: now };
|
|
@@ -3572,10 +4412,15 @@ var stampFunding = async (repository, record, fundingTxid, now) => {
|
|
|
3572
4412
|
};
|
|
3573
4413
|
var fund = async (input, record) => {
|
|
3574
4414
|
const { wallet } = input;
|
|
4415
|
+
const send = (recipient) => input.validUntil === void 0 && input.inputExpiryFloor === void 0 ? wallet.send(recipient) : wallet.send({
|
|
4416
|
+
recipients: [recipient],
|
|
4417
|
+
...input.validUntil === void 0 ? {} : { validUntil: input.validUntil },
|
|
4418
|
+
...input.inputExpiryFloor === void 0 ? {} : { inputExpiryFloor: input.inputExpiryFloor }
|
|
4419
|
+
});
|
|
3575
4420
|
if (record.family === "offer") {
|
|
3576
4421
|
const amount = fromAtomicDecimal(record.give.amount);
|
|
3577
4422
|
const depositIsBtc = isBtcAssetLenient(record.route.give.asset);
|
|
3578
|
-
return
|
|
4423
|
+
return send({
|
|
3579
4424
|
address: record.swapAddress,
|
|
3580
4425
|
// An asset deposit rides a dust-sat carrier: the solver's published one when the record
|
|
3581
4426
|
// names it (the fill is priced against it), else the SDK default.
|
|
@@ -3591,20 +4436,20 @@ var fund = async (input, record) => {
|
|
|
3591
4436
|
if (record.kind === "lightning_receive" || record.kind === "onchain_receive") {
|
|
3592
4437
|
throw new Error(`receive swap ${record.id} funds nothing from this wallet`);
|
|
3593
4438
|
}
|
|
3594
|
-
return
|
|
4439
|
+
return send({
|
|
3595
4440
|
address: record.lockupAddress,
|
|
3596
4441
|
amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
|
|
3597
4442
|
});
|
|
3598
4443
|
};
|
|
3599
4444
|
var offerExtensionOf = (record) => ({
|
|
3600
4445
|
type: OFFER_PACKET_TYPE,
|
|
3601
|
-
payload:
|
|
4446
|
+
payload: import_base9.hex.decode(record.offerHex)
|
|
3602
4447
|
});
|
|
3603
4448
|
var reconcileFunding = async (input, record) => {
|
|
3604
4449
|
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
3605
4450
|
const expected = BigInt(record.give.amount);
|
|
3606
4451
|
const reader = await input.wallet.getArkadeReader();
|
|
3607
|
-
const vtxos = await (0,
|
|
4452
|
+
const vtxos = await (0, import_sdk13.getAllNormalizedVtxos)(reader, [script]);
|
|
3608
4453
|
const deposit = vtxos.find((vtxo) => depositMatches(vtxo, record, expected));
|
|
3609
4454
|
return deposit?.txid;
|
|
3610
4455
|
};
|
|
@@ -3632,9 +4477,9 @@ var LEGACY_CORRIDORS = {
|
|
|
3632
4477
|
};
|
|
3633
4478
|
var assetOf = (market, side) => side === "base" ? market.base_asset : market.quote_asset;
|
|
3634
4479
|
var marketAssetId = (market, side) => {
|
|
3635
|
-
const
|
|
3636
|
-
if (typeof
|
|
3637
|
-
return typeof
|
|
4480
|
+
const asset8 = assetOf(market, side);
|
|
4481
|
+
if (typeof asset8?.caip19_id === "string") return asset8.caip19_id;
|
|
4482
|
+
return typeof asset8?.id === "string" ? asset8.id : void 0;
|
|
3638
4483
|
};
|
|
3639
4484
|
var chainNamespaceOf = (id) => {
|
|
3640
4485
|
if (id === void 0) return void 0;
|
|
@@ -3705,13 +4550,14 @@ var scopedToRail = (table, rail) => ({
|
|
|
3705
4550
|
});
|
|
3706
4551
|
|
|
3707
4552
|
// src/client/client.ts
|
|
3708
|
-
var
|
|
4553
|
+
var import_base21 = require("@scure/base");
|
|
4554
|
+
var import_sdk36 = require("@arkade-os/sdk");
|
|
3709
4555
|
init_repository();
|
|
3710
4556
|
|
|
3711
4557
|
// src/refund.ts
|
|
3712
|
-
var
|
|
4558
|
+
var import_base10 = require("@scure/base");
|
|
3713
4559
|
var import_sha24 = require("@noble/hashes/sha2.js");
|
|
3714
|
-
var
|
|
4560
|
+
var import_sdk14 = require("@arkade-os/sdk");
|
|
3715
4561
|
init_onchainHtlc();
|
|
3716
4562
|
init_rfq();
|
|
3717
4563
|
var walletOperator = (wallet) => {
|
|
@@ -3743,13 +4589,13 @@ var LockupNeedsRecoveryError = class extends Error {
|
|
|
3743
4589
|
};
|
|
3744
4590
|
async function findLockupVtxos(contracts, swapPkScript) {
|
|
3745
4591
|
const [row] = await contracts.getContractsWithVtxos({
|
|
3746
|
-
script:
|
|
4592
|
+
script: import_base10.hex.encode(swapPkScript)
|
|
3747
4593
|
});
|
|
3748
4594
|
const seen = /* @__PURE__ */ new Set();
|
|
3749
4595
|
const out = [];
|
|
3750
4596
|
for (const vtxo of row?.vtxos ?? []) {
|
|
3751
4597
|
if (vtxo.isUnrolled) continue;
|
|
3752
|
-
if ((0,
|
|
4598
|
+
if ((0, import_sdk14.isVtxoSpent)(vtxo)) continue;
|
|
3753
4599
|
const key = `${vtxo.txid}:${vtxo.vout}`;
|
|
3754
4600
|
if (seen.has(key)) continue;
|
|
3755
4601
|
seen.add(key);
|
|
@@ -3762,16 +4608,16 @@ async function findLockupVtxos(contracts, swapPkScript) {
|
|
|
3762
4608
|
}
|
|
3763
4609
|
return out;
|
|
3764
4610
|
}
|
|
3765
|
-
var hashesTo = (candidate, paymentHash) =>
|
|
4611
|
+
var hashesTo = (candidate, paymentHash) => import_base10.hex.encode((0, import_sha24.sha256)(candidate)) === paymentHash;
|
|
3766
4612
|
var candidateWitnessItems = (tx, inputIndex) => [
|
|
3767
|
-
...(0,
|
|
4613
|
+
...(0, import_sdk14.getArkPsbtFields)(tx, inputIndex, import_sdk14.ConditionWitness).flat(),
|
|
3768
4614
|
...tx.getInput(inputIndex).finalScriptWitness ?? []
|
|
3769
4615
|
];
|
|
3770
4616
|
async function readLockupFate(indexer, input) {
|
|
3771
|
-
const { vtxos } = await indexer.getVtxos({ scripts: [
|
|
4617
|
+
const { vtxos } = await indexer.getVtxos({ scripts: [import_base10.hex.encode(input.swapPkScript)] });
|
|
3772
4618
|
const all = vtxos ?? [];
|
|
3773
4619
|
if (all.length === 0) return { fate: "unknown" };
|
|
3774
|
-
const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0,
|
|
4620
|
+
const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0, import_sdk14.isVtxoSpent)(vtxo));
|
|
3775
4621
|
if (exited.length > 0) {
|
|
3776
4622
|
return {
|
|
3777
4623
|
fate: "exited",
|
|
@@ -3781,7 +4627,7 @@ async function readLockupFate(indexer, input) {
|
|
|
3781
4627
|
const spentBy = /* @__PURE__ */ new Map();
|
|
3782
4628
|
let everySpendNamed = true;
|
|
3783
4629
|
for (const vtxo of all) {
|
|
3784
|
-
if (!(0,
|
|
4630
|
+
if (!(0, import_sdk14.isVtxoSpent)(vtxo)) return { fate: "open" };
|
|
3785
4631
|
if (vtxo.spentBy)
|
|
3786
4632
|
spentBy.set(vtxo.spentBy, {
|
|
3787
4633
|
checkpointTxid: vtxo.spentBy,
|
|
@@ -3795,7 +4641,7 @@ async function readLockupFate(indexer, input) {
|
|
|
3795
4641
|
for (const raw of txs) {
|
|
3796
4642
|
let tx;
|
|
3797
4643
|
try {
|
|
3798
|
-
tx =
|
|
4644
|
+
tx = import_sdk14.Transaction.fromPSBT(import_base10.base64.decode(raw));
|
|
3799
4645
|
} catch {
|
|
3800
4646
|
continue;
|
|
3801
4647
|
}
|
|
@@ -3803,7 +4649,7 @@ async function readLockupFate(indexer, input) {
|
|
|
3803
4649
|
for (let i = 0; i < tx.inputsLength; i++) {
|
|
3804
4650
|
const spent = tx.getInput(i);
|
|
3805
4651
|
if (!spent.txid) continue;
|
|
3806
|
-
const txid =
|
|
4652
|
+
const txid = import_base10.hex.encode(spent.txid);
|
|
3807
4653
|
if (!all.some((vtxo) => vtxo.txid === txid && vtxo.vout === spent.index)) continue;
|
|
3808
4654
|
for (const candidate of candidateWitnessItems(tx, i)) {
|
|
3809
4655
|
if (hashesTo(candidate, input.paymentHash)) {
|
|
@@ -3825,10 +4671,10 @@ var assertNoneSwept = (vtxos, contract) => {
|
|
|
3825
4671
|
};
|
|
3826
4672
|
var operatorUnrollScript = async (operator, network) => {
|
|
3827
4673
|
const info = await operator.getInfo();
|
|
3828
|
-
return (0,
|
|
4674
|
+
return (0, import_sdk14.assertValidServerUnrollScript)(
|
|
3829
4675
|
info.checkpointTapscript,
|
|
3830
|
-
(0,
|
|
3831
|
-
advertisedForfeitPubkey: (0,
|
|
4676
|
+
(0, import_sdk14.resolveCheckpointExitDelayPolicy)(network ?? (0, import_sdk14.networkFromArkadeInfo)(info), {
|
|
4677
|
+
advertisedForfeitPubkey: (0, import_sdk14.toXOnly)(import_base10.hex.decode(info.forfeitPubkey), "forfeit key")
|
|
3832
4678
|
})
|
|
3833
4679
|
);
|
|
3834
4680
|
};
|
|
@@ -3854,25 +4700,25 @@ async function pushRefundWithoutReceiver(operator, input) {
|
|
|
3854
4700
|
const serverUnrollScript = await operatorUnrollScript(operator, input.network);
|
|
3855
4701
|
const leaf = input.contract.refundWithoutReceiver();
|
|
3856
4702
|
const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
|
|
3857
|
-
const { arkTx: tx, checkpoints } = (0,
|
|
4703
|
+
const { arkTx: tx, checkpoints } = (0, import_sdk14.buildOffchainTx)(
|
|
3858
4704
|
lockupInputs(input.vtxos, input.contract, leaf),
|
|
3859
4705
|
[{ script: refundPkScript, amount: BigInt(amount) }],
|
|
3860
4706
|
serverUnrollScript
|
|
3861
4707
|
);
|
|
3862
4708
|
const signedTx = await input.sender.sign(tx);
|
|
3863
4709
|
const submitted = await operator.submitTx(
|
|
3864
|
-
|
|
3865
|
-
checkpoints.map((c) =>
|
|
4710
|
+
import_base10.base64.encode(signedTx.toPSBT()),
|
|
4711
|
+
checkpoints.map((c) => import_base10.base64.encode(c.toPSBT()))
|
|
3866
4712
|
);
|
|
3867
|
-
(0,
|
|
3868
|
-
const matched = (0,
|
|
4713
|
+
(0, import_sdk14.assertSubmittedArkTxid)(submitted, signedTx, "refundWithoutReceiver");
|
|
4714
|
+
const matched = (0, import_sdk14.matchServerCheckpoints)(
|
|
3869
4715
|
submitted.signedCheckpointTxs,
|
|
3870
4716
|
checkpoints,
|
|
3871
4717
|
"refundWithoutReceiver"
|
|
3872
4718
|
);
|
|
3873
4719
|
const finalCheckpoints = await Promise.all(
|
|
3874
4720
|
matched.map(
|
|
3875
|
-
async ({ server }) =>
|
|
4721
|
+
async ({ server }) => import_base10.base64.encode((await input.sender.sign(server, [0])).toPSBT())
|
|
3876
4722
|
)
|
|
3877
4723
|
);
|
|
3878
4724
|
await operator.finalizeTx(submitted.arkTxid, finalCheckpoints);
|
|
@@ -3881,10 +4727,10 @@ async function pushRefundWithoutReceiver(operator, input) {
|
|
|
3881
4727
|
var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
|
|
3882
4728
|
|
|
3883
4729
|
// src/client/corridors/registry.ts
|
|
3884
|
-
var
|
|
4730
|
+
var import_sdk18 = require("@arkade-os/sdk");
|
|
3885
4731
|
|
|
3886
4732
|
// src/client/corridors/arkade.ts
|
|
3887
|
-
var
|
|
4733
|
+
var import_sdk15 = require("@arkade-os/sdk");
|
|
3888
4734
|
var ARKADE_DRIVE = {};
|
|
3889
4735
|
var messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
3890
4736
|
var arkadeCorridor = Object.assign(
|
|
@@ -3893,11 +4739,11 @@ var arkadeCorridor = Object.assign(
|
|
|
3893
4739
|
deps,
|
|
3894
4740
|
drive: ARKADE_DRIVE,
|
|
3895
4741
|
matches(raw) {
|
|
3896
|
-
const target = (0,
|
|
4742
|
+
const target = (0, import_sdk15.arkTarget)(raw);
|
|
3897
4743
|
if (target === void 0) return void 0;
|
|
3898
4744
|
try {
|
|
3899
|
-
const address =
|
|
3900
|
-
(0,
|
|
4745
|
+
const address = import_sdk15.ArkAddress.decode(target);
|
|
4746
|
+
(0, import_sdk15.assertRecipientArkadeAddress)(target, address, {
|
|
3901
4747
|
hrp: deps.network.hrp,
|
|
3902
4748
|
signerSet: deps.signerSet
|
|
3903
4749
|
});
|
|
@@ -3907,11 +4753,11 @@ var arkadeCorridor = Object.assign(
|
|
|
3907
4753
|
return { claimed: { kind: "address", address: target } };
|
|
3908
4754
|
}
|
|
3909
4755
|
}),
|
|
3910
|
-
{ target:
|
|
4756
|
+
{ target: import_sdk15.arkTarget }
|
|
3911
4757
|
);
|
|
3912
4758
|
|
|
3913
4759
|
// src/client/corridors/deps.ts
|
|
3914
|
-
var
|
|
4760
|
+
var import_sdk17 = require("@arkade-os/sdk");
|
|
3915
4761
|
init_onchainHtlc();
|
|
3916
4762
|
init_rfq();
|
|
3917
4763
|
|
|
@@ -3942,9 +4788,9 @@ var decodeBolt11 = (invoice) => {
|
|
|
3942
4788
|
};
|
|
3943
4789
|
|
|
3944
4790
|
// src/client/corridors/chainSource.ts
|
|
3945
|
-
var
|
|
4791
|
+
var import_base11 = require("@scure/base");
|
|
3946
4792
|
var btc3 = __toESM(require("@scure/btc-signer"), 1);
|
|
3947
|
-
var
|
|
4793
|
+
var import_sdk16 = require("@arkade-os/sdk");
|
|
3948
4794
|
var addressOfScript = (script, network) => btc3.Address(network).encode(btc3.OutScript.decode(script));
|
|
3949
4795
|
var chainSourceOver = (backend, network) => {
|
|
3950
4796
|
const spenderFromVins = async (txid, vout, pkScript) => {
|
|
@@ -3982,7 +4828,7 @@ var chainSourceOver = (backend, network) => {
|
|
|
3982
4828
|
if (!outspend?.spent) return null;
|
|
3983
4829
|
const spender = outspend.txid || await spenderFromVins(txid, vout, pkScript);
|
|
3984
4830
|
if (!spender) return null;
|
|
3985
|
-
return { txHex:
|
|
4831
|
+
return { txHex: import_base11.hex.encode(await backend.provider.getRawTransaction(spender)) };
|
|
3986
4832
|
},
|
|
3987
4833
|
broadcast(txHex) {
|
|
3988
4834
|
return backend.provider.broadcastTransaction(txHex);
|
|
@@ -4006,7 +4852,7 @@ var esploraTip = async (esploraUrl, fetchImpl) => {
|
|
|
4006
4852
|
};
|
|
4007
4853
|
var esploraChainSource = (input) => chainSourceOver(
|
|
4008
4854
|
{
|
|
4009
|
-
provider: new
|
|
4855
|
+
provider: new import_sdk16.EsploraProvider(input.esploraUrl),
|
|
4010
4856
|
tip: () => esploraTip(input.esploraUrl, input.fetchImpl)
|
|
4011
4857
|
},
|
|
4012
4858
|
input.network
|
|
@@ -4032,10 +4878,10 @@ var refusedIfMalformed = (value, dep) => {
|
|
|
4032
4878
|
};
|
|
4033
4879
|
var emulatorPubkeyFor = (base) => {
|
|
4034
4880
|
if (base.emulatorPubkey !== void 0) {
|
|
4035
|
-
return (0,
|
|
4881
|
+
return (0, import_sdk17.resolveEmulatorPubkey)(base.network, base.emulatorPubkey);
|
|
4036
4882
|
}
|
|
4037
4883
|
try {
|
|
4038
|
-
return (0,
|
|
4884
|
+
return (0, import_sdk17.defaultEmulatorPubkey)(base.network);
|
|
4039
4885
|
} catch {
|
|
4040
4886
|
throw new MissingCorridorDep(
|
|
4041
4887
|
"arkade",
|
|
@@ -4085,7 +4931,7 @@ function resolveCorridorDeps(corridor, overrides, base) {
|
|
|
4085
4931
|
return {
|
|
4086
4932
|
networkName: base.networkName,
|
|
4087
4933
|
chain: esploraChainSource({
|
|
4088
|
-
esploraUrl: chain?.esploraUrl ??
|
|
4934
|
+
esploraUrl: chain?.esploraUrl ?? import_sdk17.ESPLORA_URL[base.networkName],
|
|
4089
4935
|
network: L1_NETWORKS[l1NetworkFromArk(base.networkName)],
|
|
4090
4936
|
fetchImpl: base.fetchImpl
|
|
4091
4937
|
}),
|
|
@@ -4115,8 +4961,8 @@ var resolveCorridorBase = async (input) => {
|
|
|
4115
4961
|
wallet: input.wallet,
|
|
4116
4962
|
operator: input.operator,
|
|
4117
4963
|
networkName,
|
|
4118
|
-
network: (0,
|
|
4119
|
-
signerSet: (0,
|
|
4964
|
+
network: (0, import_sdk17.getNetwork)(networkName),
|
|
4965
|
+
signerSet: (0, import_sdk17.signerSetFromInfo)(info),
|
|
4120
4966
|
emulatorPubkey: input.emulatorPubkey,
|
|
4121
4967
|
fetchImpl: input.fetchImpl,
|
|
4122
4968
|
repository: input.repository
|
|
@@ -4146,7 +4992,7 @@ var corridorSet = (base, overrides) => {
|
|
|
4146
4992
|
(corridor) => CORRIDOR_FACTORIES[corridor].target(raw) !== void 0
|
|
4147
4993
|
);
|
|
4148
4994
|
if (owners.length === 0) {
|
|
4149
|
-
if ((0,
|
|
4995
|
+
if ((0, import_sdk18.isLnurl)(raw)) return void 0;
|
|
4150
4996
|
throw new AmbiguousDestination(raw, "no corridor recognises this destination");
|
|
4151
4997
|
}
|
|
4152
4998
|
const claims = [];
|
|
@@ -4170,15 +5016,15 @@ var corridorSet = (base, overrides) => {
|
|
|
4170
5016
|
};
|
|
4171
5017
|
|
|
4172
5018
|
// src/client/discovery.ts
|
|
4173
|
-
var
|
|
5019
|
+
var import_solver_discovery9 = require("@arkade-os/solver-discovery");
|
|
4174
5020
|
|
|
4175
5021
|
// src/markets.ts
|
|
4176
|
-
var
|
|
4177
|
-
var
|
|
5022
|
+
var import_solver_discovery8 = require("@arkade-os/solver-discovery");
|
|
5023
|
+
var import_sdk20 = require("@arkade-os/sdk");
|
|
4178
5024
|
init_store();
|
|
4179
5025
|
var QUOTE_OPTIONS = { safetyBps: 0 };
|
|
4180
5026
|
var makeCachedFeedFetch = (ttlMs = 3e4, fetchImpl = fetch) => {
|
|
4181
|
-
(0,
|
|
5027
|
+
(0, import_sdk20.assertNonNegativeMs)("ttlMs", ttlMs);
|
|
4182
5028
|
const cache = /* @__PURE__ */ new Map();
|
|
4183
5029
|
const inflight = /* @__PURE__ */ new Map();
|
|
4184
5030
|
return async (input, init) => {
|
|
@@ -4245,7 +5091,8 @@ var nostrCards = {
|
|
|
4245
5091
|
}
|
|
4246
5092
|
};
|
|
4247
5093
|
var transportCardsOf = (option) => option === void 0 ? nostrCards : option ?? void 0;
|
|
4248
|
-
var UNDELIVERED_CARRY_MS =
|
|
5094
|
+
var UNDELIVERED_CARRY_MS = import_solver_discovery8.MAX_CARD_AGE_SECONDS * 1e3;
|
|
5095
|
+
var DEGRADED_RETRY_MS = 6e4;
|
|
4249
5096
|
var trackDelivery = (fetcher) => {
|
|
4250
5097
|
let undelivered = /* @__PURE__ */ new Set();
|
|
4251
5098
|
if (!fetcher) return { fetcher, undelivered: () => undelivered };
|
|
@@ -4292,7 +5139,7 @@ var REGISTRY_URL = {
|
|
|
4292
5139
|
};
|
|
4293
5140
|
var HEX_64 = /^[0-9a-f]{64}$/;
|
|
4294
5141
|
var LEGACY_ASSET_ID = /^(?:btc|[0-9a-f]{68})$/;
|
|
4295
|
-
var isRelayList = (value) => Array.isArray(value) && value.length > 0 && value.length <=
|
|
5142
|
+
var isRelayList = (value) => Array.isArray(value) && value.length > 0 && value.length <= import_solver_discovery9.MAX_RELAYS && value.every((relay) => typeof relay === "string" && relay.startsWith("wss://"));
|
|
4296
5143
|
var isCorridorField = (value) => value === void 0 || CORRIDORS.includes(value);
|
|
4297
5144
|
var isUsableCard = (value) => {
|
|
4298
5145
|
const card = value;
|
|
@@ -4304,7 +5151,7 @@ var isUsableCard = (value) => {
|
|
|
4304
5151
|
const id = marketAssetId(card, side);
|
|
4305
5152
|
if (id === void 0 || !isAssetId(id) && !LEGACY_ASSET_ID.test(id)) return false;
|
|
4306
5153
|
}
|
|
4307
|
-
if ((0,
|
|
5154
|
+
if ((0, import_solver_discovery9.isRfqMarket)(card)) {
|
|
4308
5155
|
if (typeof card.discovery_pubkey !== "string" || !HEX_64.test(card.discovery_pubkey)) {
|
|
4309
5156
|
return false;
|
|
4310
5157
|
}
|
|
@@ -4322,7 +5169,6 @@ var readCache = async (repository, network, registry) => {
|
|
|
4322
5169
|
return void 0;
|
|
4323
5170
|
}
|
|
4324
5171
|
};
|
|
4325
|
-
var DEGRADED_RETRY_MS = 6e4;
|
|
4326
5172
|
var discoveryIndex = (input) => {
|
|
4327
5173
|
const config = input.config ?? {};
|
|
4328
5174
|
const network = config.network ?? input.network;
|
|
@@ -4371,6 +5217,17 @@ var discoveryIndex = (input) => {
|
|
|
4371
5217
|
held = cached;
|
|
4372
5218
|
return cached;
|
|
4373
5219
|
}
|
|
5220
|
+
const { network: indexed, registry: url } = sources();
|
|
5221
|
+
if (indexed && url && config.localCards?.length) {
|
|
5222
|
+
const { markets } = await (0, import_solver_discovery9.discover)({
|
|
5223
|
+
registries: [],
|
|
5224
|
+
localCards: [...config.localCards],
|
|
5225
|
+
network: indexed
|
|
5226
|
+
});
|
|
5227
|
+
if (markets.length > 0) {
|
|
5228
|
+
return { markets, ref: { fetchedAt: Date.now(), live: true, source: "local" } };
|
|
5229
|
+
}
|
|
5230
|
+
}
|
|
4374
5231
|
return unavailable(whyUnavailable());
|
|
4375
5232
|
};
|
|
4376
5233
|
const load = async (opts = {}) => {
|
|
@@ -4382,7 +5239,7 @@ var discoveryIndex = (input) => {
|
|
|
4382
5239
|
return unavailable(whyUnavailable());
|
|
4383
5240
|
}
|
|
4384
5241
|
const delivery = trackDelivery(transportCardsOf(config.transportCards));
|
|
4385
|
-
const result = await (0,
|
|
5242
|
+
const result = await (0, import_solver_discovery9.discover)({
|
|
4386
5243
|
registries: [url],
|
|
4387
5244
|
localCards: [...config.localCards ?? []],
|
|
4388
5245
|
network: indexed,
|
|
@@ -4431,14 +5288,14 @@ var discoveryIndex = (input) => {
|
|
|
4431
5288
|
};
|
|
4432
5289
|
|
|
4433
5290
|
// src/client/cancel.ts
|
|
4434
|
-
var
|
|
4435
|
-
var
|
|
5291
|
+
var import_base15 = require("@scure/base");
|
|
5292
|
+
var import_sdk24 = require("@arkade-os/sdk");
|
|
4436
5293
|
init_coverage();
|
|
4437
5294
|
init_offer();
|
|
4438
5295
|
|
|
4439
5296
|
// src/restore.ts
|
|
4440
|
-
var
|
|
4441
|
-
var
|
|
5297
|
+
var import_base12 = require("@scure/base");
|
|
5298
|
+
var import_sdk21 = require("@arkade-os/sdk");
|
|
4442
5299
|
init_offer();
|
|
4443
5300
|
init_store();
|
|
4444
5301
|
var TXS_PER_REQUEST = 50;
|
|
@@ -4463,7 +5320,7 @@ async function fetchParsedTxs(indexer, txids) {
|
|
|
4463
5320
|
if (result.status !== "fulfilled") continue;
|
|
4464
5321
|
for (const psbt of result.value) {
|
|
4465
5322
|
try {
|
|
4466
|
-
const parsed =
|
|
5323
|
+
const parsed = import_sdk21.Transaction.fromPSBT(import_base12.base64.decode(psbt));
|
|
4467
5324
|
parsedByTxid.set(parsed.id, parsed);
|
|
4468
5325
|
} catch {
|
|
4469
5326
|
}
|
|
@@ -4478,7 +5335,7 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
|
|
|
4478
5335
|
let leaves;
|
|
4479
5336
|
try {
|
|
4480
5337
|
const script = offerContract(offer, operatorPubkey);
|
|
4481
|
-
if (
|
|
5338
|
+
if (import_base12.hex.encode(script.pkScript) !== import_base12.hex.encode(offer.swapPkScript)) return "indeterminate";
|
|
4482
5339
|
leaves = {
|
|
4483
5340
|
// `exit` is absent on an offer with no exit closure, and drops out here
|
|
4484
5341
|
returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
|
|
@@ -4490,11 +5347,11 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
|
|
|
4490
5347
|
for (let i = 0; i < spendTx.inputsLength; i++) {
|
|
4491
5348
|
const input = spendTx.getInput(i);
|
|
4492
5349
|
if (!input.txid || input.index !== deposit.vout) continue;
|
|
4493
|
-
if (
|
|
5350
|
+
if (import_base12.hex.encode(input.txid) !== deposit.txid) continue;
|
|
4494
5351
|
for (const leaf of input.tapLeafScript ?? []) {
|
|
4495
|
-
const spent =
|
|
4496
|
-
if (leaves.returned.some((back) => spent ===
|
|
4497
|
-
if (leaves.fulfill && spent ===
|
|
5352
|
+
const spent = import_base12.hex.encode((0, import_sdk21.scriptFromTapLeafScript)(leaf));
|
|
5353
|
+
if (leaves.returned.some((back) => spent === import_base12.hex.encode(back))) return "cancelled";
|
|
5354
|
+
if (leaves.fulfill && spent === import_base12.hex.encode(leaves.fulfill)) return "fulfilled";
|
|
4498
5355
|
}
|
|
4499
5356
|
}
|
|
4500
5357
|
return "indeterminate";
|
|
@@ -4520,7 +5377,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4520
5377
|
try {
|
|
4521
5378
|
reopened.push({
|
|
4522
5379
|
fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
|
|
4523
|
-
offer: decodeOffer(
|
|
5380
|
+
offer: decodeOffer(import_base12.hex.decode(swap.offerHex)),
|
|
4524
5381
|
offerHex: swap.offerHex,
|
|
4525
5382
|
existing: swap
|
|
4526
5383
|
});
|
|
@@ -4546,19 +5403,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4546
5403
|
if (!fundingTx) continue;
|
|
4547
5404
|
fetchedTxids.push(txid);
|
|
4548
5405
|
try {
|
|
4549
|
-
const packet =
|
|
5406
|
+
const packet = import_sdk21.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
|
|
4550
5407
|
if (!packet) continue;
|
|
4551
5408
|
const payload = packet.serialize();
|
|
4552
5409
|
found.push({
|
|
4553
5410
|
fundingTx,
|
|
4554
5411
|
offer: decodeOffer(payload),
|
|
4555
|
-
offerHex:
|
|
5412
|
+
offerHex: import_base12.hex.encode(payload)
|
|
4556
5413
|
});
|
|
4557
5414
|
} catch {
|
|
4558
5415
|
}
|
|
4559
5416
|
}
|
|
4560
5417
|
if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
|
|
4561
|
-
const scripts = [...new Set(found.map((f) =>
|
|
5418
|
+
const scripts = [...new Set(found.map((f) => import_base12.hex.encode(f.offer.swapPkScript)))];
|
|
4562
5419
|
const { vtxos } = await indexer.getVtxos({ scripts });
|
|
4563
5420
|
const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
|
|
4564
5421
|
const txByAnyId = /* @__PURE__ */ new Map();
|
|
@@ -4570,7 +5427,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4570
5427
|
const spendTxids = /* @__PURE__ */ new Set();
|
|
4571
5428
|
for (const { fundingTx, offer } of found) {
|
|
4572
5429
|
const vtxo = vtxoByScriptAndTxid.get(
|
|
4573
|
-
`${
|
|
5430
|
+
`${import_base12.hex.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
|
|
4574
5431
|
);
|
|
4575
5432
|
if (!vtxo?.isSpent) continue;
|
|
4576
5433
|
for (const txid of spendTxidsOf(vtxo)) spendTxids.add(txid);
|
|
@@ -4579,7 +5436,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4579
5436
|
const restored = [];
|
|
4580
5437
|
const unresolved = /* @__PURE__ */ new Set();
|
|
4581
5438
|
for (const { fundingTx, offer, offerHex, existing } of found) {
|
|
4582
|
-
const swapPkScript =
|
|
5439
|
+
const swapPkScript = import_base12.hex.encode(offer.swapPkScript);
|
|
4583
5440
|
const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
|
|
4584
5441
|
if (!vtxo) {
|
|
4585
5442
|
unresolved.add(fundingTx.redeemTxid);
|
|
@@ -4626,7 +5483,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4626
5483
|
let swapAddress = "";
|
|
4627
5484
|
try {
|
|
4628
5485
|
const compiled = offerContract(offer, operatorPubkey);
|
|
4629
|
-
if (
|
|
5486
|
+
if (import_base12.hex.encode(compiled.pkScript) !== swapPkScript) {
|
|
4630
5487
|
unresolved.add(fundingTx.redeemTxid);
|
|
4631
5488
|
continue;
|
|
4632
5489
|
}
|
|
@@ -4663,8 +5520,8 @@ init_repository();
|
|
|
4663
5520
|
init_repository();
|
|
4664
5521
|
|
|
4665
5522
|
// src/rfqRecord.ts
|
|
4666
|
-
var
|
|
4667
|
-
var
|
|
5523
|
+
var import_sdk22 = require("@arkade-os/sdk");
|
|
5524
|
+
var import_base13 = require("@scure/base");
|
|
4668
5525
|
|
|
4669
5526
|
// src/rfqSwapState.ts
|
|
4670
5527
|
var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
|
|
@@ -4677,6 +5534,7 @@ var RFQ_SWAP_ACTIVE_STATES = [
|
|
|
4677
5534
|
var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
|
|
4678
5535
|
|
|
4679
5536
|
// src/rfqRecord.ts
|
|
5537
|
+
init_rfqCorridor();
|
|
4680
5538
|
var RFQ_SWAP_RETENTION_SECONDS = 30 * 24 * 60 * 60;
|
|
4681
5539
|
function renameLegacyClaimTxid(profile) {
|
|
4682
5540
|
const { claimArkTxid, ...rest } = profile;
|
|
@@ -4718,8 +5576,8 @@ function assertSameSwap(origin, swap) {
|
|
|
4718
5576
|
`rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
|
|
4719
5577
|
);
|
|
4720
5578
|
}
|
|
4721
|
-
const funded =
|
|
4722
|
-
const watched =
|
|
5579
|
+
const funded = import_base13.hex.encode(import_sdk22.ArkAddress.decode(origin.lockupAddress).pkScript);
|
|
5580
|
+
const watched = import_base13.hex.encode(swap.lockupPkScript);
|
|
4723
5581
|
if (funded !== watched) {
|
|
4724
5582
|
throw new Error(
|
|
4725
5583
|
`rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
|
|
@@ -4765,11 +5623,11 @@ function rfqSwapOriginOf(record) {
|
|
|
4765
5623
|
};
|
|
4766
5624
|
}
|
|
4767
5625
|
function lockupScript(params, lockupAddress) {
|
|
4768
|
-
const script =
|
|
4769
|
-
const funded =
|
|
4770
|
-
if (
|
|
5626
|
+
const script = import_sdk22.VHTLCV2ContractHandler.createScript(params);
|
|
5627
|
+
const funded = import_sdk22.ArkAddress.decode(lockupAddress).pkScript;
|
|
5628
|
+
if (import_base13.hex.encode(funded) !== import_base13.hex.encode(script.pkScript)) {
|
|
4771
5629
|
throw new Error(
|
|
4772
|
-
`rfq swap covenant params derive ${
|
|
5630
|
+
`rfq swap covenant params derive ${import_base13.hex.encode(script.pkScript)}, but the record's lockup address holds ${import_base13.hex.encode(funded)} \u2014 these params are not this swap's`
|
|
4773
5631
|
);
|
|
4774
5632
|
}
|
|
4775
5633
|
return script;
|
|
@@ -4803,9 +5661,9 @@ function shouldRetainRfqSwap(record, now) {
|
|
|
4803
5661
|
|
|
4804
5662
|
// src/client/driveRecords.ts
|
|
4805
5663
|
init_store();
|
|
4806
|
-
var
|
|
5664
|
+
var import_sdk23 = require("@arkade-os/sdk");
|
|
4807
5665
|
var import_sha25 = require("@noble/hashes/sha2.js");
|
|
4808
|
-
var
|
|
5666
|
+
var import_base14 = require("@scure/base");
|
|
4809
5667
|
var splitRecords = (records) => {
|
|
4810
5668
|
const corridor = [];
|
|
4811
5669
|
const offer = [];
|
|
@@ -4858,7 +5716,7 @@ var pageRfqRecords = (records, filter, page) => {
|
|
|
4858
5716
|
).sort(
|
|
4859
5717
|
(a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
|
|
4860
5718
|
).slice(0, page.limit + 1);
|
|
4861
|
-
return (0,
|
|
5719
|
+
return (0, import_sdk23.pageResult)(rows, page.limit, (record) => ({
|
|
4862
5720
|
updatedAt: record.updatedAt,
|
|
4863
5721
|
rfqId: record.rfqId
|
|
4864
5722
|
}));
|
|
@@ -4884,7 +5742,7 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
4884
5742
|
index,
|
|
4885
5743
|
quoteIdOf: (rfqId) => byRfqId.get(rfqId),
|
|
4886
5744
|
async getRfqSwapsPage(filter, page) {
|
|
4887
|
-
(0,
|
|
5745
|
+
(0, import_sdk23.assertPageRequest)(page);
|
|
4888
5746
|
assertRfqSwapPageFilter(filter);
|
|
4889
5747
|
const { corridor } = splitRecords(await collectSwapRecords(repository));
|
|
4890
5748
|
for (const record of corridor) index(record);
|
|
@@ -4911,13 +5769,12 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
4911
5769
|
};
|
|
4912
5770
|
var offerFactsOf = (record) => ({
|
|
4913
5771
|
id: record.id,
|
|
5772
|
+
coverageId: record.id,
|
|
4914
5773
|
status: record.status,
|
|
4915
5774
|
offerHex: record.offerHex,
|
|
4916
5775
|
swapPkScript: record.swapPkScript,
|
|
4917
5776
|
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
4918
5777
|
...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
|
|
4919
|
-
// milliseconds: `coverage.ts` compares against `Date.now()`, and seconds would leave every
|
|
4920
|
-
// issued script outstanding for the life of the process
|
|
4921
5778
|
createdAt: record.createdAt * 1e3
|
|
4922
5779
|
});
|
|
4923
5780
|
var offerRecordSource = (repository, onRecord = () => {
|
|
@@ -4993,7 +5850,7 @@ var restoredOfferRecord = (swap, network, now) => {
|
|
|
4993
5850
|
now
|
|
4994
5851
|
);
|
|
4995
5852
|
};
|
|
4996
|
-
var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network,
|
|
5853
|
+
var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk23.asset.AssetId.fromString(id));
|
|
4997
5854
|
var RESTORED_CORRIDORS = {
|
|
4998
5855
|
lightning_send: ["arkade", "lightning"],
|
|
4999
5856
|
lightning_receive: ["lightning", "arkade"],
|
|
@@ -5003,7 +5860,7 @@ var RESTORED_CORRIDORS = {
|
|
|
5003
5860
|
var restoredCorridorRecord = (stored, network, refundLocktime) => {
|
|
5004
5861
|
const v1 = normalizeRfqSwapRecord(stored);
|
|
5005
5862
|
const hashlock = v1.profile.hashlock;
|
|
5006
|
-
const hash = typeof hashlock?.paymentHash === "string" ? hashlock.paymentHash : v1.settlementPreimageHex === void 0 ? void 0 :
|
|
5863
|
+
const hash = typeof hashlock?.paymentHash === "string" ? hashlock.paymentHash : v1.settlementPreimageHex === void 0 ? void 0 : import_base14.hex.encode((0, import_sha25.sha256)(import_base14.hex.decode(v1.settlementPreimageHex)));
|
|
5007
5864
|
if (hash === void 0) throw new Error(`v1 rfq swap ${v1.rfqId} has no payment hash`);
|
|
5008
5865
|
const [giveCorridor, takeCorridor] = RESTORED_CORRIDORS[v1.kind];
|
|
5009
5866
|
const give = btcOn(railOfCorridor(giveCorridor), network);
|
|
@@ -5025,7 +5882,7 @@ var restoredCorridorRecord = (stored, network, refundLocktime) => {
|
|
|
5025
5882
|
kind: v1.kind,
|
|
5026
5883
|
rfqId: v1.rfqId,
|
|
5027
5884
|
lockupAddress: v1.lockupAddress,
|
|
5028
|
-
lockupPkScript:
|
|
5885
|
+
lockupPkScript: import_base14.hex.encode(import_sdk23.ArkAddress.decode(v1.lockupAddress).pkScript),
|
|
5029
5886
|
lock: { hash },
|
|
5030
5887
|
refundLocktime,
|
|
5031
5888
|
profile: v1.profile,
|
|
@@ -5109,7 +5966,7 @@ var cancelSwap = async (input) => {
|
|
|
5109
5966
|
return { outcome: "cancelled" };
|
|
5110
5967
|
};
|
|
5111
5968
|
var reconcileDepositSpend = async (record, indexer) => {
|
|
5112
|
-
const offer = decodeOffer(
|
|
5969
|
+
const offer = decodeOffer(import_base15.hex.decode(record.offerHex));
|
|
5113
5970
|
const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
|
|
5114
5971
|
const all = vtxos ?? [];
|
|
5115
5972
|
const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
|
|
@@ -5121,12 +5978,12 @@ var reconcileDepositSpend = async (record, indexer) => {
|
|
|
5121
5978
|
const { txs } = await indexer.getVirtualTxs(candidates);
|
|
5122
5979
|
const parsed = txs.map((psbt) => {
|
|
5123
5980
|
try {
|
|
5124
|
-
return
|
|
5981
|
+
return import_sdk24.Transaction.fromPSBT(import_base15.base64.decode(psbt));
|
|
5125
5982
|
} catch {
|
|
5126
5983
|
return void 0;
|
|
5127
5984
|
}
|
|
5128
5985
|
}).filter((tx) => tx !== void 0);
|
|
5129
|
-
const operatorPubkey =
|
|
5986
|
+
const operatorPubkey = import_sdk24.ArkAddress.decode(record.swapAddress).serverPubKey;
|
|
5130
5987
|
const kind = classifyDepositSpend(offer, operatorPubkey, parsed, {
|
|
5131
5988
|
txid: deposit.txid,
|
|
5132
5989
|
vout: deposit.vout
|
|
@@ -5156,7 +6013,8 @@ var retireOfferScripts = async (wallet, repository, record) => {
|
|
|
5156
6013
|
await retireOfferContract(
|
|
5157
6014
|
await wallet.getContractManager(),
|
|
5158
6015
|
offer.map(offerFactsOf),
|
|
5159
|
-
record.swapPkScript
|
|
6016
|
+
record.swapPkScript,
|
|
6017
|
+
{ scope: wallet }
|
|
5160
6018
|
);
|
|
5161
6019
|
} catch (error) {
|
|
5162
6020
|
console.warn(`[swap] could not retire offer script for ${record.id}`, error);
|
|
@@ -5164,11 +6022,11 @@ var retireOfferScripts = async (wallet, repository, record) => {
|
|
|
5164
6022
|
};
|
|
5165
6023
|
|
|
5166
6024
|
// src/client/drive.ts
|
|
5167
|
-
var
|
|
5168
|
-
var
|
|
6025
|
+
var import_sdk30 = require("@arkade-os/sdk");
|
|
6026
|
+
var import_base18 = require("@scure/base");
|
|
5169
6027
|
|
|
5170
6028
|
// src/claim.ts
|
|
5171
|
-
var
|
|
6029
|
+
var import_sdk25 = require("@arkade-os/sdk");
|
|
5172
6030
|
init_onchainHtlc();
|
|
5173
6031
|
var LockupAmountMismatchError = class extends Error {
|
|
5174
6032
|
name = "LockupAmountMismatchError";
|
|
@@ -5201,8 +6059,8 @@ async function pushClaim(operator, input) {
|
|
|
5201
6059
|
assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
|
|
5202
6060
|
const serverUnrollScript = await operatorUnrollScript(operator, input.network);
|
|
5203
6061
|
const leaf = input.contract.claim();
|
|
5204
|
-
const txid = await (0,
|
|
5205
|
-
identity: (0,
|
|
6062
|
+
const txid = await (0, import_sdk25.signAndSubmitOffchainTx)({
|
|
6063
|
+
identity: (0, import_sdk25.claimWithPreimageIdentity)(input.receiver, input.preimage),
|
|
5206
6064
|
provider: operator,
|
|
5207
6065
|
inputs: lockupInputs(input.vtxos, input.contract, leaf),
|
|
5208
6066
|
// One aggregate output: this leaf inspects nothing about the output set.
|
|
@@ -5220,7 +6078,7 @@ init_offer();
|
|
|
5220
6078
|
init_lockupContract();
|
|
5221
6079
|
|
|
5222
6080
|
// src/refundBlocked.ts
|
|
5223
|
-
var
|
|
6081
|
+
var import_sdk26 = require("@arkade-os/sdk");
|
|
5224
6082
|
var RefundNotLocallyPossibleError = class extends Error {
|
|
5225
6083
|
constructor(reason, message, options) {
|
|
5226
6084
|
super(message, options);
|
|
@@ -5237,16 +6095,16 @@ async function senderIdentityForSwapRecord(wallet, record) {
|
|
|
5237
6095
|
);
|
|
5238
6096
|
}
|
|
5239
6097
|
try {
|
|
5240
|
-
return await (0,
|
|
6098
|
+
return await (0, import_sdk26.contractSigner)(wallet, record.signingDescriptor);
|
|
5241
6099
|
} catch (cause) {
|
|
5242
|
-
if (cause instanceof
|
|
6100
|
+
if (cause instanceof import_sdk26.WalletCannotSignError) {
|
|
5243
6101
|
throw new RefundNotLocallyPossibleError(
|
|
5244
6102
|
"unsignable-wallet",
|
|
5245
6103
|
`this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
|
|
5246
6104
|
{ cause }
|
|
5247
6105
|
);
|
|
5248
6106
|
}
|
|
5249
|
-
if (cause instanceof
|
|
6107
|
+
if (cause instanceof import_sdk26.ForeignDescriptorError) {
|
|
5250
6108
|
throw new RefundNotLocallyPossibleError(
|
|
5251
6109
|
"foreign-descriptor",
|
|
5252
6110
|
`this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
|
|
@@ -5258,6 +6116,7 @@ async function senderIdentityForSwapRecord(wallet, record) {
|
|
|
5258
6116
|
}
|
|
5259
6117
|
|
|
5260
6118
|
// src/arkadeRefunder.ts
|
|
6119
|
+
init_rfqProfileParts();
|
|
5261
6120
|
function arkadeRefunder(deps) {
|
|
5262
6121
|
return async (swap) => {
|
|
5263
6122
|
const contract = swap.lockup?.script;
|
|
@@ -5286,12 +6145,13 @@ function arkadeRefunder(deps) {
|
|
|
5286
6145
|
}
|
|
5287
6146
|
|
|
5288
6147
|
// src/client/drive.ts
|
|
6148
|
+
init_rfqProfileParts();
|
|
5289
6149
|
init_store();
|
|
5290
6150
|
init_repository();
|
|
5291
6151
|
|
|
5292
6152
|
// src/swapManager.ts
|
|
5293
|
-
var
|
|
5294
|
-
var
|
|
6153
|
+
var import_base16 = require("@scure/base");
|
|
6154
|
+
var import_sdk27 = require("@arkade-os/sdk");
|
|
5295
6155
|
init_onchainHtlc();
|
|
5296
6156
|
init_lockupContract();
|
|
5297
6157
|
init_repository();
|
|
@@ -5422,7 +6282,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5422
6282
|
timer = null;
|
|
5423
6283
|
running = false;
|
|
5424
6284
|
constructor(deps, config = {}) {
|
|
5425
|
-
(0,
|
|
6285
|
+
(0, import_sdk27.assertTimerMs)("pollIntervalMs", config.pollIntervalMs);
|
|
5426
6286
|
this.deps = deps;
|
|
5427
6287
|
this.config = {
|
|
5428
6288
|
enableAutoActions: config.enableAutoActions ?? true,
|
|
@@ -5737,13 +6597,13 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5737
6597
|
// ── internals ────────────────────────────────────────────────────────────
|
|
5738
6598
|
track(swap) {
|
|
5739
6599
|
this.monitored.set(swap.rfqId, swap);
|
|
5740
|
-
this.byLockupScript.set(
|
|
6600
|
+
this.byLockupScript.set(import_base16.hex.encode(swap.lockupPkScript), swap);
|
|
5741
6601
|
}
|
|
5742
6602
|
/** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
|
|
5743
6603
|
* event, deliberately redundant so neither change alone re-drives a removed swap. */
|
|
5744
6604
|
untrack(rfqId) {
|
|
5745
6605
|
const swap = this.monitored.get(rfqId);
|
|
5746
|
-
if (swap) this.byLockupScript.delete(
|
|
6606
|
+
if (swap) this.byLockupScript.delete(import_base16.hex.encode(swap.lockupPkScript));
|
|
5747
6607
|
this.monitored.delete(rfqId);
|
|
5748
6608
|
this.refundRefused.delete(rfqId);
|
|
5749
6609
|
this.claimedOutpoints.delete(rfqId);
|
|
@@ -5766,7 +6626,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5766
6626
|
});
|
|
5767
6627
|
return;
|
|
5768
6628
|
}
|
|
5769
|
-
if (!(0,
|
|
6629
|
+
if (!(0, import_sdk27.isContractVtxoEvent)(event)) return;
|
|
5770
6630
|
const swap = this.byLockupScript.get(event.contractScript);
|
|
5771
6631
|
if (!swap) return;
|
|
5772
6632
|
void this.pollSwap(swap).catch(() => {
|
|
@@ -5789,7 +6649,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5789
6649
|
if (!lockup) {
|
|
5790
6650
|
try {
|
|
5791
6651
|
const [existing] = await contracts.getContracts({
|
|
5792
|
-
script:
|
|
6652
|
+
script: import_base16.hex.encode(swap.lockupPkScript)
|
|
5793
6653
|
});
|
|
5794
6654
|
if (existing) {
|
|
5795
6655
|
this.registered.set(swap.rfqId, true);
|
|
@@ -5808,13 +6668,13 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5808
6668
|
);
|
|
5809
6669
|
return;
|
|
5810
6670
|
}
|
|
5811
|
-
const script =
|
|
5812
|
-
if (script !==
|
|
6671
|
+
const script = import_base16.hex.encode(lockup.script.pkScript);
|
|
6672
|
+
if (script !== import_base16.hex.encode(swap.lockupPkScript)) {
|
|
5813
6673
|
this.registered.set(swap.rfqId, false);
|
|
5814
6674
|
this.emitFailed(
|
|
5815
6675
|
swap,
|
|
5816
6676
|
new Error(
|
|
5817
|
-
`swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${
|
|
6677
|
+
`swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${import_base16.hex.encode(swap.lockupPkScript)}`
|
|
5818
6678
|
)
|
|
5819
6679
|
);
|
|
5820
6680
|
return;
|
|
@@ -5831,7 +6691,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5831
6691
|
retireContract(swap) {
|
|
5832
6692
|
if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
|
|
5833
6693
|
if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
|
|
5834
|
-
void this.deps.contracts.setContractWatchState(
|
|
6694
|
+
void this.deps.contracts.setContractWatchState(import_base16.hex.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
|
|
5835
6695
|
}
|
|
5836
6696
|
arm() {
|
|
5837
6697
|
if (!this.running) return;
|
|
@@ -5994,8 +6854,8 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5994
6854
|
this.setState(swap, "claimed");
|
|
5995
6855
|
this.emitAction(swap, "claimLockup");
|
|
5996
6856
|
} catch (error) {
|
|
5997
|
-
const ark = (0,
|
|
5998
|
-
if ((0,
|
|
6857
|
+
const ark = (0, import_sdk27.isArkError)(error) ? error : (0, import_sdk27.maybeArkError)(error);
|
|
6858
|
+
if ((0, import_sdk27.isArkError)(ark, import_sdk27.ArkErrorName.VTXO_ALREADY_SPENT)) {
|
|
5999
6859
|
if (swap.claimFailure !== void 0) {
|
|
6000
6860
|
delete swap.claimFailure;
|
|
6001
6861
|
this.touch(swap);
|
|
@@ -6272,7 +7132,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
6272
7132
|
*/
|
|
6273
7133
|
stampSettlementPreimage(swap, preimage) {
|
|
6274
7134
|
if (swap.kind !== "lightning_send") return;
|
|
6275
|
-
swap.settlementPreimageHex =
|
|
7135
|
+
swap.settlementPreimageHex = import_base16.hex.encode(preimage);
|
|
6276
7136
|
this.touch(swap);
|
|
6277
7137
|
}
|
|
6278
7138
|
touch(swap) {
|
|
@@ -6395,8 +7255,8 @@ var errorMessage = (error) => error instanceof Error ? error.message : String(er
|
|
|
6395
7255
|
var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
|
|
6396
7256
|
|
|
6397
7257
|
// src/watch.ts
|
|
6398
|
-
var
|
|
6399
|
-
var
|
|
7258
|
+
var import_base17 = require("@scure/base");
|
|
7259
|
+
var import_sdk28 = require("@arkade-os/sdk");
|
|
6400
7260
|
init_coverage();
|
|
6401
7261
|
init_offer();
|
|
6402
7262
|
init_store();
|
|
@@ -6431,7 +7291,7 @@ async function watchOfferSwaps({
|
|
|
6431
7291
|
wallet.getAddress(),
|
|
6432
7292
|
wallet.getArkadeReader()
|
|
6433
7293
|
]);
|
|
6434
|
-
const operatorPubkey =
|
|
7294
|
+
const operatorPubkey = import_sdk28.ArkAddress.decode(address).serverPubKey;
|
|
6435
7295
|
let queue = Promise.resolve();
|
|
6436
7296
|
const enqueue = (task) => {
|
|
6437
7297
|
queue = queue.then(task).catch(() => {
|
|
@@ -6444,9 +7304,9 @@ async function watchOfferSwaps({
|
|
|
6444
7304
|
if (candidates.length === 0) return "indeterminate";
|
|
6445
7305
|
const { txs } = await indexer.getVirtualTxs(candidates);
|
|
6446
7306
|
return classifyDepositSpend(
|
|
6447
|
-
decodeOffer(
|
|
7307
|
+
decodeOffer(import_base17.hex.decode(swap.offerHex)),
|
|
6448
7308
|
operatorPubkey,
|
|
6449
|
-
txs.map((psbt) =>
|
|
7309
|
+
txs.map((psbt) => import_sdk28.Transaction.fromPSBT(import_base17.base64.decode(psbt))),
|
|
6450
7310
|
{ txid: vtxo.txid, vout: vtxo.vout }
|
|
6451
7311
|
);
|
|
6452
7312
|
} catch {
|
|
@@ -6469,12 +7329,12 @@ async function watchOfferSwaps({
|
|
|
6469
7329
|
if (!persisted) continue;
|
|
6470
7330
|
onUpdate?.(swaps.find((s) => s.id === swap.id) ?? swap);
|
|
6471
7331
|
if (changes.status && RETIRABLE.includes(changes.status)) {
|
|
6472
|
-
await retireOfferContract(manager, swaps, event.contractScript);
|
|
7332
|
+
await retireOfferContract(manager, swaps, event.contractScript, { scope: wallet });
|
|
6473
7333
|
}
|
|
6474
7334
|
}
|
|
6475
7335
|
};
|
|
6476
7336
|
const unsubscribe = manager.onContractEvent((event) => {
|
|
6477
|
-
if (!(0,
|
|
7337
|
+
if (!(0, import_sdk28.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
|
|
6478
7338
|
enqueue(() => handleSpend(event));
|
|
6479
7339
|
});
|
|
6480
7340
|
return {
|
|
@@ -6484,7 +7344,7 @@ async function watchOfferSwaps({
|
|
|
6484
7344
|
}
|
|
6485
7345
|
|
|
6486
7346
|
// src/client/legacyRecords.ts
|
|
6487
|
-
var
|
|
7347
|
+
var import_sdk29 = require("@arkade-os/sdk");
|
|
6488
7348
|
init_repository();
|
|
6489
7349
|
var readLegacyRfqSwaps = async (repository, filter = {}) => {
|
|
6490
7350
|
try {
|
|
@@ -6501,7 +7361,7 @@ var withLegacyRfqSwaps = (bridge, repository, admits) => {
|
|
|
6501
7361
|
index: bridge.index,
|
|
6502
7362
|
quoteIdOf: bridge.quoteIdOf,
|
|
6503
7363
|
async getRfqSwapsPage(filter, page) {
|
|
6504
|
-
(0,
|
|
7364
|
+
(0, import_sdk29.assertPageRequest)(page);
|
|
6505
7365
|
assertRfqSwapPageFilter(filter);
|
|
6506
7366
|
const v2 = await collectRfqSwaps(bridge, filter);
|
|
6507
7367
|
const held = new Set(
|
|
@@ -6577,6 +7437,13 @@ var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
|
|
|
6577
7437
|
var traderClaimTxid2 = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
|
|
6578
7438
|
var readableRecord = (record) => {
|
|
6579
7439
|
if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
|
|
7440
|
+
if (record.assetPayment !== void 0) {
|
|
7441
|
+
try {
|
|
7442
|
+
assetPaymentOf(record.assetPayment, record.expiresAt);
|
|
7443
|
+
} catch {
|
|
7444
|
+
return false;
|
|
7445
|
+
}
|
|
7446
|
+
}
|
|
6580
7447
|
if (record.family === "rfq") {
|
|
6581
7448
|
return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
|
|
6582
7449
|
}
|
|
@@ -6654,6 +7521,7 @@ var createSwapDrive = (config) => {
|
|
|
6654
7521
|
return traderClaimTxid2(swap) ? "claimed" : "pending";
|
|
6655
7522
|
};
|
|
6656
7523
|
const outcomeOfEntry = (record, current) => {
|
|
7524
|
+
if (fundingWasNotSubmitted(record)) return "cancelled";
|
|
6657
7525
|
if (record.family === "offer") return recordOutcome(record);
|
|
6658
7526
|
if (current === void 0) {
|
|
6659
7527
|
if (isRfqSwapTerminal(record.state)) return corridorOutcome(record.kind, record.state);
|
|
@@ -6681,7 +7549,7 @@ var createSwapDrive = (config) => {
|
|
|
6681
7549
|
};
|
|
6682
7550
|
const updateFor = (id) => {
|
|
6683
7551
|
const record = records.get(id);
|
|
6684
|
-
if (record === void 0) return void 0;
|
|
7552
|
+
if (record === void 0 || !readableRecord(record)) return void 0;
|
|
6685
7553
|
const current = live.get(id);
|
|
6686
7554
|
const outcome = outcomeOfEntry(record, current);
|
|
6687
7555
|
return {
|
|
@@ -6740,10 +7608,10 @@ var createSwapDrive = (config) => {
|
|
|
6740
7608
|
const secret = rfqClaimSecretOf(record);
|
|
6741
7609
|
if (!secret) throw new Error(`rfq swap ${swap.rfqId} carries no claim secret`);
|
|
6742
7610
|
const preimage = await preimageForSwapRecord(wallet, secret);
|
|
6743
|
-
const signer = await (0,
|
|
7611
|
+
const signer = await (0, import_sdk30.contractSigner)(wallet, await (0, import_sdk30.identityDescriptor)(wallet.identity));
|
|
6744
7612
|
const claimKey = record.profile.claimKey;
|
|
6745
7613
|
if (typeof claimKey === "string") {
|
|
6746
|
-
const held =
|
|
7614
|
+
const held = import_base18.hex.encode(await signer.xOnlyPublicKey());
|
|
6747
7615
|
if (held !== claimKey) {
|
|
6748
7616
|
throw new Error(
|
|
6749
7617
|
`this wallet's identity key ${held} is not the payout key ${claimKey} rfq swap ${swap.rfqId} was quoted against \u2014 a wrong seed, or key provisioning has drifted from the identity key`
|
|
@@ -6778,8 +7646,8 @@ var createSwapDrive = (config) => {
|
|
|
6778
7646
|
`rfq swap ${swap.rfqId} carries no refund descriptor; wire the onchain corridor's refund callback to take its L1 funding back`
|
|
6779
7647
|
);
|
|
6780
7648
|
}
|
|
6781
|
-
const signer = await (0,
|
|
6782
|
-
const held =
|
|
7649
|
+
const signer = await (0, import_sdk30.contractSigner)(wallet, descriptor);
|
|
7650
|
+
const held = import_base18.hex.encode(await signer.xOnlyPublicKey());
|
|
6783
7651
|
if (held !== record.profile.refundKey) {
|
|
6784
7652
|
throw new Error(
|
|
6785
7653
|
`the key behind ${descriptor} is ${held}, not the refund key ${String(record.profile.refundKey)} rfq swap ${swap.rfqId}'s HTLC was derived with`
|
|
@@ -6818,7 +7686,7 @@ var createSwapDrive = (config) => {
|
|
|
6818
7686
|
}
|
|
6819
7687
|
};
|
|
6820
7688
|
const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
|
|
6821
|
-
const pinnedNetwork = async () => (0,
|
|
7689
|
+
const pinnedNetwork = async () => (0, import_sdk30.getNetwork)(await config.network());
|
|
6822
7690
|
const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
|
|
6823
7691
|
const record = await corridorStore().getRfqSwap(swap.rfqId);
|
|
6824
7692
|
if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
|
|
@@ -6833,10 +7701,10 @@ var createSwapDrive = (config) => {
|
|
|
6833
7701
|
return track(
|
|
6834
7702
|
pushClaim(operator, {
|
|
6835
7703
|
contract: script,
|
|
6836
|
-
receiver: await (0,
|
|
7704
|
+
receiver: await (0, import_sdk30.contractSigner)(wallet, secret.signingDescriptor),
|
|
6837
7705
|
preimage: await preimageForSwapRecord(wallet, secret),
|
|
6838
7706
|
vtxos,
|
|
6839
|
-
destinationPkScript:
|
|
7707
|
+
destinationPkScript: import_sdk30.ArkAddress.decode(payoutAddress).pkScript,
|
|
6840
7708
|
// Passed through: `pushClaim`'s own value check decides whether `P` is published.
|
|
6841
7709
|
expectedAmount: swap.expectedAmount,
|
|
6842
7710
|
partiallyClaimed,
|
|
@@ -6904,7 +7772,7 @@ var createSwapDrive = (config) => {
|
|
|
6904
7772
|
config.network()
|
|
6905
7773
|
]);
|
|
6906
7774
|
const txs = history.map(toRestoreTx);
|
|
6907
|
-
const { hrp, serverPubKey: operatorPubkey } =
|
|
7775
|
+
const { hrp, serverPubKey: operatorPubkey } = import_sdk30.ArkAddress.decode(address);
|
|
6908
7776
|
const reopened = await legacyOfferDepositsToAdopt(store);
|
|
6909
7777
|
for (const txid of reopen) reopened.add(txid);
|
|
6910
7778
|
const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
|
|
@@ -6954,7 +7822,9 @@ var createSwapDrive = (config) => {
|
|
|
6954
7822
|
await store.markTxidsScanned(scannedTxids.filter((txid) => !stillLive.has(txid)));
|
|
6955
7823
|
const registry = managerDeps.contracts;
|
|
6956
7824
|
if (registry) {
|
|
6957
|
-
await retireSettledOfferContracts(registry, [...current.values()].map(offerFactsOf)
|
|
7825
|
+
await retireSettledOfferContracts(registry, [...current.values()].map(offerFactsOf), {
|
|
7826
|
+
scope: wallet
|
|
7827
|
+
});
|
|
6958
7828
|
}
|
|
6959
7829
|
return [...current.values()];
|
|
6960
7830
|
};
|
|
@@ -6963,6 +7833,7 @@ var createSwapDrive = (config) => {
|
|
|
6963
7833
|
getContractsWithVtxos: async (filter) => (await contractsOf()).getContractsWithVtxos(filter)
|
|
6964
7834
|
};
|
|
6965
7835
|
const registerCorridorSwap = async (record) => {
|
|
7836
|
+
if (fundingWasNotSubmitted(record)) return;
|
|
6966
7837
|
if (mode === "readonly") return;
|
|
6967
7838
|
if (!await drivable(record)) {
|
|
6968
7839
|
undrivable.add(record.id);
|
|
@@ -7044,7 +7915,23 @@ var createSwapDrive = (config) => {
|
|
|
7044
7915
|
await adoptLegacyRfqSwaps(repository);
|
|
7045
7916
|
const all = await collectSwapRecords(repository);
|
|
7046
7917
|
const { corridor, offer } = splitRecords(all.filter(readableRecord));
|
|
7047
|
-
|
|
7918
|
+
const retiredScripts = /* @__PURE__ */ new Set();
|
|
7919
|
+
for (const record of [...corridor, ...offer]) {
|
|
7920
|
+
records.set(record.id, record);
|
|
7921
|
+
if (mode !== "readonly" && fundingWasNotSubmitted(record)) {
|
|
7922
|
+
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
7923
|
+
if (retiredScripts.has(script)) continue;
|
|
7924
|
+
retiredScripts.add(script);
|
|
7925
|
+
try {
|
|
7926
|
+
await retireUnsubmittedFunding(wallet, repository, record, await contractsOf());
|
|
7927
|
+
} catch (error) {
|
|
7928
|
+
console.warn(
|
|
7929
|
+
`[swap] could not restore unsent coverage for ${record.id}`,
|
|
7930
|
+
error
|
|
7931
|
+
);
|
|
7932
|
+
}
|
|
7933
|
+
}
|
|
7934
|
+
}
|
|
7048
7935
|
const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
|
|
7049
7936
|
const store = corridorStore();
|
|
7050
7937
|
for (const record of liveCorridor) store.index(record);
|
|
@@ -7138,7 +8025,7 @@ var createSwapDrive = (config) => {
|
|
|
7138
8025
|
id
|
|
7139
8026
|
);
|
|
7140
8027
|
}
|
|
7141
|
-
const script =
|
|
8028
|
+
const script = import_base18.hex.decode(record.lockupPkScript);
|
|
7142
8029
|
const before = await recoverableAt(script);
|
|
7143
8030
|
if (before.length === 0) {
|
|
7144
8031
|
throw new SwapDriveRefusedError(
|
|
@@ -7241,6 +8128,10 @@ var createSwapDrive = (config) => {
|
|
|
7241
8128
|
adopt: (record) => {
|
|
7242
8129
|
if (disposed) throw new ClientDisposed("accept");
|
|
7243
8130
|
records.set(record.id, record);
|
|
8131
|
+
if (fundingWasNotSubmitted(record)) {
|
|
8132
|
+
emit(record.id);
|
|
8133
|
+
return swapView(record.id);
|
|
8134
|
+
}
|
|
7244
8135
|
if (record.family === "rfq") {
|
|
7245
8136
|
corridorStore().index(record);
|
|
7246
8137
|
managerDeps.repository = corridorStore();
|
|
@@ -7260,24 +8151,24 @@ var createSwapDrive = (config) => {
|
|
|
7260
8151
|
};
|
|
7261
8152
|
|
|
7262
8153
|
// src/client/quoteOffer.ts
|
|
7263
|
-
var
|
|
8154
|
+
var import_solver_discovery11 = require("@arkade-os/solver-discovery");
|
|
7264
8155
|
init_offer();
|
|
7265
8156
|
|
|
7266
8157
|
// src/client/market.ts
|
|
7267
|
-
var
|
|
8158
|
+
var import_solver_discovery10 = require("@arkade-os/solver-discovery");
|
|
7268
8159
|
var marketKeyOf = (card) => {
|
|
7269
|
-
const base = (0,
|
|
7270
|
-
const quote = (0,
|
|
7271
|
-
const baseIsArkade = (0,
|
|
7272
|
-
const quoteIsArkade = (0,
|
|
8160
|
+
const base = (0, import_solver_discovery10.marketLegKey)(card, "base");
|
|
8161
|
+
const quote = (0, import_solver_discovery10.marketLegKey)(card, "quote");
|
|
8162
|
+
const baseIsArkade = (0, import_solver_discovery10.marketCorridor)(card, "base") === "arkade";
|
|
8163
|
+
const quoteIsArkade = (0, import_solver_discovery10.marketCorridor)(card, "quote") === "arkade";
|
|
7273
8164
|
if (baseIsArkade !== quoteIsArkade) {
|
|
7274
8165
|
return baseIsArkade ? `${base}/${quote}` : `${quote}/${base}`;
|
|
7275
8166
|
}
|
|
7276
8167
|
return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
|
|
7277
8168
|
};
|
|
7278
8169
|
var hasRendezvous = (card) => typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
|
|
7279
|
-
var isAddressable = (card) => !(0,
|
|
7280
|
-
var marketBackendOf = (card) => (0,
|
|
8170
|
+
var isAddressable = (card) => !(0, import_solver_discovery10.isRfqMarket)(card) || hasRendezvous(card);
|
|
8171
|
+
var marketBackendOf = (card) => (0, import_solver_discovery10.isRfqMarket)(card) || hasRendezvous(card) ? "rfq" : "feed";
|
|
7281
8172
|
var usableMarkets = (snapshot, policy) => {
|
|
7282
8173
|
const allowed = policy?.allowedRegistries;
|
|
7283
8174
|
return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
|
|
@@ -7294,12 +8185,12 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
|
|
|
7294
8185
|
wantSide: side === "base" ? "quote" : "base",
|
|
7295
8186
|
...takeAmount === void 0 ? {} : { wantAmount: takeAmount }
|
|
7296
8187
|
};
|
|
7297
|
-
const canonical = (0,
|
|
8188
|
+
const canonical = (0, import_solver_discovery10.selectMarkets)([...markets], {
|
|
7298
8189
|
baseId: base.marketId,
|
|
7299
8190
|
quoteId: quote.marketId,
|
|
7300
8191
|
...selection
|
|
7301
8192
|
});
|
|
7302
|
-
const legacy = (0,
|
|
8193
|
+
const legacy = (0, import_solver_discovery10.selectMarkets)([...markets], {
|
|
7303
8194
|
baseId: `${base.corridor}:${base.assetId}`,
|
|
7304
8195
|
quoteId: `${quote.corridor}:${quote.assetId}`,
|
|
7305
8196
|
...selection
|
|
@@ -7358,16 +8249,16 @@ var assembleRoute = (give, take) => {
|
|
|
7358
8249
|
}
|
|
7359
8250
|
return { give, take };
|
|
7360
8251
|
};
|
|
7361
|
-
var endpoint = (corridor,
|
|
8252
|
+
var endpoint = (corridor, asset8, instrument) => ({
|
|
7362
8253
|
corridor,
|
|
7363
|
-
asset:
|
|
8254
|
+
asset: asset8,
|
|
7364
8255
|
...instrument === void 0 ? {} : { instrument }
|
|
7365
8256
|
});
|
|
7366
|
-
var legFor = (
|
|
7367
|
-
const leg = toDiscoveryLeg(
|
|
8257
|
+
var legFor = (asset8, expected) => {
|
|
8258
|
+
const leg = toDiscoveryLeg(asset8);
|
|
7368
8259
|
if (expected !== void 0 && leg.corridor !== expected) {
|
|
7369
8260
|
throw new UnsupportedRoute(
|
|
7370
|
-
`${
|
|
8261
|
+
`${asset8} settles on ${leg.corridor}, and this leg is ${expected}`,
|
|
7371
8262
|
{ give: leg.corridor, take: expected }
|
|
7372
8263
|
);
|
|
7373
8264
|
}
|
|
@@ -7704,7 +8595,7 @@ var quoteFromFeed = async (input) => {
|
|
|
7704
8595
|
if (amount === void 0) {
|
|
7705
8596
|
throw new Error("an asset swap needs an amount and the side it pins");
|
|
7706
8597
|
}
|
|
7707
|
-
const plan = await (0,
|
|
8598
|
+
const plan = await (0, import_solver_discovery11.quoteOffer)(candidate.card, {
|
|
7708
8599
|
give: candidate.give,
|
|
7709
8600
|
...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
|
|
7710
8601
|
// What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
|
|
@@ -7748,7 +8639,7 @@ var quoteFromFeed = async (input) => {
|
|
|
7748
8639
|
};
|
|
7749
8640
|
var feedSpread = (plan, take, carrierSats = 0n) => {
|
|
7750
8641
|
const payout = take > carrierSats ? take - carrierSats : 0n;
|
|
7751
|
-
const fair = (0,
|
|
8642
|
+
const fair = (0, import_solver_discovery11.computeWantAmount)({
|
|
7752
8643
|
deposit: plan.deposit.atomic,
|
|
7753
8644
|
give: plan.give,
|
|
7754
8645
|
price: plan.price,
|
|
@@ -7766,7 +8657,7 @@ var feedExpiry = (card, feed, now) => {
|
|
|
7766
8657
|
};
|
|
7767
8658
|
var verifyPlanLegs = (plan, legs, give) => {
|
|
7768
8659
|
const take = give === "base" ? "quote" : "base";
|
|
7769
|
-
const spelled = (side) => (0,
|
|
8660
|
+
const spelled = (side) => (0, import_solver_discovery11.marketLegKey)(plan.market, side);
|
|
7770
8661
|
const names = (side, leg) => spelled(side) === leg.marketId || spelled(side) === `${leg.corridor}:${leg.assetId}`;
|
|
7771
8662
|
if (plan.give !== give || !names(give, legs.give) || !names(take, legs.take)) {
|
|
7772
8663
|
throw new QuoteVerificationFailed(
|
|
@@ -7778,9 +8669,93 @@ var verifyPlanLegs = (plan, legs, give) => {
|
|
|
7778
8669
|
};
|
|
7779
8670
|
|
|
7780
8671
|
// src/client/quoteRfq.ts
|
|
7781
|
-
var
|
|
8672
|
+
var import_base20 = require("@scure/base");
|
|
8673
|
+
var import_sdk34 = require("@arkade-os/sdk");
|
|
8674
|
+
var import_solver_discovery12 = require("@arkade-os/solver-discovery");
|
|
8675
|
+
|
|
8676
|
+
// src/jointGraph.ts
|
|
8677
|
+
var import_base19 = require("@scure/base");
|
|
8678
|
+
var import_sha26 = require("@noble/hashes/sha2.js");
|
|
7782
8679
|
var import_sdk31 = require("@arkade-os/sdk");
|
|
7783
|
-
|
|
8680
|
+
function digestJointGraph(plan, template) {
|
|
8681
|
+
const parts = [];
|
|
8682
|
+
const pushU32 = (value) => {
|
|
8683
|
+
const len = new Uint8Array(4);
|
|
8684
|
+
new DataView(len.buffer).setUint32(0, value, false);
|
|
8685
|
+
parts.push(len);
|
|
8686
|
+
};
|
|
8687
|
+
const pushField = (bytes) => {
|
|
8688
|
+
pushU32(bytes.length);
|
|
8689
|
+
parts.push(bytes);
|
|
8690
|
+
};
|
|
8691
|
+
pushField(new TextEncoder().encode(template));
|
|
8692
|
+
pushField(unsignedPsbtBytes(parseGraphTx(plan.arkTx)));
|
|
8693
|
+
pushU32(plan.checkpoints.length);
|
|
8694
|
+
for (const checkpoint of plan.checkpoints) {
|
|
8695
|
+
pushField(unsignedPsbtBytes(parseGraphTx(checkpoint)));
|
|
8696
|
+
}
|
|
8697
|
+
pushU32(plan.inputOwners.length);
|
|
8698
|
+
for (const owner of plan.inputOwners) {
|
|
8699
|
+
if (owner === null) {
|
|
8700
|
+
parts.push(new Uint8Array([0]));
|
|
8701
|
+
} else {
|
|
8702
|
+
const bytes = new TextEncoder().encode(owner);
|
|
8703
|
+
parts.push(new Uint8Array([1]));
|
|
8704
|
+
pushField(bytes);
|
|
8705
|
+
}
|
|
8706
|
+
}
|
|
8707
|
+
const preimage = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
8708
|
+
let at2 = 0;
|
|
8709
|
+
for (const part of parts) {
|
|
8710
|
+
preimage.set(part, at2);
|
|
8711
|
+
at2 += part.length;
|
|
8712
|
+
}
|
|
8713
|
+
return import_base19.hex.encode((0, import_sha26.sha256)(preimage));
|
|
8714
|
+
}
|
|
8715
|
+
function verifyJointGraph(plan, template) {
|
|
8716
|
+
try {
|
|
8717
|
+
if (!plan || typeof plan !== "object") return false;
|
|
8718
|
+
if (typeof plan.arkTx !== "string" || plan.arkTx.length === 0) return false;
|
|
8719
|
+
if (!Array.isArray(plan.checkpoints) || plan.checkpoints.length < 1 || plan.checkpoints.some((c) => typeof c !== "string" || c.length === 0))
|
|
8720
|
+
return false;
|
|
8721
|
+
if (!/^[0-9a-f]{64}$/.test(plan.graphId)) return false;
|
|
8722
|
+
if (!Array.isArray(plan.inputOwners) || plan.inputOwners.some((o) => o !== null && (typeof o !== "string" || o.length === 0)))
|
|
8723
|
+
return false;
|
|
8724
|
+
if (plan.inputOwners.length !== plan.checkpoints.length) return false;
|
|
8725
|
+
const arkInputs = parseGraphTx(plan.arkTx).inputsLength;
|
|
8726
|
+
if (plan.checkpoints.length !== arkInputs) return false;
|
|
8727
|
+
if (plan.inputOwners.length !== arkInputs) return false;
|
|
8728
|
+
return digestJointGraph(
|
|
8729
|
+
{
|
|
8730
|
+
arkTx: plan.arkTx,
|
|
8731
|
+
checkpoints: [...plan.checkpoints],
|
|
8732
|
+
inputOwners: [...plan.inputOwners]
|
|
8733
|
+
},
|
|
8734
|
+
template
|
|
8735
|
+
) === plan.graphId;
|
|
8736
|
+
} catch {
|
|
8737
|
+
return false;
|
|
8738
|
+
}
|
|
8739
|
+
}
|
|
8740
|
+
function parseGraphTx(psbt) {
|
|
8741
|
+
return import_sdk31.Transaction.fromPSBT(import_base19.base64.decode(psbt));
|
|
8742
|
+
}
|
|
8743
|
+
function deepFreeze(value) {
|
|
8744
|
+
if (value !== null && typeof value === "object") {
|
|
8745
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
8746
|
+
Object.freeze(value);
|
|
8747
|
+
}
|
|
8748
|
+
return value;
|
|
8749
|
+
}
|
|
8750
|
+
function unsignedPsbtBytes(tx) {
|
|
8751
|
+
const stripped = tx.clone();
|
|
8752
|
+
for (let i = 0; i < stripped.inputsLength; i++) {
|
|
8753
|
+
stripped.updateInput(i, { tapScriptSig: void 0 });
|
|
8754
|
+
}
|
|
8755
|
+
return stripped.toPSBT();
|
|
8756
|
+
}
|
|
8757
|
+
|
|
8758
|
+
// src/client/quoteRfq.ts
|
|
7784
8759
|
init_claimPacket();
|
|
7785
8760
|
init_offer();
|
|
7786
8761
|
init_store();
|
|
@@ -7788,11 +8763,11 @@ init_onchainHtlc();
|
|
|
7788
8763
|
init_onchainHtlc();
|
|
7789
8764
|
|
|
7790
8765
|
// src/payment/onchainSwap.ts
|
|
7791
|
-
var
|
|
8766
|
+
var import_sdk33 = require("@arkade-os/sdk");
|
|
7792
8767
|
init_onchainHtlc();
|
|
7793
8768
|
|
|
7794
8769
|
// src/payment/swapRail.ts
|
|
7795
|
-
var
|
|
8770
|
+
var import_sdk32 = require("@arkade-os/sdk");
|
|
7796
8771
|
|
|
7797
8772
|
// src/client/sats.ts
|
|
7798
8773
|
var satsOf = (value, field) => {
|
|
@@ -7849,13 +8824,13 @@ var lockupOf = (derived) => ({
|
|
|
7849
8824
|
pkScript: derived.swapPkScript
|
|
7850
8825
|
});
|
|
7851
8826
|
var covenantInputs = (input) => {
|
|
7852
|
-
const network = (0,
|
|
8827
|
+
const network = (0, import_sdk34.networkFromArkadeInfo)(input.info);
|
|
7853
8828
|
const arkade2 = input.corridors.get("arkade").deps;
|
|
7854
8829
|
return {
|
|
7855
|
-
operatorPubkey: (0,
|
|
8830
|
+
operatorPubkey: (0, import_sdk34.toXOnly)(import_base20.hex.decode(input.info.signerPubkey), "ark signer key"),
|
|
7856
8831
|
// The resolved per-network pin, never operator-reported: it lands in a covenant leaf
|
|
7857
8832
|
// that decides who can move the funds.
|
|
7858
|
-
emulatorPubkey: (0,
|
|
8833
|
+
emulatorPubkey: (0, import_sdk34.toXOnly)(import_base20.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
|
|
7859
8834
|
claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
|
|
7860
8835
|
hrp: network.hrp
|
|
7861
8836
|
};
|
|
@@ -7863,7 +8838,7 @@ var covenantInputs = (input) => {
|
|
|
7863
8838
|
var sealingKey = (deps) => {
|
|
7864
8839
|
const configured = deps.covclaimd?.pubkey;
|
|
7865
8840
|
if (configured === void 0) return void 0;
|
|
7866
|
-
const key =
|
|
8841
|
+
const key = import_base20.hex.decode(configured);
|
|
7867
8842
|
if (key.length !== 33) {
|
|
7868
8843
|
throw new Error(
|
|
7869
8844
|
`the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
|
|
@@ -7883,6 +8858,8 @@ var quoteViaRfq = async (input) => {
|
|
|
7883
8858
|
expected: input.market.discoveryPubkey,
|
|
7884
8859
|
pinnable: input.market.snapshot.live
|
|
7885
8860
|
});
|
|
8861
|
+
if (input.assetPayment !== void 0 && input.route !== "arkade->arkade")
|
|
8862
|
+
throw new Error("assetPayment supports BTC-to-asset only");
|
|
7886
8863
|
switch (input.route) {
|
|
7887
8864
|
case "arkade->arkade":
|
|
7888
8865
|
return quoteArkadeAsset(input);
|
|
@@ -7898,12 +8875,12 @@ var quoteViaRfq = async (input) => {
|
|
|
7898
8875
|
};
|
|
7899
8876
|
var quoteArkadeAsset = async (input) => {
|
|
7900
8877
|
const pinned = pinnedFor(input);
|
|
7901
|
-
if (pinned.on !== "give") {
|
|
7902
|
-
throw new Error(
|
|
7903
|
-
"an asset swap is exact-in: pin the amount on the give leg. The legs carry different assets, so there is no spread to price a take-side pin back through \u2014 the solver answers `exact_out_unsupported`"
|
|
7904
|
-
);
|
|
7905
|
-
}
|
|
7906
8878
|
const sides = assetSidesOf(input.legs);
|
|
8879
|
+
if (pinned.on !== "give" && sides.wantAsset === void 0)
|
|
8880
|
+
throw new Error("asset-to-BTC is exact-in only");
|
|
8881
|
+
const payment = input.assetPayment;
|
|
8882
|
+
if (payment !== void 0 && sides.wantAsset === void 0)
|
|
8883
|
+
throw new Error("assetPayment supports BTC-to-asset only");
|
|
7907
8884
|
if (input.candidate.card.price_feed === void 0) {
|
|
7908
8885
|
throw new UnsupportedRoute(
|
|
7909
8886
|
`card ${input.candidate.card.solver} advertises no price feed to measure an asset swap's fee against`,
|
|
@@ -7913,15 +8890,43 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7913
8890
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
7914
8891
|
const rfqId = newRfqId();
|
|
7915
8892
|
const maker = await makerPosition(input.wallet);
|
|
7916
|
-
const
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
makerPublicKey: maker.publicKey
|
|
7923
|
-
})
|
|
8893
|
+
const receiveAddress = payment?.receiveAddress;
|
|
8894
|
+
const receivePkScript = resolveReceivePkScript(
|
|
8895
|
+
receiveAddress,
|
|
8896
|
+
maker.pkScript,
|
|
8897
|
+
(0, import_sdk34.networkFromArkadeInfo)(input.info).hrp,
|
|
8898
|
+
(0, import_sdk34.toXOnly)(import_base20.hex.decode(input.info.signerPubkey), "ark signer key")
|
|
7924
8899
|
);
|
|
8900
|
+
const choice = payment?.carrier;
|
|
8901
|
+
const carrierRequest = choice === void 0 ? void 0 : choice.mode === "purchase" ? { mode: "purchase" } : {
|
|
8902
|
+
mode: "recycle_receiver",
|
|
8903
|
+
quoteId: choice.quote.quoteId,
|
|
8904
|
+
taxiUrl: choice.taxi.url,
|
|
8905
|
+
taxiKey: choice.taxi.operatorKey
|
|
8906
|
+
};
|
|
8907
|
+
if (choice?.mode === "recycleReceiver") {
|
|
8908
|
+
if (choice.quote.assetId !== sides.wantAsset?.toString())
|
|
8909
|
+
throw new Error("carrier quote assetId differs from requested asset");
|
|
8910
|
+
if (choice.quote.senderKey !== import_base20.hex.encode(maker.publicKey))
|
|
8911
|
+
throw new Error("carrier quote senderKey differs from wallet identity");
|
|
8912
|
+
if (input.now >= choice.quote.expiresAt - 30)
|
|
8913
|
+
throw new Error("carrier quote expired before RFQ");
|
|
8914
|
+
}
|
|
8915
|
+
const request = arkadeSwapRequest({
|
|
8916
|
+
rfqId,
|
|
8917
|
+
...sides,
|
|
8918
|
+
amount: pinned.value,
|
|
8919
|
+
amountSide: toRfqAmountSide(pinned.on),
|
|
8920
|
+
makerPkScript: receivePkScript,
|
|
8921
|
+
makerPublicKey: maker.publicKey
|
|
8922
|
+
});
|
|
8923
|
+
const wire = await input.transport.requestQuote({
|
|
8924
|
+
...request,
|
|
8925
|
+
profile: {
|
|
8926
|
+
...request.profile,
|
|
8927
|
+
...carrierRequest === void 0 ? {} : { carrier: encodeCarrierRequest(carrierRequest) }
|
|
8928
|
+
}
|
|
8929
|
+
});
|
|
7925
8930
|
verifyPair(wire.pair, pair);
|
|
7926
8931
|
const parsed = parseRfqQuote(wire);
|
|
7927
8932
|
verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
|
|
@@ -7931,8 +8936,42 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7931
8936
|
now: input.now,
|
|
7932
8937
|
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
7933
8938
|
});
|
|
8939
|
+
let assetPayment;
|
|
8940
|
+
if (payment !== void 0) {
|
|
8941
|
+
let carrier;
|
|
8942
|
+
if (carrierRequest !== void 0) {
|
|
8943
|
+
carrier = parseCarrierEcho(wire.profile?.carrier, carrierRequest);
|
|
8944
|
+
if (carrier.physicalSats !== input.info.dust)
|
|
8945
|
+
throw new Error("carrier physical differs from server dust");
|
|
8946
|
+
if (carrier.expiresAt > parsed.validUntil)
|
|
8947
|
+
throw new Error("carrier echo extends solver expiry");
|
|
8948
|
+
if (choice?.mode === "recycleReceiver") {
|
|
8949
|
+
if (wire.carrier_sats !== void 0)
|
|
8950
|
+
throw new Error("receiver-paid quote must publish no carrier_sats");
|
|
8951
|
+
assertReceiverPaidEchoMatchesExpected(carrier, choice.quote);
|
|
8952
|
+
} else if (parseTopLevelCarrierSats(wire.carrier_sats) !== carrier.physicalSats)
|
|
8953
|
+
throw new Error("carrier echo differs from carrier_sats");
|
|
8954
|
+
}
|
|
8955
|
+
const validUntil = Math.min(
|
|
8956
|
+
parsed.validUntil,
|
|
8957
|
+
carrier?.expiresAt ?? parsed.validUntil,
|
|
8958
|
+
choice?.mode === "recycleReceiver" ? choice.quote.expiresAt : parsed.validUntil
|
|
8959
|
+
) - 30;
|
|
8960
|
+
if (input.now >= validUntil) throw new Error("asset payment terms lapsed before funding");
|
|
8961
|
+
assetPayment = {
|
|
8962
|
+
receiveAddress: receiveAddress ?? new import_sdk34.ArkAddress(
|
|
8963
|
+
(0, import_sdk34.toXOnly)(import_base20.hex.decode(input.info.signerPubkey), "ark signer key"),
|
|
8964
|
+
maker.pkScript.slice(2),
|
|
8965
|
+
(0, import_sdk34.networkFromArkadeInfo)(input.info).hrp
|
|
8966
|
+
).encode(),
|
|
8967
|
+
validUntil,
|
|
8968
|
+
...carrier === void 0 ? {} : { carrier },
|
|
8969
|
+
...choice?.mode !== "recycleReceiver" || choice.inputExpiryFloor === void 0 ? {} : { inputExpiryFloor: choice.inputExpiryFloor }
|
|
8970
|
+
};
|
|
8971
|
+
}
|
|
8972
|
+
if (assetPayment !== void 0) deepFreeze(assetPayment);
|
|
7934
8973
|
const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
|
|
7935
|
-
const reference = await (0,
|
|
8974
|
+
const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
|
|
7936
8975
|
give: input.candidate.give,
|
|
7937
8976
|
giveAmount: parsed.give,
|
|
7938
8977
|
...carrierSats === void 0 ? {} : { carrierSats },
|
|
@@ -7947,15 +8986,20 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7947
8986
|
...terms.offerAsset === void 0 ? {} : { offerAsset: terms.offerAsset },
|
|
7948
8987
|
emulatorPubkey: input.corridors.get("arkade").deps.emulatorPubkey,
|
|
7949
8988
|
maker,
|
|
8989
|
+
...receiveAddress === void 0 ? {} : { receiveAddress },
|
|
7950
8990
|
info: input.info
|
|
7951
8991
|
});
|
|
7952
8992
|
verifyingDerivation(() => verifyOfferAddress(wire, offer));
|
|
7953
8993
|
return {
|
|
7954
8994
|
quote: {
|
|
7955
8995
|
id: input.quoteId,
|
|
8996
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
7956
8997
|
route: assembleRoute(
|
|
7957
8998
|
{ ...input.endpoints.give, instrument: { kind: "wallet" } },
|
|
7958
|
-
{
|
|
8999
|
+
{
|
|
9000
|
+
...input.endpoints.take,
|
|
9001
|
+
instrument: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
9002
|
+
}
|
|
7959
9003
|
),
|
|
7960
9004
|
give: { asset: input.endpoints.give.asset, amount: parsed.give },
|
|
7961
9005
|
take: { asset: input.endpoints.take.asset, amount: parsed.take },
|
|
@@ -7975,6 +9019,10 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7975
9019
|
rfqId,
|
|
7976
9020
|
wire: parsed,
|
|
7977
9021
|
offer,
|
|
9022
|
+
...assetPayment === void 0 ? {} : {
|
|
9023
|
+
assetPayment,
|
|
9024
|
+
assetPaymentRecipient: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
9025
|
+
},
|
|
7978
9026
|
...carrierSats === void 0 ? {} : { carrierSats }
|
|
7979
9027
|
}
|
|
7980
9028
|
};
|
|
@@ -7994,14 +9042,14 @@ var assetSidesOf = (legs) => {
|
|
|
7994
9042
|
{ give: "arkade", take: "arkade" }
|
|
7995
9043
|
);
|
|
7996
9044
|
}
|
|
7997
|
-
return giveIsBtc ? { wantAsset:
|
|
9045
|
+
return giveIsBtc ? { wantAsset: import_sdk34.asset.AssetId.fromString(legs.take.assetId) } : { offerAsset: import_sdk34.asset.AssetId.fromString(legs.give.assetId) };
|
|
7998
9046
|
};
|
|
7999
9047
|
var makerPosition = async (wallet) => {
|
|
8000
9048
|
const [address, publicKey] = await Promise.all([
|
|
8001
9049
|
wallet.getAddress(),
|
|
8002
9050
|
wallet.identity.xOnlyPublicKey()
|
|
8003
9051
|
]);
|
|
8004
|
-
return { pkScript:
|
|
9052
|
+
return { pkScript: import_sdk34.ArkAddress.decode(address).pkScript, publicKey };
|
|
8005
9053
|
};
|
|
8006
9054
|
var quoteLightningSend = async (input) => {
|
|
8007
9055
|
const invoice = input.endpoints.take.instrument;
|
|
@@ -8010,7 +9058,7 @@ var quoteLightningSend = async (input) => {
|
|
|
8010
9058
|
}
|
|
8011
9059
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8012
9060
|
const rfqId = newRfqId();
|
|
8013
|
-
const secrets = await (0,
|
|
9061
|
+
const secrets = await (0, import_sdk34.provisionRefundKey)(input.wallet);
|
|
8014
9062
|
const wire = await input.transport.requestQuote(
|
|
8015
9063
|
lightningSendRequest({
|
|
8016
9064
|
rfqId,
|
|
@@ -8085,8 +9133,8 @@ var quoteLightningReceive = async (input) => {
|
|
|
8085
9133
|
const pinned = pinnedFor(input);
|
|
8086
9134
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8087
9135
|
const rfqId = newRfqId();
|
|
8088
|
-
const secrets = await (0,
|
|
8089
|
-
const paymentHash =
|
|
9136
|
+
const secrets = await (0, import_sdk34.provisionClaimSecret)(input.wallet);
|
|
9137
|
+
const paymentHash = import_base20.hex.encode(secrets.paymentHash);
|
|
8090
9138
|
const payoutAddress = await input.wallet.getAddress();
|
|
8091
9139
|
const lightning = input.corridors.get("lightning").deps;
|
|
8092
9140
|
const sealTo = sealingKey(lightning);
|
|
@@ -8197,9 +9245,9 @@ var quoteOnchainSend = async (input) => {
|
|
|
8197
9245
|
claimVsize: onchain.claimVsize
|
|
8198
9246
|
}) : void 0;
|
|
8199
9247
|
const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
|
|
8200
|
-
const secrets = await (0,
|
|
8201
|
-
const payoutKey = await (0,
|
|
8202
|
-
const paymentHash =
|
|
9248
|
+
const secrets = await (0, import_sdk34.provisionClaimSecret)(input.wallet);
|
|
9249
|
+
const payoutKey = await (0, import_sdk34.provisionRefundKey)(input.wallet);
|
|
9250
|
+
const paymentHash = import_base20.hex.encode(secrets.paymentHash);
|
|
8203
9251
|
const wire = await input.transport.requestQuote(
|
|
8204
9252
|
withCanonicalAmount(
|
|
8205
9253
|
onchainSendRequest({
|
|
@@ -8303,9 +9351,9 @@ var quoteOnchainReceive = async (input) => {
|
|
|
8303
9351
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8304
9352
|
const rfqId = newRfqId();
|
|
8305
9353
|
const l1Network = l1NetworkFromArk(input.info.network);
|
|
8306
|
-
const secrets = await (0,
|
|
8307
|
-
const refundKey = await (0,
|
|
8308
|
-
const paymentHash =
|
|
9354
|
+
const secrets = await (0, import_sdk34.provisionClaimSecret)(input.wallet);
|
|
9355
|
+
const refundKey = await (0, import_sdk34.provisionRefundKey)(input.wallet);
|
|
9356
|
+
const paymentHash = import_base20.hex.encode(secrets.paymentHash);
|
|
8309
9357
|
const payoutAddress = await input.wallet.getAddress();
|
|
8310
9358
|
const refundPkScript = l1ScriptForAddress(await input.wallet.getBoardingAddress(), l1Network);
|
|
8311
9359
|
const wire = await input.transport.requestQuote(
|
|
@@ -8412,7 +9460,7 @@ var quoteOnchainReceive = async (input) => {
|
|
|
8412
9460
|
};
|
|
8413
9461
|
|
|
8414
9462
|
// src/client/verbs.ts
|
|
8415
|
-
var
|
|
9463
|
+
var import_sdk35 = require("@arkade-os/sdk");
|
|
8416
9464
|
var enforceFeeCeiling = (quote, call, policy) => {
|
|
8417
9465
|
let ceiling;
|
|
8418
9466
|
for (const [source, limit] of [
|
|
@@ -8437,9 +9485,9 @@ var settle = async (deps, input, maxFee) => {
|
|
|
8437
9485
|
return deps.accept(quote);
|
|
8438
9486
|
};
|
|
8439
9487
|
var pay = async (deps, destination, options = {}) => {
|
|
8440
|
-
const arkade2 = (0,
|
|
9488
|
+
const arkade2 = (0, import_sdk35.arkTarget)(destination);
|
|
8441
9489
|
if (arkade2 !== void 0) {
|
|
8442
|
-
const amount = (0,
|
|
9490
|
+
const amount = (0, import_sdk35.resolveSendAmount)(
|
|
8443
9491
|
"ark",
|
|
8444
9492
|
destination,
|
|
8445
9493
|
options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
|
|
@@ -8502,7 +9550,7 @@ var nostrTransportFactory = async (rendezvous) => {
|
|
|
8502
9550
|
|
|
8503
9551
|
// src/client/client.ts
|
|
8504
9552
|
var PREPARATIONS_HELD = 64;
|
|
8505
|
-
var mintQuoteId = () =>
|
|
9553
|
+
var mintQuoteId = () => import_base21.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
|
|
8506
9554
|
var createSwapClient = (config) => {
|
|
8507
9555
|
const { wallet } = config;
|
|
8508
9556
|
const operator = config.operator ?? walletOperator(wallet);
|
|
@@ -8567,6 +9615,7 @@ var createSwapClient = (config) => {
|
|
|
8567
9615
|
return (await route(input, "resolve")).resolution;
|
|
8568
9616
|
},
|
|
8569
9617
|
quote: async (input) => {
|
|
9618
|
+
const assetPayment = captureAssetPayment(input.assetPayment);
|
|
8570
9619
|
ensureLive("quote");
|
|
8571
9620
|
const { corridors, discovery } = await resolved();
|
|
8572
9621
|
let resolvedRoute = await route(input, "quote");
|
|
@@ -8593,6 +9642,8 @@ var createSwapClient = (config) => {
|
|
|
8593
9642
|
const quoteId = mintQuoteId();
|
|
8594
9643
|
const now = Math.floor(Date.now() / 1e3);
|
|
8595
9644
|
if (market.backend === "feed") {
|
|
9645
|
+
if (assetPayment !== void 0)
|
|
9646
|
+
throw new Error("assetPayment needs a negotiated BTC-to-asset market");
|
|
8596
9647
|
const { quote, preparation } = await quoteFromFeed({
|
|
8597
9648
|
quoteId,
|
|
8598
9649
|
candidate: market,
|
|
@@ -8621,6 +9672,7 @@ var createSwapClient = (config) => {
|
|
|
8621
9672
|
const { quote, preparation } = await quoteViaRfq({
|
|
8622
9673
|
quoteId,
|
|
8623
9674
|
route: resolvedRoute.pair,
|
|
9675
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
8624
9676
|
candidate: market,
|
|
8625
9677
|
market: marketRef,
|
|
8626
9678
|
legs: resolvedRoute.legs,
|
|
@@ -8641,7 +9693,8 @@ var createSwapClient = (config) => {
|
|
|
8641
9693
|
});
|
|
8642
9694
|
}
|
|
8643
9695
|
},
|
|
8644
|
-
accept: async (quote) => {
|
|
9696
|
+
accept: async (quote, options) => {
|
|
9697
|
+
const validUntil = (0, import_sdk36.captureSendDeadline)(options?.validUntil);
|
|
8645
9698
|
ensureLive("accept");
|
|
8646
9699
|
const { corridors } = await resolved();
|
|
8647
9700
|
const drive2 = driving();
|
|
@@ -8649,6 +9702,7 @@ var createSwapClient = (config) => {
|
|
|
8649
9702
|
const preparation = preparations.get(quote.id);
|
|
8650
9703
|
return acceptQuote({
|
|
8651
9704
|
quote,
|
|
9705
|
+
...validUntil === void 0 ? {} : { validUntil },
|
|
8652
9706
|
...preparation === void 0 ? {} : { preparation },
|
|
8653
9707
|
wallet,
|
|
8654
9708
|
repository: config.repository,
|
|
@@ -8751,8 +9805,8 @@ var createSwapClient = (config) => {
|
|
|
8751
9805
|
};
|
|
8752
9806
|
|
|
8753
9807
|
// src/reveal.ts
|
|
8754
|
-
var
|
|
8755
|
-
var
|
|
9808
|
+
var import_base22 = require("@scure/base");
|
|
9809
|
+
var import_sdk37 = require("@arkade-os/sdk");
|
|
8756
9810
|
init_claimPacket();
|
|
8757
9811
|
init_onchainHtlc();
|
|
8758
9812
|
var CovclaimdRevealError = class extends Error {
|
|
@@ -8771,7 +9825,7 @@ var decodeKey = (value, field) => {
|
|
|
8771
9825
|
if (typeof value !== "string") throw new Error(`covclaimd info: ${field} is not a string`);
|
|
8772
9826
|
let bytes;
|
|
8773
9827
|
try {
|
|
8774
|
-
bytes =
|
|
9828
|
+
bytes = import_base22.hex.decode(value);
|
|
8775
9829
|
} catch {
|
|
8776
9830
|
throw new Error(`covclaimd info: ${field} is not hex`);
|
|
8777
9831
|
}
|
|
@@ -8794,7 +9848,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
|
|
|
8794
9848
|
const url = baseUrl.replace(/\/+$/, "");
|
|
8795
9849
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
8796
9850
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
8797
|
-
(0,
|
|
9851
|
+
(0, import_sdk37.assertTimerMs)("timeoutMs", timeoutMs);
|
|
8798
9852
|
const send = async (what, path, init) => {
|
|
8799
9853
|
let response;
|
|
8800
9854
|
try {
|
|
@@ -8832,7 +9886,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
|
|
|
8832
9886
|
const body = await readJson("info", response);
|
|
8833
9887
|
return {
|
|
8834
9888
|
covclaimdPubkey: decodeKey(body?.covclaimd_pub_key, "covclaimd_pub_key"),
|
|
8835
|
-
emulatorPubkey:
|
|
9889
|
+
emulatorPubkey: import_base22.hex.encode(decodeKey(body?.emulator_pub_key, "emulator_pub_key"))
|
|
8836
9890
|
};
|
|
8837
9891
|
},
|
|
8838
9892
|
async reveal(params) {
|
|
@@ -8853,13 +9907,13 @@ function revealFieldsFromScript(script) {
|
|
|
8853
9907
|
throw new Error("this covenant has no non-interactive claim leaf to reveal against");
|
|
8854
9908
|
}
|
|
8855
9909
|
return {
|
|
8856
|
-
arkadeScript:
|
|
8857
|
-
taptree:
|
|
9910
|
+
arkadeScript: import_base22.base64.encode(script.nonInteractiveClaimArkadeScript),
|
|
9911
|
+
taptree: import_base22.hex.encode(script.encode())
|
|
8858
9912
|
};
|
|
8859
9913
|
}
|
|
8860
9914
|
async function revealClaimPacket(client, input) {
|
|
8861
9915
|
const fields = revealFieldsFromScript(input.script);
|
|
8862
|
-
if (
|
|
9916
|
+
if (import_base22.hex.encode(import_sdk37.ArkAddress.decode(input.address).pkScript) !== import_base22.hex.encode(input.script.pkScript)) {
|
|
8863
9917
|
throw new Error("address does not belong to this covenant");
|
|
8864
9918
|
}
|
|
8865
9919
|
assertPreimageMatches(input.preimage, input.script.options.preimageHash);
|
|
@@ -8871,8 +9925,152 @@ async function revealClaimPacket(client, input) {
|
|
|
8871
9925
|
return { ciphertext };
|
|
8872
9926
|
}
|
|
8873
9927
|
|
|
9928
|
+
// src/offerFillPlan.ts
|
|
9929
|
+
var import_base23 = require("@scure/base");
|
|
9930
|
+
var import_sdk38 = require("@arkade-os/sdk");
|
|
9931
|
+
init_offer();
|
|
9932
|
+
var OFFER_FILL_TEMPLATE = "offer-fill/1";
|
|
9933
|
+
var OFFER_FILL_OWNERS = [null, "solver", "sponsor"];
|
|
9934
|
+
async function buildOfferFillPlan(wallet, arkServerUrl, offerHex, opts) {
|
|
9935
|
+
const {
|
|
9936
|
+
fund: fund2,
|
|
9937
|
+
payoutScript,
|
|
9938
|
+
fundingTxid,
|
|
9939
|
+
fundingOutpoint,
|
|
9940
|
+
swapAddress,
|
|
9941
|
+
assetCarrierSats = ASSET_CARRIER_SATS,
|
|
9942
|
+
sponsor
|
|
9943
|
+
} = opts;
|
|
9944
|
+
const offer = decodeOffer(import_base23.hex.decode(offerHex));
|
|
9945
|
+
const contract = await connectFillContract(wallet, arkServerUrl, offer, { swapAddress });
|
|
9946
|
+
const vtxos = await contract.getUtxos();
|
|
9947
|
+
const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
|
|
9948
|
+
const solverPayout = payoutScript ?? import_sdk38.ArkAddress.decode(await wallet.getAddress()).pkScript;
|
|
9949
|
+
const sponsorLeg = sponsor !== void 0 ? normalizeSponsor(sponsor, assetCarrierSats) : void 0;
|
|
9950
|
+
const fill = contract.functions.fulfill();
|
|
9951
|
+
const layout = assembleOfferFill(fill, {
|
|
9952
|
+
offer,
|
|
9953
|
+
vtxo,
|
|
9954
|
+
solverFund: fund2,
|
|
9955
|
+
solverPayout,
|
|
9956
|
+
assetCarrierSats,
|
|
9957
|
+
sponsor: sponsorLeg
|
|
9958
|
+
});
|
|
9959
|
+
const { arkTx, checkpoints } = await fill.build();
|
|
9960
|
+
for (const [i, input] of layout.inputs.entries()) {
|
|
9961
|
+
if (!OFFER_FILL_OWNERS.includes(input.owner)) {
|
|
9962
|
+
throw new Error(`fill plan input ${i} names unknown owner ${input.owner}`);
|
|
9963
|
+
}
|
|
9964
|
+
}
|
|
9965
|
+
return toJointGraph(arkTx, checkpoints, layout, offer.wantAsset?.toString());
|
|
9966
|
+
}
|
|
9967
|
+
function normalizeSponsor(sponsor, assetCarrierSats) {
|
|
9968
|
+
return {
|
|
9969
|
+
fund: sponsor.fund,
|
|
9970
|
+
netContributionSats: sponsor.netContributionSats,
|
|
9971
|
+
fare: sponsor.fare !== void 0 ? {
|
|
9972
|
+
...sponsor.fare.assetId !== void 0 ? { assetId: sponsor.fare.assetId, amount: sponsor.fare.amount } : {},
|
|
9973
|
+
script: sponsor.fare.script,
|
|
9974
|
+
sats: sponsor.fare.sats ?? assetCarrierSats
|
|
9975
|
+
} : void 0,
|
|
9976
|
+
changeScript: sponsor.changeScript,
|
|
9977
|
+
combineSatsFareWithChange: sponsor.combineSatsFareWithChange
|
|
9978
|
+
};
|
|
9979
|
+
}
|
|
9980
|
+
function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
|
|
9981
|
+
if (arkTx.inputsLength !== layout.inputs.length) {
|
|
9982
|
+
throw new Error(
|
|
9983
|
+
`fill plan built ${arkTx.inputsLength} inputs, expected ${layout.inputs.length}`
|
|
9984
|
+
);
|
|
9985
|
+
}
|
|
9986
|
+
if (checkpoints.length !== layout.inputs.length) {
|
|
9987
|
+
throw new Error(
|
|
9988
|
+
`fill plan built ${checkpoints.length} checkpoints, expected ${layout.inputs.length}`
|
|
9989
|
+
);
|
|
9990
|
+
}
|
|
9991
|
+
layout.inputs.forEach((input, i) => {
|
|
9992
|
+
const spent = checkpoints[i].getInput(0);
|
|
9993
|
+
if (!(spent.txid instanceof Uint8Array) || import_base23.hex.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
|
|
9994
|
+
throw new Error(`fill plan checkpoint ${i} does not spend ${input.txid}:${input.vout}`);
|
|
9995
|
+
}
|
|
9996
|
+
});
|
|
9997
|
+
const payments = layout.outputs.length;
|
|
9998
|
+
if (arkTx.outputsLength !== payments + 2) {
|
|
9999
|
+
throw new Error(
|
|
10000
|
+
`fill plan built ${arkTx.outputsLength} outputs, expected ${payments} payments plus extension and anchor`
|
|
10001
|
+
);
|
|
10002
|
+
}
|
|
10003
|
+
layout.outputs.forEach((expected, i) => {
|
|
10004
|
+
const out = arkTx.getOutput(i);
|
|
10005
|
+
if (!out?.script || import_base23.hex.encode(out.script) !== import_base23.hex.encode(expected.script)) {
|
|
10006
|
+
throw new Error(`fill plan output ${i} is not the ${expected.role} script`);
|
|
10007
|
+
}
|
|
10008
|
+
if (out.amount !== expected.sats) {
|
|
10009
|
+
throw new Error(
|
|
10010
|
+
`fill plan output ${i} carries ${out.amount}, expected ${expected.sats}`
|
|
10011
|
+
);
|
|
10012
|
+
}
|
|
10013
|
+
});
|
|
10014
|
+
const ext = arkTx.getOutput(payments);
|
|
10015
|
+
if (!ext?.script || !import_sdk38.Extension.isExtension(ext.script)) {
|
|
10016
|
+
throw new Error(`fill plan output ${payments} is not the extension packet`);
|
|
10017
|
+
}
|
|
10018
|
+
const anchor = arkTx.getOutput(payments + 1);
|
|
10019
|
+
if (!anchor?.script || import_base23.hex.encode(anchor.script) !== import_base23.hex.encode(import_sdk38.P2A.script) || anchor.amount !== import_sdk38.P2A.amount) {
|
|
10020
|
+
throw new Error(`fill plan output ${payments + 1} is not the anchor`);
|
|
10021
|
+
}
|
|
10022
|
+
const packet = import_sdk38.Extension.fromTx(arkTx).getAssetPacket();
|
|
10023
|
+
for (const group of packet?.groups ?? []) {
|
|
10024
|
+
if (group.assetId === null) throw new Error("fill plan carries an issuance group");
|
|
10025
|
+
const assetId = group.assetId.toString();
|
|
10026
|
+
const unitsIn = group.inputs.reduce((s, input) => s + input.amount, BigInt(0));
|
|
10027
|
+
const unitsOut = group.outputs.reduce((s, output) => s + output.amount, BigInt(0));
|
|
10028
|
+
if (unitsIn !== unitsOut) {
|
|
10029
|
+
throw new Error(`fill plan asset ${assetId} mints ${unitsOut - unitsIn} units`);
|
|
10030
|
+
}
|
|
10031
|
+
for (const output of group.outputs) {
|
|
10032
|
+
const hosted = arkTx.getOutput(output.vout);
|
|
10033
|
+
if (output.vout >= payments || !hosted?.script || import_sdk38.Extension.isExtension(hosted.script)) {
|
|
10034
|
+
throw new Error(
|
|
10035
|
+
`fill plan asset ${assetId} pays nonexistent output ${output.vout}`
|
|
10036
|
+
);
|
|
10037
|
+
}
|
|
10038
|
+
}
|
|
10039
|
+
}
|
|
10040
|
+
if (wantedAssetId !== void 0) {
|
|
10041
|
+
if ((packet?.groups.length ?? 0) === 0) {
|
|
10042
|
+
throw new Error(`fill plan carries no asset group, expected ${wantedAssetId}`);
|
|
10043
|
+
}
|
|
10044
|
+
const first = packet?.groups[0].assetId?.toString();
|
|
10045
|
+
if (first !== wantedAssetId) {
|
|
10046
|
+
throw new Error(
|
|
10047
|
+
`fill plan asset group 0 is ${first}, expected the wanted ${wantedAssetId}`
|
|
10048
|
+
);
|
|
10049
|
+
}
|
|
10050
|
+
}
|
|
10051
|
+
const arkTxPsbt = import_base23.base64.encode(arkTx.toPSBT());
|
|
10052
|
+
const checkpointPsbts = checkpoints.map((c) => import_base23.base64.encode(c.toPSBT()));
|
|
10053
|
+
const inputOwners = layout.inputs.map((input) => input.owner);
|
|
10054
|
+
const graph = {
|
|
10055
|
+
arkTx: arkTxPsbt,
|
|
10056
|
+
checkpoints: checkpointPsbts,
|
|
10057
|
+
graphId: digestJointGraph(
|
|
10058
|
+
{ arkTx: arkTxPsbt, checkpoints: checkpointPsbts, inputOwners },
|
|
10059
|
+
OFFER_FILL_TEMPLATE
|
|
10060
|
+
),
|
|
10061
|
+
inputOwners
|
|
10062
|
+
};
|
|
10063
|
+
return deepFreeze(graph);
|
|
10064
|
+
}
|
|
10065
|
+
function verifyOfferFillPlan(plan) {
|
|
10066
|
+
if (!plan || typeof plan !== "object" || !Array.isArray(plan.inputOwners)) return false;
|
|
10067
|
+
const allowed = OFFER_FILL_OWNERS;
|
|
10068
|
+
if (!plan.inputOwners.every((owner) => allowed.includes(owner))) return false;
|
|
10069
|
+
return verifyJointGraph(plan, OFFER_FILL_TEMPLATE);
|
|
10070
|
+
}
|
|
10071
|
+
|
|
8874
10072
|
// src/evmRfq.ts
|
|
8875
|
-
var
|
|
10073
|
+
var import_base24 = require("@scure/base");
|
|
8876
10074
|
init_rfq();
|
|
8877
10075
|
var EVM_CHAIN = "ethereum";
|
|
8878
10076
|
var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
@@ -8937,7 +10135,7 @@ var evmSendRequest = (input) => {
|
|
|
8937
10135
|
payment_hash: input.paymentHash,
|
|
8938
10136
|
evm_claim_address: assertEvmAddress(input.evmClaimAddress, "evmClaimAddress"),
|
|
8939
10137
|
refund_address: input.refundAddress,
|
|
8940
|
-
client_refund_pubkey:
|
|
10138
|
+
client_refund_pubkey: import_base24.hex.encode(input.senderPubkey)
|
|
8941
10139
|
}
|
|
8942
10140
|
};
|
|
8943
10141
|
};
|
|
@@ -8961,7 +10159,7 @@ var evmReceiveRequest = (input) => {
|
|
|
8961
10159
|
evm_timeout_block: input.evmTimeoutBlock,
|
|
8962
10160
|
evm_refund_address: assertEvmAddress(input.evmRefundAddress, "evmRefundAddress"),
|
|
8963
10161
|
payout_address: input.payoutAddress,
|
|
8964
|
-
payout_pubkey:
|
|
10162
|
+
payout_pubkey: import_base24.hex.encode(input.payoutPubkey)
|
|
8965
10163
|
}
|
|
8966
10164
|
};
|
|
8967
10165
|
};
|
|
@@ -9132,6 +10330,8 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9132
10330
|
MaxFeeExceeded,
|
|
9133
10331
|
MissingCorridorDep,
|
|
9134
10332
|
NotCancellable,
|
|
10333
|
+
OFFER_FILL_OWNERS,
|
|
10334
|
+
OFFER_FILL_TEMPLATE,
|
|
9135
10335
|
OFFER_SWAP_ID_PREFIX,
|
|
9136
10336
|
ONCHAIN_CLAIM_FEE_RATE_SATVB,
|
|
9137
10337
|
ONCHAIN_DRIVE,
|
|
@@ -9158,6 +10358,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9158
10358
|
bitcoinNetworkOf,
|
|
9159
10359
|
btcAssetPart,
|
|
9160
10360
|
btcOn,
|
|
10361
|
+
buildOfferFillPlan,
|
|
9161
10362
|
cancelSwap,
|
|
9162
10363
|
canonicalAssetId,
|
|
9163
10364
|
cardMarketOf,
|
|
@@ -9173,6 +10374,8 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9173
10374
|
createSwapDrive,
|
|
9174
10375
|
decodeBolt11,
|
|
9175
10376
|
decodeRfqAmount,
|
|
10377
|
+
deepFreeze,
|
|
10378
|
+
digestJointGraph,
|
|
9176
10379
|
discoveryIndex,
|
|
9177
10380
|
eligibleMarkets,
|
|
9178
10381
|
encodeRfqAmount,
|
|
@@ -9198,6 +10401,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9198
10401
|
formatAssetId,
|
|
9199
10402
|
fromAtomicDecimal,
|
|
9200
10403
|
fromRfqAmountSide,
|
|
10404
|
+
fundingWasNotSubmitted,
|
|
9201
10405
|
fundsFromWallet,
|
|
9202
10406
|
instrumentOf,
|
|
9203
10407
|
isAddressable,
|
|
@@ -9263,9 +10467,12 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9263
10467
|
toDiscoveryLeg,
|
|
9264
10468
|
toRfqAmountSide,
|
|
9265
10469
|
toSafeNumber,
|
|
10470
|
+
unsignedPsbtBytes,
|
|
9266
10471
|
usableMarkets,
|
|
9267
10472
|
verifiedCarrierSats,
|
|
9268
10473
|
verifyCrossAssetAmount,
|
|
10474
|
+
verifyJointGraph,
|
|
10475
|
+
verifyOfferFillPlan,
|
|
9269
10476
|
verifyPair,
|
|
9270
10477
|
verifyPlanLegs,
|
|
9271
10478
|
verifyQuoteTtl,
|