@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,76 @@
|
|
|
1
|
+
// THE NODE'S READY WINDOW, READ ONCE.
|
|
2
|
+
//
|
|
3
|
+
// A maker advertises the range in which it will accept `readyBy` for one side: `readyMinSeconds` is the shortest
|
|
4
|
+
// horizon it can finish in, `readyMaxSeconds` the longest it will sign. The SDK used to keep its own 1200 s and
|
|
5
|
+
// 20-minute numbers, so a node configured differently and the client disagreed about when a sale still had time.
|
|
6
|
+
//
|
|
7
|
+
// The lead a depositor leaves the maker is derived, not guessed: the window's spare room above the minimum is
|
|
8
|
+
// `max - min`; the client waits until `min - (max - min)` remains. The default node window is 2400..3000 s, so
|
|
9
|
+
// the lead is 1800 s: the node's settlement margin, not the old 1200 s. A narrower window gives a shorter lead,
|
|
10
|
+
// never less than the time the required confirmations need.
|
|
11
|
+
import { SdkError } from "./errors.mjs";
|
|
12
|
+
|
|
13
|
+
const int = (value) => {
|
|
14
|
+
const n = Number(value);
|
|
15
|
+
return Number.isSafeInteger(n) ? n : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Read and validate one `FirmWindow` from the signed features, or refuse by name. */
|
|
19
|
+
export function readReadyWindow(value, { side = null, field = "readyWindow" } = {}) {
|
|
20
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
21
|
+
throw new SdkError("bad-input", { field, why: "missing" });
|
|
22
|
+
}
|
|
23
|
+
const min = int(value.readyMinSeconds);
|
|
24
|
+
const max = int(value.readyMaxSeconds);
|
|
25
|
+
if (min === null || max === null || min <= 0 || max < min) {
|
|
26
|
+
throw new SdkError("bad-input", { field, why: "bounds" });
|
|
27
|
+
}
|
|
28
|
+
if (side !== null && value.side !== undefined && String(value.side) !== String(side)) {
|
|
29
|
+
throw new SdkError("bad-input", { field, why: "side" });
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({
|
|
32
|
+
market: value.market === undefined || value.market === null ? null : String(value.market),
|
|
33
|
+
side: value.side === undefined || value.side === null ? null : String(value.side),
|
|
34
|
+
xmrNetwork: value.xmrNetwork === undefined || value.xmrNetwork === null ? null : String(value.xmrNetwork),
|
|
35
|
+
readyMinSeconds: min,
|
|
36
|
+
readyMaxSeconds: max,
|
|
37
|
+
settlementMinSeconds: int(value.settlementMinSeconds),
|
|
38
|
+
settlementMaxSeconds: int(value.settlementMaxSeconds),
|
|
39
|
+
quoteTtlSeconds: int(value.quoteTtlSeconds),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* HOW LONG BEFORE `readyBy` THE DEPOSITOR MAY STILL REFUND.
|
|
45
|
+
*
|
|
46
|
+
* The maker's own settlement margin is not a wire field; the advertised window carries it implicitly. The node
|
|
47
|
+
* publishes `[min, max]` where `max - min` is the headroom it keeps above the minimum, and that headroom is the
|
|
48
|
+
* time the depositor must leave for the payout to settle before a refund. The default 2400..3000 window therefore
|
|
49
|
+
* gives 600 s, not the retired 1200 s: the old reserve woke the helper while a payout could still be confirming.
|
|
50
|
+
*/
|
|
51
|
+
export function readyLeadSec(window) {
|
|
52
|
+
const ready = readReadyWindow(window);
|
|
53
|
+
const headroom = ready.readyMaxSeconds - ready.readyMinSeconds;
|
|
54
|
+
// A window with more headroom than its minimum cannot make the depositor refund before the quote exists; cap
|
|
55
|
+
// the lead at the minimum instead of letting a degenerate signed range move it into the past.
|
|
56
|
+
return Math.max(0, Math.min(headroom, ready.readyMinSeconds));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The node's own settlement margin: the latest point at which it can still pay before `readyBy`. The advertised
|
|
60
|
+
* `settlementMinSeconds/MaxSeconds` describe `t1 - readyBy` (the claim window), not this payout margin, so they
|
|
61
|
+
* are carried for callers but do not decide the late boundary. */
|
|
62
|
+
export function readyLateSec(window) {
|
|
63
|
+
const ready = readReadyWindow(window);
|
|
64
|
+
const headroom = ready.readyMaxSeconds - ready.readyMinSeconds;
|
|
65
|
+
const derived = ready.readyMinSeconds - headroom;
|
|
66
|
+
// A range whose headroom swallows its minimum cannot advertise "pay immediately"; keep the minimum as the
|
|
67
|
+
// conservative boundary rather than disabling the check with a zero.
|
|
68
|
+
return Math.max(0, derived > 0 ? derived : ready.readyMinSeconds);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The longest wait a quote from this window can ask for, without inventing a second client-side deadline. */
|
|
72
|
+
export function readyWindowMs(window, marginSec = 300) {
|
|
73
|
+
const ready = readReadyWindow(window);
|
|
74
|
+
const margin = Number.isFinite(Number(marginSec)) && Number(marginSec) >= 0 ? Number(marginSec) : 300;
|
|
75
|
+
return (ready.readyMaxSeconds + margin) * 1000;
|
|
76
|
+
}
|
package/src/recovery-key.mjs
CHANGED
|
@@ -483,6 +483,26 @@ export async function readEscrowEvents({ escrows, evmLogs, fromBlock = "earliest
|
|
|
483
483
|
fromBlock,
|
|
484
484
|
toBlock,
|
|
485
485
|
});
|
|
486
|
+
return decodeEscrowEvents(logs);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Read the same settlement events WITHOUT naming any escrow to the RPC.
|
|
491
|
+
*
|
|
492
|
+
* The three events carry the escrow in `log.address`, so a client that must not disclose which swaps belong to a
|
|
493
|
+
* visitor can ask for the topics over a block range and filter the returned events locally by `escrow`. The
|
|
494
|
+
* decoder is the same one `readEscrowEvents` uses; this function only builds a request without an address filter.
|
|
495
|
+
*/
|
|
496
|
+
export async function readEscrowEventsByTopic({ evmLogs, fromBlock = "earliest", toBlock = "latest" } = {}) {
|
|
497
|
+
const logs = await readLogs(evmLogs, {
|
|
498
|
+
topics: [[ESCROW_EVENT_TOPICS.halfRevealed, ESCROW_EVENT_TOPICS.ready, ESCROW_EVENT_TOPICS.declined]],
|
|
499
|
+
fromBlock,
|
|
500
|
+
toBlock,
|
|
501
|
+
});
|
|
502
|
+
return decodeEscrowEvents(logs);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function decodeEscrowEvents(logs) {
|
|
486
506
|
const events = [];
|
|
487
507
|
for (const log of logs) {
|
|
488
508
|
if (!log || typeof log !== "object") continue;
|
|
@@ -637,7 +657,7 @@ async function recoveredStartHeight(order, { evmBlockTime, moneroTip, moneroBloc
|
|
|
637
657
|
*/
|
|
638
658
|
export async function findSwaps({ mnemonic, chainId, factory = null, factories = null, address = null, evmLogs,
|
|
639
659
|
fromBlock = null, deploymentBlock = null, toBlock = "latest",
|
|
640
|
-
evmBlockTime = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
|
|
660
|
+
evmBlockTime = null, evmBlockTimes = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
|
|
641
661
|
xmrNodes = null, moneroNetwork = null, fetchImpl = globalThis.fetch } = {}) {
|
|
642
662
|
// FACTORY HISTORY IS PART OF THE SEARCH. A chain can have more than one factory after a contract change;
|
|
643
663
|
// searching only the newest one hides every older order. Callers may pass `factories` as addresses or as
|
|
@@ -720,6 +740,23 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
|
|
|
720
740
|
// EACH FOUND ORDER CARRIES THE MONERO HEIGHT ITS WITHDRAWAL MAY START FROM. The rule lives here, not in a
|
|
721
741
|
// page: a widget and the recovery page must not derive two different answers from one chain.
|
|
722
742
|
const cache = new Map();
|
|
743
|
+
let readBlockTime = evmBlockTime;
|
|
744
|
+
if (typeof evmBlockTimes === "function") {
|
|
745
|
+
const blocks = [...new Set(found.map((order) => order.blockNumber).filter((block) => block !== null && block !== undefined))];
|
|
746
|
+
let timestamps;
|
|
747
|
+
try {
|
|
748
|
+
timestamps = blocks.length ? await evmBlockTimes(blocks) : new Map();
|
|
749
|
+
if (!timestamps || typeof timestamps.get !== "function") throw new Error("block-time-read");
|
|
750
|
+
} catch {
|
|
751
|
+
timestamps = new Map(blocks.map((block) => [block, new Error("block-time-read")]));
|
|
752
|
+
}
|
|
753
|
+
// Never fall back to per-order RPC after the caller chose a batch, including failed or missing items.
|
|
754
|
+
readBlockTime = async (block) => {
|
|
755
|
+
const value = timestamps.get(block);
|
|
756
|
+
if (value !== null && value !== undefined && typeof value !== "number") throw new Error("block-time-read");
|
|
757
|
+
return value;
|
|
758
|
+
};
|
|
759
|
+
}
|
|
723
760
|
let tip = moneroTip;
|
|
724
761
|
let header = moneroBlockTimestamp;
|
|
725
762
|
let readersReason = "no-height-readers";
|
|
@@ -738,7 +775,7 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
|
|
|
738
775
|
order.payTokenReason = "not-on-chain";
|
|
739
776
|
}
|
|
740
777
|
for (const order of found) {
|
|
741
|
-
Object.assign(order, await recoveredStartHeight(order, { evmBlockTime, moneroTip: tip, moneroBlockTimestamp: header, cache, readersReason }));
|
|
778
|
+
Object.assign(order, await recoveredStartHeight(order, { evmBlockTime: readBlockTime, moneroTip: tip, moneroBlockTimestamp: header, cache, readersReason }));
|
|
742
779
|
}
|
|
743
780
|
// THE XMR AMOUNT COMES FROM THE EVENT IN THE CURRENT FACTORY. The previous event has no field; those orders fall
|
|
744
781
|
// back to the clone read, where word 18 is read only from a clone of the exact shape. This is data, not a
|
package/src/recovery.mjs
CHANGED
|
@@ -4,11 +4,9 @@
|
|
|
4
4
|
// The file arrives from the interface as a string or as `{ contents }`: the SDK knows neither about
|
|
5
5
|
// <input type=file> nor about buffers - that is the interface's business.
|
|
6
6
|
//
|
|
7
|
-
// THE RESTORE HEIGHT
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
// when it is known, the file's is the fallback, and NO height is a named state - not a refusal, because the
|
|
11
|
-
// person can still type one.
|
|
7
|
+
// THE RESTORE HEIGHT COMES FROM THE FILE. The retired node route that used to answer by address is gone: the
|
|
8
|
+
// height written into the file is the only source the SDK reads, and no height is a named state - not a refusal,
|
|
9
|
+
// because the person can still type one.
|
|
12
10
|
import * as engine from "./engine.mjs";
|
|
13
11
|
import { SdkError } from "./errors.mjs";
|
|
14
12
|
|
|
@@ -18,7 +16,7 @@ const contentsOf = (file) => {
|
|
|
18
16
|
return null;
|
|
19
17
|
};
|
|
20
18
|
|
|
21
|
-
export function createRecovery(
|
|
19
|
+
export function createRecovery() {
|
|
22
20
|
return {
|
|
23
21
|
async open(file, passphrase) {
|
|
24
22
|
const contents = contentsOf(file);
|
|
@@ -86,34 +84,19 @@ export function createRecovery({ http = null, config = null } = {}) {
|
|
|
86
84
|
const address = typeof wallet.address === "string" && wallet.address ? wallet.address : null;
|
|
87
85
|
const fileHeight = Number(wallet.restoreHeight) || 0;
|
|
88
86
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
let appProblem = null;
|
|
92
|
-
if (http && config && address) {
|
|
93
|
-
appAsked = true;
|
|
94
|
-
try {
|
|
95
|
-
const answer = await http.json(config.route("swaps"));
|
|
96
|
-
const rows = Array.isArray(answer) ? answer : ((answer && answer.swaps) || []);
|
|
97
|
-
const row = rows.find((x) => String((x && x.address) || "") === String(address)) || null;
|
|
98
|
-
appHeight = Number(row && row.restoreHeight) || 0;
|
|
99
|
-
if (!row) appProblem = "no-row";
|
|
100
|
-
} catch {
|
|
101
|
-
appProblem = "unreachable";
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const height = appHeight > 0 ? appHeight : fileHeight;
|
|
106
|
-
const source = appHeight > 0 ? "app" : (fileHeight > 0 ? "file" : "none");
|
|
87
|
+
const height = fileHeight;
|
|
88
|
+
const source = fileHeight > 0 ? "file" : "none";
|
|
107
89
|
return {
|
|
108
90
|
address,
|
|
109
91
|
height,
|
|
110
92
|
source,
|
|
111
93
|
fileHeight,
|
|
112
|
-
appHeight,
|
|
113
|
-
appAsked,
|
|
94
|
+
appHeight: 0,
|
|
95
|
+
appAsked: false,
|
|
114
96
|
// Why there is no height, when there is none: a token the interface turns into words. Null when a height
|
|
115
|
-
// was found, so a reader cannot mistake "found" for "asked and failed".
|
|
116
|
-
|
|
97
|
+
// was found, so a reader cannot mistake "found" for "asked and failed". The service is not asked any more:
|
|
98
|
+
// the retired node routes are not part of the SDK.
|
|
99
|
+
appProblem: source === "none" ? "no-height" : null,
|
|
117
100
|
};
|
|
118
101
|
},
|
|
119
102
|
};
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// ONE HTTP HOP TO A RELAY CLAIM.
|
|
2
|
+
//
|
|
3
|
+
// A seller on a bid holds XMR and no ETH. The escrow pays the signed `claimTip` out of the payout, so a sender can
|
|
4
|
+
// submit the seller's one-time half and be repaid from the claim itself. This module joins the stored sale record
|
|
5
|
+
// to that wire: it builds the exact body, sends it once to the relay that answered the quote, and returns a claim
|
|
6
|
+
// ONLY when the answer carries a real transaction hash. No wallet is created, used or signed here.
|
|
7
|
+
import { SdkError } from "./errors.mjs";
|
|
8
|
+
import { createHttp } from "./http.mjs";
|
|
9
|
+
|
|
10
|
+
const ADDRESS = /^0x[0-9a-f]{40}$/;
|
|
11
|
+
const HALF = /^[0-9a-f]{64}$/;
|
|
12
|
+
const TXID = /^0x[0-9a-f]{64}$/;
|
|
13
|
+
const DECIMAL = /^(0|[1-9][0-9]*)$/;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* THE RELAY ORIGIN, NORMALISED ONCE. A claim is bound to the origin that answered the quote, so a trailing slash
|
|
17
|
+
* is not a different relay. Plain http is refused for the same reason a quote refuses it: the half must not travel
|
|
18
|
+
* through a hop any middlebox can read and change.
|
|
19
|
+
*/
|
|
20
|
+
export function relayOriginOf(value) {
|
|
21
|
+
const base = String(value === undefined || value === null ? "" : value).trim().replace(/\/+$/, "");
|
|
22
|
+
if (!base) throw new SdkError("bad-input", { field: "relayUrl" });
|
|
23
|
+
if (!/^https:\/\//i.test(base)) throw new SdkError("bad-input", { field: "relayUrl", why: "not-https" });
|
|
24
|
+
return base;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A 20-byte address, lower-cased for the path and for comparison. */
|
|
28
|
+
export function addressTextOf(value, field) {
|
|
29
|
+
const text = String(value === undefined || value === null ? "" : value).trim().toLowerCase();
|
|
30
|
+
if (!ADDRESS.test(text)) throw new SdkError("bad-input", { field });
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The seller's half in the one form the relay accepts: `0x` and exactly 64 hex digits. */
|
|
35
|
+
export function halfTextOf(value) {
|
|
36
|
+
const text = String(value === undefined || value === null ? "" : value).trim().toLowerCase().replace(/^0x/, "");
|
|
37
|
+
if (!HALF.test(text)) throw new SdkError("bad-input", { field: "halfClaimer", why: "not-in-record" });
|
|
38
|
+
return "0x" + text;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* POST the half to the relay that answered the quote.
|
|
43
|
+
*
|
|
44
|
+
* A refusal from the relay is `quote-refused` with the provider's own code kept in `params.code`; the provider's
|
|
45
|
+
* message is deliberately NOT copied, because it is not this package's user-facing text. A lost answer is
|
|
46
|
+
* `claim-unknown`: the claim may have been sent, so a second call must begin by reading the escrow, never by
|
|
47
|
+
* assuming that nothing happened. Only a validated transaction hash is a success.
|
|
48
|
+
*/
|
|
49
|
+
export async function postRelayClaim({
|
|
50
|
+
relayUrl,
|
|
51
|
+
provider,
|
|
52
|
+
escrow,
|
|
53
|
+
halfClaimer,
|
|
54
|
+
expectedTipWei,
|
|
55
|
+
fetchImpl = null,
|
|
56
|
+
timeoutMs = 20_000,
|
|
57
|
+
} = {}) {
|
|
58
|
+
const base = relayOriginOf(relayUrl);
|
|
59
|
+
const to = addressTextOf(provider, "provider");
|
|
60
|
+
const at = addressTextOf(escrow, "escrow");
|
|
61
|
+
const half = halfTextOf(halfClaimer);
|
|
62
|
+
const http = createHttp({ apiBase: base, fetchImpl, timeoutMs });
|
|
63
|
+
const body = JSON.stringify({ version: 1, halfClaimer: half });
|
|
64
|
+
|
|
65
|
+
let response;
|
|
66
|
+
try {
|
|
67
|
+
response = await http.tryJson(`/v1/claims/${to}/${at}`, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { "content-type": "application/json" },
|
|
70
|
+
body,
|
|
71
|
+
});
|
|
72
|
+
} catch (error) {
|
|
73
|
+
// A missing fetch is a caller's input problem, not an unknown claim. Everything else that prevented an answer
|
|
74
|
+
// leaves the outcome UNKNOWN: the request may have reached the relay and the claim may already be sent.
|
|
75
|
+
if (error instanceof SdkError && error.code === "bad-input") throw error;
|
|
76
|
+
throw new SdkError("claim-unknown", {
|
|
77
|
+
step: "relay-claim",
|
|
78
|
+
why: (error && error.params && error.params.why) || "answer-lost",
|
|
79
|
+
outcome: "unknown",
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const answer = response.body && typeof response.body === "object" ? response.body : null;
|
|
84
|
+
const version = answer ? Number(answer.version) : null;
|
|
85
|
+
const code = answer && typeof answer.code === "string" && answer.code ? answer.code : null;
|
|
86
|
+
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
if (code === "claim-unknown" || code === "claim_unknown") {
|
|
89
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-timeout", code, status: response.status, outcome: "unknown" });
|
|
90
|
+
}
|
|
91
|
+
if (code && version === 1) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
|
|
92
|
+
// AN UNVERSIONED NON-2XX IS NOT A REFUSAL WE CAN READ. The claim may still have been sent, so it is unknown.
|
|
93
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-status", status: response.status, outcome: "unknown" });
|
|
94
|
+
}
|
|
95
|
+
if (!answer || version !== 1) {
|
|
96
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer", outcome: "unknown" });
|
|
97
|
+
}
|
|
98
|
+
if (code) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
|
|
99
|
+
|
|
100
|
+
// ONLY A REAL TRANSACTION HASH IS A CLAIM. A body without one leaves the outcome unknown, whether the claim never
|
|
101
|
+
// left the relay or its answer was cut off.
|
|
102
|
+
const txid = String(answer.txid === undefined || answer.txid === null ? "" : answer.txid).trim().toLowerCase();
|
|
103
|
+
if (!TXID.test(txid)) {
|
|
104
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-txid", outcome: "unknown" });
|
|
105
|
+
}
|
|
106
|
+
const from = String(answer.from === undefined || answer.from === null ? "" : answer.from).trim().toLowerCase();
|
|
107
|
+
if (!ADDRESS.test(from)) {
|
|
108
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-from", outcome: "unknown" });
|
|
109
|
+
}
|
|
110
|
+
const tipWei = String(answer.tipWei === undefined || answer.tipWei === null ? "" : answer.tipWei).trim();
|
|
111
|
+
if (!DECIMAL.test(tipWei)) {
|
|
112
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-tip", outcome: "unknown" });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// THE ANSWER IS BOUND TO THE REQUEST. A relay that answers for another provider, escrow or tip has not reported
|
|
116
|
+
// this sale, and the txid it names is not evidence about this claim.
|
|
117
|
+
const answerProvider = String(answer.provider === undefined || answer.provider === null ? "" : answer.provider).trim().toLowerCase();
|
|
118
|
+
const answerEscrow = String(answer.escrow === undefined || answer.escrow === null ? "" : answer.escrow).trim().toLowerCase();
|
|
119
|
+
if (!answerProvider || !answerEscrow) {
|
|
120
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-binding", outcome: "unknown" });
|
|
121
|
+
}
|
|
122
|
+
if (answerProvider !== to) {
|
|
123
|
+
throw new SdkError("quote-refused", { step: "relay-claim", why: "answer-provider" });
|
|
124
|
+
}
|
|
125
|
+
if (answerEscrow !== at) {
|
|
126
|
+
throw new SdkError("quote-refused", { step: "relay-claim", why: "answer-escrow" });
|
|
127
|
+
}
|
|
128
|
+
if (BigInt(tipWei) !== BigInt(expectedTipWei)) {
|
|
129
|
+
throw new SdkError("quote-refused", { step: "relay-claim", why: "tip", tipWei, expectedTipWei: String(expectedTipWei) });
|
|
130
|
+
}
|
|
131
|
+
return { txid, from, tipWei };
|
|
132
|
+
}
|
package/src/relayFirmClient.mjs
CHANGED
|
@@ -141,6 +141,9 @@ export async function requestFirmQuote({
|
|
|
141
141
|
}
|
|
142
142
|
return {
|
|
143
143
|
...verified,
|
|
144
|
+
// THE ORIGIN THAT ANSWERED, KEPT FOR THE LATER CLAIM. The seller has no wallet, so the claim goes back to the
|
|
145
|
+
// same relay through `swaps.claimViaRelay`; the record stores this value and a different origin is refused.
|
|
146
|
+
relayUrl: base,
|
|
144
147
|
relay: response.body.relay ?? null,
|
|
145
148
|
offered: response.body.offered ?? null,
|
|
146
149
|
forwarded: response.body.forwarded ?? null,
|
package/src/relayQuote.mjs
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { SdkError } from "./errors.mjs";
|
|
7
7
|
import { keccak256, secp256k1 } from "./primitives.mjs";
|
|
8
8
|
import { recoverOrderQuoteKey } from "./quoteEip712.mjs";
|
|
9
|
+
import { xmrAmountVerdict } from "./xmrAmountPolicy.mjs";
|
|
9
10
|
import * as engine from "./engine.mjs";
|
|
10
11
|
|
|
11
12
|
export const RELAY_QUOTE_TYPE =
|
|
@@ -195,7 +196,6 @@ function checkOrderQuote(quote, terms, nowSec) {
|
|
|
195
196
|
["readyBy", String(order.readyBy)],
|
|
196
197
|
["t1", String(order.t1)],
|
|
197
198
|
["salt", order.salt],
|
|
198
|
-
["xmrAmount", String(terms.xmrAmount)],
|
|
199
199
|
["claimTip", String(terms.claimTip)],
|
|
200
200
|
["provider", terms.maker],
|
|
201
201
|
["registry", terms.registry],
|
|
@@ -203,6 +203,10 @@ function checkOrderQuote(quote, terms, nowSec) {
|
|
|
203
203
|
for (const [field, want] of pairs) {
|
|
204
204
|
if (!same(quote[field], want)) throw new SdkError("quote-refused", { step: "answer", why: "field", field });
|
|
205
205
|
}
|
|
206
|
+
// THE XMR SIDE IS ALLOWED TO BE BETTER, NOT WORSE. `ask` may sign at least the requested amount; `bid` may sign
|
|
207
|
+
// at most it. The ETH `amount` above stays exact because it is part of the proof context.
|
|
208
|
+
const xmr = xmrAmountVerdict({ side: terms.side, requested: terms.xmrAmount, signed: quote.xmrAmount });
|
|
209
|
+
if (!xmr.ok) throw new SdkError("quote-refused", { step: "answer", why: "field", field: "xmrAmount" });
|
|
206
210
|
if (same(quote.feeRecipient, ZERO)) {
|
|
207
211
|
throw new SdkError("quote-refused", { step: "answer", why: "fee-recipient" });
|
|
208
212
|
}
|
package/src/swap-flow.mjs
CHANGED
|
@@ -28,6 +28,11 @@
|
|
|
28
28
|
// is the RULES, not the crypto.
|
|
29
29
|
import { SdkError } from "./errors.mjs";
|
|
30
30
|
import * as engine from "./engine.mjs";
|
|
31
|
+
// THE HALF'S COMMITMENT, COMPUTED LOCALLY. The escrow checks the low 160 bits of `keccak256(x||y)` of `half*G`
|
|
32
|
+
// (NinseiEscrow.halfMatchesCommit); the same formula runs here, so an action is compared with the order without
|
|
33
|
+
// the half ever leaving this process.
|
|
34
|
+
import { halfCommitmentHex } from "../engine/atomic/orderHalfCommit.js";
|
|
35
|
+
import { keccak256, secp256k1 } from "./primitives.mjs";
|
|
31
36
|
// THE MAKER'S DECLINE (issue #40) - the escrow's `Declined` event and the neutral vocabulary the state is
|
|
32
37
|
// reported in. It is its own module because TWO surfaces ask the same question (this flow and the swaps watch)
|
|
33
38
|
// and a second implementation of the same event would be a second truth about it.
|
|
@@ -508,7 +513,10 @@ async function assertActionWindow(escrow, what, deps, now = null) {
|
|
|
508
513
|
// THE ACTION IS EXECUTED ON PAPER BEFORE IT IS SIGNED. `eth_call` runs the same call against the latest state
|
|
509
514
|
// from the same sender, so a revert becomes a named refusal instead of a mined transaction that changed nothing.
|
|
510
515
|
// The guards above answer the questions we know how to ask; this answers the contract itself, including its own
|
|
511
|
-
// deadlines
|
|
516
|
+
// deadlines. A caller without a call seam keeps the old behaviour.
|
|
517
|
+
//
|
|
518
|
+
// IT IS NOT USED FOR AN ACTION THAT CARRIES A HALF. A claim or a refund puts the half in the calldata, and the
|
|
519
|
+
// dry run would hand it to the RPC operator before any money moves; see assertHalfMatchesCommit below.
|
|
512
520
|
async function simulateAction(escrow, data, what, deps) {
|
|
513
521
|
const call = deps.call;
|
|
514
522
|
if (typeof call !== "function") return;
|
|
@@ -531,6 +539,38 @@ async function simulateAction(escrow, data, what, deps) {
|
|
|
531
539
|
}
|
|
532
540
|
}
|
|
533
541
|
|
|
542
|
+
// A DRY RUN MUST NOT HAND THE HALF TO THE RPC. `eth_call` goes to a public endpoint by default, so simulating
|
|
543
|
+
// `claim(half)` or `refund(half)` publishes the half to a third party while the escrow is still open and the ETH
|
|
544
|
+
// has not moved. Whoever keeps that call holds both halves of the Monero key when the person declines the
|
|
545
|
+
// transaction in the wallet or the send never lands (sdk#291).
|
|
546
|
+
//
|
|
547
|
+
// The simulation added exactly one check, and it is arithmetic: the half's point commitment must equal the
|
|
548
|
+
// order's. The contract compares the LOW 160 BITS of `keccak256(x||y)` of `half*G`
|
|
549
|
+
// (NinseiEscrow.halfMatchesCommit); the same formula runs here over the half we hold, against the slot READ FROM
|
|
550
|
+
// THE ESCROW. Every other refusal the contract can give (closed, unfunded, not ready, window closed) is answered
|
|
551
|
+
// by the state and clock guards above, before this line.
|
|
552
|
+
const low160Hex = (value) => String(value == null ? "" : value).replace(/^0x/i, "").toLowerCase().slice(-40);
|
|
553
|
+
async function assertHalfMatchesCommit(escrow, half, slot, what, deps) {
|
|
554
|
+
const field = what === "claim" ? "halfClaimer" : "halfLocker";
|
|
555
|
+
let got;
|
|
556
|
+
try {
|
|
557
|
+
got = low160Hex(halfCommitmentHex(BigInt(half), secp256k1, keccak256));
|
|
558
|
+
} catch {
|
|
559
|
+
throw new SdkError("bad-input", { field });
|
|
560
|
+
}
|
|
561
|
+
const call = deps.call || readContract;
|
|
562
|
+
let commit;
|
|
563
|
+
try {
|
|
564
|
+
commit = decodeBytes32(await call({ to: escrow, data: encodeRead(slot), block: deps.blockTag || "latest" }), slot + "()");
|
|
565
|
+
} catch {
|
|
566
|
+
// AN UNREAD ORDER IS NOT A MATCHING ONE.
|
|
567
|
+
throw new SdkError("contract-reverted", { step: what, why: "slots-unreadable" });
|
|
568
|
+
}
|
|
569
|
+
if (got !== low160Hex(commit)) {
|
|
570
|
+
throw new SdkError("contract-reverted", { step: what, why: "half-mismatch" });
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
534
574
|
// Claim the ETH by the CLAIMER'S half. The field name in the contract is halfClaimer (:213); the former word
|
|
535
575
|
// "secret" is a synonym of the same value (the half serves as the preimage of the commitment), while "hashlock"
|
|
536
576
|
// lied here: the current contract has NO hashlock field. Instead it has two half commitments -
|
|
@@ -540,14 +580,16 @@ async function simulateAction(escrow, data, what, deps) {
|
|
|
540
580
|
export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {} }) {
|
|
541
581
|
if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
|
|
542
582
|
if (!halfClaimer) throw new SdkError("bad-input", { field: "halfClaimer" });
|
|
543
|
-
// STATE, TIME AND
|
|
544
|
-
// whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
|
|
583
|
+
// STATE, TIME, SLOTS AND THE HALF BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY
|
|
584
|
+
// order whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
|
|
545
585
|
// `readyBy` it requires the mark, after `readyBy` it allows a claim without it. Both are checked from the
|
|
546
586
|
// chain's own timestamp when the actions facade brings one.
|
|
547
587
|
await assertOrderOpen(escrow, "claim", deps);
|
|
548
588
|
await assertActionWindow(escrow, "claim", deps);
|
|
549
589
|
await assertOrderSlots(escrow, expect, "claim", deps);
|
|
550
|
-
|
|
590
|
+
// THE HALF IS CHECKED HERE, NOT BY A DRY RUN: the escrow's own comparison, computed locally and read against
|
|
591
|
+
// the order. No call carries the half until the send.
|
|
592
|
+
await assertHalfMatchesCommit(escrow, halfClaimer, "commitHalfClaimer", "claim", deps);
|
|
551
593
|
onStep?.("confirm-claim");
|
|
552
594
|
// THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE (issue #127): the node lays exactly
|
|
553
595
|
// this limit into the gas gift. It is set explicitly and with a margin: claim has the same trap as order
|
|
@@ -575,7 +617,9 @@ export async function refundOrder({ escrow, halfLocker, onStep, expect = null, d
|
|
|
575
617
|
// for the same reason. Expectations are optional for compatibility with previous calls (the page calls without
|
|
576
618
|
// them); the core always passes them.
|
|
577
619
|
if (expect) await assertOrderSlots(escrow, expect, "refund", deps);
|
|
578
|
-
|
|
620
|
+
// THE SAME LOCAL CHECK ON THE DEPOSITOR'S HALF. A refund reveals it exactly as a claim reveals the claimer's,
|
|
621
|
+
// so it is compared with the escrow's `commitHalfLocker` before the signature and never sent to a dry run.
|
|
622
|
+
await assertHalfMatchesCommit(escrow, halfLocker, "commitHalfLocker", "refund", deps);
|
|
579
623
|
onStep?.("confirm-refund");
|
|
580
624
|
const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeRefund(halfLocker), gas: 250_000n });
|
|
581
625
|
return { hash };
|