@ninsei-labs/sdk 0.58.0 → 0.60.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.
@@ -3,7 +3,7 @@
3
3
  // Everything below this header is identical to the source.
4
4
 
5
5
  // VM-neutral deployment pins generated from deployments/<vm>/<network>.json. No address table is copied below.
6
- import { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, deploymentFor } from "./deployments.generated.js";
6
+ import { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, FACTORY_HISTORY, deploymentFor } from "./deployments.generated.js";
7
7
 
8
8
  // Demo configuration. Every number a user sees lives here. Values come from the litepaper and are marked as demo data in the UI.
9
9
  //
@@ -790,7 +790,7 @@ export const KNOWN_FACTORY_CODES = Object.freeze(Object.fromEntries(
790
790
  .map((deployment) => [deployment.network, [...deployment.knownFactoryCodes]]),
791
791
  ));
792
792
 
793
- export { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, deploymentFor };
793
+ export { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, FACTORY_HISTORY, deploymentFor };
794
794
 
795
795
  export function knownFactoryCodesFor(chainOrId) {
796
796
  const id = typeof chainOrId === "string" ? chainOrId : chainOrId && chainOrId.id;
@@ -1,5 +1,6 @@
1
1
  // GENERATED FILE - do not edit. Run: node tools/gen-deployment-pins.mjs --write
2
2
  // Source: deployments/<vm>/<network>.json, copied from the reviewed contract release manifest.
3
+ // Factory history: deployments/history/<vm>/<network>.json, mainnet-only retired factories for recovery.
3
4
  const freeze = (value) => {
4
5
  if (value && typeof value === "object") {
5
6
  Object.freeze(value);
@@ -84,10 +85,26 @@ const DATA = {
84
85
  ]
85
86
  }
86
87
  };
88
+ const HISTORY_DATA = {
89
+ "arbitrum-sepolia": [
90
+ {
91
+ "address": "0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",
92
+ "deploymentBlock": 326005419,
93
+ "release": {
94
+ "tag": "contracts-testnet-2026.11.04",
95
+ "commit": "930366a387c0c696bda6f5c038f23617447ebb78",
96
+ "toolchain": "0.8.38",
97
+ "deployedAt": "2026-11-04T15:00:55.822Z"
98
+ },
99
+ "status": "live"
100
+ }
101
+ ]
102
+ };
87
103
 
88
104
  export const DEPLOYMENTS = freeze(DATA);
89
105
  export const DEPLOYMENT_CHAINS = freeze(Object.keys(DATA).sort());
90
106
  export const DEPLOYMENT_VMS = freeze([...new Set(Object.values(DATA).map((d) => d.vm))].sort());
107
+ export const FACTORY_HISTORY = freeze(HISTORY_DATA);
91
108
 
92
109
  // Accept a network id, a CAIP-2, or an EVM chain id. No fallback to another network: an unknown deployment is null.
93
110
  export function deploymentFor(chainOrId) {
@@ -1,7 +1,7 @@
1
- // GENERATED FILE - a byte-for-byte copy of the engine module www/js/monero/scan.js for the SDK package.
2
- // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
3
- // Everything below this header is identical to the source.
4
-
1
+ // THE MONERO INDEXER FOR THE SDK. The browser bundle carries a generated copy; this module is the source the package
2
+ // checks and tests use. Edit it here and regenerate the browser copy with `pnpm run build:sdk:docker` when a bundle
3
+ // change is needed.
4
+ //
5
5
  // MONERO INDEXER: we find arrivals at the swap address ourselves by parsing blocks.
6
6
  // WHY. Before, arrivals were learned from monero-wallet-rpc through a watch-only wallet, a path that hit a defect
7
7
  // (the wallet+keys pair is created and never reopens) and where one instance held one wallet, so scanning 25
@@ -25,6 +25,7 @@
25
25
  import { ed25519 } from "@noble/curves/ed25519.js";
26
26
  import { keccak_256 } from "@noble/hashes/sha3.js";
27
27
  import { UNLOCK_TIME_BLOCK_MAX, unlockStateOf, laterBoundary } from "./unlock.js";
28
+ import { decodeAddressKeys } from "./arrivalRead.js";
28
29
  export { UNLOCK_TIME_BLOCK_MAX, unlockStateOf, laterBoundary };
29
30
 
30
31
  export function keccak(bytes) { return keccak_256(bytes); }
@@ -125,6 +126,31 @@ export function viewKeyFormForAddress(viewSecret, expectedViewPubHex) {
125
126
  return false;
126
127
  }
127
128
 
129
+ // THE KEY MATERIAL MUST BELONG TO THE ADDRESS IT IS SCANNED FOR. A public `scanRange` used to try both byte-order
130
+ // readings of the view key and could count a payment to another address as ours. This is the ONE binding rule: the
131
+ // scanner and both facade paths call it, so a host cannot get a different answer by choosing another entry point.
132
+ // A subaddress or integrated address is refused here; the joint address this SDK builds is primary.
133
+ export function watchedAddressVerdict({ address, viewSecret, spendPub } = {}) {
134
+ let keys;
135
+ try {
136
+ keys = decodeAddressKeys(address);
137
+ } catch {
138
+ return { ok: false, code: "bad-input", why: "not-a-monero-address", field: "address" };
139
+ }
140
+ if (!keys.network) return { ok: false, code: "bad-input", why: "not-a-primary-address", field: "address" };
141
+ const wantedSpend = String(spendPub === undefined || spendPub === null ? "" : spendPub).replace(/^0x/, "").toLowerCase();
142
+ if (!wantedSpend || wantedSpend !== keys.spendPub.toLowerCase()) {
143
+ return { ok: false, code: "xmr-address-mismatch", field: "spendPub" };
144
+ }
145
+ const form = viewKeyFormForAddress(viewSecret, keys.viewPub);
146
+ if (!form) return { ok: false, code: "xmr-address-mismatch", field: "viewSecret" };
147
+ const secret = viewSecretCandidates(viewSecret).find(([name]) => name === form)?.[1];
148
+ if (secret === undefined || secret === null) {
149
+ return { ok: false, code: "xmr-address-mismatch", field: "viewSecret" };
150
+ }
151
+ return { ok: true, address, keys, form, viewSecret: secret, spendPub: keys.spendPub };
152
+ }
153
+
128
154
  export function keyDerivation(txPublicKeyHex, viewSecretHex) {
129
155
  const txPub = pointFromHex(txPublicKeyHex);
130
156
  // The view key is accepted both as LE bytes from monero-rpc and as a number if already parsed.
@@ -415,7 +441,11 @@ export async function fetchTransactions(daemonUrl, hashes, fetchImpl = globalThi
415
441
 
416
442
  // Parsing one transaction against the watched addresses. watched: [{ address, viewSecret, spendPub }] - viewSecret
417
443
  // is taken as a number, LE-hex or BE-hex. The result carries viewKeyForm: the form name that matched.
418
- export function matchTransaction(tx, watched, { height = null, tipHeight = null, nowSec = null } = {}) {
444
+ //
445
+ // THE KEY BINDING IS A PROPERTY OF THE WATCHED ENTRY, NOT OF THE TRANSACTION. `scanRange` binds every entry once
446
+ // before its block loop and passes the result here; the public `matchTransaction` binds the entries it is given.
447
+ // Re-binding inside the loop made every transaction repeat base58 decoding, keccak and an ed25519 multiplication.
448
+ function matchBoundTransaction(tx, boundWatched, { height = null, tipHeight = null, nowSec = null } = {}) {
419
449
  const out = [];
420
450
  // BOTH KEY LISTS ARE PART OF THE TRANSACTION. A subaddress output carries its own key under tag 0x04; using only
421
451
  // `txPublicKeyFromExtra` drops exactly those outputs.
@@ -436,10 +466,10 @@ export function matchTransaction(tx, watched, { height = null, tipHeight = null,
436
466
  const ecdhMasks = ecdh.map((e) => e.mask);
437
467
  const outPk = ((tx.rct_signatures || {}).outPk || []);
438
468
  const rctVersion = (tx.rct_signatures || {}).type || 2;
439
- for (const w of watched) {
469
+ for (const { entry: w, bound } of boundWatched) {
440
470
  const r = findOurOutputs({
441
471
  txPublicKeys: keys.txPublicKeys, additionalPublicKeys: keys.additionalPublicKeys,
442
- viewSecretHex: w.viewSecret, spendPubHex: w.spendPub,
472
+ viewSecretHex: bound.viewSecret, spendPubHex: bound.spendPub,
443
473
  outputs, ecdhAmounts, ecdhMasks, outPk, rctVersion: Number(rctVersion) || 1,
444
474
  });
445
475
  if (r.outputs.length) out.push({ address: w.address, index: w.index ?? null, outputs: r.outputs, derivation: r.derivation, viewKeyForm: r.viewKeyForm, unlockTime: Number(tx.unlock_time) || 0, unlock });
@@ -447,6 +477,21 @@ export function matchTransaction(tx, watched, { height = null, tipHeight = null,
447
477
  return out;
448
478
  }
449
479
 
480
+ // THE PUBLIC FORM BINDS EACH WATCHED ENTRY BEFORE IT LOOKS AT THE TRANSACTION. An entry that is not a primary
481
+ // address with this spend key is skipped; the binding cannot be supplied by the caller.
482
+ function bindWatched(watched) {
483
+ const bound = [];
484
+ for (const entry of watched) {
485
+ const verdict = watchedAddressVerdict(entry);
486
+ if (verdict.ok) bound.push({ entry, bound: verdict });
487
+ }
488
+ return bound;
489
+ }
490
+
491
+ export function matchTransaction(tx, watched, options = {}) {
492
+ return matchBoundTransaction(tx, bindWatched(watched), options);
493
+ }
494
+
450
495
  // Range scan. Returns per address the sum (receivedAtomic - only the UNLOCKED), hashes, the locked sum
451
496
  // (lockedAtomic) with its boundary (lockedUntil) and the best (highest) height of a found output.
452
497
  export async function scanRange({ daemonUrl, fromHeight, toHeight, watched, log = () => {}, concurrency = 4, nowSec = null, tipHeight = null, fetchImpl = globalThis.fetch }) {
@@ -454,6 +499,9 @@ export async function scanRange({ daemonUrl, fromHeight, toHeight, watched, log
454
499
  if (!(from >= 0) || !(to >= from)) throw new Error("bad height range: " + fromHeight + ".." + toHeight);
455
500
  const acc = new Map();
456
501
  for (const w of watched) acc.set(w.address, { address: w.address, receivedAtomic: 0n, lockedAtomic: 0n, lockedUntil: null, lockedTxids: [], txids: [], bestHeight: null, outputs: 0, viewKeyForm: null });
502
+ // BIND ONCE PER WATCHED ADDRESS. The binding does not depend on the transaction, and an invalid entry is skipped
503
+ // here exactly as the public matcher skips it.
504
+ const boundWatched = bindWatched(watched);
457
505
  const heights = [];
458
506
  for (let h = from; h <= to; h++) heights.push(h);
459
507
  const missingHeights = [];
@@ -469,7 +517,7 @@ export async function scanRange({ daemonUrl, fromHeight, toHeight, watched, log
469
517
  if (!hashes.length) continue;
470
518
  const txs = await fetchTransactions(daemonUrl, hashes, fetchImpl);
471
519
  for (const tx of txs) {
472
- for (const hit of matchTransaction(tx, watched, { height: h, tipHeight: tipHeight === null || tipHeight === undefined ? to : tipHeight, nowSec })) {
520
+ for (const hit of matchBoundTransaction(tx, boundWatched, { height: h, tipHeight: tipHeight === null || tipHeight === undefined ? to : tipHeight, nowSec })) {
473
521
  const a = acc.get(hit.address);
474
522
  if (!a) continue;
475
523
  if (hit.viewKeyForm) a.viewKeyForm = hit.viewKeyForm; // what matched - this goes to the log
package/index.d.ts CHANGED
@@ -53,7 +53,9 @@ export interface NinseiOptions {
53
53
  storage?: StorageAdapter;
54
54
  /** "live" - real nodes and chain; "sim" - a sandbox (mocks, accelerated time, failure scenarios). */
55
55
  mode?: "live" | "sim";
56
- /** An injected fetch function (SSR, tests, your own transport). */
56
+ /** An injected fetch function (SSR, tests, your own transport). It is the client default for relay quotes/claims,
57
+ * Monero height probes and witness checks; per-call `fetchImpl` wins for relay quote/claim and `fetch` wins for
58
+ * arrival/witness checks. An arrival request may override it with its own `fetch`. */
57
59
  fetch?: FetchLike;
58
60
  /** The clock. In "sim" the SDK uses it to accelerate time. */
59
61
  now?: () => number;
@@ -167,9 +169,22 @@ export interface NinseiOptions {
167
169
  createRecord?: (request: StartRequest) => Promise<SwapRecord> | SwapRecord;
168
170
  }
169
171
 
172
+ /** One durable sender attempt on a sell record, written before the relay POST. */
173
+ export interface StoredClaimAttempt {
174
+ readonly sender: string;
175
+ readonly at?: number;
176
+ readonly outcome: "sending" | "refused" | "unknown" | "unconfirmed" | "claimed";
177
+ readonly code?: string | null;
178
+ readonly params?: Readonly<Record<string, unknown>> | null;
179
+ readonly txid?: string | null;
180
+ }
181
+
170
182
  /** The result of assembling the swap record: the record itself, your own side and what is missing. */
171
183
  export interface SwapRecord {
172
- readonly swap: Readonly<Record<string, unknown>>;
184
+ readonly swap: Readonly<Record<string, unknown>> & {
185
+ /** The ordered claim attempts; absent on records written before the journal existed. */
186
+ readonly claimAttempts?: readonly StoredClaimAttempt[];
187
+ };
173
188
  /** Our side of the order: halves, points, the proof and the encryption key. The shape is set by the builder. */
174
189
  readonly side: unknown;
175
190
  /** What the record is missing: for a start that is the counterparty's half (`counterparty-half`). */
@@ -540,6 +555,10 @@ export interface FirmRelayAnswer {
540
555
  readonly jointAddress: string;
541
556
  /** The escrow address predicted from the signed quote and the depositor's half. */
542
557
  readonly escrow: string;
558
+ /** Seconds left when the answer was verified; the host may show this next to the confirm button. */
559
+ readonly remainingSec: number;
560
+ /** The last Unix second at which `swaps.start` can still begin this quote. */
561
+ readonly confirmBySec: number;
543
562
  readonly recovery: { readonly kind: "salt-v2"; readonly salt: string };
544
563
  /** Everything `swaps.start` can take from the relay; the caller adds its wallet, `receiveTo` and height. */
545
564
  readonly startRequest: Readonly<{
@@ -549,9 +568,12 @@ export interface FirmRelayAnswer {
549
568
  counterparty: Readonly<Record<string, unknown>>;
550
569
  recoveryKey: unknown;
551
570
  recoverySalt: string;
571
+ escrow: string;
552
572
  }>;
553
573
  /** The relay origin that answered. `startSell` stores it for the later no-wallet claim. */
554
574
  readonly relayUrl: string;
575
+ /** The sender `GET /v1/relay` publishes for claims; null when the relay did not name one. */
576
+ readonly claimSender: string | null;
555
577
  readonly relay: string | null;
556
578
  readonly offered: number | null;
557
579
  readonly forwarded: Readonly<Record<string, unknown>> | null;
@@ -657,28 +679,27 @@ export interface SwapsApi {
657
679
  sellClaim(request: SellClaimRequest, wallet: WalletAdapter): Promise<unknown>;
658
680
  /**
659
681
  * CLAIM THE ETH ON A SELL WITHOUT A WALLET. The seller holds XMR and no ETH, so the signed `claimTip` pays the
660
- * sender. The half goes to the sender the client chose - a listed maker OTHER than the deal's maker - through
661
- * the relay that answered the quote (`POST /v1/claims/{sender}/{escrow}`). No wallet is created or used and no
662
- * chain transaction is signed.
682
+ * sender. `claimSenders` is the client's ordered list - the relay's own sender first, then the listed makers -
683
+ * sent one at a time through the relay (`POST /v1/claims/{sender}/{escrow}`). Each sender gets a 15-30 s slot; a
684
+ * refusal moves on, a txid or unknown answer is followed by reading the escrow, and only `claimed` on chain is
685
+ * success. When the list is exhausted the result is `claim-yourself` with the time left before `t1`.
663
686
  *
664
- * The sender is stored by `startSell`; a request may supply `claimSender` only when the record has none, and
665
- * may never name the deal's maker. `relayUrl` may restate the stored origin; a different origin is refused. A
666
- * node refusal is `quote-refused` with its own code in `params.code`; a lost answer is `claim-unknown` (the
667
- * claim may have been sent), never success.
687
+ * The deal's maker and its quote-key owner are refused before the half leaves the client. No wallet is created or
688
+ * used and no chain transaction is signed. `relayUrl` may restate the stored origin; a different origin is refused.
668
689
  */
669
690
  claimViaRelay(request: RelayClaimRequest): Promise<RelayClaimResult>;
670
691
  /**
671
- * WAIT FOR THE XMR TO ARRIVE at the order's joint address. The polling uses the same request as the page's
672
- * (GET /swaps/{id}), the rate and the timeout - from `config.limits` and overridable here.
673
- * It arrived - the FACT is returned (the amount, the confirmations, the txid); we did not wait - a refusal with
674
- * the CODE `xmr-timeout`, separate from the others: "the wait expired" is a state of the money, not a breakdown.
692
+ * WAIT FOR THE XMR TO ARRIVE at the order's joint address. The polling is the client's own `verify` walk; there
693
+ * is no backend status call. The rate and the timeout come from `config.limits` and are overridable here.
694
+ * It arrived - the FACT is returned (the amount, the confirmations, the txid, and the joint Monero address); we did
695
+ * not wait - a refusal with the CODE `xmr-timeout`, separate from the others: "the wait expired" is a state of the
696
+ * money, not a breakdown.
675
697
  * XMR ON THE ADDRESS BUT LOCKED BY `unlock_time` is a THIRD answer with its own code `xmr-locked` (the boundary,
676
698
  * a height or a date, is in `params.until`): locked funds are NOT an arrival, and nothing is signed under them.
677
699
  * IF `expect` AND `wallet` ARE PASSED, then after the arrival the ready mark (actions.markReady) is called with
678
- * THESE expectations: the slot check against the chain stands in it before the signature. Without them the step
679
- * names the next one (`next: "mark-ready"`) and signs nothing.
680
- * THE MAKER DECLINED - THE WAIT STOPS AT ONCE (issue #40): the escrow's `Declined` event and the service's
681
- * `declined` + `compliance` status are BOTH asked on every tick, and either one ends the wait with
700
+ * THESE expectations and the EVM escrow: the slot check against the chain stands in it before the signature.
701
+ * Without them the step names the next one (`next: "mark-ready"`) and signs nothing.
702
+ * THE MAKER DECLINED - THE WAIT STOPS AT ONCE (issue #40): the escrow's `Declined` event ends the wait with
682
703
  * `SwapDeclinedWatch` instead of running to `xmr-timeout` about an order whose ETH is already back. Nothing is
683
704
  * signed, and the decline is written into the record, so every later read of the swap reports the same state.
684
705
  */
@@ -815,6 +836,8 @@ export interface XmrArrivalRequest {
815
836
  readonly fromHeight?: number | null;
816
837
  readonly nowSec?: number;
817
838
  readonly timeoutMs?: number;
839
+ /** The transport for node and witness reads; absent - the client's `fetch`, otherwise the global fetch. */
840
+ readonly fetch?: FetchLike;
818
841
  }
819
842
 
820
843
  /** The slice check's extra input: independent witnesses that serve witness-v1. */
@@ -834,8 +857,20 @@ export interface XmrWitnessShadowReading {
834
857
  readonly operator?: string;
835
858
  readonly url?: string;
836
859
  readonly completed: boolean;
860
+ /** Distinct operators whose walk covered the target; two instances of one operator count once. */
861
+ readonly quorum: {
862
+ readonly required: number;
863
+ readonly completed: readonly string[];
864
+ /** On mainnet the Ninsei walker is not one of the two votes; this list excludes it. */
865
+ readonly independent: readonly string[];
866
+ readonly ok: boolean;
867
+ };
837
868
  readonly checked: readonly Record<string, unknown>[];
838
869
  readonly failed: readonly Record<string, unknown>[];
870
+ /** One opinion per operator: seen/txid/height/blockHash/amount/locked. */
871
+ readonly observations: readonly Record<string, unknown>[];
872
+ /** Same-operator and cross-operator contradictions, plus contradictions against the exact reading. */
873
+ readonly disagreements: readonly Record<string, unknown>[];
839
874
  }
840
875
 
841
876
  /** The exact verdict and the slice reading, side by side. This is not a swap decision. */
@@ -955,11 +990,13 @@ export interface SellStartRequest {
955
990
  /** The verified `quotes.firmRelay` answer for the bid side. */
956
991
  readonly offer: FirmRelayAnswer;
957
992
  /**
958
- * The sender the client chose for a later no-ETH claim: a listed maker other than the deal's maker. It is
959
- * stored with the record so a reload claims through the same node; the relay route names it as `provider`.
960
- * Omitted for a record that will only use the own-wallet path.
993
+ * Optional legacy single sender stored for a no-ETH claim. The ordered list passed to `claimViaRelay` is the
994
+ * authority; this scalar is only a one-element fallback for callers written before the list existed. A sender
995
+ * naming the deal's maker or its quote-key owner is refused.
961
996
  */
962
997
  readonly claimSender?: string;
998
+ /** The ordered senders stored for a later `claimViaRelay`; the relay's published sender is prepended. */
999
+ readonly claimSenders?: readonly string[];
963
1000
  /** The twelve-word key; required only when no key is stored yet. */
964
1001
  readonly recoveryKey?: string | { readonly mnemonic: string };
965
1002
  /** The recovery file's passphrase. In memory; the interface puts it on disk if it deems fit. */
@@ -982,8 +1019,10 @@ export interface SellStart {
982
1019
  readonly xmrAmount: string;
983
1020
  readonly claimTip: string | null;
984
1021
  readonly orderQuote: Readonly<Record<string, unknown>> | null;
985
- /** The no-wallet claim sender stored by `startSell`, or null when only the own-wallet path is available. */
1022
+ /** The legacy single sender stored by `startSell`, or null when the client supplies the list at claim time. */
986
1023
  readonly claimSender: string | null;
1024
+ /** The ordered senders stored by `startSell`; empty when the client supplies the list at claim time. */
1025
+ readonly claimSenders: readonly string[];
987
1026
  readonly readyWindow: ReadyWindow | null;
988
1027
  readonly resumed: boolean;
989
1028
  readonly next: "send-xmr";
@@ -999,34 +1038,91 @@ export interface SellClaimRequest {
999
1038
 
1000
1039
  /**
1001
1040
  * THE NO-WALLET CLAIM'S INPUTS. `id` names the sell record made by `startSell`; the escrow, half and signed tip
1002
- * come from it. `claimSender` is the list-member node that will send the claim: it must be a listed maker other than
1003
- * the deal's maker, and is normally stored by `startSell`. `relayUrl` is optional and may only repeat the origin
1041
+ * come from it. `claimSenders` is the client's ordered list: the relay's own sender first, then the listed makers.
1042
+ * Each entry is checked for the deal's maker and its quote-key owner. The old scalar `claimSender` is accepted as a
1043
+ * one-element fallback for callers written before the list. `relayUrl` is optional and may only repeat the origin
1004
1044
  * stored with the record - a foreign origin is refused.
1005
1045
  */
1006
1046
  export interface RelayClaimRequest {
1007
1047
  readonly id: string;
1008
- /** Only for a record made before the sender was stored; it may never name the deal's maker. */
1048
+ /** Ordered senders. Tried one at a time; the first that lands a claim on chain wins. */
1049
+ readonly claimSenders?: readonly string[];
1050
+ /** One-element fallback for a caller written before `claimSenders`; may never name the deal's maker. */
1009
1051
  readonly claimSender?: string;
1010
1052
  readonly relayUrl?: string;
1011
- readonly fetchImpl?: typeof fetch;
1053
+ /** One sender's slot; clamped to 15-30 s. Default 20 s. */
1054
+ readonly slotMs?: number;
1055
+ /** How often the escrow is read during a slot; clamped to at least 250 ms. Default 2 s. */
1056
+ readonly pollMs?: number;
1057
+ /** HTTP timeout per sender; capped at 120 s. Default 20 s. */
1012
1058
  readonly timeoutMs?: number;
1059
+ readonly fetchImpl?: typeof fetch;
1060
+ }
1061
+
1062
+ /** One sender's outcome in a list claim. */
1063
+ export interface RelayClaimAttempt {
1064
+ readonly sender: string;
1065
+ readonly outcome: "refused" | "unknown" | "unconfirmed";
1066
+ readonly code?: string | null;
1067
+ readonly params?: Readonly<Record<string, unknown>> | null;
1068
+ readonly txid?: string | null;
1013
1069
  }
1014
1070
 
1015
- /** The claim the relay sent for the record. Only a validated on-chain transaction hash is returned here. */
1016
- export interface RelayClaimResult {
1071
+ /** The claim has landed: the escrow itself reads `claimed`, not merely a txid answer. */
1072
+ export interface RelayClaimed {
1073
+ readonly state: "claimed";
1017
1074
  readonly id: string;
1018
- /** The sender the client chose; `claimSender` repeats it for callers that think in that name. */
1019
- readonly provider: string;
1020
- readonly claimSender: string;
1075
+ /** The sender whose slot found the claim; null when the escrow already read claimed before the first POST. */
1076
+ readonly provider: string | null;
1077
+ readonly claimSender: string | null;
1021
1078
  readonly escrow: string;
1022
1079
  readonly relayUrl: string;
1023
- readonly txid: string;
1024
- /** The address that sent the claim transaction (the sender node's sender, not the seller). */
1025
- readonly from: string;
1026
- /** The signed tip, in wei, paid out of the claim. */
1080
+ /** The txid when an answer carried one; `null` when the claim was found on chain without it. */
1081
+ readonly txid: string | null;
1082
+ readonly from: string | null;
1027
1083
  readonly tipWei: string;
1084
+ readonly tried: readonly RelayClaimAttempt[];
1028
1085
  }
1029
1086
 
1087
+ /** No sender landed the claim. The seller must send `sellClaim` before `t1`. */
1088
+ export interface RelayClaimYourself {
1089
+ readonly state: "claim-yourself";
1090
+ readonly reason: "senders-exhausted";
1091
+ readonly id: string;
1092
+ readonly provider: null;
1093
+ readonly claimSender: null;
1094
+ readonly escrow: string;
1095
+ readonly relayUrl: string;
1096
+ readonly txid: null;
1097
+ readonly from: null;
1098
+ readonly tipWei: string;
1099
+ readonly t1: number | null;
1100
+ readonly secondsLeft: number | null;
1101
+ readonly tried: readonly RelayClaimAttempt[];
1102
+ }
1103
+
1104
+ /**
1105
+ * The half was not handed to any sender because the escrow's own claim window is not open. The caller must not
1106
+ * retry the relay list: the state, not the sender, is the answer.
1107
+ */
1108
+ export interface RelayClaimWindow {
1109
+ readonly state: "claim-window";
1110
+ readonly reason: "not-ready" | "window-closed" | "settlement-margin" | "unreadable" | "not-funded" | "escrow-refused" | "escrow-refunded";
1111
+ readonly id: string;
1112
+ readonly provider: null;
1113
+ readonly claimSender: null;
1114
+ readonly escrow: string;
1115
+ readonly relayUrl: string;
1116
+ readonly txid: null;
1117
+ readonly from: null;
1118
+ readonly tipWei: string;
1119
+ readonly t1: number | null;
1120
+ readonly secondsLeft: number | null;
1121
+ readonly tried: readonly RelayClaimAttempt[];
1122
+ }
1123
+
1124
+ export type RelayClaimResult = RelayClaimed | RelayClaimYourself | RelayClaimWindow;
1125
+
1030
1126
  export interface SellWatchRequest {
1031
1127
  /** The escrow predicted by the relay adapter. */
1032
1128
  readonly escrow: string;
@@ -1038,14 +1134,18 @@ export interface SellWatchRequest {
1038
1134
 
1039
1135
  export interface SellWatchResult {
1040
1136
  readonly escrow: string;
1041
- readonly state: "ready" | "claim-open" | "claimed" | "refunded";
1137
+ readonly state: "ready" | "claim-open" | "claim-window-closed" | "claimed" | "refunded";
1042
1138
  readonly funded: boolean;
1043
1139
  readonly claimed: boolean;
1044
1140
  readonly refunded: boolean;
1045
1141
  /** `null` for a terminal claim/refund: the ready mark is not part of that answer. */
1046
1142
  readonly ready: boolean | null;
1047
- /** True when the escrow's readyBy has passed and no ready mark or terminal action was seen. */
1143
+ /** True when the escrow's readyBy has passed, t1 has not, and no ready mark or terminal action was seen. */
1048
1144
  readonly claimOpen: boolean;
1145
+ /** The order's deadline when the answer is about the claim window. */
1146
+ readonly t1?: number | null;
1147
+ /** Seconds from the observed clock to t1, when the answer is about the claim window. */
1148
+ readonly secondsLeft?: number | null;
1049
1149
  readonly balanceWei: string;
1050
1150
  readonly waitedMs: number;
1051
1151
  }
@@ -1053,7 +1153,7 @@ export interface SellWatchResult {
1053
1153
  export interface SwapWatchRequest {
1054
1154
  /** The local swap record identifier. */
1055
1155
  readonly id: string;
1056
- /** The escrow address for the ready mark (mandatory when `expect` and `wallet` are passed). */
1156
+ /** The escrow address for the ready mark (mandatory when `expect` and `wallet` are passed and the record has none). */
1057
1157
  readonly escrow?: string;
1058
1158
  /** How often to ask the state. Default - `config.limits.watchPollMs`. */
1059
1159
  readonly pollMs?: number;
@@ -1068,7 +1168,7 @@ export interface SwapWatchRequest {
1068
1168
  /**
1069
1169
  * CLIENT-SIDE ARRIVAL CHECK (issue #85). With this the CLIENT decides: it reads the chain itself and `ready`
1070
1170
  * opens only when two operators agree. The backend's `seen` is then only a notification and does not open the
1071
- * button. Without it the watch keeps the service's answer.
1171
+ * button. `verify` is mandatory: without it the watch refuses with `bad-input`.
1072
1172
  */
1073
1173
  readonly verify?: Omit<XmrArrivalRequest, "minConfirmations">;
1074
1174
  /** The confirmation target before `ready`. Default - `config.limits.xmrConfirmations` (10). */
@@ -1110,8 +1210,9 @@ export interface SwapDeclinedWatch {
1110
1210
  export interface SwapWatch {
1111
1211
  readonly seen: true;
1112
1212
  readonly id: string;
1213
+ /** The joint Monero address the client checked - never the EVM escrow. */
1113
1214
  readonly address: string | null;
1114
- /** The watch state at the service (awaiting_funding | funded | ready | ...). */
1215
+ /** The legacy service status; null because the watch no longer asks a service. */
1115
1216
  readonly status: string | null;
1116
1217
  readonly expectedXmr: number | null;
1117
1218
  readonly receivedXmr: number;
@@ -1151,6 +1252,14 @@ export interface StartRequest {
1151
1252
  * without it (`bad-input { step: "fund-order" }`): the factory takes a signed quote, not bare order terms.
1152
1253
  */
1153
1254
  readonly orderQuote?: QuoteLike;
1255
+ /**
1256
+ * OPTIONAL CROSS-CHECK, NOT A REQUIREMENT. A reloaded retry derives this address from the signed quote; when the
1257
+ * caller already has it, the value is compared with that prediction and a different value is refused. A request
1258
+ * without it resumes the same pending record from the quote alone.
1259
+ */
1260
+ readonly escrow?: string;
1261
+ /** Alias for `escrow` accepted by the same cross-check. */
1262
+ readonly predictedEscrow?: string;
1154
1263
  /** The swap direction for the record. Default - `buy`. */
1155
1264
  readonly side?: "buy" | "sell";
1156
1265
  /** Where to receive: for a purchase - the Monero address, for a sale - the EVM address. */
@@ -1176,7 +1285,7 @@ export interface StartRequest {
1176
1285
  restoreHeight?: number;
1177
1286
  /** Monero nodes for that one measurement; absent - the configured nodes for the swap's network. */
1178
1287
  xmrNodes?: readonly (string | { readonly url: string })[];
1179
- /** The fetch used for the height measurement (tests); absent - the global fetch. */
1288
+ /** The fetch used for the height measurement (tests); absent - the client's `fetch`, otherwise the global fetch. */
1180
1289
  fetchImpl?: typeof fetch;
1181
1290
  /**
1182
1291
  * Hand the key backup to the interface, ONCE, when this call created the key. `true` - the person saved it;
@@ -1370,7 +1479,7 @@ export interface SweepRestoreRequest {
1370
1479
  */
1371
1480
  readonly trustedNode?: boolean;
1372
1481
  };
1373
- /** The fetch used for `get_block`; absent - the global fetch. */
1482
+ /** The fetch used for `get_block`; absent - the instance `fetch` from `createNinsei`, then the global fetch. */
1374
1483
  readonly fetchImpl?: typeof fetch;
1375
1484
  }
1376
1485
 
@@ -1904,6 +2013,8 @@ export declare class SdkError extends Error {
1904
2013
  export declare const SDK_VERSION: string;
1905
2014
  /** The minimum remaining lifetime of a quote when a swap starts, in seconds. */
1906
2015
  export declare const LOCK_START_MARGIN_SEC: number;
2016
+ /** The SDK's own preparation allowance for a buy quote, in addition to the start margin. */
2017
+ export declare const START_PREP_SEC: number;
1907
2018
  /** The default firm quote lifetime, in seconds. A node may override it; the SDK default stays authoritative. */
1908
2019
  export declare const DEFAULT_ORDER_QUOTE_TTL_SEC: number;
1909
2020
  export declare const STEP_CODES: readonly StepCode[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ninsei-labs/sdk",
3
- "version": "0.58.0",
3
+ "version": "0.60.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -169,9 +169,9 @@
169
169
  "url": "https://github.com/Ninsei-Labs/sdk/issues"
170
170
  },
171
171
  "dependencies": {
172
- "@hpke/chacha20poly1305": "1.8.0",
173
- "@hpke/core": "1.10.0",
174
- "@hpke/dhkem-x25519": "1.8.0",
172
+ "@hpke/chacha20poly1305": "1.8.1",
173
+ "@hpke/core": "1.10.1",
174
+ "@hpke/dhkem-x25519": "1.8.1",
175
175
  "@noble/curves": "^2.4.0",
176
176
  "@noble/hashes": "^2.4.0",
177
177
  "@scure/bip39": "2.4.0",
package/src/index.mjs CHANGED
@@ -214,7 +214,7 @@ export function createNinsei(options) {
214
214
  const quotes = createQuotes({ config, now: o.now || (() => Date.now()), evmCall: o.evmCall || null,
215
215
  evmCode: o.evmCode || null, evmBlock: o.evmBlock || null,
216
216
  providerAllowed, knownFactoryCodes, knownImplementationCodes,
217
- denylist });
217
+ denylist, fetchImpl: o.fetch || null });
218
218
  // THE SAME CHAIN-READ SEAM AS THE LOCK AND THE CORE: checking the slots and signing must go one way, otherwise
219
219
  // part of the check goes past the wallet and part does not.
220
220
  const actions = createActions({ call: o.evmCall });
@@ -271,7 +271,7 @@ export function createNinsei(options) {
271
271
  // before signing.
272
272
  // THE CHAIN READER GOES INTO THE SWAP START: it will check the escrow address, the order state and the fee
273
273
  // before signing. The Monero watch reads the chain through the same seam; there is no backend watcher.
274
- swaps: createSwaps({ preflight, mode: o.mode, xmrNetwork: o.xmrNetwork, call: o.evmCall, now: o.now || null, evmBlock: o.evmBlock || null, store,
274
+ swaps: createSwaps({ preflight, mode: o.mode, xmrNetwork: o.xmrNetwork, call: o.evmCall, fetchImpl: o.fetch || null, now: o.now || null, evmBlock: o.evmBlock || null, store,
275
275
  // THE LOG SEAM FOR THE DECLINE CHECK: the watch asks the escrow for its `Declined` event on every tick, so
276
276
  // a declined order stops the wait at once instead of running to `xmr-timeout`.
277
277
  logs: o.evmLogs || null,
@@ -280,7 +280,7 @@ export function createNinsei(options) {
280
280
  createRecord: o.createRecord }),
281
281
  // XMR WITHDRAWAL: parsing the file and requesting data work; the withdrawal itself is named (the Monero
282
282
  // wallet as an adapter).
283
- sweep: createSweep({ call: o.evmCall }),
283
+ sweep: createSweep({ call: o.evmCall, fetchImpl: o.fetch || null }),
284
284
  });
285
285
  }
286
286
 
@@ -288,7 +288,7 @@ export { SdkError, ERROR_CODES, ERROR_META, ERROR_SIDES, STEP_CODES, CHECK_CODES
288
288
  export { SDK_VERSION } from "./version.mjs";
289
289
  // THE QUOTE LIFETIME AND THE START MARGIN ARE ONE PUBLIC DEFAULT. A node imports the lifetime, so its signed quote
290
290
  // cannot be shorter than the margin the SDK enforces before it opens the wallet.
291
- export { LOCK_START_MARGIN_SEC, DEFAULT_ORDER_QUOTE_TTL_SEC } from "./quotePolicy.mjs";
291
+ export { LOCK_START_MARGIN_SEC, START_PREP_SEC, DEFAULT_ORDER_QUOTE_TTL_SEC } from "./quotePolicy.mjs";
292
292
 
293
293
  // THE LEVEL WALK IS ON THE PACKAGE SURFACE. A maker publishes a level set (chunks of volume with their own prices)
294
294
  // and both the node and the client compute a firm price by WALKING it - the client must reach the SAME price before
@@ -0,0 +1,25 @@
1
+ // ONE PREDICTION FOR THE THREE SDK PATHS. The escrow address is a factory read of the signed quote plus the
2
+ // depositor's half; the quote check, the swap start and the pending retry all need exactly the same calldata.
3
+ // Keeping the assembly here leaves one place to change when the signed term set grows.
4
+ import * as engine from "./engine.mjs";
5
+
6
+ /** The quote the factory receives: signed terms plus the depositor's own half and the resolved factory. */
7
+ export function predictTerms({ quote, order = null, lockerHalf = null, factory = null } = {}) {
8
+ if (!quote || typeof quote !== "object") throw new Error("a signed quote is required for predict()");
9
+ const resolvedFactory = factory || (order && order.factory) || quote.factory;
10
+ if (!resolvedFactory) throw new Error("the quote names no factory");
11
+ const half = lockerHalf || {
12
+ commitHalfLocker: (order && order.commitHalfLocker) ?? quote.commitHalfLocker,
13
+ edPointLocker: (order && order.edPointLocker) ?? quote.edPointLocker,
14
+ edViewPointLocker: (order && order.edViewPointLocker) ?? quote.edViewPointLocker,
15
+ };
16
+ return { ...quote, ...half, factory: resolvedFactory };
17
+ }
18
+
19
+ /** Read the factory's predicted escrow. The caller maps a failed read; no address is guessed here. */
20
+ export async function predictEscrow({ quote, order = null, lockerHalf = null, factory = null, call } = {}) {
21
+ if (typeof call !== "function") throw new Error("a chain read is required for predict()");
22
+ const terms = predictTerms({ quote, order, lockerHalf, factory });
23
+ const raw = await call({ to: terms.factory, data: engine.evm.encodePredict(terms) });
24
+ return engine.evm.decodeAddress(raw);
25
+ }
@@ -102,7 +102,16 @@ export interface DeploymentPin {
102
102
  readonly knownFactoryCodes: readonly string[];
103
103
  }
104
104
 
105
+ /** One factory that served a network, including the current one. */
106
+ export interface FactoryHistoryEntry {
107
+ readonly address: string;
108
+ readonly deploymentBlock: number;
109
+ readonly release: { readonly tag: string | null; readonly commit?: string | null; readonly [field: string]: unknown };
110
+ readonly status: "live" | "retired";
111
+ }
112
+
105
113
  export declare const DEPLOYMENTS: Readonly<Record<string, DeploymentPin>>;
114
+ export declare const FACTORY_HISTORY: Readonly<Record<string, readonly FactoryHistoryEntry[]>>;
106
115
  export declare const DEPLOYMENT_CHAINS: readonly string[];
107
116
  export declare const DEPLOYMENT_VMS: readonly string[];
108
117
  export declare function deploymentFor(
@@ -14,5 +14,6 @@ export {
14
14
  DEPLOYMENTS,
15
15
  DEPLOYMENT_CHAINS,
16
16
  DEPLOYMENT_VMS,
17
+ FACTORY_HISTORY,
17
18
  deploymentFor,
18
19
  } from "../../engine/core/config.js";