@ninsei-labs/sdk 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +56 -5
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/halfenc.js +6 -6
  6. package/engine/core/config.js +17 -38
  7. package/engine/core/format.js +1 -1
  8. package/engine/core/sellWindow.js +1 -1
  9. package/engine/core/store.js +11 -3
  10. package/engine/core/swap.js +3 -3
  11. package/engine/evm/amounts.js +2 -2
  12. package/engine/evm/asyncRoute.js +3 -3
  13. package/engine/evm/dex.js +1 -1
  14. package/engine/evm/factory.js +1 -1
  15. package/engine/evm/fees.js +62 -0
  16. package/engine/evm/funding.js +71 -66
  17. package/engine/evm/gasReserve.js +10 -0
  18. package/engine/evm/index.js +2 -2
  19. package/engine/evm/prices.js +3 -0
  20. package/engine/evm/session.js +1 -1
  21. package/engine/monero/address.js +4 -2
  22. package/engine/monero/arrivalRead.js +15 -2
  23. package/engine/monero/keyImage.js +146 -0
  24. package/engine/monero/keys.js +1 -0
  25. package/engine/monero/mnemonic.js +2 -1
  26. package/engine/monero/node.js +1 -0
  27. package/engine/monero/scan.js +12 -2
  28. package/engine/recovery/recoveryFile.js +31 -85
  29. package/engine/sdk/bridge.js +21 -51
  30. package/index.d.ts +412 -19
  31. package/package.json +20 -2
  32. package/src/actions.mjs +72 -6
  33. package/src/addressGuard.mjs +16 -0
  34. package/src/codes.mjs +26 -9
  35. package/src/config.mjs +56 -3
  36. package/src/decline.mjs +23 -74
  37. package/src/firmRequest.mjs +80 -0
  38. package/src/index.mjs +17 -28
  39. package/src/legs/cow.mjs +2 -2
  40. package/src/legs/evm.mjs +20 -12
  41. package/src/legs/kyber-spec.mjs +2 -2
  42. package/src/legs/kyber.mjs +1 -1
  43. package/src/legs/shape.mjs +1 -1
  44. package/src/legs/uniswaprelay.mjs +16 -4
  45. package/src/legs/uniswapx.mjs +29 -7
  46. package/src/levelsWalkSpec.mjs +1 -1
  47. package/src/lock.mjs +18 -37
  48. package/src/provider/envFile.mjs +3 -3
  49. package/src/provider/sign.mjs +3 -3
  50. package/src/public/evm.d.ts +84 -0
  51. package/src/public/evm.mjs +20 -0
  52. package/src/public/order.mjs +1 -1
  53. package/src/public/provider.mjs +1 -1
  54. package/src/public/recovery.d.ts +3 -2
  55. package/src/public/recovery.mjs +1 -1
  56. package/src/public/xmr.d.ts +2 -2
  57. package/src/quoteEip712Spec.mjs +4 -4
  58. package/src/quotes.mjs +52 -11
  59. package/src/recovery-key.mjs +7 -3
  60. package/src/relayFirmClient.mjs +4 -0
  61. package/src/relayQuote.mjs +1 -0
  62. package/src/sim.mjs +1 -1
  63. package/src/swap-flow.mjs +22 -32
  64. package/src/swaps.mjs +63 -56
  65. package/src/sweep-inputs.mjs +61 -0
  66. package/src/sweep-reconcile.mjs +71 -0
  67. package/src/sweep-restore.mjs +38 -9
  68. package/src/sweep.mjs +164 -10
  69. package/src/version.mjs +1 -1
  70. package/src/wallet.mjs +1 -1
  71. package/src/xmr-arrival.mjs +1041 -43
package/src/sweep.mjs CHANGED
@@ -5,16 +5,21 @@
5
5
  // address, ask the app for the restore height (on the page it is taken by address) and say aloud what is missing
6
6
  // so the withdrawal can go. Funds do not move at this step.
7
7
  import { SdkError } from "./errors.mjs";
8
+ import { checkAddressOrThrow } from "./addressGuard.mjs";
9
+ import { assertSameKeyImages, normalizeKeyImages, signedKeyImages } from "./sweep-inputs.mjs";
8
10
  import { actionMaterialOf } from "./sweep-action.mjs";
9
11
  import { primitives } from "./primitives.mjs";
10
12
  import * as engine from "./engine.mjs";
11
13
  import { restoreWallet } from "./sweep-restore.mjs";
12
14
  import { moneroWalletAdapter } from "./adapters/monero-wallet.mjs";
13
15
  import { checkDestination } from "./destination.mjs";
