@ninsei-labs/sdk 0.57.2 → 0.58.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 +16 -0
- package/README.md +64 -27
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/assets/vendors/MANIFEST.json +1 -9
- package/assets/vendors/sdk/sdk-browser.js +4 -4
- package/engine/core/config.js +3 -22
- package/engine/core/rfqSource.js +6 -133
- package/engine/core/swap.js +1 -1
- package/engine/evm/index.js +3 -2
- package/engine/evm/session.js +46 -277
- package/engine/monero/address.js +15 -33
- package/engine/monero/keys.js +124 -0
- package/engine/monero/mnemonic.js +104 -0
- package/engine/monero/scan.js +23 -9
- package/engine/monero/wallet.js +31 -68
- package/engine/monero/wordlist.en.js +210 -0
- package/engine/recovery/restore.js +1 -1
- package/engine/sdk/bridge.js +7 -182
- package/engine/ui/walletModal.js +7 -27
- package/index.d.ts +187 -252
- package/package.json +4 -5
- package/src/codes.mjs +12 -0
- package/src/config.mjs +16 -54
- package/src/engine.mjs +3 -0
- package/src/index.mjs +24 -45
- package/src/order.mjs +2 -2
- package/src/public/recovery.d.ts +17 -1
- package/src/public/recovery.mjs +1 -0
- package/src/quotePolicy.mjs +25 -0
- package/src/quotes.mjs +21 -751
- package/src/readyWindow.mjs +76 -0
- package/src/recovery-key.mjs +39 -2
- package/src/recovery.mjs +11 -28
- package/src/relayClaim.mjs +132 -0
- package/src/relayFirmClient.mjs +3 -0
- package/src/relayQuote.mjs +5 -1
- package/src/swap-flow.mjs +49 -5
- package/src/swaps.mjs +301 -307
- package/src/sweep-action.mjs +73 -0
- package/src/sweep.mjs +7 -1
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +275 -7
- package/src/xmrAmountPolicy.mjs +35 -0
- package/assets/vendors/monero/monero-js-browser.js +0 -58
- package/assets/vendors/monero-js/LICENSE +0 -9
- package/assets/vendors/walletconnect/wc-browser.js +0 -6202
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// THE ORDER ACTION A RECOVERED HALF AUTHORIZES.
|
|
2
|
+
//
|
|
3
|
+
// A recovery caller finds an order on chain and needs two things: the half it can present, and the
|
|
4
|
+
// expectations the action's slot check compares against the live escrow. Both are derived here from the same
|
|
5
|
+
// found order and taker halves `sweep.fromOrder` already uses, so a page does not assemble a second copy of the
|
|
6
|
+
// order fields.
|
|
7
|
+
//
|
|
8
|
+
// THIS MODULE DECIDES NO STATE AND NO TIME. Whether the refund or claim window is open belongs to the caller:
|
|
9
|
+
// it reads the escrow's events and the order's deadlines. This function only says which action the half can
|
|
10
|
+
// authorize and what the live order must look like before signing.
|
|
11
|
+
|
|
12
|
+
import { SdkError } from "./errors.mjs";
|
|
13
|
+
|
|
14
|
+
const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
15
|
+
const FIELD_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
16
|
+
const INTEGER_RE = /^\d+$/;
|
|
17
|
+
|
|
18
|
+
const addressOf = (value) => (typeof value === "string" && ADDRESS_RE.test(value) ? value.toLowerCase() : null);
|
|
19
|
+
const fieldOf = (value) => (typeof value === "string" && FIELD_RE.test(value) ? value.toLowerCase() : null);
|
|
20
|
+
|
|
21
|
+
export function actionMaterialOf({ order = null, chainId = null, half = null } = {}) {
|
|
22
|
+
if (!order || typeof order !== "object") throw new SdkError("bad-input", { field: "order" });
|
|
23
|
+
const chain = Number(chainId);
|
|
24
|
+
if (!Number.isSafeInteger(chain) || chain <= 0) throw new SdkError("bad-input", { field: "chainId" });
|
|
25
|
+
const side = order.side;
|
|
26
|
+
if (side !== "locker" && side !== "claimer") throw new SdkError("bad-input", { field: "order.side" });
|
|
27
|
+
|
|
28
|
+
const escrow = addressOf(order.escrow);
|
|
29
|
+
const locker = addressOf(order.locker);
|
|
30
|
+
const claimer = addressOf(order.claimer);
|
|
31
|
+
const factory = addressOf(order.factory);
|
|
32
|
+
const salt = fieldOf(order.salt);
|
|
33
|
+
const commitHalfLocker = fieldOf(order.commitHalfLocker);
|
|
34
|
+
const commitHalfClaimer = fieldOf(order.commitHalfClaimer);
|
|
35
|
+
const edPointLocker = fieldOf(order.edPointLocker);
|
|
36
|
+
const edPointClaimer = fieldOf(order.edPointClaimer);
|
|
37
|
+
const edViewPointLocker = fieldOf(order.edViewPointLocker);
|
|
38
|
+
const ownHalf = fieldOf(half);
|
|
39
|
+
const amount = typeof order.amount === "string" ? order.amount
|
|
40
|
+
: typeof order.amount === "bigint" ? order.amount.toString() : null;
|
|
41
|
+
const readyBy = Number(order.readyBy);
|
|
42
|
+
const t1 = Number(order.t1);
|
|
43
|
+
|
|
44
|
+
const missing = [];
|
|
45
|
+
if (!escrow) missing.push("escrow");
|
|
46
|
+
if (!locker) missing.push("locker");
|
|
47
|
+
if (!claimer) missing.push("claimer");
|
|
48
|
+
if (!factory) missing.push("factory");
|
|
49
|
+
if (!salt) missing.push("salt");
|
|
50
|
+
if (!commitHalfLocker) missing.push("commitHalfLocker");
|
|
51
|
+
if (!commitHalfClaimer) missing.push("commitHalfClaimer");
|
|
52
|
+
if (!edPointLocker) missing.push("edPointLocker");
|
|
53
|
+
if (!edPointClaimer) missing.push("edPointClaimer");
|
|
54
|
+
if (!edViewPointLocker) missing.push("edViewPointLocker");
|
|
55
|
+
if (!ownHalf) missing.push("half");
|
|
56
|
+
if (!amount || !INTEGER_RE.test(amount) || BigInt(amount) <= 0n) missing.push("amount");
|
|
57
|
+
if (!Number.isSafeInteger(readyBy) || readyBy <= 0) missing.push("readyBy");
|
|
58
|
+
if (!Number.isSafeInteger(t1) || t1 <= 0) missing.push("t1");
|
|
59
|
+
if (missing.length) throw new SdkError("bad-input", { field: "order", missing });
|
|
60
|
+
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
side,
|
|
63
|
+
kind: side === "locker" ? "refund" : "claim",
|
|
64
|
+
escrow,
|
|
65
|
+
half: ownHalf,
|
|
66
|
+
claimer,
|
|
67
|
+
expect: Object.freeze({
|
|
68
|
+
chainId: chain,
|
|
69
|
+
factory, locker, claimer, amount, readyBy, t1, salt,
|
|
70
|
+
commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker,
|
|
71
|
+
}),
|
|
72
|
+
});
|
|
73
|
+
}
|
package/src/sweep.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// address, ask the app for the restore height (on the page it is taken by address) and say aloud what is missing
|
|
6
6
|
// so the withdrawal can go. Funds do not move at this step.
|
|
7
7
|
import { SdkError } from "./errors.mjs";
|
|
8
|
+
import { actionMaterialOf } from "./sweep-action.mjs";
|
|
8
9
|
import { primitives } from "./primitives.mjs";
|
|
9
10
|
import * as engine from "./engine.mjs";
|
|
10
11
|
import { restoreWallet } from "./sweep-restore.mjs";
|
|
@@ -129,10 +130,15 @@ const payloadFromOrder = async (request) => {
|
|
|
129
130
|
receiveAddress: null,
|
|
130
131
|
restoreHeight: Number(order.startHeight) > 0 ? Number(order.startHeight) : null,
|
|
131
132
|
});
|
|
133
|
+
// THE ETH ACTION MATERIAL COMES FROM THE SAME DERIVATION. The half and the order expectations are what
|
|
134
|
+
// `actions.refund` / `actions.claim` need; returning them here keeps the page from rebuilding the order fields.
|
|
135
|
+
// A found order from `findSwaps` carries every field; an incomplete order is refused before a half can be used.
|
|
136
|
+
const action = actionMaterialOf({ order, chainId, half: halves.spendHalf });
|
|
132
137
|
return {
|
|
133
138
|
payload,
|
|
134
139
|
contents: await engine.recoveryFile.createRecoveryFile(payload, passphrase),
|
|
135
140
|
address: joint.address,
|
|
141
|
+
...action,
|
|
136
142
|
};
|
|
137
143
|
};
|
|
138
144
|
|
|
@@ -169,7 +175,7 @@ const feeOf = async (wallet, signed) => {
|
|
|
169
175
|
return /^\d+$/.test(text) ? text : null;
|
|
170
176
|
};
|
|
171
177
|
|
|
172
|
-
export function createSweep({
|
|
178
|
+
export function createSweep({ call = null }) {
|
|
173
179
|
// THE NAME IS NEEDED BY THE OBJECT ITSELF: `run` calls `api.plan(...)` - the step order is held by the plan and
|
|
174
180
|
// the withdrawal living in one object, not in two copies. During a manual merge of branches the object was left
|
|
175
181
|
// unnamed, and the withdrawal failed with "api is not defined": not a refusal, but a breakdown. `node --check`
|
package/src/version.mjs
CHANGED
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
// tools/sync-version.mjs. Do not edit it by hand - set the version in package.json and run `npm run sync:version`.
|
|
7
7
|
// The `version` check in tools/check.mjs refuses a mismatch, and refuses a runtime read of package.json here.
|
|
8
8
|
|
|
9
|
-
export const SDK_VERSION = "0.
|
|
9
|
+
export const SDK_VERSION = "0.58.0";
|
package/src/xmr-arrival.mjs
CHANGED
|
@@ -57,6 +57,9 @@ const failureOf = (error, node) => {
|
|
|
57
57
|
// A NODE LIST IS A LIST OF {url, operator}. The operator is what makes two nodes two witnesses: two nodes of one
|
|
58
58
|
// operator are one opinion. A plain string is accepted and its operator is the host - a user who adds their own
|
|
59
59
|
// node is the operator of it.
|
|
60
|
+
//
|
|
61
|
+
// `protocol` is an OPTIONAL capability, not a role. It is kept here so a slice-only witness can be named on the
|
|
62
|
+
// same list without inferring an endpoint from a standard daemon URL.
|
|
60
63
|
export function normalizeNodes(nodes) {
|
|
61
64
|
if (!Array.isArray(nodes)) throw new SdkError("bad-input", { field: "nodes" });
|
|
62
65
|
const out = [];
|
|
@@ -66,7 +69,12 @@ export function normalizeNodes(nodes) {
|
|
|
66
69
|
out.push({ url, operator: hostOf(url) });
|
|
67
70
|
} else if (raw && typeof raw === "object" && isStr(raw.url)) {
|
|
68
71
|
const url = raw.url.replace(/\/+$/, "");
|
|
69
|
-
|
|
72
|
+
const node = { url, operator: isStr(raw.operator) ? raw.operator : hostOf(url) };
|
|
73
|
+
if (raw.protocol !== undefined && raw.protocol !== null) {
|
|
74
|
+
if (!isStr(raw.protocol)) throw new SdkError("bad-input", { field: "nodes.protocol" });
|
|
75
|
+
node.protocol = raw.protocol;
|
|
76
|
+
}
|
|
77
|
+
out.push(node);
|
|
70
78
|
} else {
|
|
71
79
|
throw new SdkError("bad-input", { field: "nodes", why: "each-node-is-url-or-url+operator" });
|
|
72
80
|
}
|
|
@@ -222,7 +230,27 @@ export async function verifyArrival(request) {
|
|
|
222
230
|
const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
|
|
223
231
|
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
|
|
224
232
|
const txidHint = txidOf(request.txid);
|
|
225
|
-
|
|
233
|
+
// THE KEY MUST BELONG TO THE ADDRESS, NOT MERELY BE PASSED BESIDE IT. The scanner used to try both byte orders
|
|
234
|
+
// of the view secret and accept the first match; a maker could pay to the address built from the other reading and
|
|
235
|
+
// still get `arrived` while the person's wallet saw nothing. Decode the address, keep the matching view form, and
|
|
236
|
+
// require its spend key to be the same key.
|
|
237
|
+
let addressKeys;
|
|
238
|
+
try { addressKeys = engine.xmrArrivalRead.decodeAddressKeys(request.address); }
|
|
239
|
+
catch { throw new SdkError("bad-input", { field: "address", why: "not-a-monero-address" }); }
|
|
240
|
+
// THE WATCHED ADDRESS IS A PRIMARY ADDRESS. A subaddress has a different payload layout and its view/spend points
|
|
241
|
+
// are not the ones the joint-address builder produces; refusing it by name is clearer than a spurious spend-pub
|
|
242
|
+
// mismatch. SDK-generated addresses are always primary.
|
|
243
|
+
if (!addressKeys.network) throw new SdkError("bad-input", { field: "address", why: "subaddress-not-supported" });
|
|
244
|
+
const spendPub = String(request.spendPub).replace(/^0x/, "").toLowerCase();
|
|
245
|
+
if (!addressKeys.spendPub || spendPub !== String(addressKeys.spendPub).toLowerCase()) {
|
|
246
|
+
throw new SdkError("xmr-address-mismatch", { field: "spendPub", address: request.address });
|
|
247
|
+
}
|
|
248
|
+
const viewForm = engine.xmrScan.viewKeyFormForAddress(request.viewSecret, addressKeys.viewPub);
|
|
249
|
+
if (!viewForm) {
|
|
250
|
+
throw new SdkError("xmr-address-mismatch", { field: "viewSecret", address: request.address });
|
|
251
|
+
}
|
|
252
|
+
const viewSecret = engine.xmrScan.viewSecretCandidates(request.viewSecret).find(([form]) => form === viewForm)?.[1] ?? request.viewSecret;
|
|
253
|
+
const watched = { address: request.address, viewSecret, spendPub: addressKeys.spendPub };
|
|
226
254
|
|
|
227
255
|
// 1. THE TIP, and with it the first proof that ANY node answers. All nodes down is a named refusal, not silence.
|
|
228
256
|
const live = [];
|
|
@@ -243,9 +271,16 @@ export async function verifyArrival(request) {
|
|
|
243
271
|
// 2. LOCATE: from the birth height, by whole blocks. The first reachable node does the walk.
|
|
244
272
|
let located = null;
|
|
245
273
|
const completedOperators = new Set();
|
|
246
|
-
for (const { node } of live) {
|
|
274
|
+
for (const { node, info } of live) {
|
|
275
|
+
// A WITNESS THAT IS NOT SYNCHRONIZED HAS NOT SEEN THE RANGE. Counting its empty walk as absence would let two
|
|
276
|
+
// nodes that restarted behind the payout height refund a paid swap; the same rule already guards the positive
|
|
277
|
+
// branch below.
|
|
278
|
+
if (!info.synced) {
|
|
279
|
+
failed.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
247
282
|
try {
|
|
248
|
-
located = await locate(node, { expectedAtomic, address: request.address, viewSecret
|
|
283
|
+
located = await locate(node, { expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
|
|
249
284
|
if (!located) completedOperators.add(node.operator);
|
|
250
285
|
} catch (error) {
|
|
251
286
|
failed.push(failureOf(error, node));
|
|
@@ -257,7 +292,15 @@ export async function verifyArrival(request) {
|
|
|
257
292
|
// ABSENCE IS A CLAIM ABOUT MONEY, SO IT NEEDS TWO OPERATORS. One node can withhold a transaction and make
|
|
258
293
|
// this walk look empty; a refund signed on that answer would take the depositor's ETH from a maker who paid.
|
|
259
294
|
// Only when no node finished the walk is every node unreachable.
|
|
260
|
-
if (!completedOperators.size)
|
|
295
|
+
if (!completedOperators.size) {
|
|
296
|
+
// A LIVE BUT UNSYNCHRONIZED NODE IS UNKNOWN, NOT ABSENT. Returning pending keeps the refund closed while
|
|
297
|
+
// naming the stale witness in `failed`; xmr-no-nodes would say the nodes did not answer, which they did.
|
|
298
|
+
if (live.some((entry) => !entry.info.synced)) {
|
|
299
|
+
return { seen: false, state: "pending", absent: false, txid: txidHint, tip,
|
|
300
|
+
completedOperators: [], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
|
|
301
|
+
}
|
|
302
|
+
throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
|
|
303
|
+
}
|
|
261
304
|
return { seen: false, state: "pending", absent: completedOperators.size >= 2, txid: txidHint, tip, completedOperators: [...completedOperators], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height })), failed };
|
|
262
305
|
}
|
|
263
306
|
|
|
@@ -387,18 +430,243 @@ export async function verifyArrival(request) {
|
|
|
387
430
|
operators: [...best.operators], agreedBy, checked: seen, failed };
|
|
388
431
|
}
|
|
389
432
|
|
|
433
|
+
// ---------------------------------------------------------------------------
|
|
434
|
+
// WITNESS-V1: FIXED BLOCK SLICES FOR THE SHADOW CHECK
|
|
435
|
+
// ---------------------------------------------------------------------------
|
|
436
|
+
//
|
|
437
|
+
// This is the client side of the read-only slice endpoint. It is deliberately a SEPARATE call from
|
|
438
|
+
// `verifyArrival`: the production decision still uses the exact walk until an independent operator serves
|
|
439
|
+
// witness-v1. `verifyArrivalShadow` runs both and compares them without changing ready, refund or any swap state.
|
|
440
|
+
|
|
441
|
+
export const WITNESS_SLICE_BLOCKS = 20;
|
|
442
|
+
|
|
443
|
+
export function witnessSliceIndex(height) {
|
|
444
|
+
const value = Number(height);
|
|
445
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "height" });
|
|
446
|
+
return Math.floor(value / WITNESS_SLICE_BLOCKS);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function witnessSliceStart(index) {
|
|
450
|
+
const value = Number(index);
|
|
451
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "slice" });
|
|
452
|
+
return value * WITNESS_SLICE_BLOCKS;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export function witnessSliceEnd(index) {
|
|
456
|
+
return witnessSliceStart(index) + WITNESS_SLICE_BLOCKS - 1;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const witnessHash = (value) => {
|
|
460
|
+
const text = String(value || "").replace(/^0x/, "").toLowerCase();
|
|
461
|
+
return /^[0-9a-f]{64}$/.test(text) ? text : null;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
function assertWitnessSliceBody(body, { network, index }) {
|
|
465
|
+
if (!body || typeof body !== "object") throw new SdkError("xmr-no-nodes", { why: "bad-witness-slice" });
|
|
466
|
+
if (Number(body.version) !== 1) throw new SdkError("xmr-no-nodes", { why: "bad-witness-version" });
|
|
467
|
+
if (String(body.network) !== String(network)) throw new SdkError("xmr-no-nodes", { why: "witness-network" });
|
|
468
|
+
if (Number(body.grid) !== WITNESS_SLICE_BLOCKS) throw new SdkError("xmr-no-nodes", { why: "witness-grid" });
|
|
469
|
+
if (Number(body.slice) !== index) throw new SdkError("xmr-no-nodes", { why: "witness-slice" });
|
|
470
|
+
if (Number(body.from) !== witnessSliceStart(index) || Number(body.to) !== witnessSliceEnd(index)) {
|
|
471
|
+
throw new SdkError("xmr-no-nodes", { why: "witness-bounds" });
|
|
472
|
+
}
|
|
473
|
+
if (!Array.isArray(body.blocks) || body.blocks.length !== WITNESS_SLICE_BLOCKS) {
|
|
474
|
+
throw new SdkError("xmr-no-nodes", { why: "witness-block-count" });
|
|
475
|
+
}
|
|
476
|
+
const blocks = body.blocks.map((block, i) => {
|
|
477
|
+
if (!block || Number(block.height) !== witnessSliceStart(index) + i) {
|
|
478
|
+
throw new SdkError("xmr-no-nodes", { why: "witness-height" });
|
|
479
|
+
}
|
|
480
|
+
const hash = witnessHash(block.hash);
|
|
481
|
+
if (!hash) throw new SdkError("xmr-no-nodes", { why: "witness-hash" });
|
|
482
|
+
if (!Array.isArray(block.txids)) throw new SdkError("xmr-no-nodes", { why: "witness-txids" });
|
|
483
|
+
const txids = block.txids.map((txid) => {
|
|
484
|
+
const value = witnessHash(txid);
|
|
485
|
+
if (!value) throw new SdkError("xmr-no-nodes", { why: "witness-txid" });
|
|
486
|
+
return value;
|
|
487
|
+
});
|
|
488
|
+
return { height: Number(block.height), hash, txids };
|
|
489
|
+
});
|
|
490
|
+
return { version: 1, network: String(network), grid: WITNESS_SLICE_BLOCKS, slice: index,
|
|
491
|
+
from: body.from, to: body.to, blocks };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
async function readWitnessSlice(node, index, { network, fetchImpl, timeoutMs }) {
|
|
495
|
+
if (node.protocol !== "witness-v1") throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-slice-witness" });
|
|
496
|
+
const body = await call(node, "/v1/witness/slice",
|
|
497
|
+
{ version: 1, network, grid: WITNESS_SLICE_BLOCKS, slice: index }, fetchImpl, timeoutMs);
|
|
498
|
+
return assertWitnessSliceBody(body, { network, index });
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// ALL THE TRANSACTIONS OF A SLICE, IN ONE REQUEST. The request names the whole slice's txids, not the one
|
|
502
|
+
// transaction an order is looking for.
|
|
503
|
+
async function readSliceTransactions(node, slice, { fetchImpl, timeoutMs }) {
|
|
504
|
+
const txids = [...new Set(slice.blocks.flatMap((block) => block.txids))];
|
|
505
|
+
if (!txids.length) return new Map();
|
|
506
|
+
if (txids.length > 4096) throw new SdkError("xmr-no-nodes", { node: node.url, why: "slice-too-large", count: txids.length });
|
|
507
|
+
const txs = await getBlockTxs(node, txids, fetchImpl, timeoutMs);
|
|
508
|
+
return new Map(txs.map((tx) => [String(tx.tx_hash || "").toLowerCase(), tx]));
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// FIND A PAYMENT THROUGH SLICES. The exact `fromHeight` is local: the witness sees only slice indexes.
|
|
512
|
+
async function locateInSlices(node, { expectedAtomic, address, viewSecret, spendPub, fromHeight, toHeight, nowSec, network, fetchImpl, timeoutMs }) {
|
|
513
|
+
const first = witnessSliceIndex(fromHeight);
|
|
514
|
+
const last = witnessSliceIndex(toHeight);
|
|
515
|
+
let best = null;
|
|
516
|
+
let completed = true;
|
|
517
|
+
for (let index = first; index <= last; index++) {
|
|
518
|
+
const slice = await readWitnessSlice(node, index, { network, fetchImpl, timeoutMs });
|
|
519
|
+
const txs = await readSliceTransactions(node, slice, { fetchImpl, timeoutMs });
|
|
520
|
+
for (const block of slice.blocks) {
|
|
521
|
+
for (const txid of block.txids) {
|
|
522
|
+
const tx = txs.get(txid);
|
|
523
|
+
if (!tx) continue;
|
|
524
|
+
const hit = engine.xmrScan.matchTransaction(tx, [{ address, viewSecret, spendPub }], {
|
|
525
|
+
height: block.height, tipHeight: Math.max(0, toHeight), nowSec,
|
|
526
|
+
});
|
|
527
|
+
if (!hit.length) continue;
|
|
528
|
+
const amountAtomic = sumOutputs(hit[0]);
|
|
529
|
+
const amountVerified = hit[0].outputs.every((o) => o.amountVerified === true);
|
|
530
|
+
const locked = hit[0].unlock && hit[0].unlock.locked === true;
|
|
531
|
+
const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
|
|
532
|
+
const candidate = { txid, height: block.height, blockHash: block.hash, amountAtomic, score };
|
|
533
|
+
if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) best = candidate;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// THE WHOLE SLICE WAS READ. A perfect candidate lets the walk stop after this slice, not after a block:
|
|
537
|
+
// the last witness request is still a fixed slice, never the payout height. `completed` means the full
|
|
538
|
+
// requested slice range was walked, so it stays false on an early stop.
|
|
539
|
+
if (best && best.score === 7) {
|
|
540
|
+
completed = index === last;
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return { located: best, completed };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* RUN THE PRODUCTION CHECK AND THE SLICE CHECK SIDE BY SIDE.
|
|
549
|
+
*
|
|
550
|
+
* This is a shadow: it returns the exact verdict, the slice reading and the differences. It never flips
|
|
551
|
+
* `ready`, signs anything or changes a swap. It is the first step before a slice-only default.
|
|
552
|
+
*
|
|
553
|
+
* `witnessNodes` must name at least one `{url, operator, protocol: "witness-v1"}` node. A URL without the
|
|
554
|
+
* protocol is not guessed into an endpoint.
|
|
555
|
+
*/
|
|
556
|
+
export async function verifyArrivalShadow(request) {
|
|
557
|
+
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
558
|
+
if (request.witnessNodes === undefined || request.witnessNodes === null) {
|
|
559
|
+
throw new SdkError("bad-input", { field: "witnessNodes", why: "required" });
|
|
560
|
+
}
|
|
561
|
+
const witnessNodes = normalizeNodes(request.witnessNodes);
|
|
562
|
+
if (!witnessNodes.some((node) => node.protocol === "witness-v1")) {
|
|
563
|
+
throw new SdkError("bad-input", { field: "witnessNodes", why: "no-witness-v1" });
|
|
564
|
+
}
|
|
565
|
+
let addressKeys;
|
|
566
|
+
try { addressKeys = engine.xmrArrivalRead.decodeAddressKeys(request.address); }
|
|
567
|
+
catch { throw new SdkError("bad-input", { field: "address", why: "not-a-monero-address" }); }
|
|
568
|
+
if (!addressKeys.network) throw new SdkError("bad-input", { field: "address", why: "subaddress-not-supported" });
|
|
569
|
+
const network = request.network || addressKeys.network;
|
|
570
|
+
const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
|
|
571
|
+
if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
|
|
572
|
+
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
|
|
573
|
+
const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
|
|
574
|
+
const fromHeight = Number(request.fromHeight);
|
|
575
|
+
if (!Number.isSafeInteger(fromHeight) || fromHeight <= 0) throw new SdkError("bad-input", { field: "fromHeight" });
|
|
576
|
+
let expectedAtomic;
|
|
577
|
+
try { expectedAtomic = BigInt(request.expectedAtomic); } catch { throw new SdkError("bad-input", { field: "expectedAtomic" }); }
|
|
578
|
+
if (expectedAtomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
|
|
579
|
+
if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
|
|
580
|
+
if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
|
|
581
|
+
const spendPub = String(request.spendPub).replace(/^0x/, "").toLowerCase();
|
|
582
|
+
if (spendPub !== String(addressKeys.spendPub).toLowerCase()) {
|
|
583
|
+
throw new SdkError("xmr-address-mismatch", { field: "spendPub", address: request.address });
|
|
584
|
+
}
|
|
585
|
+
const viewForm = engine.xmrScan.viewKeyFormForAddress(request.viewSecret, addressKeys.viewPub);
|
|
586
|
+
if (!viewForm) throw new SdkError("xmr-address-mismatch", { field: "viewSecret", address: request.address });
|
|
587
|
+
const viewSecret = engine.xmrScan.viewSecretCandidates(request.viewSecret).find(([form]) => form === viewForm)?.[1] ?? request.viewSecret;
|
|
588
|
+
|
|
589
|
+
let exact = null;
|
|
590
|
+
let exactError = null;
|
|
591
|
+
try { exact = await verifyArrival(request); }
|
|
592
|
+
catch (error) { exactError = { code: error && error.code ? error.code : "unknown", params: (error && error.params) || {} }; }
|
|
593
|
+
|
|
594
|
+
const checked = [];
|
|
595
|
+
const failed = [];
|
|
596
|
+
let located = null;
|
|
597
|
+
let completed = false;
|
|
598
|
+
for (const node of witnessNodes) {
|
|
599
|
+
if (node.protocol !== "witness-v1") { failed.push({ url: node.url, operator: node.operator, code: "no-slice-witness" }); continue; }
|
|
600
|
+
let info;
|
|
601
|
+
try { info = await getInfo(node, fetchImpl, timeoutMs); }
|
|
602
|
+
catch (error) { failed.push(failureOf(error, node)); checked.push({ url: node.url, operator: node.operator, state: "down" }); continue; }
|
|
603
|
+
if (!info.synced) {
|
|
604
|
+
failed.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
|
|
605
|
+
checked.push({ url: node.url, operator: node.operator, state: "stale", height: info.height });
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const top = Math.max(0, info.height - 1);
|
|
609
|
+
checked.push({ url: node.url, operator: node.operator, state: "ok", height: info.height });
|
|
610
|
+
try {
|
|
611
|
+
const found = await locateInSlices(node, {
|
|
612
|
+
expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight, toHeight: top,
|
|
613
|
+
nowSec, network, fetchImpl, timeoutMs,
|
|
614
|
+
});
|
|
615
|
+
completed = completed || found.completed;
|
|
616
|
+
if (found.located && (!located || found.located.score > located.score)) {
|
|
617
|
+
located = found.located;
|
|
618
|
+
located.operator = node.operator;
|
|
619
|
+
located.url = node.url;
|
|
620
|
+
}
|
|
621
|
+
} catch (error) {
|
|
622
|
+
failed.push(failureOf(error, node));
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const witness = located
|
|
627
|
+
? { state: "seen", txid: located.txid, height: located.height, blockHash: located.blockHash,
|
|
628
|
+
amountAtomic: located.amountAtomic.toString(), operator: located.operator, url: located.url, completed, checked, failed }
|
|
629
|
+
: { state: "pending", txid: null, height: null, blockHash: null, amountAtomic: null, completed, checked, failed };
|
|
630
|
+
|
|
631
|
+
const problems = [];
|
|
632
|
+
let agrees = null;
|
|
633
|
+
if (exactError) problems.push("exact:" + exactError.code);
|
|
634
|
+
if (located && exact && exact.txid) {
|
|
635
|
+
if (String(exact.txid).toLowerCase() !== located.txid) problems.push("txid");
|
|
636
|
+
if (Number(exact.height) !== located.height) problems.push("height");
|
|
637
|
+
if (String(exact.blockHash || "").toLowerCase() !== located.blockHash) problems.push("blockHash");
|
|
638
|
+
if (String(exact.amountAtomic ?? "") !== located.amountAtomic.toString()) problems.push("amount");
|
|
639
|
+
agrees = problems.length === 0;
|
|
640
|
+
} else if (located) {
|
|
641
|
+
problems.push("exact:no-transaction");
|
|
642
|
+
agrees = false;
|
|
643
|
+
} else if (exact && exact.absent === true) {
|
|
644
|
+
// ABSENCE NEEDS THE WHOLE SLICE WALK, NOT A SILENT WITNESS. A server that is down, stale or answered a
|
|
645
|
+
// partial slice has not shown that the money is absent; its missing answer must not become agreement.
|
|
646
|
+
if (witness.completed && witness.failed.length === 0) agrees = true;
|
|
647
|
+
else {
|
|
648
|
+
agrees = false;
|
|
649
|
+
problems.push("witness:not-completed");
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return { exact, exactError, witness, agrees, problems };
|
|
653
|
+
}
|
|
654
|
+
|
|
390
655
|
/**
|
|
391
656
|
* IS THERE STILL TIME FOR THE CONFIRMATIONS? Ten confirmations of Monero are about twenty minutes, and the ready
|
|
392
657
|
* deadline does not move. If less than that is left, the client must NAME it and not start - waiting silently would
|
|
393
658
|
* start a trade that cannot be finished in time. Returns seconds left; refuses with `xmr-too-late` otherwise.
|
|
394
659
|
*/
|
|
395
|
-
export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec } = {}) {
|
|
660
|
+
export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec, minLeadSec = null } = {}) {
|
|
396
661
|
const readyBy = Number(readyBySec);
|
|
397
662
|
const now = Number.isFinite(Number(nowSec)) ? Number(nowSec) : Math.floor(Date.now() / 1000);
|
|
398
663
|
const count = Math.max(1, intOf(minConfirmations) ?? 1);
|
|
399
664
|
const block = Number.isFinite(Number(blockTimeSec)) && Number(blockTimeSec) > 0 ? Number(blockTimeSec) : 120;
|
|
400
665
|
if (!Number.isFinite(readyBy) || readyBy <= 0) return null; // no deadline known - nothing to compare against
|
|
401
|
-
|
|
666
|
+
// THE NODE'S LEAD WINS WHEN IT IS LONGER. A maker that advertises a 2400 s minimum cannot be paid in the old
|
|
667
|
+
// 1200 s; the client uses the longer of the two so its own confirmations and the maker's settlement both fit.
|
|
668
|
+
const nodeLead = Number.isFinite(Number(minLeadSec)) && Number(minLeadSec) > 0 ? Number(minLeadSec) : 0;
|
|
669
|
+
const needSec = Math.max(count * block, nodeLead);
|
|
402
670
|
const leftSec = Math.floor(readyBy - now);
|
|
403
671
|
if (leftSec < needSec) throw new SdkError("xmr-too-late", { needSec, leftSec, minConfirmations: count, readyBy: Math.floor(readyBy) });
|
|
404
672
|
return leftSec;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// THE XMR AMOUNT A QUOTE MAY SIGN FOR A REQUESTED AMOUNT.
|
|
2
|
+
//
|
|
3
|
+
// The provider's signed `xmrAmount` is allowed to be BETTER for the client than the requested figure, never worse:
|
|
4
|
+
// ask - the client buys XMR, so the provider may sign at least the requested amount;
|
|
5
|
+
// bid - the client sells XMR, so the provider may sign at most the requested amount.
|
|
6
|
+
// The ETH side stays exact and is checked separately by both callers: it is part of the proof context, not a
|
|
7
|
+
// price that may move with the XMR amount.
|
|
8
|
+
//
|
|
9
|
+
// A value that cannot be read, a negative value and an unknown side are all refused. Returning a boolean here would
|
|
10
|
+
// turn "unreadable" into "equal", so the verdict names the reason.
|
|
11
|
+
export function xmrAmountVerdict({ side, requested, signed } = {}) {
|
|
12
|
+
const parse = (value) => {
|
|
13
|
+
if (value === undefined || value === null || value === "") return null;
|
|
14
|
+
try {
|
|
15
|
+
const amount = BigInt(String(value));
|
|
16
|
+
return amount >= 0n ? amount : null;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const want = parse(requested);
|
|
22
|
+
const got = parse(signed);
|
|
23
|
+
if (want === null || got === null) return { ok: false, reason: "unreadable" };
|
|
24
|
+
if (side === "ask") {
|
|
25
|
+
return got >= want
|
|
26
|
+
? { ok: true, side, requested: want.toString(), signed: got.toString() }
|
|
27
|
+
: { ok: false, reason: "worse", side, requested: want.toString(), signed: got.toString() };
|
|
28
|
+
}
|
|
29
|
+
if (side === "bid") {
|
|
30
|
+
return got <= want
|
|
31
|
+
? { ok: true, side, requested: want.toString(), signed: got.toString() }
|
|
32
|
+
: { ok: false, reason: "worse", side, requested: want.toString(), signed: got.toString() };
|
|
33
|
+
}
|
|
34
|
+
return { ok: false, reason: "side" };
|
|
35
|
+
}
|