@ninsei-labs/sdk 0.56.1 → 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 +29 -0
- package/LICENSE-POLICY.md +9 -2
- package/README.md +78 -28
- package/THIRD_PARTY_NOTICES.md +176 -2
- package/assets/vendors/MANIFEST.json +1 -13
- package/assets/vendors/sdk/sdk-browser.js +5 -4
- package/engine/atomic/dleq2.js +116 -15
- package/engine/atomic/order.js +21 -3
- package/engine/core/config.js +20 -46
- package/engine/core/deployments.generated.js +103 -0
- package/engine/core/rfqSource.js +6 -133
- package/engine/core/swap.js +8 -8
- package/engine/evm/asyncRoute.js +1 -1
- package/engine/evm/claimGas.js +2 -1
- package/engine/evm/escrow.js +13 -8
- package/engine/evm/factory.js +11 -6
- package/engine/evm/funding.js +8 -3
- package/engine/evm/index.js +5 -6
- package/engine/evm/session.js +48 -279
- 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 +121 -28
- package/engine/monero/wallet.js +31 -68
- package/engine/monero/wordlist.en.js +210 -0
- package/engine/recovery/restore.js +9 -9
- package/engine/sdk/bridge.js +9 -187
- package/engine/ui/walletModal.js +7 -27
- package/index.d.ts +234 -262
- package/package.json +7 -6
- package/src/actions.mjs +8 -5
- package/src/codes.mjs +17 -0
- package/src/config.mjs +17 -54
- package/src/engine.mjs +9 -6
- package/src/feeEstimate.mjs +11 -4
- package/src/http.mjs +4 -1
- package/src/index.mjs +24 -45
- package/src/legs/kyber.mjs +23 -0
- package/src/lock.mjs +1 -0
- package/src/order.mjs +110 -22
- package/src/primitives.mjs +4 -5
- package/src/probes.mjs +9 -3
- package/src/public/networks.d.ts +45 -0
- package/src/public/networks.mjs +10 -1
- package/src/public/recovery.d.ts +17 -1
- package/src/public/recovery.mjs +1 -0
- package/src/public/xmr.mjs +1 -1
- package/src/quotePolicy.mjs +25 -0
- package/src/quotes.mjs +109 -765
- package/src/readyWindow.mjs +76 -0
- package/src/recovery-key.mjs +71 -16
- package/src/recovery.mjs +11 -28
- package/src/relayClaim.mjs +132 -0
- package/src/relayFeatures.mjs +25 -13
- package/src/relayFirmClient.mjs +36 -7
- package/src/relayQuote.mjs +92 -11
- package/src/relayView.mjs +3 -3
- package/src/swap-flow.mjs +146 -60
- package/src/swaps.mjs +521 -357
- package/src/sweep-action.mjs +73 -0
- package/src/sweep-restore.mjs +8 -4
- package/src/sweep.mjs +12 -2
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +328 -29
- package/src/xmrAmountPolicy.mjs +35 -0
- package/assets/vendors/atomic/atomic-browser.js +0 -24
- 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
- package/engine/atomic/order-client.js +0 -56
- package/engine/atomic/order-worker.js +0 -156
- package/engine/evm/asyncExec.js +0 -577
- package/engine/evm/asyncLegs.js +0 -308
package/src/quotes.mjs
CHANGED
|
@@ -1,29 +1,17 @@
|
|
|
1
|
-
//
|
|
1
|
+
// FIRM QUOTES THROUGH A RELAY: the SDK's only quote path.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// precisely to notice that.
|
|
8
|
-
//
|
|
9
|
-
// WHAT MUST NOT BE LOST HERE (all three rules cost the project mistakes):
|
|
10
|
-
// 1) a row has TWO rates: rateQuote - as written in the pair, rate - how much non-XMR per 1 XMR. This is not
|
|
11
|
-
// duplication but different orientations; zero means "no direction", and it is NEVER divided and never
|
|
12
|
-
// becomes a price;
|
|
13
|
-
// 2) the size is requested in the units of the pair's ASSET (the first element): for a buy that is XMR, for a
|
|
14
|
-
// sell - the token; a size outside the provider's grid is not accepted, so the size is snapped to the grid
|
|
15
|
-
// DOWN, not to the nearest;
|
|
16
|
-
// 3) a quote older than its own ttlMs is not shown, and a row that contradicts itself (the named sides disagree
|
|
17
|
-
// with the pair's name) is not read at all.
|
|
3
|
+
// The old direct node client is gone with its routes. A quote now starts from one recovery key, goes through a
|
|
4
|
+
// relay, and comes back as a signed order quote plus the maker's view half. Every check that used to guard the
|
|
5
|
+
// direct answer - the signature, the registry/provider binding, the cashier pin, the factory and implementation
|
|
6
|
+
// code, the claim tip - still runs here, against the same signed fields.
|
|
18
7
|
import { fail } from "./errors.mjs";
|
|
19
|
-
import { SDK_VERSION } from "./version.mjs";
|
|
20
8
|
import * as engine from "./engine.mjs";
|
|
21
|
-
import { orderQuoteMissingFields, recoverOrderQuoteKey } from "./quoteEip712.mjs";
|
|
22
9
|
import { claimGasGiftWei } from "../engine/evm/claimGas.js";
|
|
23
|
-
import { parseXmr } from "../engine/core/xmrAmount.js";
|
|
24
10
|
import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
|
|
25
|
-
import {
|
|
11
|
+
import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
|
|
26
12
|
import { requestFirmQuote } from "./relayFirmClient.mjs";
|
|
13
|
+
import { readReadyWindow } from "./readyWindow.mjs";
|
|
14
|
+
import { quoteLifeVerdict } from "./quotePolicy.mjs";
|
|
27
15
|
// THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
|
|
28
16
|
// remembered: a single wrong hex digit would call another function and return a zero address - and a zero
|
|
29
17
|
// address is exactly the answer "nobody owns this key", which the caller would take as the truth.
|
|
@@ -52,203 +40,54 @@ const addressFromWord = (raw) => {
|
|
|
52
40
|
return h.length >= 40 ? "0x" + h.slice(-40).toLowerCase() : null;
|
|
53
41
|
};
|
|
54
42
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const givenRate = num(q.rate);
|
|
74
|
-
const rateQuote = givenRateQuote !== null ? givenRateQuote : givenRate;
|
|
75
|
-
let rate = null;
|
|
76
|
-
if (givenRateQuote !== null) rate = givenRate;
|
|
77
|
-
else if (rateQuote !== null) rate = currency === "XMR" ? (rateQuote > 0 ? 1 / rateQuote : null) : rateQuote;
|
|
78
|
-
const contradicts = (statedAsset && statedAsset !== asset) || (statedCurrency && statedCurrency !== currency);
|
|
79
|
-
const at = num(q.at);
|
|
80
|
-
return {
|
|
81
|
-
providerId: String(owner.providerId || q.providerId || "").trim(),
|
|
82
|
-
displayName: owner.displayName || q.displayName || null,
|
|
83
|
-
// THE PROVIDER'S MATURITY LEVEL RIDES WITH THE OFFER: a person chooses not only by price but also by how long
|
|
84
|
-
// to wait. No field - no value either, not an invented default.
|
|
85
|
-
finality: owner.finality || q.finality || null,
|
|
86
|
-
pair: text,
|
|
87
|
-
asset: statedAsset || asset,
|
|
88
|
-
currency: statedCurrency || currency,
|
|
89
|
-
assetNetwork: q.assetNetwork ? String(q.assetNetwork) : null,
|
|
90
|
-
currencyNetwork: q.currencyNetwork ? String(q.currencyNetwork) : null,
|
|
91
|
-
rateQuote,
|
|
92
|
-
rate,
|
|
93
|
-
// THE CLAIM TIP IS IN THE MAKER'S NATIVE TOKEN (wei). A sale is ranked by what the seller receives AFTER it;
|
|
94
|
-
// the value is kept as a string, because a wei amount does not fit a float reliably.
|
|
95
|
-
claimTip: (() => {
|
|
96
|
-
if (q.claimTip === undefined || q.claimTip === null || q.claimTip === "") return "0";
|
|
97
|
-
try { const n = BigInt(q.claimTip); return n < 0n ? "0" : n.toString(); }
|
|
98
|
-
catch { return "0"; }
|
|
99
|
-
})(),
|
|
100
|
-
min: num(q.min),
|
|
101
|
-
max: num(q.max),
|
|
102
|
-
step: num(q.step),
|
|
103
|
-
ttlMs: num(q.ttlMs) && num(q.ttlMs) > 0 ? num(q.ttlMs) : null,
|
|
104
|
-
at,
|
|
105
|
-
why: q.why ? String(q.why) : null,
|
|
106
|
-
disabled: q.disabled === true || (givenRate !== null && !(givenRate > 0)),
|
|
107
|
-
// NETWORKS NOT NAMED / FILLED IN BY THE RECEIVER - this is a FACT ABOUT THE QUOTE, and it is visible apart
|
|
108
|
-
// from "named and matched": the screen must say "nothing to check against" rather than attribute our network
|
|
109
|
-
// to the quote.
|
|
110
|
-
networksUnnamed: q.networksUnnamed === true,
|
|
111
|
-
networksDerived: q.networksDerived === true,
|
|
112
|
-
seq: num(q.seq) !== null ? num(q.seq) : (num(owner.seq) !== null ? num(owner.seq) : num(data.seq)),
|
|
113
|
-
signature: q.signature || owner.signature || null,
|
|
114
|
-
keyId: q.keyId || null,
|
|
115
|
-
networkStated: Boolean(q.assetNetwork || q.currencyNetwork),
|
|
116
|
-
contradicts,
|
|
117
|
-
ageMs: at === null ? null : Math.max(0, Date.now() - at),
|
|
118
|
-
};
|
|
119
|
-
}
|
|
43
|
+
// THE CASHIER IS THE NETWORK'S VAULT, NOT A FIELD THE MAKER MAY CHOOSE. The escrow binds it at birth, but the
|
|
44
|
+
// client must refuse an answer before it funds or sends XMR: a look-alike vault with the canonical runtime and
|
|
45
|
+
// crafted storage would pass the escrow's code check and make every claim revert after the payout.
|
|
46
|
+
const pinnedCashier = (config) => {
|
|
47
|
+
const chain = config && config.settlement && config.settlement.chain;
|
|
48
|
+
const value = chain && chain.escrow && chain.escrow.cashier;
|
|
49
|
+
return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? value.toLowerCase() : null;
|
|
50
|
+
};
|
|
51
|
+
const requirePinnedCashier = (quote, step, config) => {
|
|
52
|
+
const chain = config && config.settlement && config.settlement.chain;
|
|
53
|
+
const pin = pinnedCashier(config);
|
|
54
|
+
// A caller without a network profile has nothing to compare against. A profile that names a chain but no vault
|
|
55
|
+
// is a broken profile, not a free pass: refuse it before a quote can be funded.
|
|
56
|
+
if (!pin && !chain) return;
|
|
57
|
+
const got = String(quote && quote.cashier || "").toLowerCase();
|
|
58
|
+
if (!pin) fail("quote-cashier-mismatch", { step, why: "no-pinned-cashier", got: got || null });
|
|
59
|
+
if (got !== pin) fail("quote-cashier-mismatch", { step, got: got || null, want: pin });
|
|
60
|
+
};
|
|
120
61
|
|
|
121
|
-
/**
|
|
122
|
-
* THE BEST OFFER IS THE ONE THAT PAYS THE MOST, NOT THE ONE WITH THE HIGHEST RATE. On a sale the maker may move
|
|
123
|
-
* its margin into `claimTip`: the escrow pays that tip out of the seller's payout, so a higher rate with a larger
|
|
124
|
-
* tip can leave the seller with less. With no amount there is nothing to compare beyond the rate, and a buy has
|
|
125
|
-
* no tip. Native-token wei are converted at 18 decimals: a sale settles in the chain's native coin.
|
|
126
|
-
*/
|
|
127
|
-
export function rankOffers(offers = [], { direction = "buy", amount = null } = {}) {
|
|
128
|
-
const list = Array.isArray(offers) ? offers.filter((offer) => offer && Number(offer.rate) > 0) : [];
|
|
129
|
-
const amountXmr = Number(amount);
|
|
130
|
-
const score = (offer) => {
|
|
131
|
-
const rate = Number(offer.rate);
|
|
132
|
-
if (direction !== "sell" || !(amountXmr > 0)) return rate;
|
|
133
|
-
let tip = 0;
|
|
134
|
-
try { tip = Number(BigInt(offer.claimTip || "0")) / 1e18; } catch { tip = 0; }
|
|
135
|
-
return amountXmr * rate - tip;
|
|
136
|
-
};
|
|
137
|
-
const ranked = list.map((offer) => ({ offer, net: score(offer) }))
|
|
138
|
-
.sort((a, b) => (b.net - a.net) || (Number(b.offer.rate) - Number(a.offer.rate)));
|
|
139
|
-
return { best: ranked.length ? ranked[0].offer : null, net: ranked.length ? ranked[0].net : null, ranked };
|
|
140
|
-
}
|
|
141
62
|
|
|
142
63
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
64
|
+
* A CLAIM TIP IS SIZED BY THE CLAIM, NOT BY THE MAKER'S MOOD. The node's own estimate uses the chain's current
|
|
65
|
+
* base fee and the same formula; a quote may carry up to twice that estimate (gas moves between the sizing and
|
|
66
|
+
* the check). Zero is the buy side and is always allowed. An unmeasured base fee is a refusal, not a free pass.
|
|
146
67
|
*/
|
|
147
|
-
export function readBook(data, now = Date.now()) {
|
|
148
|
-
const quotes = data && data.quotes;
|
|
149
|
-
const rows = [];
|
|
150
|
-
const add = (pair, raw, owner) => { const row = readQuote(pair, raw, owner, data || {}); if (row) rows.push(row); };
|
|
151
|
-
if (Array.isArray(quotes)) {
|
|
152
|
-
for (const row of quotes) {
|
|
153
|
-
if (!row || typeof row !== "object") continue;
|
|
154
|
-
const nested = row.quotes && !Array.isArray(row.quotes) && typeof row.quotes === "object" ? row.quotes : null;
|
|
155
|
-
if (nested) for (const [pair, q] of Object.entries(nested)) add(pair, q, row);
|
|
156
|
-
else add(row.pair, row, row);
|
|
157
|
-
}
|
|
158
|
-
} else if (quotes && typeof quotes === "object") {
|
|
159
|
-
for (const [pair, q] of Object.entries(quotes)) add(pair, q, q && typeof q === "object" ? q : {});
|
|
160
|
-
}
|
|
161
|
-
// ONE QUOTE PER PAIR PER PROVIDER: if several arrived, we keep the fresh one rather than choosing arbitrarily
|
|
162
|
-
// (these are two different offers under one name).
|
|
163
|
-
const byKey = new Map();
|
|
164
|
-
for (const row of rows) {
|
|
165
|
-
const key = (row.providerId || "?") + "|" + row.pair;
|
|
166
|
-
const prev = byKey.get(key);
|
|
167
|
-
if (!prev || Number(row.at) > Number(prev.at)) byKey.set(key, row);
|
|
168
|
-
}
|
|
169
|
-
const offers = [];
|
|
170
|
-
const refused = [];
|
|
171
|
-
for (const row of byKey.values()) {
|
|
172
|
-
if (row.contradicts) { refused.push({ ...row, code: "malformed" }); continue; }
|
|
173
|
-
if (row.rateQuote === null && row.rate === null) { refused.push({ ...row, code: "malformed" }); continue; }
|
|
174
|
-
if (row.disabled || !(row.rate > 0)) { refused.push({ ...row, code: "disabled" }); continue; }
|
|
175
|
-
if (row.ttlMs && row.ageMs !== null && row.ageMs > row.ttlMs) { refused.push({ ...row, code: "stale" }); continue; }
|
|
176
|
-
offers.push(row);
|
|
177
|
-
}
|
|
178
|
-
const best = offers.slice().sort((a, b) => b.rate - a.rate)[0] || null;
|
|
179
|
-
return { offers, refused, best, at: now };
|
|
180
|
-
}
|
|
181
|
-
|
|
182
68
|
/**
|
|
183
|
-
*
|
|
184
|
-
*
|
|
69
|
+
* THE PRIORITY FEE OF A BLOCK, FROM ONE RULE. An explicit priority field wins; a plain RPC block may carry only
|
|
70
|
+
* `gasPrice`, so the priority is the part above the base fee. No block or no readable pair means zero - the
|
|
71
|
+
* caller then uses the base fee alone, which is the old, stricter behaviour.
|
|
185
72
|
*/
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
if (
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* What the user will receive and what they pay for it, by the best offer and its rate.
|
|
203
|
-
* buy: they pay with the token and receive XMR, so the size (the ASSET of the pair XMR/<token>) is XMR.
|
|
204
|
-
* sell: they give XMR and receive the token, the ASSET of the pair <token>/XMR is the token itself.
|
|
205
|
-
*/
|
|
206
|
-
export function derivedFor(offer, direction, amount, now = Date.now()) {
|
|
207
|
-
const rate = offer && Number.isFinite(Number(offer.rate)) && Number(offer.rate) > 0 ? Number(offer.rate) : null;
|
|
208
|
-
const size = direction === "sell" ? (rate !== null && amount > 0 ? amount * rate : null)
|
|
209
|
-
: (rate !== null && amount > 0 ? amount / rate : null);
|
|
210
|
-
if (size === null) return { rate, size: null, unit: null, code: "no-offer", xmr: null };
|
|
211
|
-
const settled = snapToGrid(size, offer || {});
|
|
212
|
-
return {
|
|
213
|
-
rate,
|
|
214
|
-
size: settled.size,
|
|
215
|
-
unit: direction === "sell" ? String(offer.currency || "").toUpperCase() || null : "XMR",
|
|
216
|
-
snapped: settled.snapped,
|
|
217
|
-
code: settled.code,
|
|
218
|
-
// HOW MUCH XMR FOR THE REQUESTED SIZE. For a buy this is the size, for a sell - the amount the person gives.
|
|
219
|
-
xmr: direction === "sell" ? amount : (Number.isFinite(Number(settled.size)) ? Number(settled.size) : null),
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// THE ROW FIELDS THAT GO OUT. This is a translation of the SHAPE, not a recomputation: the values are taken from
|
|
224
|
-
// the read row and are not changed. The fields are listed explicitly (and not `...row`) so that internal parsing
|
|
225
|
-
// markers do not leak out. Selection and priority are done by readBook above: a row gets here only if it has
|
|
226
|
-
// already been recognised as an offer.
|
|
227
|
-
const compactOffer = (o) => ({
|
|
228
|
-
providerId: o.providerId, displayName: o.displayName, pair: o.pair, rate: o.rate, rateQuote: o.rateQuote,
|
|
229
|
-
min: o.min, max: o.max, step: o.step, ttlMs: o.ttlMs, at: o.at, seq: o.seq,
|
|
230
|
-
// THE MATURITY LEVEL IS PART OF THE CHOICE: one provider gives a better price but only on finalized, another is
|
|
231
|
-
// pricier but faster. No field - null, not an invented default.
|
|
232
|
-
finality: o.finality || null,
|
|
233
|
-
// THE PAIR'S SIDES AND BOTH NETWORKS: the network is part of the market's identity, and the display must
|
|
234
|
-
// distinguish arbitrum from arbitrum-sepolia. `networks` is kept as the assembled view of the same values.
|
|
235
|
-
asset: o.asset, currency: o.currency,
|
|
236
|
-
assetNetwork: o.assetNetwork, currencyNetwork: o.currencyNetwork, networkStated: o.networkStated,
|
|
237
|
-
networksDerived: o.networksDerived === true, networksUnnamed: o.networksUnnamed === true,
|
|
238
|
-
// THE REASON (in the provider's words), THE PACKAGE'S SIGNATURE AND KEY, THE AGE BY ITS OWN MARK.
|
|
239
|
-
claimTip: o.claimTip, why: o.why, signature: o.signature, keyId: o.keyId, ageMs: o.ageMs,
|
|
240
|
-
networks: { asset: o.assetNetwork, currency: o.currencyNetwork, stated: o.networkStated },
|
|
241
|
-
});
|
|
73
|
+
const priorityFeeOfBlock = (block) => {
|
|
74
|
+
if (!block || typeof block !== "object") return 0n;
|
|
75
|
+
const explicit = block.priorityFeePerGas !== undefined && block.priorityFeePerGas !== null
|
|
76
|
+
? block.priorityFeePerGas
|
|
77
|
+
: (block.maxPriorityFeePerGas !== undefined && block.maxPriorityFeePerGas !== null
|
|
78
|
+
? block.maxPriorityFeePerGas : null);
|
|
79
|
+
if (explicit !== null) return explicit;
|
|
80
|
+
const base = block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei;
|
|
81
|
+
if (block.gasPrice === undefined || block.gasPrice === null || base === undefined || base === null) return 0n;
|
|
82
|
+
try {
|
|
83
|
+
const gas = BigInt(block.gasPrice);
|
|
84
|
+
const baseValue = BigInt(base);
|
|
85
|
+
return gas > baseValue ? gas - baseValue : 0n;
|
|
86
|
+
} catch { return 0n; }
|
|
87
|
+
};
|
|
242
88
|
|
|
243
|
-
|
|
244
|
-
// the price of the failed row to tell the person WHY there is no offer (and not just "none").
|
|
245
|
-
const compactRefusal = (r) => ({ ...compactOffer(r), code: r.code, why: r.why });
|
|
89
|
+
export const claimPriorityFeeOfBlock = priorityFeeOfBlock;
|
|
246
90
|
|
|
247
|
-
/**
|
|
248
|
-
* A CLAIM TIP IS SIZED BY THE CLAIM, NOT BY THE MAKER'S MOOD. The node's own estimate uses the chain's current
|
|
249
|
-
* base fee and the same formula; a quote may carry up to twice that estimate (gas moves between the sizing and
|
|
250
|
-
* the check). Zero is the buy side and is always allowed. An unmeasured base fee is a refusal, not a free pass.
|
|
251
|
-
*/
|
|
252
91
|
export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFeeWei = 0, factor = 2 } = {}) {
|
|
253
92
|
let tip = 0n;
|
|
254
93
|
try { tip = BigInt(claimTipWei === undefined || claimTipWei === null || claimTipWei === "" ? 0 : claimTipWei); }
|
|
@@ -268,7 +107,7 @@ export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFe
|
|
|
268
107
|
return { ok: true, tipWei: tip.toString(), estimateWei: estimate.toString(), ceilingWei: ceiling.toString() };
|
|
269
108
|
}
|
|
270
109
|
|
|
271
|
-
export function createQuotes({ config,
|
|
110
|
+
export function createQuotes({ config, now = () => Date.now(), evmCall = null, evmCode = null, evmBlock = null,
|
|
272
111
|
providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null }) {
|
|
273
112
|
// THE INTERFACE'S FACTORY POLICY (#103): the code hashes of factories it is willing to trade through
|
|
274
113
|
// (extcodehash semantics = keccak256 of the runtime code). An EMPTY list is "no policy" (like
|
|
@@ -282,549 +121,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
282
121
|
const implementationPolicy = Array.isArray(knownImplementationCodes) && knownImplementationCodes.length
|
|
283
122
|
? knownImplementationCodes.map((h) => String(h).toLowerCase()).filter(Boolean)
|
|
284
123
|
: null;
|
|
285
|
-
const listeners = new Set();
|
|
286
|
-
let timer = null;
|
|
287
|
-
let size = 1; // the request size in units of the pair's ASSET; we start from one, as the engine does
|
|
288
|
-
let state = null;
|
|
289
|
-
let request = { direction: "buy", token: null, amount: null };
|
|
290
|
-
let inFlight = false;
|
|
291
|
-
|
|
292
|
-
const emit = () => { for (const handler of listeners) handler(state); };
|
|
293
|
-
|
|
294
|
-
const tick = async () => {
|
|
295
|
-
if (inFlight) return;
|
|
296
|
-
inFlight = true;
|
|
297
|
-
try {
|
|
298
|
-
// THE REQUEST SIZE. Usually it is derived from the person's amount (amount) and refined on the next tick.
|
|
299
|
-
// But the caller can name it HIMSELF (size) - then it is taken AS IS rather than derived anew: it is the
|
|
300
|
-
// same size the interface has already aligned to the provider's grid. There is no second size rule here.
|
|
301
|
-
const explicit = Number.isFinite(Number(request.size)) && Number(request.size) > 0;
|
|
302
|
-
const asked = explicit ? Number(request.size) : size;
|
|
303
|
-
const data = await http.json("/rate?amount=" + encodeURIComponent(asked) + "&side=" + encodeURIComponent(request.direction));
|
|
304
|
-
const book = readBook(data, now());
|
|
305
|
-
const amount = Number.isFinite(Number(request.amount)) ? Number(request.amount) : null;
|
|
306
|
-
// A SALE IS RANKED BY THE PAYOUT AFTER THE TIP; a buy has no tip. Without an amount the rate is the only
|
|
307
|
-
// comparable number, and the service's own best remains the fallback.
|
|
308
|
-
const ranked = rankOffers(book.offers, { direction: request.direction, amount });
|
|
309
|
-
const offer = ranked.best || book.best;
|
|
310
|
-
// The size derived from the person's amount becomes the size of the NEXT request: the price does not depend
|
|
311
|
-
// on volume, and the volume is needed by the provider to say whether it takes such a size. With a named size
|
|
312
|
-
// there is nothing to derive - it stays what it was asked as.
|
|
313
|
-
const derived = offer && amount !== null && !explicit ? derivedFor(offer, request.direction, amount, now()) : null;
|
|
314
|
-
if (derived && derived.size !== null) size = derived.size;
|
|
315
|
-
// THE UNIT with a named size: a buy is measured in XMR (the ASSET of the pair XMR/<token>), a sell - in the token.
|
|
316
|
-
const unitFromOffer = offer ? (String(offer.currency || "").toUpperCase() || null) : null;
|
|
317
|
-
const settled = explicit ? (offer ? snapToGrid(asked, offer) : null) : null;
|
|
318
|
-
state = {
|
|
319
|
-
direction: request.direction,
|
|
320
|
-
token: request.token,
|
|
321
|
-
amount,
|
|
322
|
-
size: explicit ? asked : size,
|
|
323
|
-
unit: explicit ? (request.direction === "sell" ? unitFromOffer : "XMR") : (derived ? derived.unit : null),
|
|
324
|
-
rate: explicit ? (offer ? Number(offer.rate) : null) : (derived ? derived.rate : null),
|
|
325
|
-
xmr: derived ? derived.xmr : null,
|
|
326
|
-
at: now(),
|
|
327
|
-
providerId: offer ? offer.providerId : null,
|
|
328
|
-
sizeOk: explicit ? Boolean(settled && settled.code === null) : Boolean(derived && derived.code === null),
|
|
329
|
-
sizeCode: explicit ? (settled ? settled.code : "no-offer") : (derived ? derived.code : "no-offer"),
|
|
330
|
-
seq: book.offers.length ? (book.offers.find((o) => o.seq !== null) || {}).seq ?? null : null,
|
|
331
|
-
// THE BEST, AS THE SERVICE NAMED IT (for the requested volume and side). The core does NOT recompute it:
|
|
332
|
-
// these are response data the interface needs to confirm its own "best" mark by pair and provider.
|
|
333
|
-
best: data && data.best && typeof data.best === "object"
|
|
334
|
-
? { providerId: String(data.best.providerId || ""), pair: String(data.best.pair || "") } : null,
|
|
335
|
-
offers: book.offers.map(compactOffer),
|
|
336
|
-
refused: book.refused.map(compactRefusal),
|
|
337
|
-
references: Array.isArray(data && data.references) ? data.references.map((r) => ({ source: r.source, value: num(r.value), at: num(r.at) })) : [],
|
|
338
|
-
ok: book.offers.length > 0,
|
|
339
|
-
};
|
|
340
|
-
emit();
|
|
341
|
-
} catch (error) {
|
|
342
|
-
// A REFUSAL IS NOT REPLACED BY PAST NUMBERS: showing a stale price as live is worse than saying the connection
|
|
343
|
-
// is gone. The data is kept, but ok is cleared, and the interface sees it.
|
|
344
|
-
state = { ...(state || { direction: request.direction, token: request.token, amount: null, size, unit: null, rate: null, xmr: null,
|
|
345
|
-
at: now(), providerId: null, sizeOk: false, sizeCode: null, seq: null, best: null, offers: [], refused: [], references: [] }),
|
|
346
|
-
at: now(), ok: false, error: { code: error && error.code === "server-unavailable" ? "quote-unavailable" : "unknown" } };
|
|
347
|
-
emit();
|
|
348
|
-
} finally {
|
|
349
|
-
inFlight = false;
|
|
350
|
-
}
|
|
351
|
-
};
|
|
352
|
-
|
|
353
|
-
const restart = () => {
|
|
354
|
-
if (timer) clearInterval(timer);
|
|
355
|
-
timer = null;
|
|
356
|
-
if (listeners.size > 0) {
|
|
357
|
-
void tick();
|
|
358
|
-
timer = setInterval(() => { void tick(); }, config.limits.quotePollMs);
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
|
|
362
124
|
return {
|
|
363
|
-
watch(next, onSnapshot) {
|
|
364
|
-
if (typeof onSnapshot !== "function") fail("bad-input", { field: "onSnapshot" });
|
|
365
|
-
const direction = next && next.direction === "sell" ? "sell" : "buy";
|
|
366
|
-
const token = next && typeof next.token === "string" && next.token ? next.token.toLowerCase() : config.settlement.chain.nativeSymbol.toLowerCase();
|
|
367
|
-
request = {
|
|
368
|
-
direction,
|
|
369
|
-
token,
|
|
370
|
-
amount: next && next.amount !== undefined ? next.amount : null,
|
|
371
|
-
// A NAMED SIZE (in units of `unit`): an interface that has already aligned the volume to the provider's
|
|
372
|
-
// grid hands it here, and the core asks for EXACTLY it rather than deriving it from the amount anew.
|
|
373
|
-
size: next && Number.isFinite(Number(next.size)) && Number(next.size) > 0 ? Number(next.size) : null,
|
|
374
|
-
};
|
|
375
|
-
size = 1;
|
|
376
|
-
state = null;
|
|
377
|
-
listeners.add(onSnapshot);
|
|
378
|
-
restart();
|
|
379
|
-
return () => {
|
|
380
|
-
listeners.delete(onSnapshot);
|
|
381
|
-
if (listeners.size === 0) {
|
|
382
|
-
if (timer) clearInterval(timer);
|
|
383
|
-
timer = null;
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
},
|
|
387
|
-
// WHAT THE SDK KNOWS RIGHT NOW: a snapshot without waiting. Needed by an interface that subscribed later than
|
|
388
|
-
// the first poll happened.
|
|
389
|
-
snapshot: () => state,
|
|
390
|
-
// A FIRM QUOTE FOR AN ORDER. It carries a commitment under keys, so THE PROVIDER'S SIGNATURE IS CONFIRMED
|
|
391
|
-
// HERE, BY RECOVERING THE ADDRESS FROM THE EIP-712 SIGNATURE - not taken on trust from a flag the backend
|
|
392
|
-
// reports. A quote that cannot be verified is not "probably fine": a missing field, a missing signature or
|
|
393
|
-
// an unusable domain is REFUSED, never accepted (the rule the old flag carried is kept). The digest is
|
|
394
|
-
// built from the quote's own fields, so nothing signed can be swapped afterwards; the named quoteKey is
|
|
395
|
-
// matched against the recovered address. THEN THE CHAIN IS ASKED WHO OWNS THE KEY (providerOf): the
|
|
396
|
-
// signature alone certifies itself, because a key can sign anything and call itself any provider. The
|
|
397
|
-
// registry is read from the quote/order conditions - never from SDK settings: any registry can be deployed
|
|
398
|
-
// by anyone, and the order carries which one it is (the field is signed and bound into the terms). Finally
|
|
399
|
-
// the interface's allow-list, when it supplied one, is applied as policy (who is admitted at all).
|
|
400
|
-
//
|
|
401
|
-
// The path and the body are the same as the engine's (`requestOrderQuote` in www/js/core/rfqSource.js): POST to
|
|
402
|
-
// the named path, body { providerId, order }. The path is named by name, so it is overridable by options.
|
|
403
|
-
// A REVERSE-MODE TICKET. The maker sells XMR; the node answers with a signed order quote that carries the claim
|
|
404
|
-
// tip. The tip is checked HERE, on the ticket's own signed figure, with the same formula the node used: base fee
|
|
405
|
-
// plus the priority part of the gas price. A buy quote has no tip; a sale is the only route where one exists.
|
|
406
|
-
async sale(request) {
|
|
407
|
-
if (!request || typeof request !== "object") fail("bad-input", { field: "request" });
|
|
408
|
-
// THE NODE GATES THE THREE BROWSER BODY ROUTES ON THE CLIENT'S SDK LINE. The value is the package's own
|
|
409
|
-
// baked-in version, not a caller field: a caller cannot claim a line it was not built from.
|
|
410
|
-
// THE ENVELOPE IS THE REQUEST. The node accepts both `{ request: {...} }` and a bare body; every check below
|
|
411
|
-
// must read the same object the node priced, not the outer envelope that carries only `sdkVersion`.
|
|
412
|
-
const saleRequest = request.request && typeof request.request === "object" ? request.request : request;
|
|
413
|
-
const payload = { ...(request.request && typeof request.request === "object" ? request : { request }), sdkVersion: SDK_VERSION };
|
|
414
|
-
let res = null;
|
|
415
|
-
try {
|
|
416
|
-
res = await http.tryJson(config.route("orderSell"), {
|
|
417
|
-
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload),
|
|
418
|
-
});
|
|
419
|
-
} catch (error) {
|
|
420
|
-
if (error && error.code === "bad-input") throw error;
|
|
421
|
-
fail("server-unavailable", { step: "order-sell" });
|
|
422
|
-
}
|
|
423
|
-
if (!res || res.ok !== true || !res.body || res.body.ok !== true) fail("quote-refused", { step: "order-sell" });
|
|
424
|
-
const ticket = res.body;
|
|
425
|
-
const quote = (ticket.handoff && ticket.handoff.quote) || ticket.quote || null;
|
|
426
|
-
if (!quote || typeof quote !== "object") fail("quote-field-unbound", { step: "order-sell", field: "quote" });
|
|
427
|
-
// THE SALE TICKET IS A SIGNED QUOTE, AND IT GETS THE SAME GATES AS `firm`: every field of the signed set,
|
|
428
|
-
// its expiry, the EIP-712 signature and the named key, the registry's provider mapping, the interface's
|
|
429
|
-
// allow-list, and the factory/implementation policy. The one difference is the binding below: a sale has no
|
|
430
|
-
// caller-supplied order terms, so its context is checked against `ticket.order` when the node returns it.
|
|
431
|
-
// A MISSING FIELD OF THE SIGNED SET IS NOT "PROBABLY ZERO": the digest cannot be built, so the quote is
|
|
432
|
-
// not verifiable and is refused (its own code, so the interface can say which field is unbound).
|
|
433
|
-
const missingFields = orderQuoteMissingFields(quote);
|
|
434
|
-
if (missingFields.length) fail("quote-field-unbound", { step: "signature", missing: missingFields });
|
|
435
|
-
// THE QUOTE'S OWN EXPIRY, checked against the clock the core already has. It is bound in the signature too,
|
|
436
|
-
// but a stale quote is refused by its own code rather than looking like a signature failure.
|
|
437
|
-
const validUntil = Number(quote.validUntil);
|
|
438
|
-
// THE SCALE IS SECONDS: the same as the order's deadlines and block.timestamp. The core's clock is in
|
|
439
|
-
// milliseconds (Date.now), so exactly ONE boundary is converted - "now", not the quote value itself: one
|
|
440
|
-
// unit for the value, one conversion at the input.
|
|
441
|
-
const nowSec = Math.floor(now() / 1000);
|
|
442
|
-
// THE TTL IS MANDATORY AND MUST BE IN THE FUTURE. Zero, a fraction, an unsafe integer and a missing value are
|
|
443
|
-
// not "never expires": the relay path already requires a safe future integer, and a direct quote must not be
|
|
444
|
-
// weaker than the same quote after it crosses the relay.
|
|
445
|
-
if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
|
|
446
|
-
fail("quote-expired", { step: "signature", validUntil: quote.validUntil });
|
|
447
|
-
}
|
|
448
|
-
// RECOVER, THEN MATCH THE NAMED KEY. A signature that does not recover is one refusal; a valid signature
|
|
449
|
-
// that recovers to a DIFFERENT address is another (the quote names a key that did not sign it).
|
|
450
|
-
const recoveredKey = recoverOrderQuoteKey(quote);
|
|
451
|
-
if (recoveredKey === null) fail("quote-signature-invalid", { step: "signature" });
|
|
452
|
-
const declaredKey = String(quote.quoteKey).toLowerCase();
|
|
453
|
-
if (recoveredKey !== declaredKey) fail("quote-key-mismatch", { step: "signature", got: recoveredKey, want: declaredKey });
|
|
454
|
-
// WHO OWNS THE KEY - ASKED OF THE REGISTRY NAMED BY THE QUOTE. Both fields are part of the signed set, so
|
|
455
|
-
// they cannot be swapped after signing; this is what turns "a key signed it" into "this provider's key
|
|
456
|
-
// signed it". No chain-read seam - refuse rather than take the signature on trust.
|
|
457
|
-
const registry = String(quote.registry || "").toLowerCase();
|
|
458
|
-
if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) {
|
|
459
|
-
fail("quote-field-unbound", { step: "registry", field: "registry" });
|
|
460
|
-
}
|
|
461
|
-
const declaredProvider = String(quote.provider || "").toLowerCase();
|
|
462
|
-
if (!/^0x[0-9a-f]{40}$/.test(declaredProvider) || declaredProvider === ZERO_ADDRESS) {
|
|
463
|
-
fail("quote-field-unbound", { step: "registry", field: "provider" });
|
|
464
|
-
}
|
|
465
|
-
if (typeof evmCall !== "function") fail("quote-registry-unchecked", { step: "registry", why: "no-chain-read" });
|
|
466
|
-
let mappedProvider = null;
|
|
467
|
-
try {
|
|
468
|
-
mappedProvider = addressFromWord(await evmCall({ to: registry, data: providerOfData(declaredKey) }));
|
|
469
|
-
} catch {
|
|
470
|
-
fail("quote-registry-unchecked", { step: "registry", why: "read-failed", registry });
|
|
471
|
-
}
|
|
472
|
-
if (mappedProvider === null || mappedProvider === ZERO_ADDRESS) {
|
|
473
|
-
fail("quote-key-unknown", { step: "registry", registry, quoteKey: declaredKey });
|
|
474
|
-
}
|
|
475
|
-
if (mappedProvider !== declaredProvider) {
|
|
476
|
-
fail("quote-provider-mismatch", { step: "registry", got: mappedProvider, want: declaredProvider });
|
|
477
|
-
}
|
|
478
|
-
// THE INTERFACE'S OWN ADMISSION LIST - POLICY, NOT PROOF. The chain says whose key it is; whether this
|
|
479
|
-
// interface trades with that provider at all is the interface's decision, and it rides as a hook.
|
|
480
|
-
if (typeof providerAllowed === "function" && providerAllowed(declaredProvider) !== true) {
|
|
481
|
-
fail("quote-provider-not-allowed", { step: "policy", provider: declaredProvider });
|
|
482
|
-
}
|
|
483
|
-
// THE FACTORY: NAMED BY THE PROVIDER'S RECORD, CHECKED BY ITS CODE (#103). The factory will verify the
|
|
484
|
-
// quote in EVM (it is the EIP-712 verifyingContract), so it must be the one the record names AND its
|
|
485
|
-
// code must be a build this interface knows. The record lookup always runs; the code check runs when a
|
|
486
|
-
// policy list was supplied (nothing to pin against otherwise).
|
|
487
|
-
const declaredFactory = String(quote.factory || "").toLowerCase();
|
|
488
|
-
if (!/^0x[0-9a-f]{40}$/.test(declaredFactory) || declaredFactory === ZERO_ADDRESS) {
|
|
489
|
-
fail("quote-field-unbound", { step: "factory", field: "factory" });
|
|
490
|
-
}
|
|
491
|
-
let recordedFactory = null;
|
|
492
|
-
try {
|
|
493
|
-
recordedFactory = addressFromWord(await evmCall({ to: registry, data: factoryOfData(declaredProvider) }));
|
|
494
|
-
} catch {
|
|
495
|
-
fail("quote-factory-unchecked", { step: "factory", why: "read-failed", registry });
|
|
496
|
-
}
|
|
497
|
-
if (recordedFactory === null || recordedFactory === ZERO_ADDRESS) {
|
|
498
|
-
fail("quote-factory-unknown", { step: "factory", registry, provider: declaredProvider });
|
|
499
|
-
}
|
|
500
|
-
if (recordedFactory !== declaredFactory) {
|
|
501
|
-
fail("quote-factory-mismatch", { step: "factory", got: declaredFactory, want: recordedFactory });
|
|
502
|
-
}
|
|
503
|
-
if (factoryPolicy) {
|
|
504
|
-
if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
|
|
505
|
-
let codeHex = null;
|
|
506
|
-
try { codeHex = await evmCode(declaredFactory); } catch { fail("quote-factory-unchecked", { step: "factory", why: "code-read-failed", factory: declaredFactory }); }
|
|
507
|
-
const codeBytes = hexToBytesQ(codeHex);
|
|
508
|
-
// EXTCODEHASH SEMANTICS: keccak256 of the runtime code. An address with no code (empty/0x) hashes to
|
|
509
|
-
// the keccak of empty, which is not on any build list - refused like any unknown build.
|
|
510
|
-
const codeHash = bytesToHexQ(keccak256(codeBytes || new Uint8Array(0)));
|
|
511
|
-
if (!factoryPolicy.includes(codeHash)) {
|
|
512
|
-
fail("quote-factory-code-unknown", { step: "factory", factory: declaredFactory, codeHash });
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
// THE IMPLEMENTATION THE CLONES WILL EXECUTE (#114). A pinned factory CODE is not enough on its own: the
|
|
516
|
-
// implementation ADDRESS lives in the factory's STORAGE, so the client re-reads the pair the factory itself
|
|
517
|
-
// checks (implementation() / implementationCodeHash()) and the CODE at that address, then applies the same
|
|
518
|
-
// verdict (verifyFactoryImplementationOnChain). A delegatecall to an address WITHOUT code SUCCEEDS, so a
|
|
519
|
-
// clone without an implementation would take the ETH and its markReady/claim/refund would appear to go
|
|
520
|
-
// through while doing nothing - that is exactly the case this refuses. The live code is re-hashed here, so
|
|
521
|
-
// the verdict does not trust the factory's own answer alone.
|
|
522
|
-
if (implementationPolicy) {
|
|
523
|
-
if (typeof evmCall !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-chain-read" });
|
|
524
|
-
if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
|
|
525
|
-
const verdict = await engine.evm.verifyFactoryImplementationOnChain({
|
|
526
|
-
factory: declaredFactory,
|
|
527
|
-
read: evmCall,
|
|
528
|
-
code: (address) => evmCode(address),
|
|
529
|
-
policy: implementationPolicy,
|
|
530
|
-
hashCode: (codeHex) => bytesToHexQ(keccak256(hexToBytesQ(codeHex) || new Uint8Array(0))),
|
|
531
|
-
});
|
|
532
|
-
if (!verdict.ok) {
|
|
533
|
-
const unknown = verdict.why === "implementation-code-unknown" ||
|
|
534
|
-
verdict.why === "implementation-code-mismatch" || verdict.why === "implementation-has-no-code";
|
|
535
|
-
fail(unknown ? "quote-factory-code-unknown" : "quote-factory-unchecked",
|
|
536
|
-
{ step: "factory", why: verdict.why, factory: declaredFactory, implementation: verdict.implementation || null });
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
// THE PERSON SELLING IS THE CLAIMER. The interface's denylist is applied to that address, not to a
|
|
540
|
-
// caller-chosen value: a ticket that names a denied claimer must not reach the funding step.
|
|
541
|
-
const saleClaimer = String((saleRequest && saleRequest.claimer) || quote.claimer || "").toLowerCase();
|
|
542
|
-
if (saleClaimer && denylist && denylist.has(saleClaimer)) fail("address-denied", { step: "order-sell" });
|
|
543
|
-
if (saleRequest && saleRequest.claimer && quote.claimer && String(saleRequest.claimer).toLowerCase() !== String(quote.claimer).toLowerCase()) {
|
|
544
|
-
fail("quote-refused", { step: "order-sell", why: "claimer-not-bound" });
|
|
545
|
-
}
|
|
546
|
-
// THE XMR THE CALLER ASKED FOR IS THE XMR THE QUOTE SIGNED. A ticket is paid against the signed `xmrAmount`;
|
|
547
|
-
// accepting a different requested amount shows one figure and settles another.
|
|
548
|
-
const requestedXmr = saleRequest && (saleRequest.xmr !== undefined ? saleRequest.xmr
|
|
549
|
-
: (saleRequest.xmrAmount !== undefined ? saleRequest.xmrAmount : null));
|
|
550
|
-
if (requestedXmr !== null && requestedXmr !== undefined) {
|
|
551
|
-
let wanted = null;
|
|
552
|
-
try { wanted = BigInt(String(requestedXmr)); } catch { wanted = null; }
|
|
553
|
-
// A whole-XMR request (the public `xmr` field) is converted with the package's own parser; digits are
|
|
554
|
-
// already atomic. A value that cannot be read is a refusal, not a skipped check.
|
|
555
|
-
if (wanted === null || wanted < 10n ** 12n) {
|
|
556
|
-
try { wanted = parseXmr(String(requestedXmr)); } catch { wanted = null; }
|
|
557
|
-
}
|
|
558
|
-
let signedAtomic = null;
|
|
559
|
-
try { signedAtomic = quote.xmrAmount === undefined || quote.xmrAmount === null || quote.xmrAmount === ""
|
|
560
|
-
? null : BigInt(String(quote.xmrAmount)); } catch { signedAtomic = null; }
|
|
561
|
-
if (signedAtomic === null || wanted === null || wanted !== signedAtomic) {
|
|
562
|
-
fail("quote-refused", { step: "order-sell", why: "xmr-amount" });
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
// THE CONTEXT WHEN THE TICKET CARRIES ITS ORDER. The signed quote binds the order terms; when the node
|
|
566
|
-
// returns the order it priced, recompute the context with our own engine and refuse a mismatch.
|
|
567
|
-
if (ticket.order && typeof ticket.order === "object") {
|
|
568
|
-
// THE RETURNED ORDER MUST BE THE SIGNED ONE FIELD BY FIELD. `quote.context` is a derived label, not a
|
|
569
|
-
// signed field; comparing only it lets a node return another amount with a matching relabelled context.
|
|
570
|
-
const sameValue = (a, b) => String(a === undefined || a === null ? "" : a).replace(/^0x/i, "").toLowerCase()
|
|
571
|
-
=== String(b === undefined || b === null ? "" : b).replace(/^0x/i, "").toLowerCase();
|
|
572
|
-
for (const name of ["locker", "claimer", "amount", "readyBy", "t1", "salt"]) {
|
|
573
|
-
if (!sameValue(ticket.order[name], quote[name])) {
|
|
574
|
-
fail("quote-refused", { step: "order-sell", why: "other-terms", field: name });
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
// The context remains a useful cross-check when both sides carry it.
|
|
578
|
-
if (quote.context) {
|
|
579
|
-
let expectedSaleContext = null;
|
|
580
|
-
try { expectedSaleContext = engine.orderContext.orderContextString(ticket.order); } catch { expectedSaleContext = null; }
|
|
581
|
-
if (expectedSaleContext !== null && String(quote.context) !== expectedSaleContext) {
|
|
582
|
-
fail("quote-refused", { step: "order-sell", why: "other-terms", field: "context" });
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
// THE TICKET'S TIP MUST BE THE SIGNED ONE. The node returns both the ticket's `claimTip` object and the quote it
|
|
587
|
-
// signed; a difference means the figure shown to the person is not the figure the escrow will pay.
|
|
588
|
-
const shown = ticket.claimTip && ticket.claimTip.wei !== undefined && ticket.claimTip.wei !== null
|
|
589
|
-
? String(ticket.claimTip.wei) : null;
|
|
590
|
-
if (shown === null) fail("quote-field-unbound", { step: "claimTip", field: "claimTip" });
|
|
591
|
-
if (ticket.claimTip.signed !== true) fail("quote-field-unbound", { step: "claimTip", field: "signed" });
|
|
592
|
-
let signedTip = null;
|
|
593
|
-
try { signedTip = quote.claimTip === undefined || quote.claimTip === null || quote.claimTip === "" ? "0" : BigInt(quote.claimTip).toString(); }
|
|
594
|
-
catch { fail("quote-field-unbound", { step: "claimTip", field: "claimTip" }); }
|
|
595
|
-
let shownBig = null;
|
|
596
|
-
try { shownBig = BigInt(shown); } catch { fail("quote-tip-unreadable", { step: "claimTip" }); }
|
|
597
|
-
if (signedTip === null || shownBig < 0n || BigInt(signedTip) !== shownBig) {
|
|
598
|
-
fail("quote-refused", { step: "claimTip", why: "not-the-signed-tip" });
|
|
599
|
-
}
|
|
600
|
-
if (shownBig > 0n) {
|
|
601
|
-
if (typeof evmBlock !== "function") fail("quote-tip-unchecked", { step: "claimTip", why: "no-block-read" });
|
|
602
|
-
let block = null;
|
|
603
|
-
try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
|
|
604
|
-
const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
|
|
605
|
-
// THE NODE SIZES THE TIP FROM THE GAS PRICE, PRIORITY INCLUDED. The SDK used to pass only the base fee, so an
|
|
606
|
-
// honest L1 tip (or a base fee that dropped between sizing and checking) was refused.
|
|
607
|
-
let priorityFeeWei = block && block.priorityFeePerGas !== undefined ? block.priorityFeePerGas : null;
|
|
608
|
-
if (priorityFeeWei === null && block && block.gasPrice !== undefined && baseFeeWei !== undefined && baseFeeWei !== null) {
|
|
609
|
-
try {
|
|
610
|
-
const gas = BigInt(block.gasPrice); const base = BigInt(baseFeeWei);
|
|
611
|
-
priorityFeeWei = gas > base ? gas - base : 0n;
|
|
612
|
-
} catch { priorityFeeWei = 0n; }
|
|
613
|
-
}
|
|
614
|
-
const verdict = claimTipVerdict({ claimTipWei: shownBig, baseFeeWei, priorityFeeWei: priorityFeeWei === null ? 0n : priorityFeeWei });
|
|
615
|
-
if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
|
|
616
|
-
}
|
|
617
|
-
return ticket;
|
|
618
|
-
},
|
|
619
|
-
async firm(request) {
|
|
620
|
-
if (!request || typeof request !== "object") fail("bad-input", { field: "request" });
|
|
621
|
-
if (typeof request.providerId !== "string" || !request.providerId) fail("bad-input", { field: "providerId" });
|
|
622
|
-
if (!request.order || typeof request.order !== "object") fail("bad-input", { field: "order" });
|
|
623
|
-
// THE INTERFACE'S OWN ADDRESS DENYLIST (issue #16): POLICY, not proof - the interface refuses to ask for a
|
|
624
|
-
// quote for an address on its own list, and does it BEFORE any request is made. `order.locker` is the
|
|
625
|
-
// address the funds come from on a purchase (the claimer there is the node's own address, so it is
|
|
626
|
-
// deliberately not checked). An empty/absent list is "no policy"; the comparison is WITHOUT CASE.
|
|
627
|
-
if (denylist && typeof request.order.locker === "string" && denylist.has(request.order.locker.toLowerCase())) {
|
|
628
|
-
fail("address-denied", { step: "order-quote" });
|
|
629
|
-
}
|
|
630
|
-
let res = null;
|
|
631
|
-
const viewHalfClaimer = request.viewHalfClaimer === undefined || request.viewHalfClaimer === null || request.viewHalfClaimer === ""
|
|
632
|
-
? null : String(request.viewHalfClaimer);
|
|
633
|
-
try {
|
|
634
|
-
// THE ANSWER IS READ AS A VALUE (tryJson), NOT AS AN EXCEPTION: "did not answer" and "answered and
|
|
635
|
-
// refused" must stay different, and a refusal's own body carries the reason. `json` throws
|
|
636
|
-
// server-unavailable and LOSES that body.
|
|
637
|
-
res = await http.tryJson(config.route("orderQuote"), {
|
|
638
|
-
method: "POST",
|
|
639
|
-
headers: { "content-type": "application/json" },
|
|
640
|
-
body: JSON.stringify({ providerId: request.providerId, order: request.order,
|
|
641
|
-
...(viewHalfClaimer === null ? {} : { viewHalfClaimer }), sdkVersion: SDK_VERSION }),
|
|
642
|
-
});
|
|
643
|
-
} catch (error) {
|
|
644
|
-
if (error && error.code === "bad-input") throw error;
|
|
645
|
-
fail("server-unavailable", { step: "order-quote" });
|
|
646
|
-
}
|
|
647
|
-
// A NODE'S DENYLIST REFUSAL REACHES THE APP UNDER ITS OWN NEUTRAL SDK CODE, WITHOUT the `why` text and
|
|
648
|
-
// WITHOUT the address: the node names both (the maker's denylist and the address), and the interface shows
|
|
649
|
-
// the person its own neutral message. Every other refusal keeps its existing code (quote-refused etc.).
|
|
650
|
-
const refusedCode = res && res.body && typeof res.body.code === "string" ? res.body.code : null;
|
|
651
|
-
if (refusedCode === "denied-address") fail("address-denied", { step: "order-quote" });
|
|
652
|
-
if (!res || res.ok !== true || !res.body || res.body.ok !== true || !res.body.quote) {
|
|
653
|
-
fail("quote-refused", { step: "order-quote" });
|
|
654
|
-
}
|
|
655
|
-
const body = res.body;
|
|
656
|
-
const quote = body.quote;
|
|
657
|
-
// THE MAKER'S VIEW HALF IS OURS, NOT THE NODE'S CHOICE. When the caller supplies it, the quote must carry the
|
|
658
|
-
// same scalar back; otherwise the maker used another half and the joint view key cannot be rebuilt from the key.
|
|
659
|
-
if (viewHalfClaimer !== null) {
|
|
660
|
-
const echoed = quote.viewHalfClaimer;
|
|
661
|
-
if (echoed === undefined || echoed === null || echoed === "") {
|
|
662
|
-
fail("quote-field-unbound", { step: "viewHalfClaimer", field: "viewHalfClaimer" });
|
|
663
|
-
}
|
|
664
|
-
if (String(echoed).toLowerCase() !== viewHalfClaimer.toLowerCase()) {
|
|
665
|
-
fail("quote-refused", { step: "viewHalfClaimer", why: "not-echoed" });
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
// A MISSING FIELD OF THE SIGNED SET IS NOT "PROBABLY ZERO": the digest cannot be built, so the quote is
|
|
669
|
-
// not verifiable and is refused (its own code, so the interface can say which field is unbound).
|
|
670
|
-
const missingFields = orderQuoteMissingFields(quote);
|
|
671
|
-
if (missingFields.length) fail("quote-field-unbound", { step: "signature", missing: missingFields });
|
|
672
|
-
// THE QUOTE'S OWN EXPIRY, checked against the clock the core already has. It is bound in the signature too,
|
|
673
|
-
// but a stale quote is refused by its own code rather than looking like a signature failure.
|
|
674
|
-
const validUntil = Number(quote.validUntil);
|
|
675
|
-
// THE SCALE IS SECONDS: the same as the order's deadlines and block.timestamp. The core's clock is in
|
|
676
|
-
// milliseconds (Date.now), so exactly ONE boundary is converted - "now", not the quote value itself: one
|
|
677
|
-
// unit for the value, one conversion at the input.
|
|
678
|
-
const nowSec = Math.floor(now() / 1000);
|
|
679
|
-
// THE TTL IS MANDATORY AND MUST BE IN THE FUTURE. Zero, a fraction, an unsafe integer and a missing value are
|
|
680
|
-
// not "never expires": the relay path already requires a safe future integer, and a direct quote must not be
|
|
681
|
-
// weaker than the same quote after it crosses the relay.
|
|
682
|
-
if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
|
|
683
|
-
fail("quote-expired", { step: "signature", validUntil: quote.validUntil });
|
|
684
|
-
}
|
|
685
|
-
// RECOVER, THEN MATCH THE NAMED KEY. A signature that does not recover is one refusal; a valid signature
|
|
686
|
-
// that recovers to a DIFFERENT address is another (the quote names a key that did not sign it).
|
|
687
|
-
const recoveredKey = recoverOrderQuoteKey(quote);
|
|
688
|
-
if (recoveredKey === null) fail("quote-signature-invalid", { step: "signature" });
|
|
689
|
-
const declaredKey = String(quote.quoteKey).toLowerCase();
|
|
690
|
-
if (recoveredKey !== declaredKey) fail("quote-key-mismatch", { step: "signature", got: recoveredKey, want: declaredKey });
|
|
691
|
-
// WHO OWNS THE KEY - ASKED OF THE REGISTRY NAMED BY THE QUOTE. Both fields are part of the signed set, so
|
|
692
|
-
// they cannot be swapped after signing; this is what turns "a key signed it" into "this provider's key
|
|
693
|
-
// signed it". No chain-read seam - refuse rather than take the signature on trust.
|
|
694
|
-
const registry = String(quote.registry || "").toLowerCase();
|
|
695
|
-
if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) {
|
|
696
|
-
fail("quote-field-unbound", { step: "registry", field: "registry" });
|
|
697
|
-
}
|
|
698
|
-
const declaredProvider = String(quote.provider || "").toLowerCase();
|
|
699
|
-
if (!/^0x[0-9a-f]{40}$/.test(declaredProvider) || declaredProvider === ZERO_ADDRESS) {
|
|
700
|
-
fail("quote-field-unbound", { step: "registry", field: "provider" });
|
|
701
|
-
}
|
|
702
|
-
if (typeof evmCall !== "function") fail("quote-registry-unchecked", { step: "registry", why: "no-chain-read" });
|
|
703
|
-
let mappedProvider = null;
|
|
704
|
-
try {
|
|
705
|
-
mappedProvider = addressFromWord(await evmCall({ to: registry, data: providerOfData(declaredKey) }));
|
|
706
|
-
} catch {
|
|
707
|
-
fail("quote-registry-unchecked", { step: "registry", why: "read-failed", registry });
|
|
708
|
-
}
|
|
709
|
-
if (mappedProvider === null || mappedProvider === ZERO_ADDRESS) {
|
|
710
|
-
fail("quote-key-unknown", { step: "registry", registry, quoteKey: declaredKey });
|
|
711
|
-
}
|
|
712
|
-
if (mappedProvider !== declaredProvider) {
|
|
713
|
-
fail("quote-provider-mismatch", { step: "registry", got: mappedProvider, want: declaredProvider });
|
|
714
|
-
}
|
|
715
|
-
// THE INTERFACE'S OWN ADMISSION LIST - POLICY, NOT PROOF. The chain says whose key it is; whether this
|
|
716
|
-
// interface trades with that provider at all is the interface's decision, and it rides as a hook.
|
|
717
|
-
if (typeof providerAllowed === "function" && providerAllowed(declaredProvider) !== true) {
|
|
718
|
-
fail("quote-provider-not-allowed", { step: "policy", provider: declaredProvider });
|
|
719
|
-
}
|
|
720
|
-
// THE FACTORY: NAMED BY THE PROVIDER'S RECORD, CHECKED BY ITS CODE (#103). The factory will verify the
|
|
721
|
-
// quote in EVM (it is the EIP-712 verifyingContract), so it must be the one the record names AND its
|
|
722
|
-
// code must be a build this interface knows. The record lookup always runs; the code check runs when a
|
|
723
|
-
// policy list was supplied (nothing to pin against otherwise).
|
|
724
|
-
const declaredFactory = String(quote.factory || "").toLowerCase();
|
|
725
|
-
if (!/^0x[0-9a-f]{40}$/.test(declaredFactory) || declaredFactory === ZERO_ADDRESS) {
|
|
726
|
-
fail("quote-field-unbound", { step: "factory", field: "factory" });
|
|
727
|
-
}
|
|
728
|
-
let recordedFactory = null;
|
|
729
|
-
try {
|
|
730
|
-
recordedFactory = addressFromWord(await evmCall({ to: registry, data: factoryOfData(declaredProvider) }));
|
|
731
|
-
} catch {
|
|
732
|
-
fail("quote-factory-unchecked", { step: "factory", why: "read-failed", registry });
|
|
733
|
-
}
|
|
734
|
-
if (recordedFactory === null || recordedFactory === ZERO_ADDRESS) {
|
|
735
|
-
fail("quote-factory-unknown", { step: "factory", registry, provider: declaredProvider });
|
|
736
|
-
}
|
|
737
|
-
if (recordedFactory !== declaredFactory) {
|
|
738
|
-
fail("quote-factory-mismatch", { step: "factory", got: declaredFactory, want: recordedFactory });
|
|
739
|
-
}
|
|
740
|
-
if (factoryPolicy) {
|
|
741
|
-
if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
|
|
742
|
-
let codeHex = null;
|
|
743
|
-
try { codeHex = await evmCode(declaredFactory); } catch { fail("quote-factory-unchecked", { step: "factory", why: "code-read-failed", factory: declaredFactory }); }
|
|
744
|
-
const codeBytes = hexToBytesQ(codeHex);
|
|
745
|
-
// EXTCODEHASH SEMANTICS: keccak256 of the runtime code. An address with no code (empty/0x) hashes to
|
|
746
|
-
// the keccak of empty, which is not on any build list - refused like any unknown build.
|
|
747
|
-
const codeHash = bytesToHexQ(keccak256(codeBytes || new Uint8Array(0)));
|
|
748
|
-
if (!factoryPolicy.includes(codeHash)) {
|
|
749
|
-
fail("quote-factory-code-unknown", { step: "factory", factory: declaredFactory, codeHash });
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
// THE IMPLEMENTATION THE CLONES WILL EXECUTE (#114). A pinned factory CODE is not enough on its own: the
|
|
753
|
-
// implementation ADDRESS lives in the factory's STORAGE, so the client re-reads the pair the factory itself
|
|
754
|
-
// checks (implementation() / implementationCodeHash()) and the CODE at that address, then applies the same
|
|
755
|
-
// verdict (verifyFactoryImplementationOnChain). A delegatecall to an address WITHOUT code SUCCEEDS, so a
|
|
756
|
-
// clone without an implementation would take the ETH and its markReady/claim/refund would appear to go
|
|
757
|
-
// through while doing nothing - that is exactly the case this refuses. The live code is re-hashed here, so
|
|
758
|
-
// the verdict does not trust the factory's own answer alone.
|
|
759
|
-
if (implementationPolicy) {
|
|
760
|
-
if (typeof evmCall !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-chain-read" });
|
|
761
|
-
if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
|
|
762
|
-
const verdict = await engine.evm.verifyFactoryImplementationOnChain({
|
|
763
|
-
factory: declaredFactory,
|
|
764
|
-
read: evmCall,
|
|
765
|
-
code: (address) => evmCode(address),
|
|
766
|
-
policy: implementationPolicy,
|
|
767
|
-
hashCode: (codeHex) => bytesToHexQ(keccak256(hexToBytesQ(codeHex) || new Uint8Array(0))),
|
|
768
|
-
});
|
|
769
|
-
if (!verdict.ok) {
|
|
770
|
-
const unknown = verdict.why === "implementation-code-unknown" ||
|
|
771
|
-
verdict.why === "implementation-code-mismatch" || verdict.why === "implementation-has-no-code";
|
|
772
|
-
fail(unknown ? "quote-factory-code-unknown" : "quote-factory-unchecked",
|
|
773
|
-
{ step: "factory", why: verdict.why, factory: declaredFactory, implementation: verdict.implementation || null });
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
// BINDING THE QUOTE TO OUR TERMS. The signature confirms the provider signed THIS quote, but not that it is
|
|
777
|
-
// about our swap: we are responsible for the binding. The context string is computed by OUR engine module
|
|
778
|
-
// (format ninsei-order-v3; the field order is part of the protocol and must not be rearranged). There is
|
|
779
|
-
// deliberately no copy of the format here: a copy would silently drift from the protocol.
|
|
780
|
-
//
|
|
781
|
-
// THE ORDER OF THE GATES: signature first, then binding. So a refusal names the nearest reason, not the first
|
|
782
|
-
// one at hand.
|
|
783
|
-
// THE PROVIDER MAY NAME THE CLAIMER HIMSELF, AND THAT IS ALSO AN ASSEMBLED CONTEXT (a defect found). The
|
|
784
|
-
// provider may be the claimer: then it substitutes ITS OWN address into the order terms and signs the context
|
|
785
|
-
// with it already in place. Requiring the context from the caller in that case is impossible - they do not
|
|
786
|
-
// know the provider's address, and then the quote cannot be obtained at all (the live contour answered this
|
|
787
|
-
// with bad-input {field:"order"} BEFORE any network). So if the sent terms had no claimer, the context is
|
|
788
|
-
// computed from the terms WITH HIS value from the quote - exactly as the engine does it
|
|
789
|
-
// (sdk/src/swap-flow.mjs: `{ ...orderBase, claimer: claimerResolved }`). No OPTIONAL checks appeared here:
|
|
790
|
-
// a mismatched string is still a refusal (quote-refused { step: "context" }).
|
|
791
|
-
let expectedContext = null;
|
|
792
|
-
try { expectedContext = engine.orderContext.orderContextString(request.order); }
|
|
793
|
-
catch { expectedContext = null; }
|
|
794
|
-
if (expectedContext === null) {
|
|
795
|
-
const providerClaimer = quote && quote.claimer;
|
|
796
|
-
if (providerClaimer) {
|
|
797
|
-
try { expectedContext = engine.orderContext.orderContextString({ ...request.order, claimer: providerClaimer }); }
|
|
798
|
-
catch { fail("bad-input", { field: "order" }); }
|
|
799
|
-
} else {
|
|
800
|
-
fail("bad-input", { field: "order" });
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
const quoted = quote.context || "";
|
|
804
|
-
if (String(quoted) !== expectedContext) {
|
|
805
|
-
fail("quote-refused", { step: "context", why: quoted ? "other-terms" : "not-reported" });
|
|
806
|
-
}
|
|
807
|
-
// THE CLAIM TIP: the seller pays it out of the payout, so a quote that asks for more than the claim can
|
|
808
|
-
// cost is refused before it is signed. The chain's base fee is read through the caller's block seam; a
|
|
809
|
-
// missing seam or an unreadable base fee is a named refusal, never a silently accepted tip.
|
|
810
|
-
const tipCheck = (() => {
|
|
811
|
-
try { return claimTipVerdict({ claimTipWei: quote.claimTip }); }
|
|
812
|
-
catch { return { ok: true, tipWei: "0" }; }
|
|
813
|
-
})();
|
|
814
|
-
if (!tipCheck.ok && tipCheck.code === "quote-tip-unreadable") {
|
|
815
|
-
fail("quote-field-unbound", { step: "claimTip", field: "claimTip" });
|
|
816
|
-
}
|
|
817
|
-
if (tipCheck.tipWei !== "0") {
|
|
818
|
-
if (typeof evmBlock !== "function") fail("quote-tip-unchecked", { step: "claimTip", why: "no-block-read" });
|
|
819
|
-
let block = null;
|
|
820
|
-
try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
|
|
821
|
-
const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
|
|
822
|
-
const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei });
|
|
823
|
-
if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
|
|
824
|
-
}
|
|
825
|
-
return quote;
|
|
826
|
-
},
|
|
827
|
-
|
|
828
125
|
/**
|
|
829
126
|
* A firm quote through the relay, starting from the one recovery key.
|
|
830
127
|
*
|
|
@@ -845,6 +142,14 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
845
142
|
const registry = String(features.registry || "").toLowerCase();
|
|
846
143
|
if (!/^0x[0-9a-f]{40}$/.test(maker) || maker === ZERO_ADDRESS) fail("bad-input", { field: "features.provider" });
|
|
847
144
|
if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) fail("bad-input", { field: "features.registry" });
|
|
145
|
+
// THE REGISTRY IS A PROPERTY OF THE NETWORK, NOT OF THE FEATURES THAT ARRIVED WITH THE QUOTE. A relay that
|
|
146
|
+
// names its own registry can authorise its own maker. The pinned value comes from the network config; a
|
|
147
|
+
// network without a pinned registry keeps the old path until it is deployed.
|
|
148
|
+
const pinnedRegistry = config && config.settlement && config.settlement.chain &&
|
|
149
|
+
config.settlement.chain.escrow && config.settlement.chain.escrow.registry;
|
|
150
|
+
if (pinnedRegistry && !sameText(registry, pinnedRegistry)) {
|
|
151
|
+
fail("bad-input", { field: "features.registry", why: "not-the-network-registry" });
|
|
152
|
+
}
|
|
848
153
|
// THE FEATURES' HPKE KEY AND FRAME KEY BELONG TO THE REGISTERED MAKER. Check the registry mapping BEFORE
|
|
849
154
|
// sealing any view material to the HPKE key: a dishonest relay could otherwise hand us its own key, read both
|
|
850
155
|
// view halves and swap in its own node half. The answer's registry check later is not a substitute for this
|
|
@@ -862,7 +167,10 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
862
167
|
if (!sameText(featureProvider, features.provider)) {
|
|
863
168
|
fail("quote-provider-mismatch", { step: "registry", got: featureProvider, want: features.provider });
|
|
864
169
|
}
|
|
865
|
-
|
|
170
|
+
// THE CLIENT'S OWN ADDRESS IS WHAT THE DENYLIST COVERS. On an ask that is the locker; on a bid the client
|
|
171
|
+
// is the claimer, and testing the maker's locker there checks the wrong party.
|
|
172
|
+
const deniedAddress = side === "bid" ? order.claimer : order.locker;
|
|
173
|
+
if (denylist && typeof deniedAddress === "string" && denylist.has(deniedAddress.toLowerCase())) {
|
|
866
174
|
fail("address-denied", { step: "order-quote" });
|
|
867
175
|
}
|
|
868
176
|
// THE PROVIDER'S ROLE IS PART OF THE SIDE. A caller that names another claimer/locker is not asking
|
|
@@ -884,6 +192,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
884
192
|
if (!market) fail("bad-input", { field: "market" });
|
|
885
193
|
const window = windows.find((entry) => entry.market === market) || null;
|
|
886
194
|
if (!window) fail("quote-refused", { step: "features", why: "window" });
|
|
195
|
+
const readyWindow = readReadyWindow(window, { side, field: "features.firmWindows" });
|
|
887
196
|
const xmrNetwork = request.xmrNetwork !== undefined ? String(request.xmrNetwork) : window.xmrNetwork;
|
|
888
197
|
if (!xmrNetwork) fail("bad-input", { field: "xmrNetwork" });
|
|
889
198
|
if (request.xmrAmount === undefined || request.xmrAmount === null || request.xmrAmount === "") {
|
|
@@ -906,7 +215,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
906
215
|
}
|
|
907
216
|
const derived = takerHalvesV2({ mnemonic, chainId, factory: order.factory, salt });
|
|
908
217
|
const derivation = { kind: "salt-v2", salt };
|
|
909
|
-
const own =
|
|
218
|
+
const own = await buildOwnSideFromHalvesChunked(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
|
|
910
219
|
const xa = secp256k1.Point.fromHex(own.side.proof.XA);
|
|
911
220
|
const clientHalf = {
|
|
912
221
|
commitHalf: bytesToHexQ(keccak256(xa.toBytes(false).slice(1))),
|
|
@@ -937,11 +246,21 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
937
246
|
side,
|
|
938
247
|
});
|
|
939
248
|
const quote = result.quote;
|
|
249
|
+
// A QUOTE THAT IS ALREADY AT THE START MARGIN CANNOT BECOME A SWAP. The proof and the record work take
|
|
250
|
+
// seconds; refusing at the lock would show the person a confirmation that was never going to reach the wallet.
|
|
251
|
+
// The check is here, on arrival, with its own code so the caller asks again without showing confirm.
|
|
252
|
+
const answerNowSec = Math.floor(Number(now()) / 1000);
|
|
253
|
+
const life = quoteLifeVerdict({ validUntil: quote.validUntil, nowSec: answerNowSec });
|
|
254
|
+
if (!life.ok) {
|
|
255
|
+
fail("quote-too-short", { step: "answer", validUntil: Number.isFinite(Number(quote.validUntil)) ? Number(quote.validUntil) : null,
|
|
256
|
+
now: answerNowSec, remainingSec: life.remainingSec, marginSec: life.marginSec });
|
|
257
|
+
}
|
|
258
|
+
requirePinnedCashier(quote, "relay", config);
|
|
940
259
|
// THE NODE HALF IS NOT A DECORATION. The answer's proof must stand in THIS order's context and the proven
|
|
941
260
|
// point must be the one the quote commits to. For ask that is the claimer's commitment; for bid the node
|
|
942
261
|
// half is the locker's and carries its own commitment. This is the same engine check the swap path uses.
|
|
943
262
|
const nodeHalf = result.nodeHalf;
|
|
944
|
-
|
|
263
|
+
await acceptCounterpartyChunked({
|
|
945
264
|
context: own.context,
|
|
946
265
|
side: own.side,
|
|
947
266
|
counterparty: side === "ask"
|
|
@@ -1046,7 +365,8 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
1046
365
|
let block = null;
|
|
1047
366
|
try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
|
|
1048
367
|
const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
|
|
1049
|
-
const
|
|
368
|
+
const priorityFeeWei = priorityFeeOfBlock(block);
|
|
369
|
+
const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei, priorityFeeWei });
|
|
1050
370
|
if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
|
|
1051
371
|
}
|
|
1052
372
|
// THE SIGNED XMR AMOUNT TRAVELS WITH THE ORDER TERMS. `swaps.start` records its order as given, and the
|
|
@@ -1055,19 +375,43 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
|
|
|
1055
375
|
const signedAtomic = result.orderQuote && result.orderQuote.xmrAmount !== undefined && result.orderQuote.xmrAmount !== null
|
|
1056
376
|
? String(result.orderQuote.xmrAmount) : null;
|
|
1057
377
|
if (!signedAtomic) fail("quote-field-unbound", { step: "xmrAmount", field: "orderQuote.xmrAmount" });
|
|
378
|
+
// THE ANSWER IS ALSO A START REQUEST. `swaps.start` reads the paying asset from the quote; the relay answer
|
|
379
|
+
// carried only the signed order terms, so a caller that followed the guide reached `balance-unchecked`.
|
|
380
|
+
// The asset is display metadata here; the signed `orderQuote` is unchanged.
|
|
381
|
+
const marketAsset = request.market && String(request.market).includes(":")
|
|
382
|
+
? String(request.market).split(":").slice(1).join(":") : null;
|
|
383
|
+
const asset = String(order.asset || marketAsset || "").trim();
|
|
384
|
+
const startQuote = { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic, readyWindow,
|
|
385
|
+
...(asset ? { asset, token: asset.toLowerCase() } : {}),
|
|
386
|
+
// A STABLE ID FOR THE PENDING-FUNDING RECORD. The signed nonce is the one value every relay answer carries.
|
|
387
|
+
...(quote.nonce !== undefined && quote.nonce !== null ? { id: String(quote.nonce) } : {}) };
|
|
388
|
+
const startCounterparty = {
|
|
389
|
+
proof: nodeHalf.proof,
|
|
390
|
+
edPointClaimer: side === "ask" ? quote.edPointClaimer : nodeHalf.edPoint,
|
|
391
|
+
commitHalfClaimer: side === "ask" ? quote.commitHalfClaimer : nodeHalf.commitHalf,
|
|
392
|
+
viewHalfClaimer: derived.makerViewHalf,
|
|
393
|
+
viewPoint: side === "ask" ? result.edViewPointClaimer : result.edViewPointLocker,
|
|
394
|
+
};
|
|
395
|
+
// ONE ORDER OBJECT, TWO REFERENCES. `order` and `startRequest.order` must not drift apart.
|
|
396
|
+
const startOrder = { ...order, xmrAmount: signedAtomic };
|
|
1058
397
|
return {
|
|
1059
398
|
...result,
|
|
1060
|
-
quote:
|
|
1061
|
-
order:
|
|
399
|
+
quote: startQuote,
|
|
400
|
+
order: startOrder,
|
|
401
|
+
// THE NODE'S WINDOW TRAVELS WITH THE ANSWER, SO A SALE CAN USE THE SAME NUMBERS THE MAKER SIGNED.
|
|
402
|
+
readyWindow,
|
|
403
|
+
// THE CALLER ADDS ITS WALLET, `receiveTo` AND THE HEIGHT; everything the relay can know is here.
|
|
404
|
+
startRequest: {
|
|
405
|
+
quote: startQuote,
|
|
406
|
+
order: startOrder,
|
|
407
|
+
orderQuote: result.orderQuote,
|
|
408
|
+
counterparty: startCounterparty,
|
|
409
|
+
recoveryKey: request.recoveryKey,
|
|
410
|
+
recoverySalt: order.salt,
|
|
411
|
+
},
|
|
1062
412
|
// THE SHAPE `swaps.start` TAKES: the proof and the claimer commitment travel with the view half, so a
|
|
1063
413
|
// caller can pass this object as `counterparty` without rebuilding the relay fields.
|
|
1064
|
-
counterparty:
|
|
1065
|
-
proof: nodeHalf.proof,
|
|
1066
|
-
edPointClaimer: side === "ask" ? quote.edPointClaimer : nodeHalf.edPoint,
|
|
1067
|
-
commitHalfClaimer: side === "ask" ? quote.commitHalfClaimer : nodeHalf.commitHalf,
|
|
1068
|
-
viewHalfClaimer: derived.makerViewHalf,
|
|
1069
|
-
viewPoint: side === "ask" ? result.edViewPointClaimer : result.edViewPointLocker,
|
|
1070
|
-
},
|
|
414
|
+
counterparty: startCounterparty,
|
|
1071
415
|
viewHalfClaimer: derived.makerViewHalf,
|
|
1072
416
|
viewHalfPoint: derived.makerViewPoint,
|
|
1073
417
|
jointAddress: oneTimeAddress.address,
|