16
+ import { readRecovery } from "./xmr-arrival.mjs";
17
+ import { reconcileVerdict } from "./sweep-reconcile.mjs";
14
18
  import { revealedHalfWord } from "./sweep-half.mjs";
15
19
  import { takerHalvesV2 } from "./recovery-key.mjs";
16
20
  import { jointAddress } from "./order.mjs";
17
21
  import { formatXmr } from "../engine/core/xmrAmount.js";
22
+ import { keyImageFromOutput } from "../engine/monero/keyImage.js";
18
23
 
19
24
  // THE XMR AMOUNT IS PART OF THE RECOVERY FILE. A found order carries the amount the provider signed, in atomic
20
25
  // units; the file keeps it in whole XMR, the unit every other payload user reads. An order without the amount
@@ -31,6 +36,22 @@ const xmrAmountOf = (value) => {
31
36
  const MIN_PASSPHRASE = 12;
32
37
  const STEPS = ["unlock", "sync", "sweep", "relay"];
33
38
 
39
+ // The transaction ids the signed set can name before the wallet answers. They are a hint for the caller's chain
40
+ // check, not proof that a relay happened.
41
+ const txidsOf = (signed) => {
42
+ const list = Array.isArray(signed) ? signed : (signed === null || signed === undefined ? [] : [signed]);
43
+ const ids = [];
44
+ for (const tx of list) {
45
+ let id = null;
46
+ try {
47
+ id = tx && typeof tx.getHash === "function" ? tx.getHash()
48
+ : (tx && (typeof tx.hash === "string" ? tx.hash : (typeof tx.txid === "string" ? tx.txid : null)));
49
+ } catch { id = null; }
50
+ if (typeof id === "string" && id) ids.push(id);
51
+ }
52
+ return ids;
53
+ };
54
+
34
55
  // A NODE MUST NOT BE ABLE TO SET THE WITHDRAWAL FEE. The node's estimate reaches the SDK through the wallet,
35
56
  // and an untrusted node can answer with most of the balance. The absolute ceiling is deliberately far above a
36
57
  // normal priority fee (0.01 XMR) while still rejecting a percentage-sized charge. A caller that needs another
@@ -184,6 +205,10 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
184
205
  // owned by the library's wallet.
185
206
  const sessions = new Map();
186
207
  let sessionSeq = 0;
208
+ // THE SCAN THAT PRECEDED SIGNING. `sweep.restore` records its own answer against the exact wallet adapter that
209
+ // performed it; `sign` accepts only a complete scan from that same adapter. This is what keeps a stale or partial
210
+ // restore from becoming a signature, without adding a caller-supplied boolean that a page could forget or forge.
211
+ const scans = new WeakMap();
187
212
 
188
213
  // THE NETWORK NAME MONERO-TS TAKES. The adapter speaks a string ("stagenet") because that is what a node says and
189
214
  // what a human reads; the library wants its own enum. That translation used to be a callback on the sweep page -
@@ -291,6 +316,9 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
291
316
  return {
292
317
  swapId: payload.swapId || null,
293
318
  address,
319
+ // The Monero network is part of the destination check: a file's address and a recipient typed for another
320
+ // network must not be treated as interchangeable.
321
+ network: wallet.network || null,
294
322
  spendable,
295
323
  restoreHeight,
296
324
  steps: STEPS,
@@ -332,6 +360,50 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
332
360
  }
333
361
  },
334
362
 
