@arkade-os/swap 0.1.0-rc.25 → 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 +1823 -627
- package/dist/advanced.d.cts +9 -8
- package/dist/advanced.d.ts +9 -8
- package/dist/advanced.js +41 -23
- package/dist/{chunk-5PI54AVY.js → chunk-6O3L4AVI.js} +567 -294
- package/dist/{chunk-UFJEO4VV.js → chunk-DHFKCTER.js} +567 -99
- package/dist/{chunk-CZHB3ZDG.js → chunk-XBMWEK43.js} +536 -134
- package/dist/index.cjs +1856 -662
- 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-Ckp_FRdo.d.ts → offerFillPlan-BQnzburi.d.ts} +55 -6
- package/dist/{errors-DXjXCHYp.d.cts → offerFillPlan-CFT8qgTV.d.cts} +55 -6
- package/dist/protocol.cjs +699 -333
- 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) => {
|
|
@@ -3191,7 +4055,7 @@ var encodeRfqAmount = (value, field) => {
|
|
|
3191
4055
|
};
|
|
3192
4056
|
var decodeRfqAmount = (raw, field) => {
|
|
3193
4057
|
if (typeof raw === "string") {
|
|
3194
|
-
if (!(0,
|
|
4058
|
+
if (!(0, import_solver_discovery5.isAmount)(raw)) {
|
|
3195
4059
|
throw new AmountEncodingUnsupported(
|
|
3196
4060
|
field,
|
|
3197
4061
|
raw,
|
|
@@ -3212,122 +4076,20 @@ var decodeRfqAmount = (raw, field) => {
|
|
|
3212
4076
|
}
|
|
3213
4077
|
throw new AmountEncodingUnsupported(
|
|
3214
4078
|
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 }
|
|
4079
|
+
typeof raw === "bigint" || typeof raw === "boolean" ? `${raw}` : String(raw),
|
|
4080
|
+
`expected a decimal string, got ${typeof raw}`
|
|
4081
|
+
);
|
|
3283
4082
|
};
|
|
3284
|
-
var
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
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);
|
|
3291
4092
|
};
|
|
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)
|
|
3314
|
-
}
|
|
3315
|
-
},
|
|
3316
|
-
give: legOf(record.give),
|
|
3317
|
-
take: legOf(record.take),
|
|
3318
|
-
fee: legOf(record.fee),
|
|
3319
|
-
market: record.market,
|
|
3320
|
-
...record.solver === void 0 ? {} : { solver: record.solver },
|
|
3321
|
-
...record.family === "rfq" ? { lock: record.lock, refundLocktime: record.refundLocktime } : {},
|
|
3322
|
-
...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
|
|
3323
|
-
expiresAt: record.expiresAt,
|
|
3324
|
-
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
3325
|
-
...record.failure === void 0 ? {} : { failure: record.failure },
|
|
3326
|
-
...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason },
|
|
3327
|
-
createdAt: record.createdAt,
|
|
3328
|
-
updatedAt: record.updatedAt
|
|
3329
|
-
});
|
|
3330
|
-
var fundsFromWallet = (route) => route.give.instrument.kind === "wallet";
|
|
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,7 @@ 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;
|
|
4249
5095
|
var DEGRADED_RETRY_MS = 6e4;
|
|
4250
5096
|
var trackDelivery = (fetcher) => {
|
|
4251
5097
|
let undelivered = /* @__PURE__ */ new Set();
|
|
@@ -4293,7 +5139,7 @@ var REGISTRY_URL = {
|
|
|
4293
5139
|
};
|
|
4294
5140
|
var HEX_64 = /^[0-9a-f]{64}$/;
|
|
4295
5141
|
var LEGACY_ASSET_ID = /^(?:btc|[0-9a-f]{68})$/;
|
|
4296
|
-
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://"));
|
|
4297
5143
|
var isCorridorField = (value) => value === void 0 || CORRIDORS.includes(value);
|
|
4298
5144
|
var isUsableCard = (value) => {
|
|
4299
5145
|
const card = value;
|
|
@@ -4305,7 +5151,7 @@ var isUsableCard = (value) => {
|
|
|
4305
5151
|
const id = marketAssetId(card, side);
|
|
4306
5152
|
if (id === void 0 || !isAssetId(id) && !LEGACY_ASSET_ID.test(id)) return false;
|
|
4307
5153
|
}
|
|
4308
|
-
if ((0,
|
|
5154
|
+
if ((0, import_solver_discovery9.isRfqMarket)(card)) {
|
|
4309
5155
|
if (typeof card.discovery_pubkey !== "string" || !HEX_64.test(card.discovery_pubkey)) {
|
|
4310
5156
|
return false;
|
|
4311
5157
|
}
|
|
@@ -4373,7 +5219,7 @@ var discoveryIndex = (input) => {
|
|
|
4373
5219
|
}
|
|
4374
5220
|
const { network: indexed, registry: url } = sources();
|
|
4375
5221
|
if (indexed && url && config.localCards?.length) {
|
|
4376
|
-
const { markets } = await (0,
|
|
5222
|
+
const { markets } = await (0, import_solver_discovery9.discover)({
|
|
4377
5223
|
registries: [],
|
|
4378
5224
|
localCards: [...config.localCards],
|
|
4379
5225
|
network: indexed
|
|
@@ -4393,7 +5239,7 @@ var discoveryIndex = (input) => {
|
|
|
4393
5239
|
return unavailable(whyUnavailable());
|
|
4394
5240
|
}
|
|
4395
5241
|
const delivery = trackDelivery(transportCardsOf(config.transportCards));
|
|
4396
|
-
const result = await (0,
|
|
5242
|
+
const result = await (0, import_solver_discovery9.discover)({
|
|
4397
5243
|
registries: [url],
|
|
4398
5244
|
localCards: [...config.localCards ?? []],
|
|
4399
5245
|
network: indexed,
|
|
@@ -4442,14 +5288,14 @@ var discoveryIndex = (input) => {
|
|
|
4442
5288
|
};
|
|
4443
5289
|
|
|
4444
5290
|
// src/client/cancel.ts
|
|
4445
|
-
var
|
|
4446
|
-
var
|
|
5291
|
+
var import_base15 = require("@scure/base");
|
|
5292
|
+
var import_sdk24 = require("@arkade-os/sdk");
|
|
4447
5293
|
init_coverage();
|
|
4448
5294
|
init_offer();
|
|
4449
5295
|
|
|
4450
5296
|
// src/restore.ts
|
|
4451
|
-
var
|
|
4452
|
-
var
|
|
5297
|
+
var import_base12 = require("@scure/base");
|
|
5298
|
+
var import_sdk21 = require("@arkade-os/sdk");
|
|
4453
5299
|
init_offer();
|
|
4454
5300
|
init_store();
|
|
4455
5301
|
var TXS_PER_REQUEST = 50;
|
|
@@ -4474,7 +5320,7 @@ async function fetchParsedTxs(indexer, txids) {
|
|
|
4474
5320
|
if (result.status !== "fulfilled") continue;
|
|
4475
5321
|
for (const psbt of result.value) {
|
|
4476
5322
|
try {
|
|
4477
|
-
const parsed =
|
|
5323
|
+
const parsed = import_sdk21.Transaction.fromPSBT(import_base12.base64.decode(psbt));
|
|
4478
5324
|
parsedByTxid.set(parsed.id, parsed);
|
|
4479
5325
|
} catch {
|
|
4480
5326
|
}
|
|
@@ -4489,7 +5335,7 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
|
|
|
4489
5335
|
let leaves;
|
|
4490
5336
|
try {
|
|
4491
5337
|
const script = offerContract(offer, operatorPubkey);
|
|
4492
|
-
if (
|
|
5338
|
+
if (import_base12.hex.encode(script.pkScript) !== import_base12.hex.encode(offer.swapPkScript)) return "indeterminate";
|
|
4493
5339
|
leaves = {
|
|
4494
5340
|
// `exit` is absent on an offer with no exit closure, and drops out here
|
|
4495
5341
|
returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
|
|
@@ -4501,11 +5347,11 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
|
|
|
4501
5347
|
for (let i = 0; i < spendTx.inputsLength; i++) {
|
|
4502
5348
|
const input = spendTx.getInput(i);
|
|
4503
5349
|
if (!input.txid || input.index !== deposit.vout) continue;
|
|
4504
|
-
if (
|
|
5350
|
+
if (import_base12.hex.encode(input.txid) !== deposit.txid) continue;
|
|
4505
5351
|
for (const leaf of input.tapLeafScript ?? []) {
|
|
4506
|
-
const spent =
|
|
4507
|
-
if (leaves.returned.some((back) => spent ===
|
|
4508
|
-
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";
|
|
4509
5355
|
}
|
|
4510
5356
|
}
|
|
4511
5357
|
return "indeterminate";
|
|
@@ -4531,7 +5377,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4531
5377
|
try {
|
|
4532
5378
|
reopened.push({
|
|
4533
5379
|
fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
|
|
4534
|
-
offer: decodeOffer(
|
|
5380
|
+
offer: decodeOffer(import_base12.hex.decode(swap.offerHex)),
|
|
4535
5381
|
offerHex: swap.offerHex,
|
|
4536
5382
|
existing: swap
|
|
4537
5383
|
});
|
|
@@ -4557,19 +5403,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4557
5403
|
if (!fundingTx) continue;
|
|
4558
5404
|
fetchedTxids.push(txid);
|
|
4559
5405
|
try {
|
|
4560
|
-
const packet =
|
|
5406
|
+
const packet = import_sdk21.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
|
|
4561
5407
|
if (!packet) continue;
|
|
4562
5408
|
const payload = packet.serialize();
|
|
4563
5409
|
found.push({
|
|
4564
5410
|
fundingTx,
|
|
4565
5411
|
offer: decodeOffer(payload),
|
|
4566
|
-
offerHex:
|
|
5412
|
+
offerHex: import_base12.hex.encode(payload)
|
|
4567
5413
|
});
|
|
4568
5414
|
} catch {
|
|
4569
5415
|
}
|
|
4570
5416
|
}
|
|
4571
5417
|
if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
|
|
4572
|
-
const scripts = [...new Set(found.map((f) =>
|
|
5418
|
+
const scripts = [...new Set(found.map((f) => import_base12.hex.encode(f.offer.swapPkScript)))];
|
|
4573
5419
|
const { vtxos } = await indexer.getVtxos({ scripts });
|
|
4574
5420
|
const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
|
|
4575
5421
|
const txByAnyId = /* @__PURE__ */ new Map();
|
|
@@ -4581,7 +5427,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4581
5427
|
const spendTxids = /* @__PURE__ */ new Set();
|
|
4582
5428
|
for (const { fundingTx, offer } of found) {
|
|
4583
5429
|
const vtxo = vtxoByScriptAndTxid.get(
|
|
4584
|
-
`${
|
|
5430
|
+
`${import_base12.hex.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
|
|
4585
5431
|
);
|
|
4586
5432
|
if (!vtxo?.isSpent) continue;
|
|
4587
5433
|
for (const txid of spendTxidsOf(vtxo)) spendTxids.add(txid);
|
|
@@ -4590,7 +5436,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4590
5436
|
const restored = [];
|
|
4591
5437
|
const unresolved = /* @__PURE__ */ new Set();
|
|
4592
5438
|
for (const { fundingTx, offer, offerHex, existing } of found) {
|
|
4593
|
-
const swapPkScript =
|
|
5439
|
+
const swapPkScript = import_base12.hex.encode(offer.swapPkScript);
|
|
4594
5440
|
const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
|
|
4595
5441
|
if (!vtxo) {
|
|
4596
5442
|
unresolved.add(fundingTx.redeemTxid);
|
|
@@ -4637,7 +5483,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
|
|
|
4637
5483
|
let swapAddress = "";
|
|
4638
5484
|
try {
|
|
4639
5485
|
const compiled = offerContract(offer, operatorPubkey);
|
|
4640
|
-
if (
|
|
5486
|
+
if (import_base12.hex.encode(compiled.pkScript) !== swapPkScript) {
|
|
4641
5487
|
unresolved.add(fundingTx.redeemTxid);
|
|
4642
5488
|
continue;
|
|
4643
5489
|
}
|
|
@@ -4674,8 +5520,8 @@ init_repository();
|
|
|
4674
5520
|
init_repository();
|
|
4675
5521
|
|
|
4676
5522
|
// src/rfqRecord.ts
|
|
4677
|
-
var
|
|
4678
|
-
var
|
|
5523
|
+
var import_sdk22 = require("@arkade-os/sdk");
|
|
5524
|
+
var import_base13 = require("@scure/base");
|
|
4679
5525
|
|
|
4680
5526
|
// src/rfqSwapState.ts
|
|
4681
5527
|
var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
|
|
@@ -4688,6 +5534,7 @@ var RFQ_SWAP_ACTIVE_STATES = [
|
|
|
4688
5534
|
var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
|
|
4689
5535
|
|
|
4690
5536
|
// src/rfqRecord.ts
|
|
5537
|
+
init_rfqCorridor();
|
|
4691
5538
|
var RFQ_SWAP_RETENTION_SECONDS = 30 * 24 * 60 * 60;
|
|
4692
5539
|
function renameLegacyClaimTxid(profile) {
|
|
4693
5540
|
const { claimArkTxid, ...rest } = profile;
|
|
@@ -4729,8 +5576,8 @@ function assertSameSwap(origin, swap) {
|
|
|
4729
5576
|
`rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
|
|
4730
5577
|
);
|
|
4731
5578
|
}
|
|
4732
|
-
const funded =
|
|
4733
|
-
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);
|
|
4734
5581
|
if (funded !== watched) {
|
|
4735
5582
|
throw new Error(
|
|
4736
5583
|
`rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
|
|
@@ -4776,11 +5623,11 @@ function rfqSwapOriginOf(record) {
|
|
|
4776
5623
|
};
|
|
4777
5624
|
}
|
|
4778
5625
|
function lockupScript(params, lockupAddress) {
|
|
4779
|
-
const script =
|
|
4780
|
-
const funded =
|
|
4781
|
-
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)) {
|
|
4782
5629
|
throw new Error(
|
|
4783
|
-
`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`
|
|
4784
5631
|
);
|
|
4785
5632
|
}
|
|
4786
5633
|
return script;
|
|
@@ -4814,9 +5661,9 @@ function shouldRetainRfqSwap(record, now) {
|
|
|
4814
5661
|
|
|
4815
5662
|
// src/client/driveRecords.ts
|
|
4816
5663
|
init_store();
|
|
4817
|
-
var
|
|
5664
|
+
var import_sdk23 = require("@arkade-os/sdk");
|
|
4818
5665
|
var import_sha25 = require("@noble/hashes/sha2.js");
|
|
4819
|
-
var
|
|
5666
|
+
var import_base14 = require("@scure/base");
|
|
4820
5667
|
var splitRecords = (records) => {
|
|
4821
5668
|
const corridor = [];
|
|
4822
5669
|
const offer = [];
|
|
@@ -4869,7 +5716,7 @@ var pageRfqRecords = (records, filter, page) => {
|
|
|
4869
5716
|
).sort(
|
|
4870
5717
|
(a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
|
|
4871
5718
|
).slice(0, page.limit + 1);
|
|
4872
|
-
return (0,
|
|
5719
|
+
return (0, import_sdk23.pageResult)(rows, page.limit, (record) => ({
|
|
4873
5720
|
updatedAt: record.updatedAt,
|
|
4874
5721
|
rfqId: record.rfqId
|
|
4875
5722
|
}));
|
|
@@ -4895,7 +5742,7 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
4895
5742
|
index,
|
|
4896
5743
|
quoteIdOf: (rfqId) => byRfqId.get(rfqId),
|
|
4897
5744
|
async getRfqSwapsPage(filter, page) {
|
|
4898
|
-
(0,
|
|
5745
|
+
(0, import_sdk23.assertPageRequest)(page);
|
|
4899
5746
|
assertRfqSwapPageFilter(filter);
|
|
4900
5747
|
const { corridor } = splitRecords(await collectSwapRecords(repository));
|
|
4901
5748
|
for (const record of corridor) index(record);
|
|
@@ -4922,13 +5769,12 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
4922
5769
|
};
|
|
4923
5770
|
var offerFactsOf = (record) => ({
|
|
4924
5771
|
id: record.id,
|
|
5772
|
+
coverageId: record.id,
|
|
4925
5773
|
status: record.status,
|
|
4926
5774
|
offerHex: record.offerHex,
|
|
4927
5775
|
swapPkScript: record.swapPkScript,
|
|
4928
5776
|
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
4929
5777
|
...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
|
|
4930
|
-
// milliseconds: `coverage.ts` compares against `Date.now()`, and seconds would leave every
|
|
4931
|
-
// issued script outstanding for the life of the process
|
|
4932
5778
|
createdAt: record.createdAt * 1e3
|
|
4933
5779
|
});
|
|
4934
5780
|
var offerRecordSource = (repository, onRecord = () => {
|
|
@@ -5004,7 +5850,7 @@ var restoredOfferRecord = (swap, network, now) => {
|
|
|
5004
5850
|
now
|
|
5005
5851
|
);
|
|
5006
5852
|
};
|
|
5007
|
-
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));
|
|
5008
5854
|
var RESTORED_CORRIDORS = {
|
|
5009
5855
|
lightning_send: ["arkade", "lightning"],
|
|
5010
5856
|
lightning_receive: ["lightning", "arkade"],
|
|
@@ -5014,7 +5860,7 @@ var RESTORED_CORRIDORS = {
|
|
|
5014
5860
|
var restoredCorridorRecord = (stored, network, refundLocktime) => {
|
|
5015
5861
|
const v1 = normalizeRfqSwapRecord(stored);
|
|
5016
5862
|
const hashlock = v1.profile.hashlock;
|
|
5017
|
-
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)));
|
|
5018
5864
|
if (hash === void 0) throw new Error(`v1 rfq swap ${v1.rfqId} has no payment hash`);
|
|
5019
5865
|
const [giveCorridor, takeCorridor] = RESTORED_CORRIDORS[v1.kind];
|
|
5020
5866
|
const give = btcOn(railOfCorridor(giveCorridor), network);
|
|
@@ -5036,7 +5882,7 @@ var restoredCorridorRecord = (stored, network, refundLocktime) => {
|
|
|
5036
5882
|
kind: v1.kind,
|
|
5037
5883
|
rfqId: v1.rfqId,
|
|
5038
5884
|
lockupAddress: v1.lockupAddress,
|
|
5039
|
-
lockupPkScript:
|
|
5885
|
+
lockupPkScript: import_base14.hex.encode(import_sdk23.ArkAddress.decode(v1.lockupAddress).pkScript),
|
|
5040
5886
|
lock: { hash },
|
|
5041
5887
|
refundLocktime,
|
|
5042
5888
|
profile: v1.profile,
|
|
@@ -5120,7 +5966,7 @@ var cancelSwap = async (input) => {
|
|
|
5120
5966
|
return { outcome: "cancelled" };
|
|
5121
5967
|
};
|
|
5122
5968
|
var reconcileDepositSpend = async (record, indexer) => {
|
|
5123
|
-
const offer = decodeOffer(
|
|
5969
|
+
const offer = decodeOffer(import_base15.hex.decode(record.offerHex));
|
|
5124
5970
|
const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
|
|
5125
5971
|
const all = vtxos ?? [];
|
|
5126
5972
|
const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
|
|
@@ -5132,12 +5978,12 @@ var reconcileDepositSpend = async (record, indexer) => {
|
|
|
5132
5978
|
const { txs } = await indexer.getVirtualTxs(candidates);
|
|
5133
5979
|
const parsed = txs.map((psbt) => {
|
|
5134
5980
|
try {
|
|
5135
|
-
return
|
|
5981
|
+
return import_sdk24.Transaction.fromPSBT(import_base15.base64.decode(psbt));
|
|
5136
5982
|
} catch {
|
|
5137
5983
|
return void 0;
|
|
5138
5984
|
}
|
|
5139
5985
|
}).filter((tx) => tx !== void 0);
|
|
5140
|
-
const operatorPubkey =
|
|
5986
|
+
const operatorPubkey = import_sdk24.ArkAddress.decode(record.swapAddress).serverPubKey;
|
|
5141
5987
|
const kind = classifyDepositSpend(offer, operatorPubkey, parsed, {
|
|
5142
5988
|
txid: deposit.txid,
|
|
5143
5989
|
vout: deposit.vout
|
|
@@ -5167,7 +6013,8 @@ var retireOfferScripts = async (wallet, repository, record) => {
|
|
|
5167
6013
|
await retireOfferContract(
|
|
5168
6014
|
await wallet.getContractManager(),
|
|
5169
6015
|
offer.map(offerFactsOf),
|
|
5170
|
-
record.swapPkScript
|
|
6016
|
+
record.swapPkScript,
|
|
6017
|
+
{ scope: wallet }
|
|
5171
6018
|
);
|
|
5172
6019
|
} catch (error) {
|
|
5173
6020
|
console.warn(`[swap] could not retire offer script for ${record.id}`, error);
|
|
@@ -5175,11 +6022,11 @@ var retireOfferScripts = async (wallet, repository, record) => {
|
|
|
5175
6022
|
};
|
|
5176
6023
|
|
|
5177
6024
|
// src/client/drive.ts
|
|
5178
|
-
var
|
|
5179
|
-
var
|
|
6025
|
+
var import_sdk30 = require("@arkade-os/sdk");
|
|
6026
|
+
var import_base18 = require("@scure/base");
|
|
5180
6027
|
|
|
5181
6028
|
// src/claim.ts
|
|
5182
|
-
var
|
|
6029
|
+
var import_sdk25 = require("@arkade-os/sdk");
|
|
5183
6030
|
init_onchainHtlc();
|
|
5184
6031
|
var LockupAmountMismatchError = class extends Error {
|
|
5185
6032
|
name = "LockupAmountMismatchError";
|
|
@@ -5212,8 +6059,8 @@ async function pushClaim(operator, input) {
|
|
|
5212
6059
|
assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
|
|
5213
6060
|
const serverUnrollScript = await operatorUnrollScript(operator, input.network);
|
|
5214
6061
|
const leaf = input.contract.claim();
|
|
5215
|
-
const txid = await (0,
|
|
5216
|
-
identity: (0,
|
|
6062
|
+
const txid = await (0, import_sdk25.signAndSubmitOffchainTx)({
|
|
6063
|
+
identity: (0, import_sdk25.claimWithPreimageIdentity)(input.receiver, input.preimage),
|
|
5217
6064
|
provider: operator,
|
|
5218
6065
|
inputs: lockupInputs(input.vtxos, input.contract, leaf),
|
|
5219
6066
|
// One aggregate output: this leaf inspects nothing about the output set.
|
|
@@ -5231,7 +6078,7 @@ init_offer();
|
|
|
5231
6078
|
init_lockupContract();
|
|
5232
6079
|
|
|
5233
6080
|
// src/refundBlocked.ts
|
|
5234
|
-
var
|
|
6081
|
+
var import_sdk26 = require("@arkade-os/sdk");
|
|
5235
6082
|
var RefundNotLocallyPossibleError = class extends Error {
|
|
5236
6083
|
constructor(reason, message, options) {
|
|
5237
6084
|
super(message, options);
|
|
@@ -5248,16 +6095,16 @@ async function senderIdentityForSwapRecord(wallet, record) {
|
|
|
5248
6095
|
);
|
|
5249
6096
|
}
|
|
5250
6097
|
try {
|
|
5251
|
-
return await (0,
|
|
6098
|
+
return await (0, import_sdk26.contractSigner)(wallet, record.signingDescriptor);
|
|
5252
6099
|
} catch (cause) {
|
|
5253
|
-
if (cause instanceof
|
|
6100
|
+
if (cause instanceof import_sdk26.WalletCannotSignError) {
|
|
5254
6101
|
throw new RefundNotLocallyPossibleError(
|
|
5255
6102
|
"unsignable-wallet",
|
|
5256
6103
|
`this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
|
|
5257
6104
|
{ cause }
|
|
5258
6105
|
);
|
|
5259
6106
|
}
|
|
5260
|
-
if (cause instanceof
|
|
6107
|
+
if (cause instanceof import_sdk26.ForeignDescriptorError) {
|
|
5261
6108
|
throw new RefundNotLocallyPossibleError(
|
|
5262
6109
|
"foreign-descriptor",
|
|
5263
6110
|
`this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
|
|
@@ -5269,6 +6116,7 @@ async function senderIdentityForSwapRecord(wallet, record) {
|
|
|
5269
6116
|
}
|
|
5270
6117
|
|
|
5271
6118
|
// src/arkadeRefunder.ts
|
|
6119
|
+
init_rfqProfileParts();
|
|
5272
6120
|
function arkadeRefunder(deps) {
|
|
5273
6121
|
return async (swap) => {
|
|
5274
6122
|
const contract = swap.lockup?.script;
|
|
@@ -5297,12 +6145,13 @@ function arkadeRefunder(deps) {
|
|
|
5297
6145
|
}
|
|
5298
6146
|
|
|
5299
6147
|
// src/client/drive.ts
|
|
6148
|
+
init_rfqProfileParts();
|
|
5300
6149
|
init_store();
|
|
5301
6150
|
init_repository();
|
|
5302
6151
|
|
|
5303
6152
|
// src/swapManager.ts
|
|
5304
|
-
var
|
|
5305
|
-
var
|
|
6153
|
+
var import_base16 = require("@scure/base");
|
|
6154
|
+
var import_sdk27 = require("@arkade-os/sdk");
|
|
5306
6155
|
init_onchainHtlc();
|
|
5307
6156
|
init_lockupContract();
|
|
5308
6157
|
init_repository();
|
|
@@ -5433,7 +6282,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5433
6282
|
timer = null;
|
|
5434
6283
|
running = false;
|
|
5435
6284
|
constructor(deps, config = {}) {
|
|
5436
|
-
(0,
|
|
6285
|
+
(0, import_sdk27.assertTimerMs)("pollIntervalMs", config.pollIntervalMs);
|
|
5437
6286
|
this.deps = deps;
|
|
5438
6287
|
this.config = {
|
|
5439
6288
|
enableAutoActions: config.enableAutoActions ?? true,
|
|
@@ -5748,13 +6597,13 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5748
6597
|
// ── internals ────────────────────────────────────────────────────────────
|
|
5749
6598
|
track(swap) {
|
|
5750
6599
|
this.monitored.set(swap.rfqId, swap);
|
|
5751
|
-
this.byLockupScript.set(
|
|
6600
|
+
this.byLockupScript.set(import_base16.hex.encode(swap.lockupPkScript), swap);
|
|
5752
6601
|
}
|
|
5753
6602
|
/** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
|
|
5754
6603
|
* event, deliberately redundant so neither change alone re-drives a removed swap. */
|
|
5755
6604
|
untrack(rfqId) {
|
|
5756
6605
|
const swap = this.monitored.get(rfqId);
|
|
5757
|
-
if (swap) this.byLockupScript.delete(
|
|
6606
|
+
if (swap) this.byLockupScript.delete(import_base16.hex.encode(swap.lockupPkScript));
|
|
5758
6607
|
this.monitored.delete(rfqId);
|
|
5759
6608
|
this.refundRefused.delete(rfqId);
|
|
5760
6609
|
this.claimedOutpoints.delete(rfqId);
|
|
@@ -5777,7 +6626,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5777
6626
|
});
|
|
5778
6627
|
return;
|
|
5779
6628
|
}
|
|
5780
|
-
if (!(0,
|
|
6629
|
+
if (!(0, import_sdk27.isContractVtxoEvent)(event)) return;
|
|
5781
6630
|
const swap = this.byLockupScript.get(event.contractScript);
|
|
5782
6631
|
if (!swap) return;
|
|
5783
6632
|
void this.pollSwap(swap).catch(() => {
|
|
@@ -5800,7 +6649,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5800
6649
|
if (!lockup) {
|
|
5801
6650
|
try {
|
|
5802
6651
|
const [existing] = await contracts.getContracts({
|
|
5803
|
-
script:
|
|
6652
|
+
script: import_base16.hex.encode(swap.lockupPkScript)
|
|
5804
6653
|
});
|
|
5805
6654
|
if (existing) {
|
|
5806
6655
|
this.registered.set(swap.rfqId, true);
|
|
@@ -5819,13 +6668,13 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5819
6668
|
);
|
|
5820
6669
|
return;
|
|
5821
6670
|
}
|
|
5822
|
-
const script =
|
|
5823
|
-
if (script !==
|
|
6671
|
+
const script = import_base16.hex.encode(lockup.script.pkScript);
|
|
6672
|
+
if (script !== import_base16.hex.encode(swap.lockupPkScript)) {
|
|
5824
6673
|
this.registered.set(swap.rfqId, false);
|
|
5825
6674
|
this.emitFailed(
|
|
5826
6675
|
swap,
|
|
5827
6676
|
new Error(
|
|
5828
|
-
`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)}`
|
|
5829
6678
|
)
|
|
5830
6679
|
);
|
|
5831
6680
|
return;
|
|
@@ -5842,7 +6691,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
5842
6691
|
retireContract(swap) {
|
|
5843
6692
|
if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
|
|
5844
6693
|
if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
|
|
5845
|
-
void this.deps.contracts.setContractWatchState(
|
|
6694
|
+
void this.deps.contracts.setContractWatchState(import_base16.hex.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
|
|
5846
6695
|
}
|
|
5847
6696
|
arm() {
|
|
5848
6697
|
if (!this.running) return;
|
|
@@ -6005,8 +6854,8 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
6005
6854
|
this.setState(swap, "claimed");
|
|
6006
6855
|
this.emitAction(swap, "claimLockup");
|
|
6007
6856
|
} catch (error) {
|
|
6008
|
-
const ark = (0,
|
|
6009
|
-
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)) {
|
|
6010
6859
|
if (swap.claimFailure !== void 0) {
|
|
6011
6860
|
delete swap.claimFailure;
|
|
6012
6861
|
this.touch(swap);
|
|
@@ -6283,7 +7132,7 @@ var RfqSwapManager = class _RfqSwapManager {
|
|
|
6283
7132
|
*/
|
|
6284
7133
|
stampSettlementPreimage(swap, preimage) {
|
|
6285
7134
|
if (swap.kind !== "lightning_send") return;
|
|
6286
|
-
swap.settlementPreimageHex =
|
|
7135
|
+
swap.settlementPreimageHex = import_base16.hex.encode(preimage);
|
|
6287
7136
|
this.touch(swap);
|
|
6288
7137
|
}
|
|
6289
7138
|
touch(swap) {
|
|
@@ -6406,8 +7255,8 @@ var errorMessage = (error) => error instanceof Error ? error.message : String(er
|
|
|
6406
7255
|
var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
|
|
6407
7256
|
|
|
6408
7257
|
// src/watch.ts
|
|
6409
|
-
var
|
|
6410
|
-
var
|
|
7258
|
+
var import_base17 = require("@scure/base");
|
|
7259
|
+
var import_sdk28 = require("@arkade-os/sdk");
|
|
6411
7260
|
init_coverage();
|
|
6412
7261
|
init_offer();
|
|
6413
7262
|
init_store();
|
|
@@ -6442,7 +7291,7 @@ async function watchOfferSwaps({
|
|
|
6442
7291
|
wallet.getAddress(),
|
|
6443
7292
|
wallet.getArkadeReader()
|
|
6444
7293
|
]);
|
|
6445
|
-
const operatorPubkey =
|
|
7294
|
+
const operatorPubkey = import_sdk28.ArkAddress.decode(address).serverPubKey;
|
|
6446
7295
|
let queue = Promise.resolve();
|
|
6447
7296
|
const enqueue = (task) => {
|
|
6448
7297
|
queue = queue.then(task).catch(() => {
|
|
@@ -6455,9 +7304,9 @@ async function watchOfferSwaps({
|
|
|
6455
7304
|
if (candidates.length === 0) return "indeterminate";
|
|
6456
7305
|
const { txs } = await indexer.getVirtualTxs(candidates);
|
|
6457
7306
|
return classifyDepositSpend(
|
|
6458
|
-
decodeOffer(
|
|
7307
|
+
decodeOffer(import_base17.hex.decode(swap.offerHex)),
|
|
6459
7308
|
operatorPubkey,
|
|
6460
|
-
txs.map((psbt) =>
|
|
7309
|
+
txs.map((psbt) => import_sdk28.Transaction.fromPSBT(import_base17.base64.decode(psbt))),
|
|
6461
7310
|
{ txid: vtxo.txid, vout: vtxo.vout }
|
|
6462
7311
|
);
|
|
6463
7312
|
} catch {
|
|
@@ -6480,12 +7329,12 @@ async function watchOfferSwaps({
|
|
|
6480
7329
|
if (!persisted) continue;
|
|
6481
7330
|
onUpdate?.(swaps.find((s) => s.id === swap.id) ?? swap);
|
|
6482
7331
|
if (changes.status && RETIRABLE.includes(changes.status)) {
|
|
6483
|
-
await retireOfferContract(manager, swaps, event.contractScript);
|
|
7332
|
+
await retireOfferContract(manager, swaps, event.contractScript, { scope: wallet });
|
|
6484
7333
|
}
|
|
6485
7334
|
}
|
|
6486
7335
|
};
|
|
6487
7336
|
const unsubscribe = manager.onContractEvent((event) => {
|
|
6488
|
-
if (!(0,
|
|
7337
|
+
if (!(0, import_sdk28.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
|
|
6489
7338
|
enqueue(() => handleSpend(event));
|
|
6490
7339
|
});
|
|
6491
7340
|
return {
|
|
@@ -6495,7 +7344,7 @@ async function watchOfferSwaps({
|
|
|
6495
7344
|
}
|
|
6496
7345
|
|
|
6497
7346
|
// src/client/legacyRecords.ts
|
|
6498
|
-
var
|
|
7347
|
+
var import_sdk29 = require("@arkade-os/sdk");
|
|
6499
7348
|
init_repository();
|
|
6500
7349
|
var readLegacyRfqSwaps = async (repository, filter = {}) => {
|
|
6501
7350
|
try {
|
|
@@ -6512,7 +7361,7 @@ var withLegacyRfqSwaps = (bridge, repository, admits) => {
|
|
|
6512
7361
|
index: bridge.index,
|
|
6513
7362
|
quoteIdOf: bridge.quoteIdOf,
|
|
6514
7363
|
async getRfqSwapsPage(filter, page) {
|
|
6515
|
-
(0,
|
|
7364
|
+
(0, import_sdk29.assertPageRequest)(page);
|
|
6516
7365
|
assertRfqSwapPageFilter(filter);
|
|
6517
7366
|
const v2 = await collectRfqSwaps(bridge, filter);
|
|
6518
7367
|
const held = new Set(
|
|
@@ -6588,6 +7437,13 @@ var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
|
|
|
6588
7437
|
var traderClaimTxid2 = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
|
|
6589
7438
|
var readableRecord = (record) => {
|
|
6590
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
|
+
}
|
|
6591
7447
|
if (record.family === "rfq") {
|
|
6592
7448
|
return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
|
|
6593
7449
|
}
|
|
@@ -6665,6 +7521,7 @@ var createSwapDrive = (config) => {
|
|
|
6665
7521
|
return traderClaimTxid2(swap) ? "claimed" : "pending";
|
|
6666
7522
|
};
|
|
6667
7523
|
const outcomeOfEntry = (record, current) => {
|
|
7524
|
+
if (fundingWasNotSubmitted(record)) return "cancelled";
|
|
6668
7525
|
if (record.family === "offer") return recordOutcome(record);
|
|
6669
7526
|
if (current === void 0) {
|
|
6670
7527
|
if (isRfqSwapTerminal(record.state)) return corridorOutcome(record.kind, record.state);
|
|
@@ -6692,7 +7549,7 @@ var createSwapDrive = (config) => {
|
|
|
6692
7549
|
};
|
|
6693
7550
|
const updateFor = (id) => {
|
|
6694
7551
|
const record = records.get(id);
|
|
6695
|
-
if (record === void 0) return void 0;
|
|
7552
|
+
if (record === void 0 || !readableRecord(record)) return void 0;
|
|
6696
7553
|
const current = live.get(id);
|
|
6697
7554
|
const outcome = outcomeOfEntry(record, current);
|
|
6698
7555
|
return {
|
|
@@ -6751,10 +7608,10 @@ var createSwapDrive = (config) => {
|
|
|
6751
7608
|
const secret = rfqClaimSecretOf(record);
|
|
6752
7609
|
if (!secret) throw new Error(`rfq swap ${swap.rfqId} carries no claim secret`);
|
|
6753
7610
|
const preimage = await preimageForSwapRecord(wallet, secret);
|
|
6754
|
-
const signer = await (0,
|
|
7611
|
+
const signer = await (0, import_sdk30.contractSigner)(wallet, await (0, import_sdk30.identityDescriptor)(wallet.identity));
|
|
6755
7612
|
const claimKey = record.profile.claimKey;
|
|
6756
7613
|
if (typeof claimKey === "string") {
|
|
6757
|
-
const held =
|
|
7614
|
+
const held = import_base18.hex.encode(await signer.xOnlyPublicKey());
|
|
6758
7615
|
if (held !== claimKey) {
|
|
6759
7616
|
throw new Error(
|
|
6760
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`
|
|
@@ -6789,8 +7646,8 @@ var createSwapDrive = (config) => {
|
|
|
6789
7646
|
`rfq swap ${swap.rfqId} carries no refund descriptor; wire the onchain corridor's refund callback to take its L1 funding back`
|
|
6790
7647
|
);
|
|
6791
7648
|
}
|
|
6792
|
-
const signer = await (0,
|
|
6793
|
-
const held =
|
|
7649
|
+
const signer = await (0, import_sdk30.contractSigner)(wallet, descriptor);
|
|
7650
|
+
const held = import_base18.hex.encode(await signer.xOnlyPublicKey());
|
|
6794
7651
|
if (held !== record.profile.refundKey) {
|
|
6795
7652
|
throw new Error(
|
|
6796
7653
|
`the key behind ${descriptor} is ${held}, not the refund key ${String(record.profile.refundKey)} rfq swap ${swap.rfqId}'s HTLC was derived with`
|
|
@@ -6829,7 +7686,7 @@ var createSwapDrive = (config) => {
|
|
|
6829
7686
|
}
|
|
6830
7687
|
};
|
|
6831
7688
|
const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
|
|
6832
|
-
const pinnedNetwork = async () => (0,
|
|
7689
|
+
const pinnedNetwork = async () => (0, import_sdk30.getNetwork)(await config.network());
|
|
6833
7690
|
const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
|
|
6834
7691
|
const record = await corridorStore().getRfqSwap(swap.rfqId);
|
|
6835
7692
|
if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
|
|
@@ -6844,10 +7701,10 @@ var createSwapDrive = (config) => {
|
|
|
6844
7701
|
return track(
|
|
6845
7702
|
pushClaim(operator, {
|
|
6846
7703
|
contract: script,
|
|
6847
|
-
receiver: await (0,
|
|
7704
|
+
receiver: await (0, import_sdk30.contractSigner)(wallet, secret.signingDescriptor),
|
|
6848
7705
|
preimage: await preimageForSwapRecord(wallet, secret),
|
|
6849
7706
|
vtxos,
|
|
6850
|
-
destinationPkScript:
|
|
7707
|
+
destinationPkScript: import_sdk30.ArkAddress.decode(payoutAddress).pkScript,
|
|
6851
7708
|
// Passed through: `pushClaim`'s own value check decides whether `P` is published.
|
|
6852
7709
|
expectedAmount: swap.expectedAmount,
|
|
6853
7710
|
partiallyClaimed,
|
|
@@ -6915,7 +7772,7 @@ var createSwapDrive = (config) => {
|
|
|
6915
7772
|
config.network()
|
|
6916
7773
|
]);
|
|
6917
7774
|
const txs = history.map(toRestoreTx);
|
|
6918
|
-
const { hrp, serverPubKey: operatorPubkey } =
|
|
7775
|
+
const { hrp, serverPubKey: operatorPubkey } = import_sdk30.ArkAddress.decode(address);
|
|
6919
7776
|
const reopened = await legacyOfferDepositsToAdopt(store);
|
|
6920
7777
|
for (const txid of reopen) reopened.add(txid);
|
|
6921
7778
|
const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
|
|
@@ -6965,7 +7822,9 @@ var createSwapDrive = (config) => {
|
|
|
6965
7822
|
await store.markTxidsScanned(scannedTxids.filter((txid) => !stillLive.has(txid)));
|
|
6966
7823
|
const registry = managerDeps.contracts;
|
|
6967
7824
|
if (registry) {
|
|
6968
|
-
await retireSettledOfferContracts(registry, [...current.values()].map(offerFactsOf)
|
|
7825
|
+
await retireSettledOfferContracts(registry, [...current.values()].map(offerFactsOf), {
|
|
7826
|
+
scope: wallet
|
|
7827
|
+
});
|
|
6969
7828
|
}
|
|
6970
7829
|
return [...current.values()];
|
|
6971
7830
|
};
|
|
@@ -6974,6 +7833,7 @@ var createSwapDrive = (config) => {
|
|
|
6974
7833
|
getContractsWithVtxos: async (filter) => (await contractsOf()).getContractsWithVtxos(filter)
|
|
6975
7834
|
};
|
|
6976
7835
|
const registerCorridorSwap = async (record) => {
|
|
7836
|
+
if (fundingWasNotSubmitted(record)) return;
|
|
6977
7837
|
if (mode === "readonly") return;
|
|
6978
7838
|
if (!await drivable(record)) {
|
|
6979
7839
|
undrivable.add(record.id);
|
|
@@ -7055,7 +7915,23 @@ var createSwapDrive = (config) => {
|
|
|
7055
7915
|
await adoptLegacyRfqSwaps(repository);
|
|
7056
7916
|
const all = await collectSwapRecords(repository);
|
|
7057
7917
|
const { corridor, offer } = splitRecords(all.filter(readableRecord));
|
|
7058
|
-
|
|
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
|
+
}
|
|
7059
7935
|
const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
|
|
7060
7936
|
const store = corridorStore();
|
|
7061
7937
|
for (const record of liveCorridor) store.index(record);
|
|
@@ -7149,7 +8025,7 @@ var createSwapDrive = (config) => {
|
|
|
7149
8025
|
id
|
|
7150
8026
|
);
|
|
7151
8027
|
}
|
|
7152
|
-
const script =
|
|
8028
|
+
const script = import_base18.hex.decode(record.lockupPkScript);
|
|
7153
8029
|
const before = await recoverableAt(script);
|
|
7154
8030
|
if (before.length === 0) {
|
|
7155
8031
|
throw new SwapDriveRefusedError(
|
|
@@ -7252,6 +8128,10 @@ var createSwapDrive = (config) => {
|
|
|
7252
8128
|
adopt: (record) => {
|
|
7253
8129
|
if (disposed) throw new ClientDisposed("accept");
|
|
7254
8130
|
records.set(record.id, record);
|
|
8131
|
+
if (fundingWasNotSubmitted(record)) {
|
|
8132
|
+
emit(record.id);
|
|
8133
|
+
return swapView(record.id);
|
|
8134
|
+
}
|
|
7255
8135
|
if (record.family === "rfq") {
|
|
7256
8136
|
corridorStore().index(record);
|
|
7257
8137
|
managerDeps.repository = corridorStore();
|
|
@@ -7271,24 +8151,24 @@ var createSwapDrive = (config) => {
|
|
|
7271
8151
|
};
|
|
7272
8152
|
|
|
7273
8153
|
// src/client/quoteOffer.ts
|
|
7274
|
-
var
|
|
8154
|
+
var import_solver_discovery11 = require("@arkade-os/solver-discovery");
|
|
7275
8155
|
init_offer();
|
|
7276
8156
|
|
|
7277
8157
|
// src/client/market.ts
|
|
7278
|
-
var
|
|
8158
|
+
var import_solver_discovery10 = require("@arkade-os/solver-discovery");
|
|
7279
8159
|
var marketKeyOf = (card) => {
|
|
7280
|
-
const base = (0,
|
|
7281
|
-
const quote = (0,
|
|
7282
|
-
const baseIsArkade = (0,
|
|
7283
|
-
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";
|
|
7284
8164
|
if (baseIsArkade !== quoteIsArkade) {
|
|
7285
8165
|
return baseIsArkade ? `${base}/${quote}` : `${quote}/${base}`;
|
|
7286
8166
|
}
|
|
7287
8167
|
return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
|
|
7288
8168
|
};
|
|
7289
8169
|
var hasRendezvous = (card) => typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
|
|
7290
|
-
var isAddressable = (card) => !(0,
|
|
7291
|
-
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";
|
|
7292
8172
|
var usableMarkets = (snapshot, policy) => {
|
|
7293
8173
|
const allowed = policy?.allowedRegistries;
|
|
7294
8174
|
return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
|
|
@@ -7305,12 +8185,12 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
|
|
|
7305
8185
|
wantSide: side === "base" ? "quote" : "base",
|
|
7306
8186
|
...takeAmount === void 0 ? {} : { wantAmount: takeAmount }
|
|
7307
8187
|
};
|
|
7308
|
-
const canonical = (0,
|
|
8188
|
+
const canonical = (0, import_solver_discovery10.selectMarkets)([...markets], {
|
|
7309
8189
|
baseId: base.marketId,
|
|
7310
8190
|
quoteId: quote.marketId,
|
|
7311
8191
|
...selection
|
|
7312
8192
|
});
|
|
7313
|
-
const legacy = (0,
|
|
8193
|
+
const legacy = (0, import_solver_discovery10.selectMarkets)([...markets], {
|
|
7314
8194
|
baseId: `${base.corridor}:${base.assetId}`,
|
|
7315
8195
|
quoteId: `${quote.corridor}:${quote.assetId}`,
|
|
7316
8196
|
...selection
|
|
@@ -7369,16 +8249,16 @@ var assembleRoute = (give, take) => {
|
|
|
7369
8249
|
}
|
|
7370
8250
|
return { give, take };
|
|
7371
8251
|
};
|
|
7372
|
-
var endpoint = (corridor,
|
|
8252
|
+
var endpoint = (corridor, asset8, instrument) => ({
|
|
7373
8253
|
corridor,
|
|
7374
|
-
asset:
|
|
8254
|
+
asset: asset8,
|
|
7375
8255
|
...instrument === void 0 ? {} : { instrument }
|
|
7376
8256
|
});
|
|
7377
|
-
var legFor = (
|
|
7378
|
-
const leg = toDiscoveryLeg(
|
|
8257
|
+
var legFor = (asset8, expected) => {
|
|
8258
|
+
const leg = toDiscoveryLeg(asset8);
|
|
7379
8259
|
if (expected !== void 0 && leg.corridor !== expected) {
|
|
7380
8260
|
throw new UnsupportedRoute(
|
|
7381
|
-
`${
|
|
8261
|
+
`${asset8} settles on ${leg.corridor}, and this leg is ${expected}`,
|
|
7382
8262
|
{ give: leg.corridor, take: expected }
|
|
7383
8263
|
);
|
|
7384
8264
|
}
|
|
@@ -7715,7 +8595,7 @@ var quoteFromFeed = async (input) => {
|
|
|
7715
8595
|
if (amount === void 0) {
|
|
7716
8596
|
throw new Error("an asset swap needs an amount and the side it pins");
|
|
7717
8597
|
}
|
|
7718
|
-
const plan = await (0,
|
|
8598
|
+
const plan = await (0, import_solver_discovery11.quoteOffer)(candidate.card, {
|
|
7719
8599
|
give: candidate.give,
|
|
7720
8600
|
...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
|
|
7721
8601
|
// What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
|
|
@@ -7759,7 +8639,7 @@ var quoteFromFeed = async (input) => {
|
|
|
7759
8639
|
};
|
|
7760
8640
|
var feedSpread = (plan, take, carrierSats = 0n) => {
|
|
7761
8641
|
const payout = take > carrierSats ? take - carrierSats : 0n;
|
|
7762
|
-
const fair = (0,
|
|
8642
|
+
const fair = (0, import_solver_discovery11.computeWantAmount)({
|
|
7763
8643
|
deposit: plan.deposit.atomic,
|
|
7764
8644
|
give: plan.give,
|
|
7765
8645
|
price: plan.price,
|
|
@@ -7777,7 +8657,7 @@ var feedExpiry = (card, feed, now) => {
|
|
|
7777
8657
|
};
|
|
7778
8658
|
var verifyPlanLegs = (plan, legs, give) => {
|
|
7779
8659
|
const take = give === "base" ? "quote" : "base";
|
|
7780
|
-
const spelled = (side) => (0,
|
|
8660
|
+
const spelled = (side) => (0, import_solver_discovery11.marketLegKey)(plan.market, side);
|
|
7781
8661
|
const names = (side, leg) => spelled(side) === leg.marketId || spelled(side) === `${leg.corridor}:${leg.assetId}`;
|
|
7782
8662
|
if (plan.give !== give || !names(give, legs.give) || !names(take, legs.take)) {
|
|
7783
8663
|
throw new QuoteVerificationFailed(
|
|
@@ -7789,9 +8669,93 @@ var verifyPlanLegs = (plan, legs, give) => {
|
|
|
7789
8669
|
};
|
|
7790
8670
|
|
|
7791
8671
|
// src/client/quoteRfq.ts
|
|
7792
|
-
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");
|
|
7793
8679
|
var import_sdk31 = require("@arkade-os/sdk");
|
|
7794
|
-
|
|
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
|
|
7795
8759
|
init_claimPacket();
|
|
7796
8760
|
init_offer();
|
|
7797
8761
|
init_store();
|
|
@@ -7799,11 +8763,11 @@ init_onchainHtlc();
|
|
|
7799
8763
|
init_onchainHtlc();
|
|
7800
8764
|
|
|
7801
8765
|
// src/payment/onchainSwap.ts
|
|
7802
|
-
var
|
|
8766
|
+
var import_sdk33 = require("@arkade-os/sdk");
|
|
7803
8767
|
init_onchainHtlc();
|
|
7804
8768
|
|
|
7805
8769
|
// src/payment/swapRail.ts
|
|
7806
|
-
var
|
|
8770
|
+
var import_sdk32 = require("@arkade-os/sdk");
|
|
7807
8771
|
|
|
7808
8772
|
// src/client/sats.ts
|
|
7809
8773
|
var satsOf = (value, field) => {
|
|
@@ -7860,13 +8824,13 @@ var lockupOf = (derived) => ({
|
|
|
7860
8824
|
pkScript: derived.swapPkScript
|
|
7861
8825
|
});
|
|
7862
8826
|
var covenantInputs = (input) => {
|
|
7863
|
-
const network = (0,
|
|
8827
|
+
const network = (0, import_sdk34.networkFromArkadeInfo)(input.info);
|
|
7864
8828
|
const arkade2 = input.corridors.get("arkade").deps;
|
|
7865
8829
|
return {
|
|
7866
|
-
operatorPubkey: (0,
|
|
8830
|
+
operatorPubkey: (0, import_sdk34.toXOnly)(import_base20.hex.decode(input.info.signerPubkey), "ark signer key"),
|
|
7867
8831
|
// The resolved per-network pin, never operator-reported: it lands in a covenant leaf
|
|
7868
8832
|
// that decides who can move the funds.
|
|
7869
|
-
emulatorPubkey: (0,
|
|
8833
|
+
emulatorPubkey: (0, import_sdk34.toXOnly)(import_base20.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
|
|
7870
8834
|
claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
|
|
7871
8835
|
hrp: network.hrp
|
|
7872
8836
|
};
|
|
@@ -7874,7 +8838,7 @@ var covenantInputs = (input) => {
|
|
|
7874
8838
|
var sealingKey = (deps) => {
|
|
7875
8839
|
const configured = deps.covclaimd?.pubkey;
|
|
7876
8840
|
if (configured === void 0) return void 0;
|
|
7877
|
-
const key =
|
|
8841
|
+
const key = import_base20.hex.decode(configured);
|
|
7878
8842
|
if (key.length !== 33) {
|
|
7879
8843
|
throw new Error(
|
|
7880
8844
|
`the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
|
|
@@ -7894,6 +8858,8 @@ var quoteViaRfq = async (input) => {
|
|
|
7894
8858
|
expected: input.market.discoveryPubkey,
|
|
7895
8859
|
pinnable: input.market.snapshot.live
|
|
7896
8860
|
});
|
|
8861
|
+
if (input.assetPayment !== void 0 && input.route !== "arkade->arkade")
|
|
8862
|
+
throw new Error("assetPayment supports BTC-to-asset only");
|
|
7897
8863
|
switch (input.route) {
|
|
7898
8864
|
case "arkade->arkade":
|
|
7899
8865
|
return quoteArkadeAsset(input);
|
|
@@ -7909,12 +8875,12 @@ var quoteViaRfq = async (input) => {
|
|
|
7909
8875
|
};
|
|
7910
8876
|
var quoteArkadeAsset = async (input) => {
|
|
7911
8877
|
const pinned = pinnedFor(input);
|
|
7912
|
-
if (pinned.on !== "give") {
|
|
7913
|
-
throw new Error(
|
|
7914
|
-
"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`"
|
|
7915
|
-
);
|
|
7916
|
-
}
|
|
7917
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");
|
|
7918
8884
|
if (input.candidate.card.price_feed === void 0) {
|
|
7919
8885
|
throw new UnsupportedRoute(
|
|
7920
8886
|
`card ${input.candidate.card.solver} advertises no price feed to measure an asset swap's fee against`,
|
|
@@ -7924,15 +8890,43 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7924
8890
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
7925
8891
|
const rfqId = newRfqId();
|
|
7926
8892
|
const maker = await makerPosition(input.wallet);
|
|
7927
|
-
const
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
makerPublicKey: maker.publicKey
|
|
7934
|
-
})
|
|
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")
|
|
7935
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
|
+
});
|
|
7936
8930
|
verifyPair(wire.pair, pair);
|
|
7937
8931
|
const parsed = parseRfqQuote(wire);
|
|
7938
8932
|
verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
|
|
@@ -7942,8 +8936,42 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7942
8936
|
now: input.now,
|
|
7943
8937
|
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
7944
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);
|
|
7945
8973
|
const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
|
|
7946
|
-
const reference = await (0,
|
|
8974
|
+
const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
|
|
7947
8975
|
give: input.candidate.give,
|
|
7948
8976
|
giveAmount: parsed.give,
|
|
7949
8977
|
...carrierSats === void 0 ? {} : { carrierSats },
|
|
@@ -7958,15 +8986,20 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7958
8986
|
...terms.offerAsset === void 0 ? {} : { offerAsset: terms.offerAsset },
|
|
7959
8987
|
emulatorPubkey: input.corridors.get("arkade").deps.emulatorPubkey,
|
|
7960
8988
|
maker,
|
|
8989
|
+
...receiveAddress === void 0 ? {} : { receiveAddress },
|
|
7961
8990
|
info: input.info
|
|
7962
8991
|
});
|
|
7963
8992
|
verifyingDerivation(() => verifyOfferAddress(wire, offer));
|
|
7964
8993
|
return {
|
|
7965
8994
|
quote: {
|
|
7966
8995
|
id: input.quoteId,
|
|
8996
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
7967
8997
|
route: assembleRoute(
|
|
7968
8998
|
{ ...input.endpoints.give, instrument: { kind: "wallet" } },
|
|
7969
|
-
{
|
|
8999
|
+
{
|
|
9000
|
+
...input.endpoints.take,
|
|
9001
|
+
instrument: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
9002
|
+
}
|
|
7970
9003
|
),
|
|
7971
9004
|
give: { asset: input.endpoints.give.asset, amount: parsed.give },
|
|
7972
9005
|
take: { asset: input.endpoints.take.asset, amount: parsed.take },
|
|
@@ -7986,6 +9019,10 @@ var quoteArkadeAsset = async (input) => {
|
|
|
7986
9019
|
rfqId,
|
|
7987
9020
|
wire: parsed,
|
|
7988
9021
|
offer,
|
|
9022
|
+
...assetPayment === void 0 ? {} : {
|
|
9023
|
+
assetPayment,
|
|
9024
|
+
assetPaymentRecipient: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
9025
|
+
},
|
|
7989
9026
|
...carrierSats === void 0 ? {} : { carrierSats }
|
|
7990
9027
|
}
|
|
7991
9028
|
};
|
|
@@ -8005,14 +9042,14 @@ var assetSidesOf = (legs) => {
|
|
|
8005
9042
|
{ give: "arkade", take: "arkade" }
|
|
8006
9043
|
);
|
|
8007
9044
|
}
|
|
8008
|
-
return giveIsBtc ? { wantAsset:
|
|
9045
|
+
return giveIsBtc ? { wantAsset: import_sdk34.asset.AssetId.fromString(legs.take.assetId) } : { offerAsset: import_sdk34.asset.AssetId.fromString(legs.give.assetId) };
|
|
8009
9046
|
};
|
|
8010
9047
|
var makerPosition = async (wallet) => {
|
|
8011
9048
|
const [address, publicKey] = await Promise.all([
|
|
8012
9049
|
wallet.getAddress(),
|
|
8013
9050
|
wallet.identity.xOnlyPublicKey()
|
|
8014
9051
|
]);
|
|
8015
|
-
return { pkScript:
|
|
9052
|
+
return { pkScript: import_sdk34.ArkAddress.decode(address).pkScript, publicKey };
|
|
8016
9053
|
};
|
|
8017
9054
|
var quoteLightningSend = async (input) => {
|
|
8018
9055
|
const invoice = input.endpoints.take.instrument;
|
|
@@ -8021,7 +9058,7 @@ var quoteLightningSend = async (input) => {
|
|
|
8021
9058
|
}
|
|
8022
9059
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8023
9060
|
const rfqId = newRfqId();
|
|
8024
|
-
const secrets = await (0,
|
|
9061
|
+
const secrets = await (0, import_sdk34.provisionRefundKey)(input.wallet);
|
|
8025
9062
|
const wire = await input.transport.requestQuote(
|
|
8026
9063
|
lightningSendRequest({
|
|
8027
9064
|
rfqId,
|
|
@@ -8096,8 +9133,8 @@ var quoteLightningReceive = async (input) => {
|
|
|
8096
9133
|
const pinned = pinnedFor(input);
|
|
8097
9134
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8098
9135
|
const rfqId = newRfqId();
|
|
8099
|
-
const secrets = await (0,
|
|
8100
|
-
const paymentHash =
|
|
9136
|
+
const secrets = await (0, import_sdk34.provisionClaimSecret)(input.wallet);
|
|
9137
|
+
const paymentHash = import_base20.hex.encode(secrets.paymentHash);
|
|
8101
9138
|
const payoutAddress = await input.wallet.getAddress();
|
|
8102
9139
|
const lightning = input.corridors.get("lightning").deps;
|
|
8103
9140
|
const sealTo = sealingKey(lightning);
|
|
@@ -8208,9 +9245,9 @@ var quoteOnchainSend = async (input) => {
|
|
|
8208
9245
|
claimVsize: onchain.claimVsize
|
|
8209
9246
|
}) : void 0;
|
|
8210
9247
|
const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
|
|
8211
|
-
const secrets = await (0,
|
|
8212
|
-
const payoutKey = await (0,
|
|
8213
|
-
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);
|
|
8214
9251
|
const wire = await input.transport.requestQuote(
|
|
8215
9252
|
withCanonicalAmount(
|
|
8216
9253
|
onchainSendRequest({
|
|
@@ -8314,9 +9351,9 @@ var quoteOnchainReceive = async (input) => {
|
|
|
8314
9351
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
8315
9352
|
const rfqId = newRfqId();
|
|
8316
9353
|
const l1Network = l1NetworkFromArk(input.info.network);
|
|
8317
|
-
const secrets = await (0,
|
|
8318
|
-
const refundKey = await (0,
|
|
8319
|
-
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);
|
|
8320
9357
|
const payoutAddress = await input.wallet.getAddress();
|
|
8321
9358
|
const refundPkScript = l1ScriptForAddress(await input.wallet.getBoardingAddress(), l1Network);
|
|
8322
9359
|
const wire = await input.transport.requestQuote(
|
|
@@ -8423,7 +9460,7 @@ var quoteOnchainReceive = async (input) => {
|
|
|
8423
9460
|
};
|
|
8424
9461
|
|
|
8425
9462
|
// src/client/verbs.ts
|
|
8426
|
-
var
|
|
9463
|
+
var import_sdk35 = require("@arkade-os/sdk");
|
|
8427
9464
|
var enforceFeeCeiling = (quote, call, policy) => {
|
|
8428
9465
|
let ceiling;
|
|
8429
9466
|
for (const [source, limit] of [
|
|
@@ -8448,9 +9485,9 @@ var settle = async (deps, input, maxFee) => {
|
|
|
8448
9485
|
return deps.accept(quote);
|
|
8449
9486
|
};
|
|
8450
9487
|
var pay = async (deps, destination, options = {}) => {
|
|
8451
|
-
const arkade2 = (0,
|
|
9488
|
+
const arkade2 = (0, import_sdk35.arkTarget)(destination);
|
|
8452
9489
|
if (arkade2 !== void 0) {
|
|
8453
|
-
const amount = (0,
|
|
9490
|
+
const amount = (0, import_sdk35.resolveSendAmount)(
|
|
8454
9491
|
"ark",
|
|
8455
9492
|
destination,
|
|
8456
9493
|
options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
|
|
@@ -8513,7 +9550,7 @@ var nostrTransportFactory = async (rendezvous) => {
|
|
|
8513
9550
|
|
|
8514
9551
|
// src/client/client.ts
|
|
8515
9552
|
var PREPARATIONS_HELD = 64;
|
|
8516
|
-
var mintQuoteId = () =>
|
|
9553
|
+
var mintQuoteId = () => import_base21.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
|
|
8517
9554
|
var createSwapClient = (config) => {
|
|
8518
9555
|
const { wallet } = config;
|
|
8519
9556
|
const operator = config.operator ?? walletOperator(wallet);
|
|
@@ -8578,6 +9615,7 @@ var createSwapClient = (config) => {
|
|
|
8578
9615
|
return (await route(input, "resolve")).resolution;
|
|
8579
9616
|
},
|
|
8580
9617
|
quote: async (input) => {
|
|
9618
|
+
const assetPayment = captureAssetPayment(input.assetPayment);
|
|
8581
9619
|
ensureLive("quote");
|
|
8582
9620
|
const { corridors, discovery } = await resolved();
|
|
8583
9621
|
let resolvedRoute = await route(input, "quote");
|
|
@@ -8604,6 +9642,8 @@ var createSwapClient = (config) => {
|
|
|
8604
9642
|
const quoteId = mintQuoteId();
|
|
8605
9643
|
const now = Math.floor(Date.now() / 1e3);
|
|
8606
9644
|
if (market.backend === "feed") {
|
|
9645
|
+
if (assetPayment !== void 0)
|
|
9646
|
+
throw new Error("assetPayment needs a negotiated BTC-to-asset market");
|
|
8607
9647
|
const { quote, preparation } = await quoteFromFeed({
|
|
8608
9648
|
quoteId,
|
|
8609
9649
|
candidate: market,
|
|
@@ -8632,6 +9672,7 @@ var createSwapClient = (config) => {
|
|
|
8632
9672
|
const { quote, preparation } = await quoteViaRfq({
|
|
8633
9673
|
quoteId,
|
|
8634
9674
|
route: resolvedRoute.pair,
|
|
9675
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
8635
9676
|
candidate: market,
|
|
8636
9677
|
market: marketRef,
|
|
8637
9678
|
legs: resolvedRoute.legs,
|
|
@@ -8652,7 +9693,8 @@ var createSwapClient = (config) => {
|
|
|
8652
9693
|
});
|
|
8653
9694
|
}
|
|
8654
9695
|
},
|
|
8655
|
-
accept: async (quote) => {
|
|
9696
|
+
accept: async (quote, options) => {
|
|
9697
|
+
const validUntil = (0, import_sdk36.captureSendDeadline)(options?.validUntil);
|
|
8656
9698
|
ensureLive("accept");
|
|
8657
9699
|
const { corridors } = await resolved();
|
|
8658
9700
|
const drive2 = driving();
|
|
@@ -8660,6 +9702,7 @@ var createSwapClient = (config) => {
|
|
|
8660
9702
|
const preparation = preparations.get(quote.id);
|
|
8661
9703
|
return acceptQuote({
|
|
8662
9704
|
quote,
|
|
9705
|
+
...validUntil === void 0 ? {} : { validUntil },
|
|
8663
9706
|
...preparation === void 0 ? {} : { preparation },
|
|
8664
9707
|
wallet,
|
|
8665
9708
|
repository: config.repository,
|
|
@@ -8762,8 +9805,8 @@ var createSwapClient = (config) => {
|
|
|
8762
9805
|
};
|
|
8763
9806
|
|
|
8764
9807
|
// src/reveal.ts
|
|
8765
|
-
var
|
|
8766
|
-
var
|
|
9808
|
+
var import_base22 = require("@scure/base");
|
|
9809
|
+
var import_sdk37 = require("@arkade-os/sdk");
|
|
8767
9810
|
init_claimPacket();
|
|
8768
9811
|
init_onchainHtlc();
|
|
8769
9812
|
var CovclaimdRevealError = class extends Error {
|
|
@@ -8782,7 +9825,7 @@ var decodeKey = (value, field) => {
|
|
|
8782
9825
|
if (typeof value !== "string") throw new Error(`covclaimd info: ${field} is not a string`);
|
|
8783
9826
|
let bytes;
|
|
8784
9827
|
try {
|
|
8785
|
-
bytes =
|
|
9828
|
+
bytes = import_base22.hex.decode(value);
|
|
8786
9829
|
} catch {
|
|
8787
9830
|
throw new Error(`covclaimd info: ${field} is not hex`);
|
|
8788
9831
|
}
|
|
@@ -8805,7 +9848,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
|
|
|
8805
9848
|
const url = baseUrl.replace(/\/+$/, "");
|
|
8806
9849
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
8807
9850
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
8808
|
-
(0,
|
|
9851
|
+
(0, import_sdk37.assertTimerMs)("timeoutMs", timeoutMs);
|
|
8809
9852
|
const send = async (what, path, init) => {
|
|
8810
9853
|
let response;
|
|
8811
9854
|
try {
|
|
@@ -8843,7 +9886,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
|
|
|
8843
9886
|
const body = await readJson("info", response);
|
|
8844
9887
|
return {
|
|
8845
9888
|
covclaimdPubkey: decodeKey(body?.covclaimd_pub_key, "covclaimd_pub_key"),
|
|
8846
|
-
emulatorPubkey:
|
|
9889
|
+
emulatorPubkey: import_base22.hex.encode(decodeKey(body?.emulator_pub_key, "emulator_pub_key"))
|
|
8847
9890
|
};
|
|
8848
9891
|
},
|
|
8849
9892
|
async reveal(params) {
|
|
@@ -8864,13 +9907,13 @@ function revealFieldsFromScript(script) {
|
|
|
8864
9907
|
throw new Error("this covenant has no non-interactive claim leaf to reveal against");
|
|
8865
9908
|
}
|
|
8866
9909
|
return {
|
|
8867
|
-
arkadeScript:
|
|
8868
|
-
taptree:
|
|
9910
|
+
arkadeScript: import_base22.base64.encode(script.nonInteractiveClaimArkadeScript),
|
|
9911
|
+
taptree: import_base22.hex.encode(script.encode())
|
|
8869
9912
|
};
|
|
8870
9913
|
}
|
|
8871
9914
|
async function revealClaimPacket(client, input) {
|
|
8872
9915
|
const fields = revealFieldsFromScript(input.script);
|
|
8873
|
-
if (
|
|
9916
|
+
if (import_base22.hex.encode(import_sdk37.ArkAddress.decode(input.address).pkScript) !== import_base22.hex.encode(input.script.pkScript)) {
|
|
8874
9917
|
throw new Error("address does not belong to this covenant");
|
|
8875
9918
|
}
|
|
8876
9919
|
assertPreimageMatches(input.preimage, input.script.options.preimageHash);
|
|
@@ -8882,8 +9925,152 @@ async function revealClaimPacket(client, input) {
|
|
|
8882
9925
|
return { ciphertext };
|
|
8883
9926
|
}
|
|
8884
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
|
+
|
|
8885
10072
|
// src/evmRfq.ts
|
|
8886
|
-
var
|
|
10073
|
+
var import_base24 = require("@scure/base");
|
|
8887
10074
|
init_rfq();
|
|
8888
10075
|
var EVM_CHAIN = "ethereum";
|
|
8889
10076
|
var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
@@ -8948,7 +10135,7 @@ var evmSendRequest = (input) => {
|
|
|
8948
10135
|
payment_hash: input.paymentHash,
|
|
8949
10136
|
evm_claim_address: assertEvmAddress(input.evmClaimAddress, "evmClaimAddress"),
|
|
8950
10137
|
refund_address: input.refundAddress,
|
|
8951
|
-
client_refund_pubkey:
|
|
10138
|
+
client_refund_pubkey: import_base24.hex.encode(input.senderPubkey)
|
|
8952
10139
|
}
|
|
8953
10140
|
};
|
|
8954
10141
|
};
|
|
@@ -8972,7 +10159,7 @@ var evmReceiveRequest = (input) => {
|
|
|
8972
10159
|
evm_timeout_block: input.evmTimeoutBlock,
|
|
8973
10160
|
evm_refund_address: assertEvmAddress(input.evmRefundAddress, "evmRefundAddress"),
|
|
8974
10161
|
payout_address: input.payoutAddress,
|
|
8975
|
-
payout_pubkey:
|
|
10162
|
+
payout_pubkey: import_base24.hex.encode(input.payoutPubkey)
|
|
8976
10163
|
}
|
|
8977
10164
|
};
|
|
8978
10165
|
};
|
|
@@ -9143,6 +10330,8 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9143
10330
|
MaxFeeExceeded,
|
|
9144
10331
|
MissingCorridorDep,
|
|
9145
10332
|
NotCancellable,
|
|
10333
|
+
OFFER_FILL_OWNERS,
|
|
10334
|
+
OFFER_FILL_TEMPLATE,
|
|
9146
10335
|
OFFER_SWAP_ID_PREFIX,
|
|
9147
10336
|
ONCHAIN_CLAIM_FEE_RATE_SATVB,
|
|
9148
10337
|
ONCHAIN_DRIVE,
|
|
@@ -9169,6 +10358,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9169
10358
|
bitcoinNetworkOf,
|
|
9170
10359
|
btcAssetPart,
|
|
9171
10360
|
btcOn,
|
|
10361
|
+
buildOfferFillPlan,
|
|
9172
10362
|
cancelSwap,
|
|
9173
10363
|
canonicalAssetId,
|
|
9174
10364
|
cardMarketOf,
|
|
@@ -9184,6 +10374,8 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9184
10374
|
createSwapDrive,
|
|
9185
10375
|
decodeBolt11,
|
|
9186
10376
|
decodeRfqAmount,
|
|
10377
|
+
deepFreeze,
|
|
10378
|
+
digestJointGraph,
|
|
9187
10379
|
discoveryIndex,
|
|
9188
10380
|
eligibleMarkets,
|
|
9189
10381
|
encodeRfqAmount,
|
|
@@ -9209,6 +10401,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9209
10401
|
formatAssetId,
|
|
9210
10402
|
fromAtomicDecimal,
|
|
9211
10403
|
fromRfqAmountSide,
|
|
10404
|
+
fundingWasNotSubmitted,
|
|
9212
10405
|
fundsFromWallet,
|
|
9213
10406
|
instrumentOf,
|
|
9214
10407
|
isAddressable,
|
|
@@ -9274,9 +10467,12 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
|
|
|
9274
10467
|
toDiscoveryLeg,
|
|
9275
10468
|
toRfqAmountSide,
|
|
9276
10469
|
toSafeNumber,
|
|
10470
|
+
unsignedPsbtBytes,
|
|
9277
10471
|
usableMarkets,
|
|
9278
10472
|
verifiedCarrierSats,
|
|
9279
10473
|
verifyCrossAssetAmount,
|
|
10474
|
+
verifyJointGraph,
|
|
10475
|
+
verifyOfferFillPlan,
|
|
9280
10476
|
verifyPair,
|
|
9281
10477
|
verifyPlanLegs,
|
|
9282
10478
|
verifyQuoteTtl,
|