@ninsei-labs/sdk 0.55.4 → 0.57.2
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 +60 -0
- package/LICENSE-POLICY.md +9 -2
- package/README.md +51 -24
- package/THIRD_PARTY_NOTICES.md +174 -0
- package/assets/vendors/MANIFEST.json +18 -0
- package/assets/vendors/sdk/sdk-browser.js +2059 -2
- package/engine/atomic/dleq2.js +187 -22
- package/engine/atomic/order.js +21 -3
- package/engine/core/config.js +17 -24
- package/engine/core/deployments.generated.js +103 -0
- package/engine/core/store.js +25 -4
- package/engine/core/swap.js +54 -52
- 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 +24 -26
- package/engine/evm/funding.js +8 -3
- package/engine/evm/index.js +2 -4
- package/engine/evm/session.js +3 -3
- package/engine/monero/scan.js +101 -22
- package/engine/recovery/restore.js +8 -8
- package/engine/sdk/bridge.js +3 -6
- package/index.d.ts +57 -27
- package/package.json +25 -8
- package/src/actions.mjs +52 -9
- package/src/adapters/evm-wallet.mjs +24 -5
- package/src/adapters/index.d.ts +66 -0
- package/src/adapters/index.mjs +0 -6
- package/src/codes.mjs +14 -0
- package/src/config.mjs +1 -0
- package/src/engine.mjs +6 -6
- package/src/feeEstimate.mjs +11 -4
- package/src/http.mjs +4 -1
- package/src/index.mjs +4 -3
- package/src/legs/kyber.mjs +23 -0
- package/src/lock.mjs +2 -1
- package/src/order.mjs +108 -20
- package/src/primitives.mjs +4 -5
- package/src/probes.mjs +9 -3
- package/src/provider/envFile.mjs +11 -1
- package/src/public/networks.d.ts +45 -0
- package/src/public/networks.mjs +10 -1
- package/src/public/order.d.ts +4 -0
- package/src/public/recovery.d.ts +40 -54
- package/src/public/recovery.mjs +2 -8
- package/src/public/xmr.d.ts +14 -3
- package/src/public/xmr.mjs +1 -1
- package/src/quoteEip712Spec.mjs +9 -1
- package/src/quotes.mjs +118 -49
- package/src/record.mjs +3 -3
- package/src/recovery-key.mjs +161 -237
- package/src/relayFeatures.mjs +25 -13
- package/src/relayFirmClient.mjs +69 -6
- package/src/relayQuote.mjs +87 -10
- package/src/relayRequest.mjs +12 -3
- package/src/relayView.mjs +3 -3
- package/src/swap-flow.mjs +153 -67
- package/src/swaps.mjs +346 -174
- package/src/sweep-restore.mjs +14 -6
- package/src/sweep.mjs +34 -11
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +55 -24
- package/assets/vendors/atomic/atomic-browser.js +0 -24
- 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/adapters/node-test-evm-wallet.mjs +0 -357
package/src/recovery-key.mjs
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
//
|
|
3
3
|
// The taker used to make a random secret per swap and ask a person to save a file before funding. One BIP39 key,
|
|
4
4
|
// made once and saved once, removes that step. The seeds of this module are the ONLY source of the taker's
|
|
5
|
-
// halves: the spend and view halves for
|
|
6
|
-
//
|
|
7
|
-
//
|
|
5
|
+
// halves: the spend and view halves for an order come from halfFromSeed with a v2 binding that names the chain,
|
|
6
|
+
// the role, the public order salt and the factory. The factory is part of the binding, so a redeployment produces
|
|
7
|
+
// different halves; recovery must read the factory the order names.
|
|
8
8
|
//
|
|
9
9
|
// THE KEY NEVER LEAVES THE CLIENT. The search sends an address and the OrderCreated topic to a log reader; it
|
|
10
10
|
// never sends the words, the seed, a half or a commitment. A service that answered "which of these are mine"
|
|
@@ -27,22 +27,11 @@ const halves = createHalves({ ed25519, secp256k1, keccak256, randomBytes });
|
|
|
27
27
|
/** A BIP39 mnemonic with 128 bits of entropy: twelve words. */
|
|
28
28
|
export const RECOVERY_KEY_VERSION = 1;
|
|
29
29
|
export const RECOVERY_KEY_WORDS = 12;
|
|
30
|
-
// The allocator's ceiling. Discovery must use the same range: a search that stops earlier can miss an order
|
|
31
|
-
// whose number was skipped by an abandoned start or by a swap on another chain.
|
|
32
|
-
export const RECOVERY_INDEX_MAX = 100000;
|
|
33
|
-
// A DISCOVERY SCAN IS BOUNDED BY DEFAULT. The allocator can reach 100,000, but deriving a secp256k1 point for
|
|
34
|
-
// every number on a phone is not a page-open cost. One thousand indices keeps the common case inside a short
|
|
35
|
-
// call and, more importantly, the result NAMES that it stopped: the caller can continue from `nextIndex`.
|
|
36
|
-
export const RECOVERY_SCAN_DEFAULT = 1000;
|
|
37
|
-
// The scan yields to the event loop between chunks. A page must be able to paint and answer a cancel click even
|
|
38
|
-
// when a caller explicitly asks for a large range; a synchronous loop of 100,000 derivations froze the page.
|
|
39
|
-
export const RECOVERY_SCAN_YIELD_EVERY = 64;
|
|
40
30
|
export const RECOVERY_KEY_STORE = "ninsei.recovery.key.v1";
|
|
41
31
|
export const RECOVERY_KEY_FILE_MAGIC = "NINSEI RECOVERY KEY";
|
|
42
|
-
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
// elsewhere. The salt is already public in `OrderCreated`; recovery reads it back instead of reserving a number.
|
|
32
|
+
// ONE DERIVATION: the binding names the fresh order salt, the factory and the role, so two orders cannot share a
|
|
33
|
+
// taker half even when the words are restored elsewhere. The salt is already public in `OrderCreated`; recovery
|
|
34
|
+
// reads it back instead of reserving a number.
|
|
46
35
|
export const RECOVERY_KEY_DOMAIN_V2 = "ninsei-taker-v2";
|
|
47
36
|
// The counterparty's view half is derived from the SAME ONE KEY, in a domain of its own. The taker sends this
|
|
48
37
|
// number to the maker (the node), which uses it as its own view half; the taker keeps it, so the joint view key
|
|
@@ -124,21 +113,6 @@ function numberField(value, field) {
|
|
|
124
113
|
return n;
|
|
125
114
|
}
|
|
126
115
|
|
|
127
|
-
/** The binding a swap number is derived from. The chain id keeps testnet and mainnet keys apart. */
|
|
128
|
-
export function recoveryBinding(chainId, index) {
|
|
129
|
-
return `${RECOVERY_KEY_DOMAIN}|${numberField(chainId, "chainId")}|${numberField(index, "index")}`;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* The taker's two halves for swap number `index`.
|
|
134
|
-
*
|
|
135
|
-
* The halves are returned as 0x-prefixed scalars (64 hex digits), not BigInt: every crossing of JSON in this
|
|
136
|
-
* package is a hex string, and a BigInt that reaches JSON.stringify fails the whole record.
|
|
137
|
-
*/
|
|
138
|
-
export function takerHalves({ mnemonic, chainId, index }) {
|
|
139
|
-
return takerHalvesFromSeed(seedOf(mnemonic), chainId, index);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
116
|
// THE SAME KEY, A PUBLIC PER-ORDER SALT. The factory and role are in the binding, so the same words, chain and
|
|
143
117
|
// salt at another factory produce another half. `role` is fixed for the taker's side; the maker's view half is
|
|
144
118
|
// separated by its own domain. Salt is the `salt` word from `OrderCreated`, never a secret.
|
|
@@ -153,7 +127,6 @@ export function takerHalvesV2({ mnemonic, chainId, factory, role = "taker", salt
|
|
|
153
127
|
const binding = recoveryBindingV2({ chainId, factory, role, salt: normalized });
|
|
154
128
|
return {
|
|
155
129
|
...halvesFromBinding(seedOf(mnemonic), binding),
|
|
156
|
-
index: null,
|
|
157
130
|
derivation: "salt-v2",
|
|
158
131
|
factory: factory.toLowerCase(),
|
|
159
132
|
role,
|
|
@@ -161,12 +134,6 @@ export function takerHalvesV2({ mnemonic, chainId, factory, role = "taker", salt
|
|
|
161
134
|
};
|
|
162
135
|
}
|
|
163
136
|
|
|
164
|
-
// Discovery derives thousands of numbers from one mnemonic. The BIP39 seed is the expensive part (PBKDF2), so it
|
|
165
|
-
// is computed once by the caller and passed here; the per-number work is only HMAC and a curve point.
|
|
166
|
-
function takerHalvesFromSeed(seed, chainId, index) {
|
|
167
|
-
return { index: numberField(index, "index"), ...halvesFromBinding(seed, recoveryBinding(chainId, index)) };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
137
|
function halvesFromBinding(seed, binding) {
|
|
171
138
|
const spendHalf = halves.halfFromSeed(seed, binding, halves.HALF_DOMAIN);
|
|
172
139
|
const viewHalf = halves.halfFromSeed(seed, binding, halves.VIEW_HALF_DOMAIN);
|
|
@@ -188,14 +155,6 @@ function halvesFromBinding(seed, binding) {
|
|
|
188
155
|
};
|
|
189
156
|
}
|
|
190
157
|
|
|
191
|
-
// DISCOVERY NEEDS ONE COMMITMENT, NOT THREE POINTS. The view and maker-view halves are not compared during a
|
|
192
|
-
// search, and their Edwards points are the expensive part of `takerHalves`; deriving only the spend scalar keeps
|
|
193
|
-
// a full-range scan practical.
|
|
194
|
-
function spendCommitmentFromSeed(seed, chainId, index) {
|
|
195
|
-
const spendHalf = halves.halfFromSeed(seed, recoveryBinding(chainId, index), halves.HALF_DOMAIN);
|
|
196
|
-
return halfCommitmentHex(spendHalf, secp256k1, keccak256).toLowerCase();
|
|
197
|
-
}
|
|
198
|
-
|
|
199
158
|
function spendCommitmentFromSeedV2(seed, { chainId, factory, role = "taker", salt }) {
|
|
200
159
|
const binding = recoveryBindingV2({ chainId, factory, role, salt });
|
|
201
160
|
const spendHalf = halves.halfFromSeed(seed, binding, halves.HALF_DOMAIN);
|
|
@@ -288,6 +247,10 @@ export async function createRecoveryKeyFile({ mnemonic, createdAt, passphrase =
|
|
|
288
247
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
289
248
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
290
249
|
const header = {
|
|
250
|
+
// THE ENCRYPTED FILE NAMES ITSELF TOO. The plain file has its magic line; without a `kind` the JSON backup was
|
|
251
|
+
// indistinguishable from any other ciphertext object. It is outside the AAD (which carries the same constant),
|
|
252
|
+
// so older files without it still open.
|
|
253
|
+
kind: "ninsei-recovery-key",
|
|
291
254
|
v: RECOVERY_KEY_ENVELOPE_VERSION,
|
|
292
255
|
alg: RECOVERY_KEY_ALG,
|
|
293
256
|
iter: RECOVERY_KEY_ITER,
|
|
@@ -317,7 +280,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
|
|
|
317
280
|
if (lines[0].trim() !== RECOVERY_KEY_FILE_MAGIC) throw failed("parse");
|
|
318
281
|
const words = lines.slice(1).map((line) => line.trim()).find((line) => line && validateMnemonic(line.toLowerCase(), wordlist));
|
|
319
282
|
if (!words) throw failed("parse");
|
|
320
|
-
|
|
283
|
+
// THE HEADER DATE IS PART OF THE FILE. The header carries a day, not a time, so the opened key gets that day
|
|
284
|
+
// at 00:00 UTC; a caller can then search from the key's creation instead of parsing the file itself.
|
|
285
|
+
const stamp = lines.map((line) => line.trim()).find((line) => /^Key [0-9a-f]{4}, created \d{4}-\d{2}-\d{2}$/.test(line));
|
|
286
|
+
const createdAt = stamp ? stamp.slice(stamp.lastIndexOf(" ") + 1) : undefined;
|
|
287
|
+
return recoveryKeyOf(words, createdAt);
|
|
321
288
|
}
|
|
322
289
|
|
|
323
290
|
let envelope;
|
|
@@ -326,9 +293,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
|
|
|
326
293
|
} catch {
|
|
327
294
|
throw failed("parse");
|
|
328
295
|
}
|
|
329
|
-
if (!envelope || envelope.
|
|
296
|
+
if (!envelope || (envelope.kind !== undefined && envelope.kind !== "ninsei-recovery-key")
|
|
297
|
+
|| envelope.v !== RECOVERY_KEY_ENVELOPE_VERSION || envelope.alg !== RECOVERY_KEY_ALG) throw failed("parse");
|
|
330
298
|
for (const field of ["salt", "iv", "ciphertext"]) if (typeof envelope[field] !== "string" || !envelope[field]) throw failed("parse");
|
|
331
|
-
|
|
299
|
+
let iter = null;
|
|
300
|
+
try { iter = Number(envelope.iter); } catch { iter = null; }
|
|
332
301
|
if (!Number.isInteger(iter) || iter < ITER_MIN || iter > ITER_MAX) throw failed("parse");
|
|
333
302
|
if (passphrase.length < 12) throw failed("passphrase");
|
|
334
303
|
|
|
@@ -344,7 +313,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
|
|
|
344
313
|
} catch {
|
|
345
314
|
throw failed("decrypt");
|
|
346
315
|
}
|
|
347
|
-
|
|
316
|
+
// THE SEALED METADATA IS AUTHENTICATED BY THE AAD. Keep its full creation time; the password file promised
|
|
317
|
+
// more precision than the plain header and the opener must not replace it with the time of opening.
|
|
318
|
+
let key;
|
|
319
|
+
try { key = recoveryKeyOf(payload && payload.mnemonic, envelope.meta && envelope.meta.createdAt); }
|
|
320
|
+
catch { throw failed("parse"); }
|
|
348
321
|
if (envelope.meta && envelope.meta.fingerprint && envelope.meta.fingerprint !== key.fingerprint) throw failed("fingerprint");
|
|
349
322
|
return key;
|
|
350
323
|
}
|
|
@@ -376,8 +349,7 @@ const writeStore = (storage, value) => {
|
|
|
376
349
|
/** Save the key next to the swap records. The words are the secret; the store is the caller's. */
|
|
377
350
|
export function saveRecoveryKey(storage, key) {
|
|
378
351
|
const checked = recoveryKeyOf(key && key.mnemonic, key && key.createdAt);
|
|
379
|
-
writeStore(storage, { ...checked,
|
|
380
|
-
reserved: key.reserved || {}, retired: key.retired || {}, backupConfirmed: key.backupConfirmed === true });
|
|
352
|
+
writeStore(storage, { ...checked, backupConfirmed: key.backupConfirmed === true });
|
|
381
353
|
return checked;
|
|
382
354
|
}
|
|
383
355
|
|
|
@@ -387,52 +359,6 @@ export function loadRecoveryKey(storage) {
|
|
|
387
359
|
return { ...value, fingerprint: value.fingerprint || fingerprintOf(value.mnemonic) };
|
|
388
360
|
}
|
|
389
361
|
|
|
390
|
-
/**
|
|
391
|
-
* Reserve a number for a request. A reservation is not a spent number: if the request is abandoned, the caller
|
|
392
|
-
* releases it and the same number is used again. The chain check belongs to the caller: a number is retired only
|
|
393
|
-
* when an order with its commitment exists.
|
|
394
|
-
*/
|
|
395
|
-
export function reserveRecoveryIndex(storage, { chainId, swapId = null } = {}) {
|
|
396
|
-
const key = loadRecoveryKey(storage);
|
|
397
|
-
if (!key) throw failed("key-missing");
|
|
398
|
-
const chain = String(numberField(chainId, "chainId"));
|
|
399
|
-
const reserved = { ...(key.reserved || {}) };
|
|
400
|
-
const retired = { ...(key.retired || {}) };
|
|
401
|
-
const index = Number(key.nextIndex) || 0;
|
|
402
|
-
// Holes left by RELEASED numbers are reused; a retired number was seen on chain and is never reused.
|
|
403
|
-
for (let i = 0; i < index; i += 1) {
|
|
404
|
-
if (!Object.prototype.hasOwnProperty.call(reserved, i) && !Object.prototype.hasOwnProperty.call(retired, i)) {
|
|
405
|
-
reserved[i] = { chainId: chain, swapId, at: new Date().toISOString() };
|
|
406
|
-
writeStore(storage, { ...key, reserved, retired });
|
|
407
|
-
return i;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
if (index >= RECOVERY_INDEX_MAX) throw failed("index-exhausted");
|
|
411
|
-
reserved[index] = { chainId: chain, swapId, at: new Date().toISOString() };
|
|
412
|
-
writeStore(storage, { ...key, nextIndex: index + 1, reserved, retired });
|
|
413
|
-
return index;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
export function releaseRecoveryIndex(storage, index) {
|
|
417
|
-
const key = loadRecoveryKey(storage);
|
|
418
|
-
if (!key) throw failed("key-missing");
|
|
419
|
-
const reserved = { ...(key.reserved || {}) };
|
|
420
|
-
delete reserved[String(numberField(index, "index"))];
|
|
421
|
-
writeStore(storage, { ...key, reserved });
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/** Retire a number after its order exists on chain: it is never reused, so a later scan has no collision. */
|
|
425
|
-
export function commitRecoveryIndex(storage, index) {
|
|
426
|
-
const key = loadRecoveryKey(storage);
|
|
427
|
-
if (!key) throw failed("key-missing");
|
|
428
|
-
const reserved = { ...(key.reserved || {}) };
|
|
429
|
-
const retired = { ...(key.retired || {}) };
|
|
430
|
-
const n = numberField(index, "index");
|
|
431
|
-
delete reserved[String(n)];
|
|
432
|
-
retired[String(n)] = true;
|
|
433
|
-
writeStore(storage, { ...key, reserved, retired });
|
|
434
|
-
}
|
|
435
|
-
|
|
436
362
|
// ---------------------------------------------------------------------------------------------------
|
|
437
363
|
// THE SEARCH
|
|
438
364
|
// ---------------------------------------------------------------------------------------------------
|
|
@@ -443,12 +369,18 @@ function topicAddress(address) {
|
|
|
443
369
|
}
|
|
444
370
|
|
|
445
371
|
function decodeOrderLog(log) {
|
|
446
|
-
|
|
447
|
-
const
|
|
448
|
-
if (topics.length < 4 ||
|
|
449
|
-
const
|
|
372
|
+
if (!log || typeof log !== "object") return null;
|
|
373
|
+
const topics = Array.isArray(log.topics) ? log.topics : [];
|
|
374
|
+
if (topics.length < 4 || topics.some((topic) => typeof topic !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(topic))) return null;
|
|
375
|
+
const topic0 = topics[0].toLowerCase();
|
|
376
|
+
if (!ORDER_CREATED_TOPICS.includes(topic0)) return null;
|
|
377
|
+
if (typeof log.data !== "string" || !/^0x[0-9a-fA-F]*$/.test(log.data)) return null;
|
|
378
|
+
const data = log.data.slice(2);
|
|
450
379
|
const modern = topic0 === ORDER_CREATED_TOPIC;
|
|
451
|
-
if (data.length < 64 * (modern ? 13 : 12)) return null;
|
|
380
|
+
if (data.length < 64 * (modern ? 13 : 12) || data.length % 64 !== 0) return null;
|
|
381
|
+
if (log.transactionHash !== undefined && log.transactionHash !== null && typeof log.transactionHash !== "string") return null;
|
|
382
|
+
if (log.blockNumber !== undefined && log.blockNumber !== null && typeof log.blockNumber !== "number" && typeof log.blockNumber !== "string") return null;
|
|
383
|
+
if (log.logIndex !== undefined && log.logIndex !== null && typeof log.logIndex !== "number" && typeof log.logIndex !== "string") return null;
|
|
452
384
|
const word = (i) => "0x" + data.slice(i * 64, (i + 1) * 64).toLowerCase();
|
|
453
385
|
// THE FIELD OFFSETS MOVED WHEN `xmrAmount` JOINED THE EVENT. The old topic has no XMR amount; its orders fall
|
|
454
386
|
// back to the clone read, and a caller can still tell why from `xmrAmountReason`.
|
|
@@ -470,15 +402,15 @@ function decodeOrderLog(log) {
|
|
|
470
402
|
registry: "0x" + data.slice((9 + shift) * 64 + 24, (10 + shift) * 64),
|
|
471
403
|
provider: "0x" + data.slice((10 + shift) * 64 + 24, (11 + shift) * 64),
|
|
472
404
|
quoteKey: "0x" + data.slice((11 + shift) * 64 + 24, (12 + shift) * 64),
|
|
473
|
-
transactionHash: log.transactionHash
|
|
405
|
+
transactionHash: typeof log.transactionHash === "string" ? log.transactionHash : null,
|
|
474
406
|
blockNumber: log.blockNumber != null ? Number(log.blockNumber) : null,
|
|
475
407
|
logIndex: log.logIndex != null ? Number(log.logIndex) : null,
|
|
476
408
|
};
|
|
477
409
|
}
|
|
478
410
|
|
|
479
|
-
// THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. OrderCreated
|
|
480
|
-
// has no getter
|
|
481
|
-
// shape: a contract of another size is not this order and must not yield a guessed number.
|
|
411
|
+
// THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. The legacy OrderCreated has no `xmrAmount`; the modern
|
|
412
|
+
// event carries it, while a clone has no getter, but word 18 of the condition blob is in its code. Read the clone
|
|
413
|
+
// only from the exact shape: a contract of another size is not this order and must not yield a guessed number.
|
|
482
414
|
const CLONE_CODE_BYTES = 877;
|
|
483
415
|
const XMR_AMOUNT_WORD = 18;
|
|
484
416
|
const CLONE_PROXY_BYTES = 45;
|
|
@@ -509,23 +441,70 @@ async function readLogs(evmLogs, request) {
|
|
|
509
441
|
return logs;
|
|
510
442
|
}
|
|
511
443
|
|
|
444
|
+
// THE SETTLEMENT EVENTS A RECOVERY PAGE NEEDS, READ IN ONE RPC. Asking status() and revealedHalf() per order
|
|
445
|
+
// names every escrow to the public RPC operator next to the visitor's IP. One eth_getLogs with an address list and
|
|
446
|
+
// the three event topics returns the same facts without the per-order calls.
|
|
447
|
+
const eventTopic = (signature) => "0x" + Array.from(keccak256(new TextEncoder().encode(signature)),
|
|
448
|
+
(byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
449
|
+
export const ESCROW_EVENT_TOPICS = Object.freeze({
|
|
450
|
+
halfRevealed: eventTopic("HalfRevealed(bytes32,bool)"),
|
|
451
|
+
ready: eventTopic("Ready(address)"),
|
|
452
|
+
declined: eventTopic("Declined(address)"),
|
|
453
|
+
});
|
|
454
|
+
const ESCROW_EVENT_NAMES = new Map([
|
|
455
|
+
[ESCROW_EVENT_TOPICS.halfRevealed, "HalfRevealed"],
|
|
456
|
+
[ESCROW_EVENT_TOPICS.ready, "Ready"],
|
|
457
|
+
[ESCROW_EVENT_TOPICS.declined, "Declined"],
|
|
458
|
+
]);
|
|
459
|
+
const wordOf = (data, index) => {
|
|
460
|
+
const body = String(data || "").replace(/^0x/, "");
|
|
461
|
+
return body.length >= (index + 1) * 64 ? body.slice(index * 64, (index + 1) * 64) : null;
|
|
462
|
+
};
|
|
463
|
+
const addressTopic = (topic) => {
|
|
464
|
+
const body = String(topic || "").replace(/^0x/, "");
|
|
465
|
+
return body.length === 64 ? "0x" + body.slice(24).toLowerCase() : null;
|
|
466
|
+
};
|
|
467
|
+
|
|
512
468
|
/**
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
* A browser store is per device. The same twelve words opened on a second device, or restored before any search, start
|
|
516
|
-
* at number 0 again; two swaps would then share the taker's halves, and a refund of one publishes a half the other's
|
|
517
|
-
* maker can use. The check is the factory's own `OrderCreated` log, matched by the spend commitment the number derives.
|
|
469
|
+
* Read settlement events for a list of escrows in one `eth_getLogs` call.
|
|
518
470
|
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
471
|
+
* `evmLogs` is the caller's seam and must accept an address array, a topic array and a block range. A page can
|
|
472
|
+
* use the result to rebuild the revealed half, the ready mark and a decline without asking the public RPC about
|
|
473
|
+
* each order separately. An unreadable request is a named `recovery-failed { step: "logs" }`, not an empty list.
|
|
521
474
|
*/
|
|
522
|
-
export async function
|
|
523
|
-
if (
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
475
|
+
export async function readEscrowEvents({ escrows, evmLogs, fromBlock = "earliest", toBlock = "latest" } = {}) {
|
|
476
|
+
if (!Array.isArray(escrows) || !escrows.length) throw bad("escrows");
|
|
477
|
+
for (const escrow of escrows) {
|
|
478
|
+
if (typeof escrow !== "string" || !ADDRESS_RE.test(escrow)) throw bad("escrows");
|
|
479
|
+
}
|
|
480
|
+
const logs = await readLogs(evmLogs, {
|
|
481
|
+
address: [...new Set(escrows.map((escrow) => escrow.toLowerCase()))],
|
|
482
|
+
topics: [[ESCROW_EVENT_TOPICS.halfRevealed, ESCROW_EVENT_TOPICS.ready, ESCROW_EVENT_TOPICS.declined]],
|
|
483
|
+
fromBlock,
|
|
484
|
+
toBlock,
|
|
485
|
+
});
|
|
486
|
+
const events = [];
|
|
487
|
+
for (const log of logs) {
|
|
488
|
+
if (!log || typeof log !== "object") continue;
|
|
489
|
+
const topics = Array.isArray(log.topics) ? log.topics : [];
|
|
490
|
+
const topic0 = String(topics[0] || "").toLowerCase();
|
|
491
|
+
const name = ESCROW_EVENT_NAMES.get(topic0);
|
|
492
|
+
if (!name) continue;
|
|
493
|
+
const escrow = String(log.address || "").toLowerCase();
|
|
494
|
+
if (!ADDRESS_RE.test(escrow)) continue;
|
|
495
|
+
const common = { escrow, event: name, blockNumber: log.blockNumber ?? null, transactionHash: log.transactionHash || null,
|
|
496
|
+
logIndex: log.logIndex ?? null };
|
|
497
|
+
if (name === "HalfRevealed") {
|
|
498
|
+
const half = wordOf(log.data, 0);
|
|
499
|
+
const flag = wordOf(log.data, 1);
|
|
500
|
+
if (!half || !flag) continue;
|
|
501
|
+
events.push({ ...common, half: "0x" + half.toLowerCase(), byClaimer: BigInt("0x" + flag) !== 0n });
|
|
502
|
+
} else {
|
|
503
|
+
const by = addressTopic(topics[1]);
|
|
504
|
+
if (by) events.push({ ...common, by });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return events.sort((a, b) => Number(a.blockNumber || 0) - Number(b.blockNumber || 0) || Number(a.logIndex || 0) - Number(b.logIndex || 0));
|
|
529
508
|
}
|
|
530
509
|
|
|
531
510
|
// THE MONERO HEIGHT A RECOVERED ORDER STARTED AT. With one key there is no per-swap file to carry it, so it is
|
|
@@ -656,64 +635,76 @@ async function recoveredStartHeight(order, { evmBlockTime, moneroTip, moneroBloc
|
|
|
656
635
|
* search asks for it as the locker and as the claimer (two queries; the RPC topic filter cannot say OR across two
|
|
657
636
|
* positions) and merges the answers. Without one, every OrderCreated of the factory is read and matched locally.
|
|
658
637
|
*/
|
|
659
|
-
export async function findSwaps({ mnemonic, chainId, factory, address = null, evmLogs,
|
|
660
|
-
fromBlock = null, deploymentBlock = null, toBlock = "latest",
|
|
661
|
-
fromIndex = 0, maxIndex = RECOVERY_SCAN_DEFAULT,
|
|
662
|
-
signal = null, onProgress = null,
|
|
638
|
+
export async function findSwaps({ mnemonic, chainId, factory = null, factories = null, address = null, evmLogs,
|
|
639
|
+
fromBlock = null, deploymentBlock = null, toBlock = "latest",
|
|
663
640
|
evmBlockTime = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
|
|
664
641
|
xmrNodes = null, moneroNetwork = null, fetchImpl = globalThis.fetch } = {}) {
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
// `
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
642
|
+
// FACTORY HISTORY IS PART OF THE SEARCH. A chain can have more than one factory after a contract change;
|
|
643
|
+
// searching only the newest one hides every older order. Callers may pass `factories` as addresses or as
|
|
644
|
+
// `{ address|factory, deploymentBlock }`; a single `factory`/`deploymentBlock` remains the compatible form.
|
|
645
|
+
let targets = [];
|
|
646
|
+
if (Array.isArray(factories) && factories.length) {
|
|
647
|
+
targets = factories.map((entry) => {
|
|
648
|
+
const target = typeof entry === "string" ? entry : entry && (entry.factory || entry.address);
|
|
649
|
+
if (typeof target !== "string" || !ADDRESS_RE.test(target)) throw bad("factories");
|
|
650
|
+
const block = typeof entry === "object" && entry ? entry.deploymentBlock : null;
|
|
651
|
+
if (block !== null && block !== undefined && !Number.isSafeInteger(Number(block))) throw bad("factories.deploymentBlock");
|
|
652
|
+
return { factory: target, deploymentBlock: block === null || block === undefined ? null : Number(block) };
|
|
653
|
+
});
|
|
654
|
+
} else {
|
|
655
|
+
if (typeof factory !== "string" || !ADDRESS_RE.test(factory)) throw bad("factory");
|
|
656
|
+
if (deploymentBlock !== null && deploymentBlock !== undefined && !Number.isSafeInteger(Number(deploymentBlock))) {
|
|
657
|
+
throw bad("deploymentBlock");
|
|
658
|
+
}
|
|
659
|
+
targets = [{ factory, deploymentBlock: deploymentBlock === null || deploymentBlock === undefined ? null : Number(deploymentBlock) }];
|
|
680
660
|
}
|
|
681
|
-
const
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
const
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
]
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
const
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
661
|
+
const chain = numberField(chainId, "chainId");
|
|
662
|
+
let orders = [];
|
|
663
|
+
const seenLogs = new Set();
|
|
664
|
+
for (const target of targets) {
|
|
665
|
+
// THE CHAIN SAYS WHERE ITS ORDERS CAN START. An explicit fromBlock wins; otherwise the factory's own
|
|
666
|
+
// deployment block is used. Zero remains the last resort for a caller that knows the factory existed at genesis.
|
|
667
|
+
const startBlock = fromBlock === null || fromBlock === undefined
|
|
668
|
+
? (target.deploymentBlock === null ? 0 : target.deploymentBlock)
|
|
669
|
+
: fromBlock;
|
|
670
|
+
const base = { address: target.factory, fromBlock: startBlock, toBlock };
|
|
671
|
+
let logs = [];
|
|
672
|
+
if (address) {
|
|
673
|
+
const padded = topicAddress(address);
|
|
674
|
+
const [asLocker, asClaimer] = await Promise.all([
|
|
675
|
+
readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, padded, null] }),
|
|
676
|
+
readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, null, padded] }),
|
|
677
|
+
]);
|
|
678
|
+
logs = asLocker.concat(asClaimer);
|
|
679
|
+
} else {
|
|
680
|
+
logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
|
|
681
|
+
}
|
|
682
|
+
for (const log of logs) {
|
|
683
|
+
if (!log || typeof log !== "object") continue;
|
|
684
|
+
const logAddress = typeof log.address === "string" ? log.address : "";
|
|
685
|
+
const logTx = typeof log.transactionHash === "string" ? log.transactionHash : "";
|
|
686
|
+
const logIndex = typeof log.logIndex === "number" || typeof log.logIndex === "string" ? log.logIndex : "";
|
|
687
|
+
const id = `${target.factory}:${logAddress}:${logTx}:${logIndex}`;
|
|
688
|
+
if (seenLogs.has(id)) continue;
|
|
689
|
+
let order = null;
|
|
690
|
+
try { order = decodeOrderLog(log); } catch { order = null; }
|
|
691
|
+
if (!order) continue;
|
|
692
|
+
seenLogs.add(id);
|
|
693
|
+
orders.push({ ...order, factory: target.factory });
|
|
698
694
|
}
|
|
699
|
-
} else {
|
|
700
|
-
logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
|
|
701
695
|
}
|
|
702
|
-
const
|
|
703
|
-
for (const order of orders) order.factory = factory;
|
|
704
|
-
const orderKey = (order) => `${order.transactionHash || ""}:${order.logIndex ?? ""}`;
|
|
696
|
+
const orderKey = (order) => `${order.factory || ""}:${order.transactionHash || ""}:${order.logIndex ?? ""}`;
|
|
705
697
|
const seed = seedOf(mnemonic);
|
|
706
698
|
const found = [];
|
|
707
699
|
const foundKeys = new Set();
|
|
708
|
-
const v2Matched = new Set();
|
|
709
700
|
|
|
710
701
|
// A V2 ORDER IS FOUND FROM ITS OWN SALT. No index is reserved and no range is scanned: the binding names the
|
|
711
702
|
// factory, the role and the public `OrderCreated` salt, so the same words on another device or at another
|
|
712
|
-
// factory produce a different half.
|
|
703
|
+
// factory produce a different half.
|
|
713
704
|
for (const order of orders) {
|
|
714
705
|
let commitment;
|
|
715
706
|
try {
|
|
716
|
-
commitment = spendCommitmentFromSeedV2(seed, { chainId: chain, factory, role: "taker", salt: order.salt });
|
|
707
|
+
commitment = spendCommitmentFromSeedV2(seed, { chainId: chain, factory: order.factory, role: "taker", salt: order.salt });
|
|
717
708
|
} catch {
|
|
718
709
|
continue;
|
|
719
710
|
}
|
|
@@ -724,67 +715,7 @@ export async function findSwaps({ mnemonic, chainId, factory, address = null, ev
|
|
|
724
715
|
const key = orderKey(order);
|
|
725
716
|
if (foundKeys.has(key)) continue;
|
|
726
717
|
foundKeys.add(key);
|
|
727
|
-
|
|
728
|
-
found.push({ ...order, index: null, derivation: "salt-v2", side });
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
// MATCH V1 BY COMMITMENT, NOT BY A DENSE INDEX RANGE. The logs are already in hand; the only cost of a missing
|
|
732
|
-
// index is one derivation. Building the map first also keeps each order from being compared against every
|
|
733
|
-
// index.
|
|
734
|
-
const byCommit = new Map();
|
|
735
|
-
for (const order of orders) {
|
|
736
|
-
if (v2Matched.has(orderKey(order))) continue;
|
|
737
|
-
const locker = order.commitHalfLocker.toLowerCase();
|
|
738
|
-
const claimer = order.commitHalfClaimer.toLowerCase();
|
|
739
|
-
if (locker) {
|
|
740
|
-
if (!byCommit.has(locker)) byCommit.set(locker, []);
|
|
741
|
-
byCommit.get(locker).push({ order, side: "locker" });
|
|
742
|
-
}
|
|
743
|
-
if (claimer && claimer !== locker) {
|
|
744
|
-
if (!byCommit.has(claimer)) byCommit.set(claimer, []);
|
|
745
|
-
byCommit.get(claimer).push({ order, side: "claimer" });
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
const v1Keys = orders.filter((order) => !v2Matched.has(orderKey(order))).map(orderKey);
|
|
749
|
-
const v1Needed = v1Keys.length > 0;
|
|
750
|
-
const remaining = new Set(v1Keys);
|
|
751
|
-
let scanned = 0;
|
|
752
|
-
let stoppedBy = null;
|
|
753
|
-
if (onProgress !== null && typeof onProgress !== "function") throw bad("onProgress");
|
|
754
|
-
if (v1Needed && signal && signal.aborted === true) stoppedBy = "aborted";
|
|
755
|
-
if (v1Needed && stoppedBy === null) {
|
|
756
|
-
for (let offset = 0; offset < max; offset += 1) {
|
|
757
|
-
const index = startIndex + offset;
|
|
758
|
-
scanned = offset + 1;
|
|
759
|
-
const commitment = spendCommitmentFromSeed(seed, chain, index);
|
|
760
|
-
const matches = byCommit.get(commitment) || [];
|
|
761
|
-
for (const { order, side } of matches) {
|
|
762
|
-
const key = orderKey(order);
|
|
763
|
-
if (foundKeys.has(key)) continue;
|
|
764
|
-
foundKeys.add(key);
|
|
765
|
-
remaining.delete(key);
|
|
766
|
-
found.push({ ...order, index, derivation: "index-v1", side });
|
|
767
|
-
}
|
|
768
|
-
// EVERY MATCHED ORDER ENDS ITS OWN SEARCH. A key with only its own orders in the logs does not pay for
|
|
769
|
-
// the rest of the bound once the last one is found. A shared factory keeps the unrelated logs, so the
|
|
770
|
-
// scan continues to the requested bound and reports that it stopped there.
|
|
771
|
-
const final = remaining.size === 0 || offset === max - 1;
|
|
772
|
-
if (final || scanned % RECOVERY_SCAN_YIELD_EVERY === 0) {
|
|
773
|
-
// Progress is advisory: a page callback that throws must not turn a completed scan into a failed one.
|
|
774
|
-
if (typeof onProgress === "function") {
|
|
775
|
-
try { onProgress({ scanned, index }); } catch { /* progress is not the result */ }
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
// A CALLER CAN CANCEL. The check is after the progress callback, so a worker that aborts from its
|
|
779
|
-
// progress handler stops at this chunk instead of finishing the requested range.
|
|
780
|
-
if (signal && signal.aborted === true) { stoppedBy = "aborted"; break; }
|
|
781
|
-
if (remaining.size === 0) break;
|
|
782
|
-
// A LARGE CALLER-SUPPLIED BOUND MUST NOT OWN THE MAIN THREAD. The scan yields between chunks so the page
|
|
783
|
-
// can paint, and a later call can continue from `nextIndex`.
|
|
784
|
-
if (scanned % RECOVERY_SCAN_YIELD_EVERY === 0) {
|
|
785
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
786
|
-
}
|
|
787
|
-
}
|
|
718
|
+
found.push({ ...order, derivation: "salt-v2", side });
|
|
788
719
|
}
|
|
789
720
|
// EACH FOUND ORDER CARRIES THE MONERO HEIGHT ITS WITHDRAWAL MAY START FROM. The rule lives here, not in a
|
|
790
721
|
// page: a widget and the recovery page must not derive two different answers from one chain.
|
|
@@ -834,17 +765,10 @@ export async function findSwaps({ mnemonic, chainId, factory, address = null, ev
|
|
|
834
765
|
order.xmrAmount = read.value;
|
|
835
766
|
order.xmrAmountReason = read.reason;
|
|
836
767
|
}
|
|
837
|
-
const searchedUpTo = scanned ? startIndex + scanned - 1 : null;
|
|
838
|
-
const complete = !v1Needed || remaining.size === 0 || startIndex + scanned >= RECOVERY_INDEX_MAX;
|
|
839
|
-
const nextIndex = complete ? null : startIndex + scanned;
|
|
840
768
|
return {
|
|
841
769
|
swaps: found,
|
|
842
|
-
|
|
843
|
-
//
|
|
844
|
-
|
|
845
|
-
// orders has no range to search and is complete by construction.
|
|
846
|
-
searchedUpTo,
|
|
847
|
-
complete,
|
|
848
|
-
...(complete ? {} : { incompleteReason: stoppedBy || "max-index", nextIndex }),
|
|
770
|
+
// EVERY ORDER IN THE LOGS WAS READ. There is no index range to exhaust, so a result cannot be partial by
|
|
771
|
+
// construction; an unreadable log request is a refusal from `readLogs`, not an incomplete answer.
|
|
772
|
+
complete: true,
|
|
849
773
|
};
|
|
850
774
|
}
|