363
+ // THE KEY IMAGES OF THE VERIFIED FUNDING OUTPUTS. This is the wallet-free half of the spent check: the page
364
+ // already has the spend key and the outputs from `verifyArrival` / `verifyRecovery`; a full monero-ts wallet
365
+ // would have to download the block-hash history before it could answer the same question.
366
+ //
367
+ // EVERY OUTPUT MUST ALREADY BE VERIFIED. An amount the Pedersen commitment did not confirm is not a funding
368
+ // output, and a key image for it would be a guess. Missing derivations are refused too: an older caller can
369
+ // pass an arrival from a build before this field existed, and an empty answer would look like "nothing spent".
370
+ async keyImages(request = {}) {
371
+ const keys = request && request.keys;
372
+ const arrival = request && request.arrival;
373
+ if (!keys || typeof keys !== "object" || typeof keys.privateSpendKey !== "string") {
374
+ throw new SdkError("bad-input", { field: "keys" });
375
+ }
376
+ if (!arrival || typeof arrival !== "object" || !Array.isArray(arrival.outputs) || !arrival.outputs.length) {
377
+ throw new SdkError("bad-input", { field: "arrival.outputs" });
378
+ }
379
+ const seen = new Set();
380
+ return arrival.outputs.map((output, position) => {
381
+ if (!output || typeof output !== "object" || !Number.isSafeInteger(Number(output.index)) || Number(output.index) < 0) {
382
+ throw new SdkError("bad-input", { field: "arrival.outputs", why: "index", position });
383
+ }
384
+ if (output.amountVerified !== true || output.amountAtomic === null || output.amountAtomic === undefined) {
385
+ throw new SdkError("bad-input", { field: "arrival.outputs", why: "unverified", position });
386
+ }
387
+ if (typeof output.key !== "string" || typeof output.derivation !== "string") {
388
+ throw new SdkError("bad-input", { field: "arrival.outputs", why: "derivation", position });
389
+ }
390
+ const id = String(output.key).replace(/^0x/i, "").toLowerCase() + ":" + Number(output.index);
391
+ if (seen.has(id)) throw new SdkError("bad-input", { field: "arrival.outputs", why: "duplicate", position });
392
+ seen.add(id);
393
+ let keyImage;
394
+ try {
395
+ keyImage = keyImageFromOutput({
396
+ outputKey: output.key, derivation: output.derivation, index: Number(output.index),
397
+ privateSpendKey: keys.privateSpendKey,
398
+ });
399
+ } catch {
400
+ throw new SdkError("bad-input", { field: "arrival.outputs", why: "key-image", position });
401
+ }
402
+ return { outputKey: String(output.key).replace(/^0x/i, "").toLowerCase(),
403
+ amountAtomic: String(output.amountAtomic), keyImage };
404
+ });
405
+ },
406
+
335
407
  // THE PASS BEFORE SIGNING: set the height, rescan, sync, read the balance, and - when coins exist but none is
336
408
  // spendable - re-check the spent status once. The wallet is the same withdrawal adapter `sign` takes; the page
337
409
  // no longer decides when a second pass is needed.
@@ -343,7 +415,19 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
343
415
  // THE INSTANCE TRANSPORT REACHES THE WINDOW AND KEY-IMAGE READS TOO. A per-call `fetchImpl` still wins;
344
416
  // without this fallback a Tor/proxy caller's restore would silently use the page's global fetch.
345
417
  if (typeof merged.fetchImpl !== "function" && typeof fetchImpl === "function") merged.fetchImpl = fetchImpl;
346
- return await restoreWallet(merged);
418
+ const result = await restoreWallet(merged);
419
+ // A PARTIAL SCAN IS STILL RECORDED: `sign` must name why it refuses, not pretend no restore ever happened.
420
+ // COPY THE VERDICT. The returned object belongs to the caller; keeping that reference would let a page flip
421
+ // `scanComplete` after the fact and turn the guard off.
422
+ if (merged.wallet && result && typeof result === "object") {
423
+ scans.set(merged.wallet, {
424
+ scanComplete: result.scanComplete === true,
425
+ ...(result.scanIncompleteReason ? { scanIncompleteReason: result.scanIncompleteReason } : {}),
426
+ walletHeight: result.walletHeight ?? null,
427
+ nodeHeight: result.nodeHeight ?? null,
428
+ });
429
+ }
430
+ return result;
347
431
  },
348
432
 
349
433
  // THE WITHDRAWAL ITSELF. The wallet arrives as an adapter (the WASM and the worker live with whoever builds the
