@ninsei-labs/sdk 0.61.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +56 -5
- package/assets/vendors/MANIFEST.json +1 -1
- package/assets/vendors/sdk/sdk-browser.js +4 -4
- package/engine/atomic/halfenc.js +6 -6
- package/engine/core/config.js +17 -38
- package/engine/core/format.js +1 -1
- package/engine/core/sellWindow.js +1 -1
- package/engine/core/store.js +11 -3
- package/engine/core/swap.js +3 -3
- package/engine/evm/amounts.js +2 -2
- package/engine/evm/asyncRoute.js +3 -3
- package/engine/evm/dex.js +1 -1
- package/engine/evm/factory.js +1 -1
- package/engine/evm/fees.js +62 -0
- package/engine/evm/funding.js +71 -66
- package/engine/evm/gasReserve.js +10 -0
- package/engine/evm/index.js +2 -2
- package/engine/evm/prices.js +3 -0
- package/engine/evm/session.js +1 -1
- package/engine/monero/address.js +4 -2
- package/engine/monero/arrivalRead.js +15 -2
- package/engine/monero/keyImage.js +146 -0
- package/engine/monero/keys.js +1 -0
- package/engine/monero/mnemonic.js +2 -1
- package/engine/monero/node.js +1 -0
- package/engine/monero/scan.js +12 -2
- package/engine/recovery/recoveryFile.js +31 -85
- package/engine/sdk/bridge.js +21 -51
- package/index.d.ts +412 -19
- package/package.json +20 -2
- package/src/actions.mjs +72 -6
- package/src/addressGuard.mjs +16 -0
- package/src/codes.mjs +26 -9
- package/src/config.mjs +56 -3
- package/src/decline.mjs +23 -74
- package/src/firmRequest.mjs +80 -0
- package/src/index.mjs +17 -28
- package/src/legs/cow.mjs +2 -2
- package/src/legs/evm.mjs +20 -12
- package/src/legs/kyber-spec.mjs +2 -2
- package/src/legs/kyber.mjs +1 -1
- package/src/legs/shape.mjs +1 -1
- package/src/legs/uniswaprelay.mjs +16 -4
- package/src/legs/uniswapx.mjs +29 -7
- package/src/levelsWalkSpec.mjs +1 -1
- package/src/lock.mjs +18 -37
- package/src/provider/envFile.mjs +3 -3
- package/src/provider/sign.mjs +3 -3
- package/src/public/evm.d.ts +84 -0
- package/src/public/evm.mjs +20 -0
- package/src/public/order.mjs +1 -1
- package/src/public/provider.mjs +1 -1
- package/src/public/recovery.d.ts +3 -2
- package/src/public/recovery.mjs +1 -1
- package/src/public/xmr.d.ts +2 -2
- package/src/quoteEip712Spec.mjs +4 -4
- package/src/quotes.mjs +52 -11
- package/src/recovery-key.mjs +7 -3
- package/src/relayFirmClient.mjs +4 -0
- package/src/relayQuote.mjs +1 -0
- package/src/sim.mjs +1 -1
- package/src/swap-flow.mjs +22 -32
- package/src/swaps.mjs +63 -56
- package/src/sweep-inputs.mjs +61 -0
- package/src/sweep-reconcile.mjs +71 -0
- package/src/sweep-restore.mjs +38 -9
- package/src/sweep.mjs +164 -10
- package/src/version.mjs +1 -1
- package/src/wallet.mjs +1 -1
- package/src/xmr-arrival.mjs +1041 -43
package/src/swaps.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// order and halves -> server -> watching the Monero address. A lock without a recovery file is a lock with nothing
|
|
6
6
|
// to open it with if the browser is lost, so the confirmation stands BEFORE anything that locks funds.
|
|
7
7
|
import { SdkError } from "./errors.mjs";
|
|
8
|
+
import { checkAddressOrThrow } from "./addressGuard.mjs";
|
|
8
9
|
import { quoteLifeVerdict } from "./quotePolicy.mjs";
|
|
9
10
|
import { SDK_VERSION } from "./version.mjs";
|
|
10
11
|
import * as engine from "./engine.mjs";
|
|
@@ -28,16 +29,16 @@ import { probeMoneroNode } from "./probes.mjs";
|
|
|
28
29
|
// MARKING READY - A FINISHED STEP, NOT A SECOND IMPLEMENTATION OF IT: it requires the order expectations and checks
|
|
29
30
|
// the slots against the chain BEFORE signing (actions.markReady). The watch must call exactly it, otherwise "we saw
|
|
30
31
|
// the XMR" and "we allowed the settlement to be taken" would diverge.
|
|
31
|
-
import { createActions } from "./actions.mjs";
|
|
32
|
-
// THE ONE RECOVERY KEY
|
|
32
|
+
import { createActions, walletError } from "./actions.mjs";
|
|
33
|
+
// THE ONE RECOVERY KEY: the taker's halves come from it, not from a fresh random pair per swap.
|
|
33
34
|
import {
|
|
34
35
|
createRecoveryKeyFile, importRecoveryKey, loadRecoveryKey,
|
|
35
36
|
recoveryKeyFileName, recoverySaltOf, saveRecoveryKey,
|
|
36
37
|
newRecoverySalt, takerHalvesV2,
|
|
37
38
|
} from "./recovery-key.mjs";
|
|
38
|
-
// THE XMR ARRIVAL CHECK ON TWO NODES
|
|
39
|
+
// THE XMR ARRIVAL CHECK ON TWO NODES - IN THE CORE, from the same mirrored rule and block parser.
|
|
39
40
|
import * as xmrArrival from "./xmr-arrival.mjs";
|
|
40
|
-
// THE MAKER'S DECLINE
|
|
41
|
+
// THE MAKER'S DECLINE: the escrow's `Declined` event is the decision. The node's `declined` +
|
|
41
42
|
// `compliance` status is an observation on the wire, not a second source this file trusts; the detectors and the
|
|
42
43
|
// neutral vocabulary live in one module, so this file names the state instead of re-reading either.
|
|
43
44
|
import { declineOf, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0, DECLINED_TERMINAL, DECLINED_CODE } from "./decline.mjs";
|
|
@@ -46,34 +47,9 @@ import { readReadyWindow, readyLeadSec, readyLateSec, readyWindowMs } from "./re
|
|
|
46
47
|
// signed tip. This module speaks that one wire; swaps.mjs decides which record may be claimed.
|
|
47
48
|
import { relayOriginOf, addressTextOf, halfTextOf, postRelayClaim } from "./relayClaim.mjs";
|
|
48
49
|
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
// The
|
|
52
|
-
// `kind: "refund_eth"`), and `xmr_returned` and `closed`, for which no settlement with that kind is written
|
|
53
|
-
// anywhere in the engine or in this package. A REFUND therefore never met its key and fell into the fallback:
|
|
54
|
-
// get/list/progress told the app `closed` about an order whose ETH was already back in the wallet - the very
|
|
55
|
-
// distinction that became load-bearing once the maker's decline was made a state of its own (issue #40).
|
|
56
|
-
//
|
|
57
|
-
// WHAT CAN BE A KIND, EXHAUSTIVELY. The record's settlement belongs to the engine (engine/core/swap.js, the only
|
|
58
|
-
// module that assigns swap.settlement), and `declined` is the one kind written by us (src/decline.mjs):
|
|
59
|
-
// `success` - the swap completed and the XMR is on the depositor's address (sweepNow and the auto-sweep in the
|
|
60
|
-
// ticker; the SDK does not take it from a backend session);
|
|
61
|
-
// `refund_eth` - the ETH went back to the depositor. TWO WRITERS, ONE KIND: the person's own refund (refundEth)
|
|
62
|
-
// and the watchtower inside the ticker both write `kind: "refund_eth"` with the phase
|
|
63
|
-
// `refunded_eth`, so there is exactly ONE refund-shaped kind here and nothing is collapsed;
|
|
64
|
-
// `declined` - the maker refused a funded order. Not the engine's: the escrow reads `refunded` either way, so
|
|
65
|
-
// the engine cannot tell a decline from a refund, and the SDK writes this kind itself when it SEES
|
|
66
|
-
// the decline (src/decline.mjs). From then on every surface that reads the record reports it
|
|
67
|
-
// without asking the chain again.
|
|
68
|
-
//
|
|
69
|
-
// AND WHAT IS NOT A KEY: an unknown kind is named, not invented - it comes out as "closed", the fallback in
|
|
70
|
-
// toState below, which is why `closed` is a code here and not a key (no settlement carries that kind; the string
|
|
71
|
-
// `closed` in the engine is the XMR SESSION's status vocabulary, not a settlement). The maker taking the XMR back
|
|
72
|
-
// without a ready mark is NOT a kind either: it does not end a swap - the depositor's ETH is still in the escrow -
|
|
73
|
-
// so it is a PHASE of a live swap (`xmr_reclaimed`, engine/core/swap.js, told apart by that code from the maker who
|
|
74
|
-
// never locked), and the swap ends later as `refunded_eth`. `xmr_returned`, which stood in the engine's terminal
|
|
75
|
-
// table and in the `TerminalCode` type as a state nothing could produce, is gone with it. Every one of these facts
|
|
76
|
-
// is asserted by the `terminal` check rather than left to a reader.
|
|
50
|
+
// The engine writes `success` and `refund_eth`. The SDK writes `declined` when it sees the maker's decline.
|
|
51
|
+
// An unknown kind is not invented: it becomes `closed` in toState. `closed` is a code, not a settlement kind.
|
|
52
|
+
// The `terminal` check asserts these facts.
|
|
77
53
|
const TERMINAL = {
|
|
78
54
|
success: "success",
|
|
79
55
|
refund_eth: "refunded_eth",
|
|
@@ -81,8 +57,7 @@ const TERMINAL = {
|
|
|
81
57
|
};
|
|
82
58
|
|
|
83
59
|
const num = (v) => {
|
|
84
|
-
//
|
|
85
|
-
// a missing number is a missing fact and the state/interface must see null.
|
|
60
|
+
// Null, undefined and empty are not zero. A missing number is a missing fact, and the state must see null.
|
|
86
61
|
if (v === null || v === undefined || v === "") return null;
|
|
87
62
|
const n = Number(v);
|
|
88
63
|
return Number.isFinite(n) ? n : null;
|
|
@@ -217,7 +192,7 @@ export function toState(swap) {
|
|
|
217
192
|
status: d.phase || null,
|
|
218
193
|
txs: (swap.escrow && (swap.escrow.txids || swap.escrow.txs)) || [],
|
|
219
194
|
},
|
|
220
|
-
// A DECLINED ORDER OFFERS NOTHING, AND THAT IS THE POINT OF THE STATE
|
|
195
|
+
// A DECLINED ORDER OFFERS NOTHING, AND THAT IS THE POINT OF THE STATE. The ETH - the fee
|
|
221
196
|
// included - is already back in the depositor's wallet and no half was revealed, so there is no ready mark to
|
|
222
197
|
// place, no XMR to sweep and NO REFUND TO SIGN: the flags are OFF rather than left to whatever the engine's
|
|
223
198
|
// `can` says about an order whose escrow merely reads `refunded`. The app needs no second source for "there
|
|
@@ -417,15 +392,16 @@ function swapByEscrow(store, escrow) {
|
|
|
417
392
|
}
|
|
418
393
|
|
|
419
394
|
export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, fetchImpl = null, now = null, sleep = null, evmBlock = null, store = engine.store,
|
|
395
|
+
chunkOptions = null,
|
|
420
396
|
// THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
|
|
421
397
|
// no server step and no route table to consult.
|
|
422
398
|
config = null,
|
|
423
|
-
// THE INTERFACE'S ADDRESS DENYLIST
|
|
399
|
+
// THE INTERFACE'S ADDRESS DENYLIST, a Set of lower-cased addresses already assembled by the facade.
|
|
424
400
|
// The check on the ACTUAL sender is done in start() below, ONE place, right before the send - the wallet adapter
|
|
425
401
|
// only HANDS OUT the current account (`address()`), it does not carry the policy.
|
|
426
402
|
denylist = null,
|
|
427
403
|
watch: watchOptions = null,
|
|
428
|
-
// THE CHAIN LOG READER FOR THE DECLINE CHECK
|
|
404
|
+
// THE CHAIN LOG READER FOR THE DECLINE CHECK. A seam, as the chain read is: by default the logs are
|
|
429
405
|
// read through the page's wallet (`readDeclinedLogs`), and from outside a caller brings its own
|
|
430
406
|
// ({ address, topics, fromBlock, toBlock }) -> logs. It is a READ of the escrow's own event, not a node
|
|
431
407
|
// substitution - the address is the escrow of the swap being watched.
|
|
@@ -484,7 +460,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
484
460
|
// for hosts that did not configure `evmBlock` at all (simulation and tests).
|
|
485
461
|
if (typeof evmBlock === "function") return null;
|
|
486
462
|
if (typeof now === "function") {
|
|
487
|
-
|
|
463
|
+
// AN INJECTED CLOCK THAT IS NOT A NUMBER IS NOT A DEVICE CLOCK. The old `clockMs` fallback turned NaN into
|
|
464
|
+
// Date.now(), so a broken caller clock silently became a valid one.
|
|
465
|
+
const value = Math.floor(Number(now()) / 1000);
|
|
488
466
|
return Number.isSafeInteger(value) && value > 0 ? value : null;
|
|
489
467
|
}
|
|
490
468
|
return null;
|
|
@@ -682,7 +660,15 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
682
660
|
// Compatibility with a caller that has neither a wallet nor a block seam: the reads still go to `latest`,
|
|
683
661
|
// and the deadline falls back to the documented `now` seam. A live sell carries one of the two.
|
|
684
662
|
const gate = { call: reader, blockTag: snapshot ? snapshot.blockTag : "latest" };
|
|
685
|
-
|
|
663
|
+
let chainNow = snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0
|
|
664
|
+
? Number(snapshot.timestamp) : null;
|
|
665
|
+
if (chainNow === null) {
|
|
666
|
+
const raw = typeof now === "function" ? Number(now()) : Date.now();
|
|
667
|
+
chainNow = Number.isFinite(raw) ? Math.floor(raw / 1000) : null;
|
|
668
|
+
}
|
|
669
|
+
if (!Number.isSafeInteger(chainNow) || chainNow <= 0) {
|
|
670
|
+
throw new SdkError("quote-refused", { step: "send-xmr", why: "clock-unreadable" });
|
|
671
|
+
}
|
|
686
672
|
let status = null;
|
|
687
673
|
try { status = await flow.orderStatus(escrow, gate); }
|
|
688
674
|
catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-unreadable" }); }
|
|
@@ -811,6 +797,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
811
797
|
// THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
|
|
812
798
|
// want to run both itself. The watch uses exactly these, so there is one decision, not two.
|
|
813
799
|
verifyArrival: (request) => xmrArrival.verifyArrival(withDefaultFetch(request)),
|
|
800
|
+
verifyArrivalFromRead: (request) => xmrArrival.verifyArrivalFromRead(withDefaultFetch(request)),
|
|
801
|
+
verifyRecovery: (request) => xmrArrival.verifyRecovery(withDefaultFetch(request)),
|
|
802
|
+
readRecovery: (request) => xmrArrival.readRecovery(withDefaultFetch(request)),
|
|
803
|
+
readRecoveryWitness: (request) => xmrArrival.readRecoveryWitness(withDefaultFetch(request)),
|
|
814
804
|
/**
|
|
815
805
|
* SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
|
|
816
806
|
* slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
|
|
@@ -820,7 +810,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
820
810
|
assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
|
|
821
811
|
|
|
822
812
|
/**
|
|
823
|
-
* THE CLIENT'S OWN EARLY REFUND WHEN THE XMR DID NOT ARRIVE
|
|
813
|
+
* THE CLIENT'S OWN EARLY REFUND WHEN THE XMR DID NOT ARRIVE. After `readyBy` the maker may claim
|
|
824
814
|
* even without the ready mark, and the early-refund window closes; so while the interface is open a depositor
|
|
825
815
|
* who sees no XMR must take the ETH back BEFORE `readyBy`. The arrival is decided by THE SAME rule the watch
|
|
826
816
|
* uses (xmr-arrival.verifyArrival): two nodes of different operators on one block, and money barred by
|
|
@@ -930,13 +920,16 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
930
920
|
if (request.side === "sell") {
|
|
931
921
|
throw new SdkError("bad-input", { field: "side", why: "sell-not-supported", surface: "swaps.start" });
|
|
932
922
|
}
|
|
923
|
+
if (!request.receiveTo || typeof request.receiveTo !== "string") throw new SdkError("bad-input", { field: "receiveTo" });
|
|
924
|
+
// THE RECIPIENT IS CHECKED BEFORE THE QUOTE, THE RECOVERY KEY OR THE CHAIN. A bad checksum or another Monero
|
|
925
|
+
// network would otherwise be recorded into the swap and only discovered at withdrawal, after the XMR had arrived.
|
|
926
|
+
await checkAddressOrThrow(request.receiveTo, xmrNetwork, "receiveTo");
|
|
933
927
|
if (!request.quote || typeof request.quote !== "object") throw new SdkError("bad-input", { field: "quote" });
|
|
934
928
|
// THE PER-SWAP FILE PATH IS GONE. One key covers every swap, and a per-swap file issued before funding cannot
|
|
935
929
|
// name the escrow (it does not exist yet), so `sweep.plan` could not read the revealed half from it.
|
|
936
930
|
if (request.recoveryKey === undefined || request.recoveryKey === null) {
|
|
937
931
|
throw new SdkError("bad-input", { field: "recoveryKey", why: "required" });
|
|
938
932
|
}
|
|
939
|
-
if (!request.receiveTo || typeof request.receiveTo !== "string") throw new SdkError("bad-input", { field: "receiveTo" });
|
|
940
933
|
// A START WITHOUT THE SIGNED XMR AMOUNT IS NOT A START. `quote.size` is a rounded display value and the relay
|
|
941
934
|
// answer does not carry it; the arrival check needs the exact integer the order quote signed. Refuse here, before
|
|
942
935
|
// a wallet or a funding send, instead of recording an incomplete swap that later reads "no amount".
|
|
@@ -1138,6 +1131,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1138
1131
|
const step = await orderStepChunked({
|
|
1139
1132
|
order: request.order, side: made.side || null, counterparty: request.counterparty || null,
|
|
1140
1133
|
standIn: mode !== "live", network: (record.swap.moneroNetwork || xmrNetwork || null),
|
|
1134
|
+
options: chunkOptions || {},
|
|
1141
1135
|
});
|
|
1142
1136
|
// THE RECORD FIELDS ARE UNDER THE VERY NAMES THE ENGINE READS. So the record, after a page reload, again yields a
|
|
1143
1137
|
// wallet from the halves (`halvesWalletOf`), rather than losing the address together with the tab.
|
|
@@ -1196,7 +1190,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1196
1190
|
if (!wallet || typeof wallet.send !== "function" || typeof wallet.receipt !== "function") {
|
|
1197
1191
|
throw new SdkError("bad-input", { field: "wallet", missing: ["send", "receipt"], surface: "swaps.start", step: "lock" });
|
|
1198
1192
|
}
|
|
1199
|
-
// THE INTERFACE'S ADDRESS DENYLIST, ON THE ACTUAL SENDER
|
|
1193
|
+
// THE INTERFACE'S ADDRESS DENYLIST, ON THE ACTUAL SENDER. The person may have switched accounts
|
|
1200
1194
|
// in the wallet, so what matters is the address the funding transaction will really be sent from AT THIS
|
|
1201
1195
|
// MOMENT, not `order.locker` checked earlier. The wallet adapter hands out the current account (the adapter's
|
|
1202
1196
|
// `address()` reads `eth_accounts[0]`); the comparison lives HERE, one place, right before the send - not
|
|
@@ -1227,7 +1221,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1227
1221
|
} : {};
|
|
1228
1222
|
const lockRequest = { ...request.order, ...derived, amountWei: request.order.amount };
|
|
1229
1223
|
// THE SIGNED QUOTE: the fee, the registry address and the provider live in IT, not in the factory
|
|
1230
|
-
|
|
1224
|
+
//. The caller brings it (the interface got it from the maker); without it the lock is not signed.
|
|
1231
1225
|
// THE QUOTE MUST NAME THE SAME COUNTERPARTY HALF THAT WAS VERIFIED. `orderStep` verifies
|
|
1232
1226
|
// `request.counterparty`, while funding encodes `request.orderQuote`; a caller that brings both can otherwise
|
|
1233
1227
|
// prove one point and fund another. The same comparison is repeated in funding.js, at the money boundary.
|
|
@@ -1245,23 +1239,33 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1245
1239
|
}
|
|
1246
1240
|
// THE SIGNED QUOTE MUST STILL BE VALID WHEN THE MONEY MOVES. The proof and the record work take seconds; a
|
|
1247
1241
|
// quote that expired in that window would reach the wallet and revert at the factory. Check the signed field
|
|
1248
|
-
// immediately before the send, with a small margin for the next block.
|
|
1242
|
+
// immediately before the send, against the CHAIN clock, with a small margin for the next block.
|
|
1243
|
+
let lockNowSec = null;
|
|
1249
1244
|
const validUntil = request.orderQuote && request.orderQuote.validUntil !== undefined
|
|
1250
1245
|
? request.orderQuote.validUntil
|
|
1251
1246
|
: undefined;
|
|
1252
1247
|
if (validUntil !== undefined && validUntil !== null) {
|
|
1253
1248
|
const until = Number(validUntil);
|
|
1254
|
-
//
|
|
1255
|
-
|
|
1256
|
-
|
|
1249
|
+
// AN UNREADABLE BLOCK IS A NAMED REFUSAL, NOT AN UNCODED ERROR. The sell gate already maps this failure to
|
|
1250
|
+
// `block-unreadable`; the lock path must speak the same vocabulary.
|
|
1251
|
+
let snapshot = null;
|
|
1252
|
+
try { snapshot = await chainSnapshot(wallet); }
|
|
1253
|
+
catch { throw new SdkError("quote-unchecked", { step: "lock", why: "clock-unreadable" }); }
|
|
1254
|
+
lockNowSec = snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0
|
|
1255
|
+
? Number(snapshot.timestamp)
|
|
1256
|
+
: (typeof evmBlock === "function" ? null
|
|
1257
|
+
: Math.floor(Number(typeof now === "function" ? now() : Date.now()) / 1000));
|
|
1258
|
+
if (!Number.isSafeInteger(lockNowSec) || lockNowSec <= 0) {
|
|
1259
|
+
throw new SdkError("quote-unchecked", { step: "lock", why: "clock-unreadable" });
|
|
1260
|
+
}
|
|
1257
1261
|
// THE PREPARATION WAS ALREADY PAID FOR AT THE ANSWER. This check runs after the proof, the record and the
|
|
1258
1262
|
// chain reads; requiring START_PREP_SEC again would refuse a quote that the answer accepted and spent those
|
|
1259
1263
|
// seconds on. Only the next-block margin remains between here and the send.
|
|
1260
|
-
const life = quoteLifeVerdict({ validUntil: until, nowSec, side: "ask", prepSec: 0 });
|
|
1264
|
+
const life = quoteLifeVerdict({ validUntil: until, nowSec: lockNowSec, side: "ask", prepSec: 0 });
|
|
1261
1265
|
if (!life.ok) {
|
|
1262
1266
|
throw new SdkError("quote-expired", {
|
|
1263
1267
|
validUntil: Number.isFinite(until) ? until : null,
|
|
1264
|
-
now:
|
|
1268
|
+
now: lockNowSec,
|
|
1265
1269
|
remainingSec: life.remainingSec,
|
|
1266
1270
|
marginSec: life.marginSec,
|
|
1267
1271
|
prepSec: life.prepSec,
|
|
@@ -1284,7 +1288,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1284
1288
|
catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
|
|
1285
1289
|
};
|
|
1286
1290
|
let funded = null;
|
|
1287
|
-
try { funded = await lock.send(lockRequest, wallet, { call: reader, onPredicted: notePredicted }); }
|
|
1291
|
+
try { funded = await lock.send(lockRequest, wallet, { call: reader, nowSec: lockNowSec, onPredicted: notePredicted }); }
|
|
1288
1292
|
catch (error) {
|
|
1289
1293
|
// A REJECTION BEFORE BROADCAST MUST NOT LEAVE THE SWAP STUCK IN funding-pending. The pre-send record exists
|
|
1290
1294
|
// for a process that dies while the send is in flight; an explicit wallet refusal is the other case, and the
|
|
@@ -1295,8 +1299,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1295
1299
|
record.swap.escrow = { ...record.swap.escrow, fundingPending: false, fundingReason: "send-rejected" };
|
|
1296
1300
|
try { engine.swap.saveSwap(record.swap, store); } catch { /* the pending record stays; never resend blind */ }
|
|
1297
1301
|
}
|
|
1298
|
-
|
|
1299
|
-
|
|
1302
|
+
// A NUMERIC WALLET ERROR IS NOT A SERVER FAILURE. Use the same classifier as markReady/claim/refund:
|
|
1303
|
+
// 4001 stays a rejection, 4100/-32002/transport stay wallet-side, and only a real revert is a chain answer.
|
|
1304
|
+
throw walletError(error, "lock");
|
|
1300
1305
|
}
|
|
1301
1306
|
// A SENT TRANSACTION IS NOT A FUNDED ESCROW. Without a status-1 receipt and the expected OrderCreated, the
|
|
1302
1307
|
// address is unknown and calling the step xmr-incoming would make the person wait for XMR at a guess. Keep
|
|
@@ -1400,7 +1405,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1400
1405
|
: (config && typeof config.nodesFor === "function" ? config.nodesFor(request.verify.network || request.network || xmrNetwork) : []),
|
|
1401
1406
|
minConfirmations }
|
|
1402
1407
|
: null;
|
|
1403
|
-
// LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED
|
|
1408
|
+
// LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED.
|
|
1404
1409
|
if (verifyRequest) {
|
|
1405
1410
|
if (!readyWindowRaw) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
|
|
1406
1411
|
const readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
|
|
@@ -1428,7 +1433,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1428
1433
|
}
|
|
1429
1434
|
if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
|
|
1430
1435
|
const started = Date.now();
|
|
1431
|
-
// --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL
|
|
1436
|
+
// --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL. -------------------------------------
|
|
1432
1437
|
// A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
|
|
1433
1438
|
// this, the wait runs to its timeout and the app is told the generic `xmr-timeout` about an order that is
|
|
1434
1439
|
// CLOSED and whose ETH is already back - or, worse, the app offers the recovery file and a manual refund
|
|
@@ -2023,8 +2028,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
2023
2028
|
params: entry.params || null, txid: entry.txid || null,
|
|
2024
2029
|
}));
|
|
2025
2030
|
const latest = priorAttempts[priorAttempts.length - 1];
|
|
2026
|
-
|
|
2027
|
-
|
|
2031
|
+
// A PREVIOUS ATTEMPT OWNS ITS SLOT EVEN WHEN IT REFUSED. The refusal proves that THIS POST sent nothing, but
|
|
2032
|
+
// the next call still starts after the slot closes: the retry is bounded by the same clock as a first run and
|
|
2033
|
+
// cannot race a request whose answer was lost or still in flight.
|
|
2034
|
+
if (latest && Number.isFinite(Number(latest.at))) {
|
|
2028
2035
|
const gate = await windowOf();
|
|
2029
2036
|
if (!gate.ok) {
|
|
2030
2037
|
// A PRIOR ATTEMPT MAY HAVE SENT THE HALF. The same late-read rule as the sender loop applies here: do not
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// THE INPUTS OF THE SIGNED TRANSACTION ARE THE UNSPENT OUTPUTS THE CALLER VERIFIED.
|
|
2
|
+
//
|
|
3
|
+
// The page used to parse the serialized transaction itself. That parser is tied to the transaction format; the SDK
|
|
4
|
+
// owns the comparison now. The signed transaction object exposes its inputs through the wallet library, so a format
|
|
5
|
+
// change does not silently turn the check off.
|
|
6
|
+
import { SdkError } from "./errors.mjs";
|
|
7
|
+
|
|
8
|
+
const HASH = /^[0-9a-f]{64}$/i;
|
|
9
|
+
const lower = (value) => String(value).toLowerCase();
|
|
10
|
+
|
|
11
|
+
// `sweep.keyImages` returns records; a page that already has the hex strings may pass those instead.
|
|
12
|
+
export function normalizeKeyImages(value) {
|
|
13
|
+
if (!Array.isArray(value)) throw new SdkError("bad-input", { field: "keyImages" });
|
|
14
|
+
const images = value.map((entry, position) => {
|
|
15
|
+
const image = typeof entry === "string" ? entry : entry && entry.keyImage;
|
|
16
|
+
if (typeof image !== "string" || !HASH.test(image)) {
|
|
17
|
+
throw new SdkError("bad-input", { field: "keyImages", why: "key-image", position });
|
|
18
|
+
}
|
|
19
|
+
return lower(image);
|
|
20
|
+
});
|
|
21
|
+
if (!images.length) throw new SdkError("bad-input", { field: "keyImages", why: "empty" });
|
|
22
|
+
if (new Set(images).size !== images.length) throw new SdkError("bad-input", { field: "keyImages", why: "duplicate" });
|
|
23
|
+
return images;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The wallet library's signed transaction carries `getInputs()` and each input carries its key image. A signed
|
|
27
|
+
// object that cannot answer is unknown, never an empty set: an empty set would falsely match a caller with no images.
|
|
28
|
+
export function signedKeyImages(signed) {
|
|
29
|
+
const list = Array.isArray(signed) ? signed : (signed === null || signed === undefined ? [] : [signed]);
|
|
30
|
+
const images = [];
|
|
31
|
+
for (const tx of list) {
|
|
32
|
+
if (!tx || typeof tx.getInputs !== "function") {
|
|
33
|
+
throw new SdkError("sweep-inputs-unknown", { why: "no-inputs" });
|
|
34
|
+
}
|
|
35
|
+
const inputs = tx.getInputs();
|
|
36
|
+
if (!Array.isArray(inputs)) throw new SdkError("sweep-inputs-unknown", { why: "inputs-shape" });
|
|
37
|
+
for (const input of inputs) {
|
|
38
|
+
const keyImage = input && typeof input.getKeyImage === "function" ? input.getKeyImage() : input && input.keyImage;
|
|
39
|
+
const hex = typeof keyImage === "string" ? keyImage
|
|
40
|
+
: (keyImage && typeof keyImage.getHex === "function" ? keyImage.getHex() : keyImage && keyImage.hex);
|
|
41
|
+
if (typeof hex !== "string" || !HASH.test(hex)) {
|
|
42
|
+
throw new SdkError("sweep-inputs-unknown", { why: "key-image" });
|
|
43
|
+
}
|
|
44
|
+
images.push(lower(hex));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!images.length) throw new SdkError("sweep-inputs-unknown", { why: "empty" });
|
|
48
|
+
if (new Set(images).size !== images.length) throw new SdkError("sweep-inputs-unknown", { why: "duplicate" });
|
|
49
|
+
return images;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function sameKeyImages(left, right) {
|
|
53
|
+
if (left.length !== right.length) return false;
|
|
54
|
+
const expected = new Set(left);
|
|
55
|
+
return right.every((image) => expected.has(image));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function assertSameKeyImages(expected, actual, phase) {
|
|
59
|
+
if (sameKeyImages(expected, actual)) return;
|
|
60
|
+
throw new SdkError("sweep-inputs-changed", { phase, expected: expected.length, signed: actual.length });
|
|
61
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// A LATER LOOK AT A SIGNED WITHDRAWAL. The session token is gone; only the signed bytes, their hash and the inputs
|
|
2
|
+
// that were verified before signing remain. This is a decision over ONE read of the swap address, never a relay:
|
|
3
|
+
// a present hash sends nothing, an incomplete read keeps the bytes and signs nothing, and only a complete read that
|
|
4
|
+
// shows both the hash absent and every input unspent permits the very same bytes to be sent again.
|
|
5
|
+
import { SdkError } from "./errors.mjs";
|
|
6
|
+
|
|
7
|
+
const HASH64 = /^[0-9a-f]{64}$/;
|
|
8
|
+
|
|
9
|
+
const normalizedTxid = (value) => String(value == null ? "" : value).replace(/^0x/i, "").toLowerCase();
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Turn one recovery read into the reconcile answer. `read.target` is filled by `readRecovery` when the signed hash
|
|
13
|
+
* was found in a block or in the pool; `read.spends` names the key images the same read saw spent.
|
|
14
|
+
*/
|
|
15
|
+
export function reconcileVerdict({ read, txid, keyImages }) {
|
|
16
|
+
const hash = normalizedTxid(txid);
|
|
17
|
+
if (!HASH64.test(hash)) throw new SdkError("bad-input", { field: "txid" });
|
|
18
|
+
if (!read || typeof read !== "object") throw new SdkError("bad-input", { field: "read" });
|
|
19
|
+
const wanted = new Set((keyImages || []).map((image) => normalizedTxid(image && image.keyImage !== undefined ? image.keyImage : image)));
|
|
20
|
+
const spent = (read.spends || []).filter((spend) => wanted.has(normalizedTxid(spend.keyImage)));
|
|
21
|
+
if (read.target) {
|
|
22
|
+
return {
|
|
23
|
+
outcome: "present",
|
|
24
|
+
resend: false,
|
|
25
|
+
txid: hash,
|
|
26
|
+
height: read.target.height === undefined ? null : read.target.height,
|
|
27
|
+
blockHash: read.target.blockHash === undefined ? null : read.target.blockHash,
|
|
28
|
+
pool: read.target.pool === true,
|
|
29
|
+
complete: read.complete === true,
|
|
30
|
+
failed: read.failed || [],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (spent.length) {
|
|
34
|
+
return {
|
|
35
|
+
outcome: "inputs-spent",
|
|
36
|
+
resend: false,
|
|
37
|
+
txid: hash,
|
|
38
|
+
height: null,
|
|
39
|
+
blockHash: null,
|
|
40
|
+
pool: spent.some((spend) => spend.pool === true),
|
|
41
|
+
complete: read.complete === true,
|
|
42
|
+
failed: read.failed || [],
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// A START ABOVE THE TIP READ NO BLOCKS. The pool is read by readRecovery, but an absent hash there is not proof
|
|
46
|
+
// that the hash is absent from the chain: the caller named a range that never reached a block.
|
|
47
|
+
const noBlockRange = read.through === null && Number.isFinite(read.fromHeight) && Number.isFinite(read.tip)
|
|
48
|
+
&& read.fromHeight > Math.max(0, read.tip - 1);
|
|
49
|
+
if (read.complete !== true || noBlockRange) {
|
|
50
|
+
return {
|
|
51
|
+
outcome: "unknown",
|
|
52
|
+
resend: false,
|
|
53
|
+
txid: hash,
|
|
54
|
+
height: null,
|
|
55
|
+
blockHash: null,
|
|
56
|
+
pool: false,
|
|
57
|
+
complete: read.complete === true && !noBlockRange,
|
|
58
|
+
failed: read.failed || [],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
outcome: "absent",
|
|
63
|
+
resend: true,
|
|
64
|
+
txid: hash,
|
|
65
|
+
height: null,
|
|
66
|
+
blockHash: null,
|
|
67
|
+
pool: false,
|
|
68
|
+
complete: true,
|
|
69
|
+
failed: read.failed || [],
|
|
70
|
+
};
|
|
71
|
+
}
|
package/src/sweep-restore.mjs
CHANGED
|
@@ -270,9 +270,22 @@ export async function restoreWallet(request = {}) {
|
|
|
270
270
|
});
|
|
271
271
|
const body = response && response.ok === true ? await response.json() : null;
|
|
272
272
|
if (body && Array.isArray(body.spent_status)) {
|
|
273
|
-
windowReport.spent = body.spent_status.filter((value) => value === true || value === 1).length;
|
|
274
273
|
windowReport.keyImages = hexes.length;
|
|
275
|
-
|
|
274
|
+
// The node must answer for every key image, and only 0, 1 or 2 are known. A short, long or
|
|
275
|
+
// non-integer list is not a spent count.
|
|
276
|
+
const statuses = body.spent_status;
|
|
277
|
+
const valid = statuses.length === hexes.length
|
|
278
|
+
&& statuses.every((value) => Number.isInteger(value) && value >= 0 && value <= 2);
|
|
279
|
+
if (valid) {
|
|
280
|
+
windowReport.spent = statuses.filter((value) => value === 1 || value === 2).length;
|
|
281
|
+
} else {
|
|
282
|
+
windowReport.spent = null;
|
|
283
|
+
windowReport.spentWhy = "spent-status-invalid";
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
windowReport.spent = null;
|
|
287
|
+
windowReport.spentWhy = "spent-status-unreadable";
|
|
288
|
+
}
|
|
276
289
|
} else { windowReport.spent = null; windowReport.spentWhy = "no-key-images"; }
|
|
277
290
|
} catch { windowReport.spent = null; windowReport.spentWhy = "check-failed"; }
|
|
278
291
|
} else if (windowReport.used && requestWindow.nodeUrl) {
|
|
@@ -320,20 +333,36 @@ export async function restoreWallet(request = {}) {
|
|
|
320
333
|
let unlocked = asAmount(await step("unlockedBalance", () => wallet.unlockedBalance()), "unlockedBalance");
|
|
321
334
|
let passes = 1;
|
|
322
335
|
let lockedPass = false;
|
|
336
|
+
// A LOCKED BALANCE MAY NEED THE OPTIONAL SPENT-STATUS PASS. A public node can refuse that call; the full scan
|
|
337
|
+
// itself is still complete, but "no spendable coins" cannot be read as "nothing is locked" when the status was
|
|
338
|
+
// never checked. Keep the scan and name the missing fact instead of failing the whole restore.
|
|
339
|
+
let spentChecked = true;
|
|
323
340
|
|
|
324
341
|
// THE SECOND PASS: coins exist but none is spendable. The spent status is re-checked and the wallet is synced
|
|
325
342
|
// again; the arrival may have been locked by time rather than lost.
|
|
326
343
|
const rescanWhenLocked = request.rescanWhenLocked !== false;
|
|
327
|
-
if (rescanWhenLocked && total > 0n && unlocked === 0n &&
|
|
344
|
+
if (rescanWhenLocked && total > 0n && unlocked === 0n && passes < PASSES) {
|
|
328
345
|
lockedPass = true;
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
346
|
+
if (typeof driver.rescanSpent !== "function") {
|
|
347
|
+
spentChecked = false;
|
|
348
|
+
} else {
|
|
349
|
+
try {
|
|
350
|
+
await step("rescanSpent", () => driver.rescanSpent());
|
|
351
|
+
} catch {
|
|
352
|
+
// THE OPTIONAL PASS IS NOT THE FULL SCAN. A node that refuses `rescanSpent` must not discard the balances
|
|
353
|
+
// already read; the caller receives `spent-status-unavailable` and can still decide what to do.
|
|
354
|
+
spentChecked = false;
|
|
355
|
+
}
|
|
356
|
+
if (spentChecked) {
|
|
357
|
+
try { await wallet.sync(); } catch (error) { syncError = error; }
|
|
358
|
+
total = asAmount(await step("getBalance", () => driver.getBalance()), "balance");
|
|
359
|
+
unlocked = asAmount(await step("unlockedBalance", () => wallet.unlockedBalance()), "unlockedBalance");
|
|
360
|
+
passes += 1;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
334
363
|
}
|
|
335
364
|
|
|
336
|
-
const completeness = await scanCompleteness(driver, { syncError, rescanError });
|
|
365
|
+
const completeness = await scanCompleteness(driver, { syncError, rescanError, spentChecked });
|
|
337
366
|
return {
|
|
338
367
|
total: total.toString(),
|
|
339
368
|
unlocked: unlocked.toString(),
|