@ninsei-labs/sdk 0.55.3 → 0.56.1
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/CHANGELOG.md +64 -0
- package/README.md +34 -20
- package/assets/vendors/MANIFEST.json +22 -0
- package/assets/vendors/sdk/sdk-browser.js +2058 -2
- package/engine/atomic/dleq2.js +74 -10
- package/engine/core/config.js +14 -14
- package/engine/core/store.js +25 -4
- package/engine/core/swap.js +52 -50
- package/engine/evm/factory.js +13 -20
- package/engine/sdk/bridge.js +1 -1
- package/index.d.ts +9 -16
- package/package.json +22 -7
- package/src/actions.mjs +49 -9
- package/src/adapters/evm-wallet.mjs +24 -5
- package/src/adapters/index.d.ts +66 -0
- package/src/adapters/index.mjs +0 -6
- package/src/codes.mjs +9 -0
- package/src/factoryPolicy.mjs +24 -0
- package/src/index.mjs +10 -4
- package/src/lock.mjs +1 -1
- package/src/provider/envFile.mjs +11 -1
- package/src/public/order.d.ts +4 -0
- package/src/public/recovery.d.ts +40 -54
- package/src/public/recovery.mjs +2 -8
- package/src/public/xmr.d.ts +14 -3
- package/src/quoteEip712Spec.mjs +9 -1
- package/src/quotes.mjs +21 -26
- package/src/record.mjs +3 -3
- package/src/recovery-key.mjs +132 -226
- package/src/relayFirmClient.mjs +40 -3
- package/src/relayQuote.mjs +1 -1
- package/src/relayRequest.mjs +12 -3
- package/src/swap-flow.mjs +59 -15
- package/src/swaps.mjs +115 -113
- package/src/sweep-restore.mjs +6 -2
- package/src/sweep.mjs +30 -11
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +22 -6
- package/src/adapters/node-test-evm-wallet.mjs +0 -357
package/src/swap-flow.mjs
CHANGED
|
@@ -70,6 +70,7 @@ export function escrowCashierAddress(chainSlug) {
|
|
|
70
70
|
// The full flow. onStage(stage, detail) is called on every step - the interface must show what is going on.
|
|
71
71
|
export async function runAtomicOrder({
|
|
72
72
|
chainSlug, locker, claimer, amountWei, amountLabel, providerId = null,
|
|
73
|
+
xmrNetwork = null,
|
|
73
74
|
claimWindowSeconds = 3600, readyWindowSeconds = 14400, salt: providedSalt, onStage,
|
|
74
75
|
// THE SUBSTITUTION POINTS FOR THE SAKE OF THE CHECK, and they are not decoration. The live flow could be
|
|
75
76
|
// neither run in a check nor covered otherwise: it requires a browser Worker and a signature in the wallet.
|
|
@@ -230,7 +231,7 @@ export async function runAtomicOrder({
|
|
|
230
231
|
const joint = await worker.jointAddress({
|
|
231
232
|
ownSpendHalf: mine.half, ownViewHalf: mine.viewHalf,
|
|
232
233
|
otherSpendPoint: counter.edPub, otherViewPoint,
|
|
233
|
-
network: (chain.monero && chain.monero.networkType) || MONERO.networkType,
|
|
234
|
+
network: xmrNetwork || (chain.monero && chain.monero.networkType) || MONERO.networkType,
|
|
234
235
|
});
|
|
235
236
|
|
|
236
237
|
// THE COUNTERPARTY STAND-IN ON A LIVE NETWORK IS A REFUSAL, NOT A SIGNATURE (the auditor's finding, review_02
|
|
@@ -454,6 +455,43 @@ export async function assertOrderSlots(escrow, expect, what = "signature", deps
|
|
|
454
455
|
return verdict;
|
|
455
456
|
}
|
|
456
457
|
|
|
458
|
+
// THE ORDER MUST STILL BE OPEN BEFORE A HALF IS REVEALED. A closed order (claimed or refunded) and an
|
|
459
|
+
// unfunded address have no action to take; the slot check alone cannot see that. The deadline rule is separate:
|
|
460
|
+
// this guard answers the state question, not the clock.
|
|
461
|
+
async function assertOrderOpen(escrow, what, deps) {
|
|
462
|
+
const state = await orderStatus(escrow, deps);
|
|
463
|
+
if (!state.isFunded || state.isClaimed || state.isRefunded) {
|
|
464
|
+
throw new SdkError("contract-reverted", { step: what, why: "closed" });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// THE CONTRACT'S CLOCK RULE, READ FROM THE SAME CHAIN. Without a block-time seam the time checks are skipped (a
|
|
469
|
+
// direct caller that has no block reader is not given a promise the core cannot keep); the actions facade always
|
|
470
|
+
// brings one. The ready mark is read once, so claim/refund/mark-ready cannot disagree about it.
|
|
471
|
+
async function assertActionWindow(escrow, what, deps, now = null) {
|
|
472
|
+
if (typeof deps.blockTime !== "function") return;
|
|
473
|
+
const call = deps.call || readContract;
|
|
474
|
+
const [readyRaw, deadlines] = await Promise.all([
|
|
475
|
+
call({ to: escrow, data: encodeRead("ready") }),
|
|
476
|
+
orderDeadlines(escrow, deps),
|
|
477
|
+
]);
|
|
478
|
+
const marked = BigInt(readyRaw) !== 0n;
|
|
479
|
+
const at = now === null ? Number(await deps.blockTime()) : Number(now);
|
|
480
|
+
if (!Number.isSafeInteger(at) || at <= 0) return; // no chain time: do not sign a time verdict
|
|
481
|
+
if (what === "claim") {
|
|
482
|
+
if (at >= Number(deadlines.t1)) throw new SdkError("contract-reverted", { step: what, why: "window-closed" });
|
|
483
|
+
if (!marked && at < Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "not-ready" });
|
|
484
|
+
} else if (what === "refund") {
|
|
485
|
+
// refund(): before t1 it is allowed only while the mark is absent and readyBy has not passed.
|
|
486
|
+
if (at < Number(deadlines.t1) && (at >= Number(deadlines.readyBy) || marked)) {
|
|
487
|
+
throw new SdkError("contract-reverted", { step: what, why: "too-early" });
|
|
488
|
+
}
|
|
489
|
+
} else if (what === "mark-ready") {
|
|
490
|
+
if (marked) throw new SdkError("contract-reverted", { step: what, why: "already-ready" });
|
|
491
|
+
if (at >= Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "ready-window-closed" });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
457
495
|
// Claim the ETH by the CLAIMER'S half. The field name in the contract is halfClaimer (:213); the former word
|
|
458
496
|
// "secret" is a synonym of the same value (the half serves as the preimage of the commitment), while "hashlock"
|
|
459
497
|
// lied here: the current contract has NO hashlock field. Instead it has two half commitments -
|
|
@@ -463,8 +501,12 @@ export async function assertOrderSlots(escrow, expect, what = "signature", deps
|
|
|
463
501
|
export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {} }) {
|
|
464
502
|
if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
|
|
465
503
|
if (!halfClaimer) throw new SdkError("bad-input", { field: "halfClaimer" });
|
|
466
|
-
//
|
|
467
|
-
// commitments we know.
|
|
504
|
+
// STATE, TIME AND SLOTS BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY order
|
|
505
|
+
// whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
|
|
506
|
+
// `readyBy` it requires the mark, after `readyBy` it allows a claim without it. Both are checked from the
|
|
507
|
+
// chain's own timestamp when the actions facade brings one.
|
|
508
|
+
await assertOrderOpen(escrow, "claim", deps);
|
|
509
|
+
await assertActionWindow(escrow, "claim", deps);
|
|
468
510
|
await assertOrderSlots(escrow, expect, "claim", deps);
|
|
469
511
|
onStep?.("confirm-claim");
|
|
470
512
|
// THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE (issue #127): the node lays exactly
|
|
@@ -484,29 +526,31 @@ export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {
|
|
|
484
526
|
export async function refundOrder({ escrow, halfLocker, onStep, expect = null, deps = {} }) {
|
|
485
527
|
if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
|
|
486
528
|
if (!halfLocker) throw new SdkError("bad-input", { field: "halfLocker" });
|
|
487
|
-
|
|
529
|
+
// A CLOSED ORDER IS NOT A REFUND. The state is read before the half is signed; the deadline itself stays with
|
|
530
|
+
// the caller and the contract (there is one boundary, t1).
|
|
531
|
+
await assertOrderOpen(escrow, "refund", deps);
|
|
532
|
+
await assertActionWindow(escrow, "refund", deps);
|
|
488
533
|
// THE SLOT CHECK HERE TOO, WHEN EXPECTATIONS ARE GIVEN. A refund REVEALS the half - that is, it is as
|
|
489
534
|
// irreversible as a claim, and signing it under an order whose commitments we have not checked is forbidden
|
|
490
535
|
// for the same reason. Expectations are optional for compatibility with previous calls (the page calls without
|
|
491
536
|
// them); the core always passes them.
|
|
492
537
|
if (expect) await assertOrderSlots(escrow, expect, "refund", deps);
|
|
538
|
+
onStep?.("confirm-refund");
|
|
493
539
|
const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeRefund(halfLocker), gas: 250_000n });
|
|
494
540
|
return { hash };
|
|
495
541
|
}
|
|
496
542
|
|
|
497
|
-
// Readiness: "I saw the XMR on the shared address
|
|
498
|
-
//
|
|
499
|
-
// the
|
|
500
|
-
//
|
|
501
|
-
// a funded order, only before readyBy and only once (:200-204). After readyBy without the mark the order closes
|
|
502
|
-
// by a refund (decision 30.09.2026): the claim window did not open, so claim is forbidden while refund opens
|
|
503
|
-
// immediately. There used to be a dead zone here: neither claim (needs ready) nor refund (needs the deadline)
|
|
504
|
-
// would go through.
|
|
543
|
+
// Readiness: "I saw the XMR on the shared address". Before `readyBy` the contract requires it for a claim and
|
|
544
|
+
// refuses a refund; after `readyBy` a claim is allowed even without it, while a refund opens only at `t1`
|
|
545
|
+
// (the mark itself can no longer be set). The party that deposited the ETH sets it, and only after it has itself
|
|
546
|
+
// seen the XMR lock. THE MARK WINDOW IS LIMITED: only on a funded order, only before readyBy and only once.
|
|
505
547
|
export async function markReadyOrder({ escrow, expect, onStep, deps = {} }) {
|
|
506
548
|
if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
|
|
507
|
-
//
|
|
508
|
-
// to the VERY order whose points and commitments we have
|
|
509
|
-
// under what we did not assemble.
|
|
549
|
+
// A MARK ON A CLOSED OR ALREADY MARKED ORDER IS REFUSED. Then the slot check: ready() grants the claimer
|
|
550
|
+
// settlement at its own address, and the grant is given to the VERY order whose points and commitments we have
|
|
551
|
+
// checked. A mark on a foreign order is a signature under what we did not assemble.
|
|
552
|
+
await assertOrderOpen(escrow, "mark-ready", deps);
|
|
553
|
+
await assertActionWindow(escrow, "mark-ready", deps);
|
|
510
554
|
await assertOrderSlots(escrow, expect, "mark-ready", deps);
|
|
511
555
|
onStep?.("confirm-mark-ready");
|
|
512
556
|
const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeMarkReady(), gas: 120_000n });
|
package/src/swaps.mjs
CHANGED
|
@@ -29,9 +29,9 @@ import { probeMoneroNode } from "./probes.mjs";
|
|
|
29
29
|
import { createActions } from "./actions.mjs";
|
|
30
30
|
// THE ONE RECOVERY KEY (sdk#76): the taker's halves come from it, not from a fresh random pair per swap.
|
|
31
31
|
import {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
newRecoverySalt,
|
|
32
|
+
createRecoveryKeyFile, importRecoveryKey, loadRecoveryKey,
|
|
33
|
+
recoveryKeyFileName, recoverySaltOf, saveRecoveryKey,
|
|
34
|
+
newRecoverySalt, takerHalvesV2,
|
|
35
35
|
} from "./recovery-key.mjs";
|
|
36
36
|
// THE XMR ARRIVAL CHECK ON TWO NODES (issue #85) - IN THE CORE, from the same mirrored rule and block parser.
|
|
37
37
|
import * as xmrArrival from "./xmr-arrival.mjs";
|
|
@@ -289,12 +289,15 @@ const MIN_PASSPHRASE = 12;
|
|
|
289
289
|
// `receiveAddress`.
|
|
290
290
|
// Exported for the relay/record seam check: the function is the only place that decides which amount reaches
|
|
291
291
|
// the arrival check, and a unit test of createRecord alone cannot see that decision.
|
|
292
|
-
export const recordInputOf = (request) => {
|
|
292
|
+
export const recordInputOf = (request, xmrNetwork = null) => {
|
|
293
293
|
const quote = request && request.quote && typeof request.quote === "object" ? request.quote : {};
|
|
294
294
|
const pass = (v) => (v === undefined || v === null || v === "" ? undefined : v);
|
|
295
295
|
return {
|
|
296
296
|
side: request.side || "buy",
|
|
297
297
|
network: quote.chain ? quote.chain : undefined,
|
|
298
|
+
// THE RECORD'S MONERO NETWORK COMES FROM THE INSTANCE, NOT THE DEMO CONSTANT. A testnet instance that recorded
|
|
299
|
+
// stagenet made the recovery file and the start-height probe disagree with the node it was configured for.
|
|
300
|
+
moneroNetwork: request.moneroNetwork || xmrNetwork || undefined,
|
|
298
301
|
payToken: quote.asset ? String(quote.asset).toLowerCase() : undefined,
|
|
299
302
|
payAmount: quote.amount !== undefined ? quote.amount : undefined,
|
|
300
303
|
xmrAmount: quote.size !== undefined ? quote.size : undefined,
|
|
@@ -335,13 +338,35 @@ export async function startHeightFromNodes({ nodes = [], network = null, fetchIm
|
|
|
335
338
|
try { return await probeMoneroNode({ url, fetchImpl }); }
|
|
336
339
|
catch { return { ok: false, why: "unreachable" }; }
|
|
337
340
|
}));
|
|
338
|
-
const good = answers.
|
|
339
|
-
if (good)
|
|
341
|
+
const good = answers.filter((answer) => answer.ok === true && (!network || answer.network === network));
|
|
342
|
+
if (good.length) {
|
|
343
|
+
// A LAGGING NODE MUST NOT HIDE THE TRANSFER. The scan starts at the OLDEST height any good witness reports, so
|
|
344
|
+
// a node that answers too high cannot move the walk past the arrival. A large spread means the witnesses do not
|
|
345
|
+
// agree on the chain: refuse the measurement instead of choosing one and calling it the chain's height.
|
|
346
|
+
const heights = good.map((answer) => Number(answer.height)).filter((height) => Number.isSafeInteger(height) && height >= 0);
|
|
347
|
+
if (!heights.length) throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why: "no-height" });
|
|
348
|
+
const low = Math.min(...heights);
|
|
349
|
+
const high = Math.max(...heights);
|
|
350
|
+
if (high - low > 100) throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why: "disagree", low, high });
|
|
351
|
+
return low;
|
|
352
|
+
}
|
|
340
353
|
const why = answers.find((answer) => answer.ok === true) ? "network" : (answers[0] && answers[0].why) || "no-node";
|
|
341
354
|
throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why });
|
|
342
355
|
}
|
|
343
356
|
|
|
344
|
-
|
|
357
|
+
// THE SELL WAIT MUST OUTLIVE THE READY DEADLINE. The old fixed 20-minute wait equalled the mean time of ten
|
|
358
|
+
// Monero blocks, so about half of honest sales expired before `ready`. A caller may set an explicit timeout;
|
|
359
|
+
// otherwise the configured wait is extended to cover the remaining time to `readyBy` plus one confirmation margin.
|
|
360
|
+
const SELL_WATCH_MARGIN_SEC = 300;
|
|
361
|
+
export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null, nowSec = Math.floor(Date.now() / 1000) } = {}) {
|
|
362
|
+
const configured = Number.isFinite(Number(configuredMs)) && Number(configuredMs) > 0 ? Number(configuredMs) : 1_200_000;
|
|
363
|
+
const readyAt = Number(readyBySec);
|
|
364
|
+
const now = Number(nowSec);
|
|
365
|
+
if (!Number.isSafeInteger(readyAt) || !Number.isSafeInteger(now) || readyAt <= now) return configured;
|
|
366
|
+
return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function createSwaps({ preflight, http, createRecord, mode = null, xmrNetwork = null, call = null, store = engine.store,
|
|
345
370
|
// THE PATHS AND LIMITS ARE BROUGHT BY THE CONFIGURATION: the "server" step's paths are named by names (config.route),
|
|
346
371
|
// and the timeout and rate of the watch polling - in config.limits. Without the configuration the step answers with a
|
|
347
372
|
// code rather than following invented paths.
|
|
@@ -390,7 +415,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
390
415
|
fetchImpl: request.fetchImpl || (typeof fetch === "function" ? fetch : null) });
|
|
391
416
|
}
|
|
392
417
|
const records = () => {
|
|
393
|
-
const state =
|
|
418
|
+
const state = store.loadState();
|
|
394
419
|
const all = Object.values((state && state.swaps) || {}).filter((s) => s && s.id);
|
|
395
420
|
return all.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0));
|
|
396
421
|
};
|
|
@@ -407,14 +432,21 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
407
432
|
const swap = record.swap || record;
|
|
408
433
|
const escrowRecord = swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
|
|
409
434
|
const txHash = escrowRecord.fundTx || swap.fundTx || null;
|
|
410
|
-
|
|
435
|
+
// THE RECEIPT IS A HANDLE, NOT THE ONLY SOURCE OF TRUTH. A Safe over WalletConnect, a sped-up transaction or
|
|
436
|
+
// a provider that lost the receipt can hide a funded escrow; the predicted address is already on the record,
|
|
437
|
+
// so its own status() is asked before the start is left pending forever. A failed read is not "not funded".
|
|
438
|
+
let onChain = null;
|
|
439
|
+
if (escrowRecord.address) {
|
|
440
|
+
try { onChain = await flow.orderStatus(escrowRecord.address, { call: reader }); } catch { onChain = null; }
|
|
441
|
+
}
|
|
442
|
+
if (!txHash && !(onChain && onChain.isFunded)) {
|
|
411
443
|
return { id: swap.id || null, escrow: escrowRecord.address || null,
|
|
412
444
|
address: (record.swapWallet && record.swapWallet.address) || null,
|
|
413
445
|
step: "funding-pending", txHash: null, reason: "no-transaction-hash", next: "receipt" };
|
|
414
446
|
}
|
|
415
447
|
const wallet = request.wallet;
|
|
416
448
|
let receipt = null;
|
|
417
|
-
if (wallet && typeof wallet.receipt === "function") {
|
|
449
|
+
if (txHash && wallet && typeof wallet.receipt === "function") {
|
|
418
450
|
try { receipt = await wallet.receipt(txHash); } catch { receipt = null; }
|
|
419
451
|
}
|
|
420
452
|
const order = request.order && typeof request.order === "object" ? request.order : {};
|
|
@@ -423,12 +455,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
423
455
|
expectedEscrow: escrowRecord.address || null,
|
|
424
456
|
});
|
|
425
457
|
if (verdict.status === "reverted") throw new SdkError("contract-reverted", { step: "funding" });
|
|
426
|
-
if (verdict.status === "funded") {
|
|
427
|
-
|
|
458
|
+
if (verdict.status === "funded" || (onChain && onChain.isFunded)) {
|
|
459
|
+
const escrow = verdict.status === "funded" ? verdict.escrow : escrowRecord.address;
|
|
460
|
+
if (!escrow) throw new SdkError("funding-pending", { reason: "no-escrow-address" });
|
|
461
|
+
swap.escrow = { ...escrowRecord, address: escrow, fundingPending: false,
|
|
428
462
|
evmBirthBlock: Number(verdict.birthBlock) > 0 ? Number(verdict.birthBlock) : (escrowRecord.evmBirthBlock ?? null) };
|
|
429
463
|
delete swap.fundingPending;
|
|
430
|
-
try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
|
|
431
|
-
return { id: swap.id || null, escrow
|
|
464
|
+
try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
|
|
465
|
+
return { id: swap.id || null, escrow,
|
|
432
466
|
address: (record.swapWallet && record.swapWallet.address) || null,
|
|
433
467
|
step: "xmr-incoming", server: null, watch: null, next: "watch" };
|
|
434
468
|
}
|
|
@@ -646,7 +680,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
646
680
|
*/
|
|
647
681
|
async progress(id) {
|
|
648
682
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
649
|
-
const swap = engine.swap.getSwap(id);
|
|
683
|
+
const swap = engine.swap.getSwap(id, store);
|
|
650
684
|
if (!swap) return null;
|
|
651
685
|
return {
|
|
652
686
|
id: String(swap.id || id),
|
|
@@ -669,15 +703,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
669
703
|
*/
|
|
670
704
|
async confirmReady(id) {
|
|
671
705
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
672
|
-
return engine.swap.confirmReady(id);
|
|
706
|
+
return engine.swap.confirmReady(id, store);
|
|
673
707
|
},
|
|
674
708
|
async refundEth(id, by = "you") {
|
|
675
709
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
676
|
-
return engine.swap.refundEth(id, by);
|
|
710
|
+
return engine.swap.refundEth(id, by, store);
|
|
677
711
|
},
|
|
678
712
|
async sweepNow(id) {
|
|
679
713
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
680
|
-
return engine.swap.sweepNow(id);
|
|
714
|
+
return engine.swap.sweepNow(id, store);
|
|
681
715
|
},
|
|
682
716
|
|
|
683
717
|
/**
|
|
@@ -688,10 +722,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
688
722
|
async setDestination(id, address) {
|
|
689
723
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
690
724
|
if (typeof address !== "string" || !address) throw new SdkError("bad-input", { field: "address" });
|
|
691
|
-
const swap = engine.swap.getSwap(id);
|
|
725
|
+
const swap = engine.swap.getSwap(id, store);
|
|
692
726
|
if (!swap) return null;
|
|
693
727
|
swap.receiveAddress = address;
|
|
694
|
-
return engine.swap.saveSwap(swap);
|
|
728
|
+
return engine.swap.saveSwap(swap, store);
|
|
695
729
|
},
|
|
696
730
|
|
|
697
731
|
/**
|
|
@@ -712,11 +746,11 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
712
746
|
async forget(id) {
|
|
713
747
|
if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
|
|
714
748
|
let state = null;
|
|
715
|
-
try { state =
|
|
749
|
+
try { state = store.loadState(); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
|
|
716
750
|
const swaps = state && state.swaps;
|
|
717
751
|
if (!swaps || !swaps[id]) return false;
|
|
718
752
|
delete swaps[id];
|
|
719
|
-
try {
|
|
753
|
+
try { store.saveState(state); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
|
|
720
754
|
return true;
|
|
721
755
|
},
|
|
722
756
|
|
|
@@ -749,7 +783,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
749
783
|
// not look like "the service has no swaps" - the two are different, and only one of them means "synced".
|
|
750
784
|
const body = answer.body;
|
|
751
785
|
if (!body || !Array.isArray(body.swaps)) throw new SdkError("server-unavailable", { step: "sync", why: "bad-response" });
|
|
752
|
-
const added = engine.swap.addServerSwaps(body.swaps);
|
|
786
|
+
const added = engine.swap.addServerSwaps(body.swaps, store);
|
|
753
787
|
return { ok: true, added, seen: body.swaps.length };
|
|
754
788
|
},
|
|
755
789
|
|
|
@@ -851,7 +885,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
851
885
|
// A START WITHOUT THE SIGNED XMR AMOUNT IS NOT A START. `quote.size` is a rounded display value and the relay
|
|
852
886
|
// answer does not carry it; the arrival check needs the exact integer the order quote signed. Refuse here, before
|
|
853
887
|
// a wallet or a funding send, instead of recording an incomplete swap that later reads "no amount".
|
|
854
|
-
if (!recordInputOf(request).expectedAtomic) {
|
|
888
|
+
if (!recordInputOf(request, xmrNetwork).expectedAtomic) {
|
|
855
889
|
throw new SdkError("bad-input", { field: "expectedAtomic", why: "signed-amount-missing" });
|
|
856
890
|
}
|
|
857
891
|
|
|
@@ -860,12 +894,9 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
860
894
|
const quoteForResume = (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null;
|
|
861
895
|
const pendingRecord = pendingFundingOf(quoteForResume);
|
|
862
896
|
if (pendingRecord) return await resumePendingFunding(pendingRecord, request);
|
|
863
|
-
// A NEW START USES A PER-ORDER SALT
|
|
864
|
-
//
|
|
865
|
-
|
|
866
|
-
// An explicit `recoveryIndex` keeps the legacy path for restoring an old order; it is not a new-start default.
|
|
867
|
-
const explicitRecoveryIndex = request.recoveryIndex !== undefined && request.recoveryIndex !== null;
|
|
868
|
-
if ((request.recoverySalt === undefined || request.recoverySalt === null) && !explicitRecoveryIndex) {
|
|
897
|
+
// A NEW START USES A PER-ORDER SALT. When the caller brings no `recoverySalt`, the order's own salt is the
|
|
898
|
+
// client salt; a missing salt is drawn here and written into the order before its context is built.
|
|
899
|
+
if (request.recoverySalt === undefined || request.recoverySalt === null) {
|
|
869
900
|
if (!request.order || typeof request.order !== "object") throw new SdkError("bad-input", { field: "order" });
|
|
870
901
|
if (request.order.salt === undefined || request.order.salt === null || request.order.salt === "") {
|
|
871
902
|
request.order = { ...request.order, salt: newRecoverySalt() };
|
|
@@ -902,7 +933,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
902
933
|
let keySide = null;
|
|
903
934
|
let derivedViewHalf = null;
|
|
904
935
|
const makeRecord = typeof createRecord === "function" ? createRecord
|
|
905
|
-
: async (req) => recordModule.createRecord(recordInputOf(req), { order: req.order, side: keySide });
|
|
936
|
+
: async (req) => recordModule.createRecord(recordInputOf(req, xmrNetwork), { order: req.order, side: keySide, store });
|
|
906
937
|
const passphrase = typeof request.passphrase === "string" ? request.passphrase : "";
|
|
907
938
|
if (typeof passphrase !== "string") throw new SdkError("bad-input", { field: "passphrase" });
|
|
908
939
|
if (passphrase.length > 0 && passphrase.length < MIN_PASSPHRASE) throw new SdkError("bad-input", { field: "passphrase", min: MIN_PASSPHRASE });
|
|
@@ -916,7 +947,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
916
947
|
// No per-swap file is assembled on this path.
|
|
917
948
|
let recovery = null;
|
|
918
949
|
{
|
|
919
|
-
const storage =
|
|
950
|
+
const storage = store.storage();
|
|
920
951
|
const supplied = typeof request.recoveryKey === "string"
|
|
921
952
|
? request.recoveryKey
|
|
922
953
|
: request.recoveryKey && typeof request.recoveryKey.mnemonic === "string" ? request.recoveryKey.mnemonic : null;
|
|
@@ -927,56 +958,22 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
927
958
|
if (!saved && !supplied) throw new SdkError("bad-input", { field: "recoveryKey" });
|
|
928
959
|
const key = saved || importRecoveryKey(supplied);
|
|
929
960
|
// THE KEY IS SAVED, BUT NOT YET BACKED UP. `backupConfirmed` is its own fact: a key in storage is not a
|
|
930
|
-
// key the person has saved. Saving it here
|
|
961
|
+
// key the person has saved. Saving it here keeps the key across a refresh; funding waits for the flag.
|
|
931
962
|
if (!saved) saveRecoveryKey(storage, { ...key, backupConfirmed: false });
|
|
932
963
|
const chainId = request.order.chainId;
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
if (
|
|
937
|
-
|
|
938
|
-
// the caller composes the signed quote with this value and passes it here. The order's own salt must be
|
|
939
|
-
// the same bytes; a mismatch means the quote is not the one being started.
|
|
940
|
-
if (explicit) throw new SdkError("bad-input", { field: "recoverySalt", why: "with-recovery-index" });
|
|
941
|
-
if (typeof request.order.factory !== "string" || !request.order.factory) {
|
|
942
|
-
throw new SdkError("bad-input", { field: "order.factory" });
|
|
943
|
-
}
|
|
944
|
-
let salt;
|
|
945
|
-
try { salt = recoverySaltOf(request.recoverySalt); } catch { throw new SdkError("bad-input", { field: "recoverySalt" }); }
|
|
946
|
-
let orderSalt;
|
|
947
|
-
try { orderSalt = recoverySaltOf(request.order.salt); } catch { throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" }); }
|
|
948
|
-
if (salt !== orderSalt) throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" });
|
|
949
|
-
derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: request.order.factory, salt });
|
|
950
|
-
recovery = { storage, key, salt, derivation: "salt-v2", newKey: !saved || saved.backupConfirmed !== true };
|
|
951
|
-
} else {
|
|
952
|
-
let index = explicit ? Number(request.recoveryIndex) : reserveRecoveryIndex(storage, { chainId });
|
|
953
|
-
if (!Number.isSafeInteger(index) || index < 0) throw new SdkError("bad-input", { field: "recoveryIndex" });
|
|
954
|
-
// A BROWSER STORE IS PER DEVICE. The same words opened elsewhere start at the same number, so the factory's own
|
|
955
|
-
// log is asked before the number is used; a taken number is retired locally and the next one is reserved.
|
|
956
|
-
// Without a log seam the previous behaviour is kept - the caller cannot be asked to invent a chain read.
|
|
957
|
-
if (typeof chainLogs === "function" && request.order.factory) {
|
|
958
|
-
// THE CHAIN'S BIRTH HEIGHT IS THE DEFAULT START, NOT ZERO. The factory's own log cannot hold an order
|
|
959
|
-
// before it existed; asking from zero is tens of log queries per number on a public RPC. An explicit
|
|
960
|
-
// `fromBlock` still wins, including the literal zero.
|
|
961
|
-
const chain = config && Array.isArray(config.chains)
|
|
962
|
-
? config.chains.find((entry) => Number(entry.chainId) === Number(chainId)) : null;
|
|
963
|
-
const deploymentBlock = chain && chain.escrow ? chain.escrow.deploymentBlock : null;
|
|
964
|
-
const fromBlock = request.fromBlock !== undefined
|
|
965
|
-
? request.fromBlock
|
|
966
|
-
: (Number.isSafeInteger(deploymentBlock) ? deploymentBlock : 0);
|
|
967
|
-
let hops = 0;
|
|
968
|
-
while (await recoveryIndexTaken({ mnemonic: key.mnemonic, chainId, index, factory: request.order.factory,
|
|
969
|
-
evmLogs: chainLogs, fromBlock })) {
|
|
970
|
-
if (explicit) throw new SdkError("bad-input", { field: "recoveryIndex", why: "on-chain" });
|
|
971
|
-
commitRecoveryIndex(storage, index);
|
|
972
|
-
index = reserveRecoveryIndex(storage, { chainId });
|
|
973
|
-
hops += 1;
|
|
974
|
-
if (!Number.isSafeInteger(index) || index < 0 || hops > 1000) throw new SdkError("bad-input", { field: "recoveryIndex", why: "exhausted" });
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
derived = takerHalves({ mnemonic: key.mnemonic, chainId, index });
|
|
978
|
-
recovery = { storage, key, index, derivation: "index-v1", newKey: !saved || saved.backupConfirmed !== true };
|
|
964
|
+
// THE CLIENT OWNS THE SALT. A maker that chose it could hand the same salt to the same client twice, so
|
|
965
|
+
// the caller composes the signed quote with this value and passes it here. The order's own salt must be
|
|
966
|
+
// the same bytes; a mismatch means the quote is not the one being started.
|
|
967
|
+
if (typeof request.order.factory !== "string" || !request.order.factory) {
|
|
968
|
+
throw new SdkError("bad-input", { field: "order.factory" });
|
|
979
969
|
}
|
|
970
|
+
let salt;
|
|
971
|
+
try { salt = recoverySaltOf(request.recoverySalt); } catch { throw new SdkError("bad-input", { field: "recoverySalt" }); }
|
|
972
|
+
let orderSalt;
|
|
973
|
+
try { orderSalt = recoverySaltOf(request.order.salt); } catch { throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" }); }
|
|
974
|
+
if (salt !== orderSalt) throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" });
|
|
975
|
+
const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: request.order.factory, salt });
|
|
976
|
+
recovery = { storage, key, salt, derivation: "salt-v2", newKey: !saved || saved.backupConfirmed !== true };
|
|
980
977
|
keySide = buildOwnSideFromHalves(request.order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf }).side;
|
|
981
978
|
// THE MAKER'S VIEW HALF IS DERIVED FROM THE KEY, NOT CHOSEN BY THE NODE. Without this binding a
|
|
982
979
|
// signed quote could carry another view half; the funded address would differ from the one the twelve
|
|
@@ -1036,7 +1033,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1036
1033
|
moneroNetwork: step.wallet.network, standIn: step.counterparty.standIn,
|
|
1037
1034
|
providerId: step.counterparty.providerId, orderContext: step.context,
|
|
1038
1035
|
};
|
|
1039
|
-
try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
|
|
1036
|
+
try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
|
|
1040
1037
|
record = { ...record, swapWallet: engine.swap.halvesWalletOf(record.swap) };
|
|
1041
1038
|
if (!record.swapWallet) throw new SdkError("bad-input", { field: "swapWallet" });
|
|
1042
1039
|
builtSide = step;
|
|
@@ -1049,7 +1046,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1049
1046
|
record.swap.restoreHeight = measuredHeight;
|
|
1050
1047
|
record.restoreHeight = measuredHeight;
|
|
1051
1048
|
record.swap.escrow = { ...(record.swap.escrow || {}), moneroRestoreHeight: measuredHeight };
|
|
1052
|
-
try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-restore-height" }); }
|
|
1049
|
+
try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-restore-height" }); }
|
|
1053
1050
|
|
|
1054
1051
|
// 2a. THE KEY IS CONFIRMED ONCE. The same twelve words cover every swap, and a person who already saved them
|
|
1055
1052
|
// is not asked again. A new key is shown before the money moves - no saved key, no funding.
|
|
@@ -1064,12 +1061,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1064
1061
|
} catch { throw new SdkError("recovery-failed", { step: "encrypt-key" }); }
|
|
1065
1062
|
const confirmed = await request.onRecoveryKey(file);
|
|
1066
1063
|
if (confirmed !== true) throw new SdkError("recovery-declined", { key: recovery.key.fingerprint });
|
|
1067
|
-
// ONLY THE PERSON'S TRUE ANSWER MAKES THE KEY "BACKED UP". The record already exists
|
|
1068
|
-
//
|
|
1064
|
+
// ONLY THE PERSON'S TRUE ANSWER MAKES THE KEY "BACKED UP". The record already exists; this flag is what a
|
|
1065
|
+
// later start reads. A failed write is a refusal before any funds move.
|
|
1069
1066
|
try {
|
|
1070
|
-
|
|
1071
|
-
saveRecoveryKey(recovery.storage, { ...recovery.key, nextIndex: stored.nextIndex,
|
|
1072
|
-
reserved: stored.reserved, retired: stored.retired, backupConfirmed: true });
|
|
1067
|
+
saveRecoveryKey(recovery.storage, { ...recovery.key, backupConfirmed: true });
|
|
1073
1068
|
recovery.key = { ...recovery.key, backupConfirmed: true };
|
|
1074
1069
|
} catch { throw new SdkError("storage-unavailable", { step: "save-recovery-key" }); }
|
|
1075
1070
|
}
|
|
@@ -1150,7 +1145,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1150
1145
|
record.swap.escrow = { ...escrowRecord, address: predicted || escrowRecord.address || null,
|
|
1151
1146
|
fundTx: pendingTx || escrowRecord.fundTx || null, fundingPending: true,
|
|
1152
1147
|
fundingReason: funded.pendingReason || "no-receipt" };
|
|
1153
|
-
try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
|
|
1148
|
+
try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
|
|
1154
1149
|
return { id: record.swap.id || null, escrow: record.swap.escrow.address || null,
|
|
1155
1150
|
address: (record.swapWallet && record.swapWallet.address) || null,
|
|
1156
1151
|
step: "funding-pending", txHash: pendingTx,
|
|
@@ -1167,12 +1162,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1167
1162
|
// watch and the recovery file take the Monero height measured above. The old name `birthHeight` stays
|
|
1168
1163
|
// readable on records written before this split.
|
|
1169
1164
|
evmBirthBlock: Number(funded.birthBlock) > 0 ? Number(funded.birthBlock) : (escrowRecord.evmBirthBlock ?? escrowRecord.birthHeight ?? null) };
|
|
1170
|
-
try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
|
|
1171
|
-
// THE
|
|
1172
|
-
// reservation, so a retry uses the same number and the later search has no gap.
|
|
1173
|
-
if (recovery && recovery.index !== undefined) {
|
|
1174
|
-
try { commitRecoveryIndex(recovery.storage, recovery.index); } catch { /* the reservation stays; the key still works */ }
|
|
1175
|
-
}
|
|
1165
|
+
try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
|
|
1166
|
+
// THE SALT IS THE RECOVERY BINDING; there is no index reservation to commit here.
|
|
1176
1167
|
}
|
|
1177
1168
|
|
|
1178
1169
|
// 5. A BACKEND IS OPTIONAL AND NEVER A DEFAULT. When the caller configured an API base, the swap is recorded
|
|
@@ -1267,7 +1258,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1267
1258
|
// durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
|
|
1268
1259
|
// must not start failing where it did not before.
|
|
1269
1260
|
let record = null;
|
|
1270
|
-
try { record = engine.swap.getSwap(id); } catch { record = null; }
|
|
1261
|
+
try { record = engine.swap.getSwap(id, store); } catch { record = null; }
|
|
1271
1262
|
const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
|
|
1272
1263
|
// FROM THE ESCROW'S BIRTH HEIGHT when the record knows it: the event cannot be older than the funding, and
|
|
1273
1264
|
// walking the whole chain every tick is a cost with no answer behind it.
|
|
@@ -1291,7 +1282,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1291
1282
|
const settleDecline = (swap, at) => {
|
|
1292
1283
|
if (!swap || swap.settlement) return;
|
|
1293
1284
|
swap.settlement = { kind: DECLINED_TERMINAL, phase: DECLINED_TERMINAL, at };
|
|
1294
|
-
try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
|
|
1285
|
+
try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
|
|
1295
1286
|
};
|
|
1296
1287
|
// THE STATE THE WATCH REPORTS FOR A DECLINE: no arrival, the state's own code, the node's own token and
|
|
1297
1288
|
// WHERE it was seen ("event", "status", or "record" when it was already written down). NO reason, category
|
|
@@ -1436,7 +1427,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1436
1427
|
claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
|
|
1437
1428
|
resumed: true, next: "send-xmr" };
|
|
1438
1429
|
}
|
|
1439
|
-
const storage =
|
|
1430
|
+
const storage = store.storage();
|
|
1440
1431
|
const supplied = typeof request.recoveryKey === "string"
|
|
1441
1432
|
? request.recoveryKey
|
|
1442
1433
|
: request.recoveryKey && typeof request.recoveryKey.mnemonic === "string" ? request.recoveryKey.mnemonic : null;
|
|
@@ -1448,17 +1439,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1448
1439
|
const chainId = Number(order.chainId);
|
|
1449
1440
|
if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new SdkError("bad-input", { field: "order.chainId" });
|
|
1450
1441
|
if (!order.factory || order.salt === undefined || order.salt === null) throw new SdkError("bad-input", { field: "order" });
|
|
1451
|
-
let
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
derived = takerHalves({ mnemonic: key.mnemonic, chainId, index });
|
|
1456
|
-
} else {
|
|
1457
|
-
let salt = null;
|
|
1458
|
-
try { salt = recoverySaltOf(offer.recovery && offer.recovery.salt ? offer.recovery.salt : order.salt); }
|
|
1459
|
-
catch { throw new SdkError("bad-input", { field: "offer.recovery" }); }
|
|
1460
|
-
derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: order.factory, salt });
|
|
1461
|
-
}
|
|
1442
|
+
let salt = null;
|
|
1443
|
+
try { salt = recoverySaltOf(offer.recovery && offer.recovery.salt ? offer.recovery.salt : order.salt); }
|
|
1444
|
+
catch { throw new SdkError("bad-input", { field: "offer.recovery" }); }
|
|
1445
|
+
const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: order.factory, salt });
|
|
1462
1446
|
const own = buildOwnSideFromHalves(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
|
|
1463
1447
|
// THE OFFER MUST NAME THE HALF THIS KEY ACTUALLY PRODUCES. The relay already checked the proof; the record
|
|
1464
1448
|
// needs the same point and commitment, otherwise a later claim would reveal a half the escrow rejects.
|
|
@@ -1480,12 +1464,13 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1480
1464
|
}
|
|
1481
1465
|
const made = recordModule.createRecord({
|
|
1482
1466
|
side: "sell", network: String(order.chainId),
|
|
1467
|
+
moneroNetwork: xmrNetwork || undefined,
|
|
1483
1468
|
payToken: order.asset || quote.asset || undefined,
|
|
1484
1469
|
payAmount: quote.amount, xmrAmount: Number(quote.xmrAmount) / 1e12,
|
|
1485
1470
|
orderQuoteId: quoteId || undefined,
|
|
1486
1471
|
receiveAddress: order.claimer,
|
|
1487
1472
|
makerId: quote.provider || null,
|
|
1488
|
-
}, { order, side: own.side });
|
|
1473
|
+
}, { order, side: own.side, store });
|
|
1489
1474
|
const swap = made.swap;
|
|
1490
1475
|
swap.side = "sell";
|
|
1491
1476
|
swap.order = order;
|
|
@@ -1511,8 +1496,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1511
1496
|
commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
|
|
1512
1497
|
orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
|
|
1513
1498
|
};
|
|
1514
|
-
|
|
1515
|
-
|
|
1499
|
+
// THE RECORD IS NOT A RECEIPT FOR A GATE THAT FAILED. createRecord has already written it, so a refusal
|
|
1500
|
+
// from the escrow/deadline/slot gate must remove it again; otherwise the interface lists send-xmr for an
|
|
1501
|
+
// order the SDK never checked.
|
|
1502
|
+
try {
|
|
1503
|
+
await sellEscrowGate(offer.escrow, swap.expect);
|
|
1504
|
+
} catch (error) {
|
|
1505
|
+
try { engine.swap.forgetSwap(swap.id, store); } catch { /* the gate's refusal is the actionable one */ }
|
|
1506
|
+
throw error;
|
|
1507
|
+
}
|
|
1508
|
+
try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
|
|
1516
1509
|
return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
|
|
1517
1510
|
xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
|
|
1518
1511
|
resumed: false, next: "send-xmr" };
|
|
@@ -1527,7 +1520,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1527
1520
|
const id = String(request.id || "").trim();
|
|
1528
1521
|
if (!id) throw new SdkError("bad-input", { field: "id" });
|
|
1529
1522
|
let swap = null;
|
|
1530
|
-
try { swap = engine.swap.getSwap(id); } catch { swap = null; }
|
|
1523
|
+
try { swap = engine.swap.getSwap(id, store); } catch { swap = null; }
|
|
1531
1524
|
if (!swap || swap.side !== "sell") throw new SdkError("bad-input", { field: "id", why: "sell-not-found" });
|
|
1532
1525
|
const escrow = request.escrow || (swap.escrow && swap.escrow.address) || null;
|
|
1533
1526
|
const halfClaimer = request.halfClaimer || (swap.escrow && swap.escrow.half) || null;
|
|
@@ -1547,10 +1540,19 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
|
|
|
1547
1540
|
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
1548
1541
|
const escrow = String(request.escrow || "").trim();
|
|
1549
1542
|
if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
|
|
1550
|
-
|
|
1551
|
-
|
|
1543
|
+
// THE WAIT IS BOUNDED BY THE ORDER'S OWN READY DEADLINE, NOT BY A FIXED 20 MINUTES. Ten confirmations
|
|
1544
|
+
// average about twenty minutes, so the old default timed out roughly half of honest sales. A request may
|
|
1545
|
+
// still set an explicit timeout; otherwise the wait covers the remaining time to readyBy plus a margin.
|
|
1552
1546
|
const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
|
|
1553
1547
|
? Number(request.pollMs) : limitOf("watchPollMs", 6_000);
|
|
1548
|
+
let timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
|
|
1549
|
+
? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
|
|
1550
|
+
if (!(Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0)) {
|
|
1551
|
+
try {
|
|
1552
|
+
const deadlines = await flow.orderDeadlines(escrow, { call: reader });
|
|
1553
|
+
timeoutMs = sellWatchTimeoutMs({ configuredMs: timeoutMs, readyBySec: deadlines.readyBy });
|
|
1554
|
+
} catch { /* no deadline read: keep the configured wait */ }
|
|
1555
|
+
}
|
|
1554
1556
|
const started = Date.now();
|
|
1555
1557
|
let lastStatus = null;
|
|
1556
1558
|
let lastError = null;
|
package/src/sweep-restore.mjs
CHANGED
|
@@ -65,7 +65,7 @@ const heightOf = async (driver, name) => {
|
|
|
65
65
|
// AN INCOMPLETE SCAN IS A NAMED OUTCOME, NOT A ZERO BALANCE. The wallet library's sync is best-effort: a node
|
|
66
66
|
// that refuses block downloads leaves a wallet at height 0, and a caller that only reads `unlocked` shows "no
|
|
67
67
|
// XMR". The heights and the sync error decide the verdict here, so the page does not have to guess.
|
|
68
|
-
const scanCompleteness = async (driver, { syncError = null, rescanError = null } = {}) => {
|
|
68
|
+
const scanCompleteness = async (driver, { syncError = null, rescanError = null, spentChecked = true } = {}) => {
|
|
69
69
|
const walletHeight = await heightOf(driver, "getHeight");
|
|
70
70
|
const nodeHeight = await heightOf(driver, "getDaemonHeight");
|
|
71
71
|
let reason = null;
|
|
@@ -76,6 +76,9 @@ const scanCompleteness = async (driver, { syncError = null, rescanError = null }
|
|
|
76
76
|
else if (syncError) reason = "sync-failed";
|
|
77
77
|
else if (walletHeight === null || nodeHeight === null) reason = "no-heights";
|
|
78
78
|
else if (walletHeight < nodeHeight) reason = "behind-node";
|
|
79
|
+
// A BALANCE FROM A WINDOW IS NOT A COMPLETE SCAN WHEN SPENT STATUS WAS NEVER READ. An output spent just after
|
|
80
|
+
// `t1` would still look withdrawable; naming the gap is safer than reporting a complete pass over it.
|
|
81
|
+
else if (!spentChecked) reason = "spent-status-unavailable";
|
|
79
82
|
return { scanComplete: reason === null, ...(reason === null ? {} : { scanIncompleteReason: reason }), walletHeight, nodeHeight };
|
|
80
83
|
};
|
|
81
84
|
|
|
@@ -275,7 +278,8 @@ export async function restoreWallet(request = {}) {
|
|
|
275
278
|
// A WINDOW WITH COINS IS THE ANSWER. A window with none falls through to the full scan unless the caller
|
|
276
279
|
// explicitly turned the fallback off.
|
|
277
280
|
if (windowReport.used && (windowTotal > 0n || windowUnlocked > 0n || requestWindow.fallback === false)) {
|
|
278
|
-
const completeness = await scanCompleteness(driver, { syncError: windowSyncError
|
|
281
|
+
const completeness = await scanCompleteness(driver, { syncError: windowSyncError,
|
|
282
|
+
spentChecked: windowReport.spent !== null && windowReport.spent !== undefined });
|
|
279
283
|
return {
|
|
280
284
|
total: windowTotal.toString(), unlocked: windowUnlocked.toString(), scanHeight,
|
|
281
285
|
...completeness, passes: 1, lockedPass: false, window: windowReport,
|