@@ -369,6 +453,12 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
369
453
  async sign(request) {
370
454
  const plan = await api.plan(request);
371
455
  if (!request || typeof request.to !== "string" || !request.to) throw new SdkError("bad-input", { field: "to" });
456
+ // THE ADDRESS IS CHECKED BEFORE THE WALLET IS OPENED. A typo or a destination for another Monero network is
457
+ // refused here, not discovered by the wallet after it has already built a transaction.
458
+ await checkAddressOrThrow(request.to, plan.network, "to");
459
+ // THE UNSPENT SET IS REQUIRED. Without it there is nothing to compare the signature with; a missing list is
460
+ // not an empty wallet, and an empty list would make every signed input look foreign.
461
+ const expectedImages = normalizeKeyImages(request.keyImages);
372
462
  // ONE ADAPTER FOR RESTORE AND SIGN. A caller that already holds the opened and synced wallet passes it as
373
463
  // `wallet`; a caller that wants the SDK to build one passes `connectWallet`.
374
464
  const wallet = request.wallet !== undefined && request.wallet !== null
@@ -380,6 +470,17 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
380
470
  const missing = role.filter((name) => !wallet || typeof wallet[name] !== "function");
381
471
  if (missing.length) throw new SdkError("bad-input", { field: "wallet", missing });
382
472
 
473
+ // NO COMPLETE SCAN, NO SIGNATURE. The check is tied to this exact wallet adapter because `restore` stored its
474
+ // answer against that object; a restore for another wallet or another node is not evidence for this one.
475
+ const scan = scans.get(wallet);
476
+ if (!scan || scan.scanComplete !== true) {
477
+ throw new SdkError("sweep-scan-incomplete", {
478
+ reason: scan && scan.scanIncompleteReason ? scan.scanIncompleteReason : "no-complete-scan",
479
+ walletHeight: scan && scan.walletHeight !== undefined ? scan.walletHeight : null,
480
+ nodeHeight: scan && scan.nodeHeight !== undefined ? scan.nodeHeight : null,
481
+ });
482
+ }
483
+
383
484
  await wallet.open(plan);
384
485
  try {
385
486
  // A SYNC PASS - BEST-EFFORT, NOT THE VERDICT. A node whose chain the wallet cannot scan makes the library
@@ -390,6 +491,15 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
390
491
  // zero, and the refusal would look like success.
391
492
  if (unlocked <= 0n) throw new SdkError("insufficient-funds", { unlocked: unlocked.toString() });
392
493
  const signed = await walletStep("sweepUnlocked", () => wallet.sweepUnlocked({ address: request.to, relay: false }));
494
+ // ONE SWAP ADDRESS, ONE TRANSACTION. A wallet that had to split the sweep pays a fee on every part and the
495
+ // page cannot present one withdrawal as several; refuse before the signed set can reach `relay`.
496
+ if (Array.isArray(signed) && signed.length > 1) {
497
+ throw new SdkError("sweep-split", { count: signed.length });
498
+ }
499
+ // THE SIGNED INPUTS ARE THE UNSPENT SET, NOT A SUPERSET AND NOT A DIFFERENT SET. The comparison reads the
500
+ // library's transaction inputs; an opaque signed object is `sweep-inputs-unknown`, never a pass.
501
+ const signedImages = signedKeyImages(signed);
502
+ assertSameKeyImages(expectedImages, signedImages, "sign");
393
503
  // WHAT THE TRANSFER COSTS, WHEN THE WALLET CAN SAY. A withdrawal moves the whole free remainder, so the fee
394
504
  // is not extra money on top - it is taken out of it, and the recipient receives the remainder MINUS the fee.
395
505
  // An adapter that cannot report a fee answers null; publishing 0 there would be a claim the package cannot
@@ -403,7 +513,7 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
403
513
  });
404
514
  if (!feeVerdict.ok) throw new SdkError(feeVerdict.code, { fee: feeVerdict.fee, limit: feeVerdict.limit, amount: feeVerdict.amount, why: feeVerdict.why });
405
515
  const token = "sweep-" + (++sessionSeq);
406
- sessions.set(token, { wallet, plan, signed });
516
+ sessions.set(token, { wallet, plan, signed, expectedImages, signedImages, relayAttempted: false, txids: [] });
407
517
  return {
408
518
  token,
409
519
  amount: unlocked.toString(),
@@ -425,28 +535,72 @@ export function createSweep({ call = null, fetchImpl = null } = {}) {
425
535
 
426
536
  // SENDING THE SIGNED AND MARKING THE WITHDRAWAL. Sending is split from signing by the same seam as the session:
427
537
  // the person has time to see the transfer before it leaves.
538
+ //
539
+ // A LOST ANSWER IS NOT A LOST SIGNATURE. The session stays open when the wallet throws or answers without a
540
+ // transaction id: the signed set may already be on the Monero network, and deleting the handle would make it
541
+ // impossible to check. The same token never sends that set again; a later call reports the same unknown state.
428
542
  async relay(request) {
429
543
  if (!request || typeof request.token !== "string" || !request.token) throw new SdkError("bad-input", { field: "token" });
430
544
  const session = sessions.get(request.token);
431
545
  if (!session) throw new SdkError("bad-input", { field: "token", why: "no-open-session" });
432
- sessions.delete(request.token);
546
+ if (session.relayAttempted) {
547
+ throw new SdkError("sweep-relay-unknown", { token: request.token, why: "already-attempted",
548
+ outcome: "unknown", txids: session.txids, swept: session.plan.address });
549
+ }
550
+ // A FRESH UNSPENT SET IS CHECKED AGAIN BEFORE THE SEND. The signed bytes cannot change, so this comparison is
551
+ // about the caller's new observation: if the set it just verified no longer equals the signed inputs, nothing
552
+ // leaves and the session stays open for a correct retry.
553
+ assertSameKeyImages(session.signedImages, normalizeKeyImages(request.keyImages), "relay");
554
+ session.relayAttempted = true;
433
555
  const { wallet, plan, signed } = session;
556
+ let txids;
434
557
  try {
435
- const txids = await wallet.relay(signed);
436
- const list = Array.isArray(txids) ? txids : [];
437
- // NO SERVICE REPORT. The transfer is on the Monero network; the SDK does not ask the page's own host to
438
- // record it, so the host cannot link the visitor's IP to the escrow and the withdrawal.
439
- return { txids: list, swept: plan.address };
558
+ txids = await wallet.relay(signed);
559
+ } catch {
560
+ session.txids = txidsOf(signed);
561
+ throw new SdkError("sweep-relay-unknown", { token: request.token, why: "answer-lost",
562
+ outcome: "unknown", txids: session.txids, swept: plan.address });
440
563
  } finally {
441
- await wallet.close();
564
+ // Closing must not hide the relay outcome. The session still holds the signed set when the answer is unknown.
565
+ try { await wallet.close(); } catch { /* the close result is not the transfer result */ }
566
+ }
567
+ const list = Array.isArray(txids) ? txids.filter((txid) => typeof txid === "string" && txid) : [];
568
+ if (!list.length) {
569
+ session.txids = txidsOf(signed);
570
+ throw new SdkError("sweep-relay-unknown", { token: request.token, why: "answer-txid",
571
+ outcome: "unknown", txids: session.txids, swept: plan.address });
572
+ }
573
+ sessions.delete(request.token);
574
+ // NO SERVICE REPORT. The transfer is on the Monero network; the SDK does not ask the page's own host to
575
+ // record it, so the host cannot link the visitor's IP to the escrow and the withdrawal.
576
+ return { outcome: "sent", txids: list, swept: plan.address };
577
+ },
578
+
579
+ // A LATER LOOK AFTER THE TOKEN IS GONE. The signed bytes and their hash are the caller's; this only reads the
580
+ // swap address through the same recovery read and says whether those bytes may be sent again. It never
581
+ // signs: `absent` with `resend: true` is the only answer that permits the same bytes, and every incomplete or
582
+ // positive answer forbids a resend.
583
+ async reconcile(request) {
584
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
585
+ const txid = String(request.txid == null ? "" : request.txid).replace(/^0x/i, "").toLowerCase();
586
+ if (!/^[0-9a-f]{64}$/.test(txid)) throw new SdkError("bad-input", { field: "txid" });
587
+ if (request.node === undefined || request.node === null) throw new SdkError("bad-input", { field: "node" });
588
+ if (!Number.isSafeInteger(request.fromHeight) || request.fromHeight < 0) {
589
+ throw new SdkError("bad-input", { field: "fromHeight" });
590
+ }
591
+ if (!Array.isArray(request.keyImages) || !request.keyImages.length) {
592
+ throw new SdkError("bad-input", { field: "keyImages", why: "empty" });
442
593
  }
594
+ const keyImages = request.keyImages;
595
+ const read = await readRecovery({ ...request, txid, keyImages, checkpoint: undefined });
596
+ return reconcileVerdict({ read, txid, keyImages });
443
597
  },
444
598
 
445
599
  // THE WITHDRAWAL AS A WHOLE - THE SAME ORDER, ONE CALL. This is a WRAPPER over sign and relay, NOT a second
446
600
  // step order: otherwise an edit in one place would diverge from the other.
447
601
  async run(request) {
448
602
  const opened = await api.sign(request);
449
- return await api.relay({ token: opened.token });
603
+ return await api.relay({ token: opened.token, keyImages: request.keyImages });
450
604
  },
451
605
  };
452
606
  return api;
package/src/version.mjs CHANGED
@@ -6,4 +6,4 @@
6
6
  // tools/sync-version.mjs. Do not edit it by hand - set the version in package.json and run `npm run sync:version`.
7
7
  // The `version` check in tools/check.mjs refuses a mismatch, and refuses a runtime read of package.json here.
8
8
 
9
- export const SDK_VERSION = "0.61.0";
9
+ export const SDK_VERSION = "0.62.0";
package/src/wallet.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // THE WALLET OUTSIDE AND WITHOUT KNOWLEDGE OF THE CHAIN (issue #32, requirement 4; extensibility for Tron and Solana).
1
+ // THE WALLET OUTSIDE AND WITHOUT KNOWLEDGE OF THE CHAIN.
2
2
  //
3
3
  // The SDK core knows neither EIP-1193, nor WalletConnect, nor the Solana wallet-standard. It knows the ADAPTER
4
4
  // INTERFACE: vm, connect, disconnect, address, chainId, subscribe, driver - and requires the adapter to be for