@ninsei-labs/sdk 0.55.2 → 0.55.4

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 CHANGED
@@ -1,3 +1,29 @@
1
+ ## 0.55.4 — 2026-11-01
2
+
3
+ - `createNinsei` now defaults the factory and escrow-implementation pins from the settlement network; a caller's
4
+ explicit list still wins. A browser caller with default options no longer funds whatever factory the maker's
5
+ registry names. An unknown network keeps no implementation policy instead of inheriting the default chain's pin.
6
+ - `verifyArrival` classifies a browser `TimeoutError` as `timeout` (not `network`) and a body cut by the same
7
+ timeout as `timeout` (not `bad-answer`); every answered witness carries its height, and `xmr-locked`,
8
+ `xmr-underpaid` and the observation disagreement carry the failed nodes.
9
+
10
+ ## 0.55.3 — 2026-10-31
11
+
12
+ - Relay ask carries both view scalars: 64 bytes of plaintext and an 80-byte ciphertext, the same shape as bid.
13
+ A maker can rebuild the joint view key after a taker refunds an ask.
14
+ - The default `arbitrum-sepolia` factory is pinned by code hash (`0x4d51…615c`), measured from the deployed
15
+ `contracts-testnet-2026.10.26` build. A quote through an unknown factory is refused before signing.
16
+ - `verifyArrival` reports why each Monero node failed (`timeout`, `network`, `http` with status, `bad-answer`)
17
+ and keeps a completed walk pending when another node was unreachable.
18
+ - `swaps.startSell` reads the funded escrow before it returns `send-xmr`: code at the predicted address, an open
19
+ `funded` status, the slots matching the verified halves, and the deadlines by chain time. A missing or late
20
+ escrow is refused instead of handing out the XMR address.
21
+ - The registry read happens before view material is sealed to the features' HPKE key, and the quote's factory is
22
+ checked against the network's pinned build. A relay cannot substitute its own keys or factory.
23
+ - `order.fund` builds the commitment from the verified proof, not from a counterparty-provided `half` field.
24
+ - The wallet's chain is read before funding, claim and refund. **Breaking:** `actions.refund` now requires
25
+ `expect.chainId` and refuses with `bad-input {field: "chainId"}` without it.
26
+
1
27
  ## 0.55.2 — 2026-10-30
2
28
 
3
29
  - `quotes.firmRelay` now carries the signed `orderQuote.xmrAmount` on the order terms it returns, and
@@ -797,7 +797,11 @@ export function allowedProvidersFor(chainOrId) {
797
797
  // record, and its code is compared against this list. Empty for a network = no policy (the factory must still be
798
798
  // named by the record and match the signed quote). Filled at deploy: the factory has no immutables, so one build
799
799
  // gives the same hash to anyone who deployed it - a provider's own factory lands in the same list.
800
- export const KNOWN_FACTORY_CODES = {};
800
+ export const KNOWN_FACTORY_CODES = {
801
+ // contracts-testnet-2026.10.26, factory deployed at 0x69b5a6878b542960af4d239ecc60ad1c9e3e6932.
802
+ // The factory has no immutables; this hash is reproducible from that release's source.
803
+ "arbitrum-sepolia": ["0x4d51e943b7786be7d3f9e2c44ad0b54f82932dba12ac6fa34be5088500d6615c"],
804
+ };
801
805
 
802
806
  export function knownFactoryCodesFor(chainOrId) {
803
807
  const id = typeof chainOrId === "string" ? chainOrId : chainOrId && chainOrId.id;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ninsei-labs/sdk",
3
- "version": "0.55.2",
3
+ "version": "0.55.4",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
package/src/actions.mjs CHANGED
@@ -14,6 +14,7 @@ import * as engine from "./engine.mjs";
14
14
  // sdk/src/swap-flow.mjs. The actions therefore call the module directly instead of reaching it through the
15
15
  // mirror - there is exactly one implementation, and it lives here.
16
16
  import * as flow from "./swap-flow.mjs";
17
+ import { assertWalletChain } from "./chainGuard.mjs";
17
18
 
18
19
  const missingFields = (object, fields) =>
19
20
  fields.filter((k) => object[k] === undefined || object[k] === null || object[k] === "");
@@ -64,6 +65,7 @@ export function createActions({ call = null } = {}) {
64
65
  requestOrFail(request, []);
65
66
  walletOrFail(wallet);
66
67
  const { escrow, expect, onStep } = request;
68
+ await assertWalletChain(wallet, expect.chainId, "mark-ready");
67
69
  return await withCodes("mark-ready", () => flow.markReadyOrder({ escrow, expect, onStep, deps: deps(wallet) }));
68
70
  },
69
71
  /** Claiming: it reveals your own half, so expectations are mandatory. */
@@ -74,6 +76,7 @@ export function createActions({ call = null } = {}) {
74
76
  const sender = typeof wallet.address === "function" ? await wallet.address() : null;
75
77
  const verdict = claimSenderVerdict({ sender, claimer: request.claimer || (expect && expect.claimer) });
76
78
  if (!verdict.ok) throw new SdkError(verdict.code, { field: verdict.field, why: verdict.why, surface: "actions.claim" });
79
+ await assertWalletChain(wallet, expect.chainId, "claim");
77
80
  return await withCodes("claim", () => flow.claimOrder({ escrow, halfClaimer, expect, onStep, deps: deps(wallet) }));
78
81
  },
79
82
  /** Refunding: it also reveals a half. The core passes the expectations ALWAYS, though the engine does not require them. */
@@ -81,6 +84,7 @@ export function createActions({ call = null } = {}) {
81
84
  requestOrFail(request, ["halfLocker"]);
82
85
  walletOrFail(wallet);
83
86
  const { escrow, halfLocker, expect, onStep } = request;
87
+ await assertWalletChain(wallet, expect.chainId, "refund");
84
88
  return await withCodes("refund", () => flow.refundOrder({ escrow, halfLocker, expect, onStep, deps: deps(wallet) }));
85
89
  },
86
90
  };
@@ -0,0 +1,27 @@
1
+ // THE NETWORK A TRANSACTION IS ABOUT TO BE SIGNED ON.
2
+ //
3
+ // The wallet signs on whatever chain it currently serves, while the order, the escrow and the quote were assembled
4
+ // for `expect.chainId`. A wallet left on another network would sign a transaction the contract cannot accept - or,
5
+ // worse, one for a same-address contract on another chain. Read the wallet's chain immediately before the send and
6
+ // refuse a mismatch by name.
7
+ import { SdkError } from "./errors.mjs";
8
+
9
+ export async function assertWalletChain(wallet, chainId, step = "send") {
10
+ const want = Number(chainId);
11
+ if (!Number.isSafeInteger(want) || want <= 0) {
12
+ throw new SdkError("bad-input", { field: "chainId", step });
13
+ }
14
+ // A wallet adapter that cannot answer its chain cannot prove which network it signs on. The production adapters
15
+ // do answer; a caller bringing a bare send/receipt adapter is refused rather than sent blind.
16
+ if (!wallet || typeof wallet.chainId !== "function") {
17
+ throw new SdkError("bad-input", { field: "wallet.chainId", step });
18
+ }
19
+ let got = null;
20
+ try { got = Number(await wallet.chainId()); }
21
+ catch { throw new SdkError("wrong-chain", { vm: "evm", step, want, got: null, why: "unreadable" }); }
22
+ if (!Number.isSafeInteger(got) || got <= 0) {
23
+ throw new SdkError("wrong-chain", { vm: "evm", step, want, got: null, why: "unreadable" });
24
+ }
25
+ if (got !== want) throw new SdkError("wrong-chain", { vm: "evm", step, want, got });
26
+ return want;
27
+ }
@@ -0,0 +1,24 @@
1
+ // THE DEFAULT FACTORY POLICY, AT THE ONE DOOR EVERY CALLER COMES THROUGH.
2
+ //
3
+ // The engine's network registry pins the deployed factory build by code hash. `engine/sdk/bridge.js` passed that
4
+ // list explicitly, but `createNinsei` did not: a browser caller with default options got no policy, so a quote
5
+ // naming any factory from the maker's registry was funded. The pin has to reach the core, not only the bridge.
6
+ //
7
+ // An explicit list from the caller still wins, including an empty array ("no policy" on purpose). Only absent or
8
+ // null is replaced by the network's list; a network with no deployed factory keeps null.
9
+ import * as engine from "./engine.mjs";
10
+
11
+ export function factoryCodesForChain({ chain, knownFactoryCodes } = {}) {
12
+ if (knownFactoryCodes !== undefined && knownFactoryCodes !== null) return knownFactoryCodes;
13
+ return engine.config.knownFactoryCodesFor(chain);
14
+ }
15
+
16
+ export function implementationCodesForChain({ chain, knownImplementationCodes } = {}) {
17
+ if (knownImplementationCodes !== undefined && knownImplementationCodes !== null) return knownImplementationCodes;
18
+ // `knownImplementationCodesFor` falls back to the default chain for an unknown id; a policy from another
19
+ // network must not be applied here. Only an exact network record gets its pin.
20
+ const id = typeof chain === "string" ? chain : chain && chain.id;
21
+ const record = id ? engine.config.chainById(id) : null;
22
+ if (!record || String(record.id) !== String(id)) return null;
23
+ return engine.config.knownImplementationCodesFor(chain);
24
+ }
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // THE SDK ENTRY POINT. Assembles the facades and holds rules common to all: no DOM, no texts, no windows.
2
2
  import { buildConfig } from "./config.mjs";
3
+ import { factoryCodesForChain, implementationCodesForChain } from "./factoryPolicy.mjs";
3
4
  import { createHttp } from "./http.mjs";
4
5
  import { createQuotes } from "./quotes.mjs";
5
6
  import { createPreflight } from "./preflight.mjs";
@@ -185,6 +186,10 @@ export function createNinsei(options) {
185
186
  nodes: o.nodes,
186
187
  addNodes: o.addNodes,
187
188
  });
189
+ // THE NETWORK'S PINS REACH THE CORE. The bridge passed them explicitly; a caller with default options did not,
190
+ // so the factory policy was null and the quote could name any factory. An explicit caller list still wins.
191
+ const knownFactoryCodes = factoryCodesForChain({ chain: config.settlement.chain, knownFactoryCodes: o.knownFactoryCodes });
192
+ const knownImplementationCodes = implementationCodesForChain({ chain: config.settlement.chain, knownImplementationCodes: o.knownImplementationCodes });
188
193
  const leg = legFor(config.settlement.vm);
189
194
  const wallet = createWallet({ settlement: config.settlement.chain, leg });
190
195
  // THE GUARDS READ THE NETWORK UNDER THE NAME evmNetwork, WHILE THE CONFIGURATION BUILDER RETURNS IT AS
@@ -221,7 +226,7 @@ export function createNinsei(options) {
221
226
  : null;
222
227
  const quotes = createQuotes({ config, http, now: o.now || (() => Date.now()), evmCall: o.evmCall || null,
223
228
  evmCode: o.evmCode || null, evmBlock: o.evmBlock || null,
224
- providerAllowed, knownFactoryCodes: o.knownFactoryCodes, knownImplementationCodes: o.knownImplementationCodes,
229
+ providerAllowed, knownFactoryCodes, knownImplementationCodes,
225
230
  denylist });
226
231
  // THE SAME CHAIN-READ SEAM AS THE LOCK AND THE CORE: checking the slots and signing must go one way, otherwise
227
232
  // part of the check goes past the wallet and part does not.
package/src/lock.mjs CHANGED
@@ -13,6 +13,7 @@ import * as engine from "./engine.mjs";
13
13
  // THE DEAL FLOW IS A PACKAGE MODULE NOW (#32, wave 3): the registry address is read through it, exactly as
14
14
  // the actions read the order flow.
15
15
  import * as flow from "./swap-flow.mjs";
16
+ import { assertWalletChain } from "./chainGuard.mjs";
16
17
 
17
18
  // THE ORDER'S WORD-ADDRESSES ARE BROUGHT TO 0x HERE, AT THE BOUNDARY, NOT AT EVERY CALLER.
18
19
  //
@@ -88,6 +89,7 @@ export async function send(request, wallet, deps = {}) {
88
89
  const canonical = canonicalTerms(request);
89
90
  terms({ ...canonical, amount: canonical.amountWei });
90
91
  const evm = engine.evm;
92
+ await assertWalletChain(wallet, canonical.chainId, "fund-order");
91
93
  // WHAT READS THE CHAIN IS ALSO A SEAM (as in actions.mjs): by default it is the engine's read, but the caller
92
94
  // can substitute its own. Without this capability the lock step could not be checked beyond predicting the
93
95
  // address - and then "the address from the receipt" would remain an argument on trust, not a verified property.
package/src/order.mjs CHANGED
@@ -272,9 +272,9 @@ export function orderStep({ order, side = null, counterparty = null, standIn = f
272
272
  // computation here. The other's half may not arrive (the order brings it) - then the counterparty's
273
273
  // commitment is taken ready-made or stays null, not invented.
274
274
  commitHalfLocker: norm(builder().halfCommitment(own.side.half)),
275
- commitHalfClaimer: other.half !== undefined && other.half !== null
276
- ? norm(builder().halfCommitment(other.half))
277
- : (other.commitHalfClaimer || null),
275
+ // THE COMMITMENT IS THE ONE THE PROOF WAS VERIFIED AGAINST. A `half` in the counterparty object is not a
276
+ // second source: taking it here would fund a commitment nobody proved and leave the proven half unopened.
277
+ commitHalfClaimer: other.commitHalfClaimer || null,
278
278
  network: network || null,
279
279
  },
280
280
  };
package/src/quotes.mjs CHANGED
@@ -839,6 +839,23 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
839
839
  const registry = String(features.registry || "").toLowerCase();
840
840
  if (!/^0x[0-9a-f]{40}$/.test(maker) || maker === ZERO_ADDRESS) fail("bad-input", { field: "features.provider" });
841
841
  if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) fail("bad-input", { field: "features.registry" });
842
+ // THE FEATURES' HPKE KEY AND FRAME KEY BELONG TO THE REGISTERED MAKER. Check the registry mapping BEFORE
843
+ // sealing any view material to the HPKE key: a dishonest relay could otherwise hand us its own key, read both
844
+ // view halves and swap in its own node half. The answer's registry check later is not a substitute for this
845
+ // one - by then the view material has already been sealed.
846
+ if (!/^0x[0-9a-f]{40}$/.test(String(features.quoteKey || "").toLowerCase()) || String(features.quoteKey).toLowerCase() === ZERO_ADDRESS) {
847
+ fail("bad-input", { field: "features.quoteKey" });
848
+ }
849
+ if (typeof evmCall !== "function") fail("quote-registry-unchecked", { step: "features", why: "no-chain-read", registry });
850
+ let featureProvider = null;
851
+ try { featureProvider = addressFromWord(await evmCall({ to: registry, data: providerOfData(features.quoteKey) })); }
852
+ catch { fail("quote-registry-unchecked", { step: "features", why: "read-failed", registry }); }
853
+ if (featureProvider === null || featureProvider === ZERO_ADDRESS) {
854
+ fail("quote-key-unknown", { step: "registry", registry, quoteKey: features.quoteKey });
855
+ }
856
+ if (!sameText(featureProvider, features.provider)) {
857
+ fail("quote-provider-mismatch", { step: "registry", got: featureProvider, want: features.provider });
858
+ }
842
859
  if (denylist && typeof order.locker === "string" && denylist.has(order.locker.toLowerCase())) {
843
860
  fail("address-denied", { step: "order-quote" });
844
861
  }
@@ -921,7 +938,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
921
938
  edViewPointClient: own.side.viewPub,
922
939
  edViewPointNode: derived.makerViewPoint,
923
940
  nodeViewScalar: derived.makerViewHalf,
924
- clientViewScalar: side === "bid" ? derived.viewHalf : null,
941
+ clientViewScalar: derived.viewHalf,
925
942
  side,
926
943
  });
927
944
  const quote = result.quote;
@@ -82,7 +82,8 @@ function normaliseProof(proof) {
82
82
  * `features` is the signed public object the relay forwarded; `terms` is the client's request terms (its
83
83
  * `featuresHash` may be omitted and is filled from the verified features). `clientHalf` is
84
84
  * `{commitHalf, edPoint, proof}`; `nodeViewScalar` and `clientViewScalar` are the two view halves the client
85
- * chose. On ask only the node scalar is sent; on bid both.
85
+ * chose. Both are sent on both sides: after a taker refund on an ask the maker needs the taker's view scalar to
86
+ * rebuild the joint view key.
86
87
  */
87
88
  export async function buildFirmRequest({
88
89
  features, terms, clientHalf, edViewPointClient, edViewPointNode,
@@ -130,12 +131,9 @@ export async function buildFirmRequest({
130
131
  if (pointOf(nodeViewScalar, "nodeViewScalar").toLowerCase() !== nodeViewPoint.toLowerCase()) {
131
132
  throw new SdkError("bad-input", { field: "edViewPointNode" });
132
133
  }
133
- let clientScalar = null;
134
- if (requestSide === "bid") {
135
- clientScalar = scalarBytes(clientViewScalar, "clientViewScalar");
136
- if (pointOf(clientViewScalar, "clientViewScalar").toLowerCase() !== clientViewPoint.toLowerCase()) {
137
- throw new SdkError("bad-input", { field: "edViewPointClient" });
138
- }
134
+ const clientScalar = scalarBytes(clientViewScalar, "clientViewScalar");
135
+ if (pointOf(clientViewScalar, "clientViewScalar").toLowerCase() !== clientViewPoint.toLowerCase()) {
136
+ throw new SdkError("bad-input", { field: "edViewPointClient" });
139
137
  }
140
138
  const requestTerms = {
141
139
  market: String(terms.market),
@@ -167,9 +165,9 @@ export async function buildFirmRequest({
167
165
  edViewPointClient: clientViewPoint,
168
166
  edViewPointNode: nodeViewPoint,
169
167
  });
170
- const plaintext = new Uint8Array(requestSide === "ask" ? 32 : 64);
168
+ const plaintext = new Uint8Array(64);
171
169
  plaintext.set(nodeScalar, 0);
172
- if (requestSide === "bid") plaintext.set(clientScalar, 32);
170
+ plaintext.set(clientScalar, 32);
173
171
  const viewEnvelope = await sealViewEnvelope({ hpkeKey: verdict.hpkeKey, info, plaintext });
174
172
  const payload = JSON.stringify({
175
173
  terms: requestTerms,
package/src/swaps.mjs CHANGED
@@ -126,6 +126,7 @@ export function markBodyOf(swap, escrow, order = null) {
126
126
  }
127
127
  return null;
128
128
  };
129
+
129
130
  return {
130
131
  id: swap.id || null,
131
132
  network: swap.network || swap.chain || null,
@@ -592,6 +593,36 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
592
593
  return answer.body;
593
594
  }
594
595
 
596
+ // A SELL SENDS XMR ONLY INTO AN ESCROW THE CHAIN ALREADY HOLDS. The relay answer proves the maker signed the
597
+ // terms; it does not prove that the maker funded them. Read the escrow itself (code, status, slots and
598
+ // deadlines), compare the slots with the halves this offer verified, and refuse before `send-xmr`.
599
+ async function sellEscrowGate(escrow, expect) {
600
+ if (!escrow || !expect) throw new SdkError("bad-input", { field: "escrow" });
601
+ let status = null;
602
+ try { status = await flow.orderStatus(escrow, { call: reader }); }
603
+ catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-unreadable" }); }
604
+ if (!status || status.isFunded !== true || status.isClaimed === true || status.isRefunded === true) {
605
+ throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-not-open" });
606
+ }
607
+ let deadlines = null;
608
+ try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
609
+ catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-unreadable" }); }
610
+ if (Number(deadlines.readyBy) !== Number(expect.readyBy) || Number(deadlines.t1) !== Number(expect.t1)) {
611
+ throw new SdkError("quote-refused", { step: "send-xmr", why: "terms-mismatch" });
612
+ }
613
+ // Leave time for the XMR to be sent and confirmed before the maker's ready mark closes. The lead is a
614
+ // node setting (`limits.sellReadyLeadSec`), not a second protocol constant.
615
+ const leadSec = Number(limitOf("sellReadyLeadSec", 600));
616
+ if (Math.floor(Date.now() / 1000) + leadSec >= Number(deadlines.readyBy)) {
617
+ throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-too-close" });
618
+ }
619
+ try { await flow.assertOrderSlots(escrow, expect, "send-xmr", { call: reader }); }
620
+ catch (e) {
621
+ if (e && e.code === "contract-reverted") throw e;
622
+ throw new SdkError("quote-refused", { step: "send-xmr", why: "slots-unreadable" });
623
+ }
624
+ }
625
+
595
626
  return {
596
627
  // list/get DO NOT ASK THE NETWORK: the state lies in storage, and after a page reload the interface raises the swaps
597
628
  // from it, not from memory.
@@ -1398,6 +1429,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1398
1429
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1399
1430
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1400
1431
  }
1432
+ await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null);
1401
1433
  return { id: existing.id, side: "sell", escrow: (existing.escrow && existing.escrow.address) || offer.escrow,
1402
1434
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1403
1435
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
@@ -1479,6 +1511,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1479
1511
  commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
1480
1512
  orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
1481
1513
  };
1514
+ await sellEscrowGate(offer.escrow, swap.expect);
1482
1515
  try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1483
1516
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1484
1517
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
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.55.2";
9
+ export const SDK_VERSION = "0.55.4";
@@ -34,6 +34,26 @@ const intOf = (v) => { const n = Number(v); return Number.isFinite(n) ? Math.tru
34
34
  const txidOf = (v) => (isStr(v) ? v.trim().replace(/^0x/, "").toLowerCase() : null);
35
35
  const hostOf = (url) => { try { return new URL(url).host; } catch { throw new SdkError("bad-input", { field: "nodes.url", unknown: url }); } };
36
36
 
37
+ // ONE FAILED REQUEST, IN THE SHAPE THE CALLER CAN SHOW. A node that did not answer is not evidence about the
38
+ // transaction; it is a visible reason: a timeout, a transport failure, an HTTP status or a bad answer. The list
39
+ // travels beside `checked`, so a pending or arrived verdict never hides a node that failed.
40
+ const failureOf = (error, node) => {
41
+ const params = (error && error.params) || {};
42
+ let code = "network";
43
+ const why = params.why === undefined || params.why === null ? "" : String(params.why);
44
+ // A BROWSER NAMES A TIMEOUT BY THE ERROR'S NAME, NOT ITS MESSAGE. Chromium says "signal timed out" where Node
45
+ // says "The operation was aborted due to timeout"; the name is the one stable word. Check it before rewrapping
46
+ // the answer as a bad one.
47
+ const name = String(params.name || (error && error.name) || "");
48
+ if (params.status !== undefined && params.status !== null) code = "http";
49
+ else if (/^(TimeoutError|AbortError)$/.test(name) || /timeout|abort/i.test(why) || /timeout|abort/i.test(name)) code = "timeout";
50
+ else if (why === "bad-json" || why === "no-height" || why === "no-block") code = "bad-answer";
51
+ const out = { url: node.url, operator: node.operator, code };
52
+ if (params.status !== undefined && params.status !== null) out.status = params.status;
53
+ if (why) out.why = why;
54
+ return out;
55
+ };
56
+
37
57
  // A NODE LIST IS A LIST OF {url, operator}. The operator is what makes two nodes two witnesses: two nodes of one
38
58
  // operator are one opinion. A plain string is accepted and its operator is the host - a user who adds their own
39
59
  // node is the operator of it.
@@ -67,10 +87,19 @@ async function call(node, path, body, fetchImpl, timeoutMs) {
67
87
  signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : undefined,
68
88
  });
69
89
  } catch (error) {
70
- throw new SdkError("xmr-no-nodes", { node: node.url, why: String((error && error.message) || error).slice(0, 120) });
90
+ // KEEP THE NAME: `AbortSignal.timeout` is "TimeoutError" in a browser and "AbortError" in Node; the message
91
+ // alone is not portable, and the arrival report has to say timeout rather than network.
92
+ throw new SdkError("xmr-no-nodes", { node: node.url, name: String((error && error.name) || ""),
93
+ why: String((error && error.message) || error).slice(0, 120) });
71
94
  }
72
95
  if (!res || res.ok !== true) throw new SdkError("xmr-no-nodes", { node: node.url, status: res ? res.status : null });
73
- try { return await res.json(); } catch { throw new SdkError("xmr-no-nodes", { node: node.url, why: "bad-json" }); }
96
+ try { return await res.json(); } catch (error) {
97
+ // A BODY CUT BY THE TIMEOUT IS STILL A TIMEOUT. `res.json()` rejects after the signal fired; in Node and in
98
+ // browsers that is a TimeoutError/AbortError, not a malformed answer.
99
+ const name = String((error && error.name) || "");
100
+ const timedOut = /^(TimeoutError|AbortError)$/.test(name) || /timeout|abort/i.test(name);
101
+ throw new SdkError("xmr-no-nodes", { node: node.url, name, why: timedOut ? "timeout" : "bad-json" });
102
+ }
74
103
  }
75
104
 
76
105
  async function getInfo(node, fetchImpl, timeoutMs) {
@@ -167,11 +196,12 @@ export async function verifyArrival(request) {
167
196
 
168
197
  // 1. THE TIP, and with it the first proof that ANY node answers. All nodes down is a named refusal, not silence.
169
198
  const live = [];
199
+ const failed = [];
170
200
  for (const node of nodes) {
171
201
  try { const info = await getInfo(node, fetchImpl, timeoutMs); live.push({ node, info }); }
172
- catch { /* a failed node does not count and blocks nothing */ }
202
+ catch (error) { failed.push(failureOf(error, node)); /* a failed node does not count and blocks nothing */ }
173
203
  }
174
- if (!live.length) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url) });
204
+ if (!live.length) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
175
205
  const tip = Math.max(...live.map((l) => l.info.height));
176
206
  // THE REPORTED HEIGHT IS THE NEXT BLOCK, NOT A REACHABLE ONE. monerod's get_info returns height = "the block that
177
207
  // will be mined next", so get_block(height) refuses with "greater than current top block". The backend already
@@ -182,15 +212,22 @@ export async function verifyArrival(request) {
182
212
 
183
213
  // 2. LOCATE: from the birth height, by whole blocks. The first reachable node does the walk.
184
214
  let located = null;
185
- let walkError = null;
215
+ let completedWalk = false;
186
216
  for (const { node } of live) {
187
- try { located = await locate(node, { txid: txidHint, address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs }); }
188
- catch (error) { walkError = error; located = null; }
217
+ try {
218
+ located = await locate(node, { txid: txidHint, address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
219
+ completedWalk = true;
220
+ } catch (error) {
221
+ failed.push(failureOf(error, node));
222
+ located = null;
223
+ }
189
224
  if (located) break;
190
225
  }
191
226
  if (!located) {
192
- if (walkError && walkError.code === "xmr-no-nodes") throw walkError;
193
- return { seen: false, state: "pending", txid: txidHint, tip, checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height })) };
227
+ // ONE NODE FINISHED THE WALK AND FOUND NOTHING: that is a complete answer, even when another node failed.
228
+ // Only when NO node finished the walk is every node unreachable.
229
+ if (!completedWalk) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
230
+ return { seen: false, state: "pending", txid: txidHint, tip, checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height })), failed };
194
231
  }
195
232
 
196
233
  // 3. VERIFY ON EVERY NODE: the SAME block hash, the SAME transaction inside it, the confirmations and the money.
@@ -199,18 +236,21 @@ export async function verifyArrival(request) {
199
236
  const record = { url: node.url, operator: node.operator };
200
237
  let info;
201
238
  try { info = await getInfo(node, fetchImpl, timeoutMs); }
202
- catch { record.state = "down"; seen.push(record); continue; }
239
+ catch (error) { record.state = "down"; record.failure = failureOf(error, node); failed.push(record.failure); seen.push(record); continue; }
203
240
  // A LAGGING NODE IS NOT A WITNESS and is not a disagreement: it simply cannot see the block yet.
204
241
  if (!info.synced || info.height < located.height) { record.state = "stale"; record.height = info.height; seen.push(record); continue; }
242
+ // A WITNESS THAT ANSWERED HAS A HEIGHT, whether it is still confirming or already arrived; the caller can say
243
+ // "answered, height N" without inferring it from the block only when the state is stale.
244
+ record.height = info.height;
205
245
  let block;
206
246
  try { block = await getBlock(node, located.height, fetchImpl, timeoutMs); }
207
- catch { record.state = "down"; seen.push(record); continue; }
247
+ catch (error) { record.state = "down"; record.failure = failureOf(error, node); failed.push(record.failure); seen.push(record); continue; }
208
248
  record.blockHash = block.hash;
209
249
  // A SYNCED NODE WITHOUT THIS TRANSACTION IN THAT BLOCK IS A DISAGREEMENT (it may hold a different block hash).
210
250
  if (!block.hash || !block.txHashes.includes(located.txid)) { record.state = "no-tx"; seen.push(record); continue; }
211
251
  let body = null;
212
252
  try { body = (await getBlockTxs(node, block.txHashes, fetchImpl, timeoutMs)).find((t) => t.tx_hash === located.txid) || null; }
213
- catch { record.state = "down"; seen.push(record); continue; }
253
+ catch (error) { record.state = "down"; record.failure = failureOf(error, node); failed.push(record.failure); seen.push(record); continue; }
214
254
  if (!body) { record.state = "no-tx"; seen.push(record); continue; }
215
255
  // THE LOCK IS JUDGED AT THE WITNESS'S TIP, NOT AT THE BLOCK THAT MINED THE TRANSFER. `located.height` stays for
216
256
  // confirmations; a height lock that has matured is no longer `xmr-locked`.
@@ -258,11 +298,12 @@ export async function verifyArrival(request) {
258
298
  txid: located.txid, height: located.height,
259
299
  nodes: disagreeing.map((r) => ({ url: r.url, operator: r.operator, blockHash: r.blockHash || null, why: r.state, outputs: r.outputs || null })),
260
300
  agreed: seen.filter((r) => r.state === "ok").map((r) => ({ url: r.url, operator: r.operator, blockHash: r.blockHash })),
301
+ failed,
261
302
  });
262
303
  }
263
304
 
264
305
  const okay = seen.filter((r) => r.state === "ok");
265
- if (!okay.length) return { seen: false, state: "pending", txid: located.txid, height: located.height, checked: seen };
306
+ if (!okay.length) return { seen: false, state: "pending", txid: located.txid, height: located.height, checked: seen, failed };
266
307
 
267
308
  // THE OBSERVATIONS MUST BE IDENTICAL. Grouping by the whole observation (not just the block hash) means a
268
309
  // node that reports a different amount, output key or unlock state does not count as agreeing with anyone.
@@ -278,7 +319,7 @@ export async function verifyArrival(request) {
278
319
  throw new SdkError("xmr-nodes-disagree", {
279
320
  txid: located.txid, height: located.height,
280
321
  nodes: okay.map((r) => ({ url: r.url, operator: r.operator, blockHash: r.blockHash || null, outputs: r.outputs, why: "observation" })),
281
- agreed: [],
322
+ agreed: [], failed,
282
323
  });
283
324
  }
284
325
  const best = [...byObservation.values()][0];
@@ -293,26 +334,26 @@ export async function verifyArrival(request) {
293
334
  if (locked) {
294
335
  const until = locked.unlock;
295
336
  throw new SdkError("xmr-locked", { txid: located.txid, height: located.height, address: request.address,
296
- untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null });
337
+ untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null, failed });
297
338
  }
298
339
 
299
340
  // THE AMOUNT IS NOT LESS THAN EXPECTED. A shortfall is named rather than shown as a completed swap. The figure
300
341
  // comes from the agreed observation, never from the largest answer of one node: that maximum was the defect.
301
342
  if (amountAtomic < expectedAtomic) {
302
- throw new SdkError("xmr-underpaid", { txid: located.txid, height: located.height, got: amountAtomic.toString(), want: expectedAtomic.toString() });
343
+ throw new SdkError("xmr-underpaid", { txid: located.txid, height: located.height, got: amountAtomic.toString(), want: expectedAtomic.toString(), failed });
303
344
  }
304
345
 
305
346
  if (best.operators.size < 2) {
306
347
  return { seen: false, state: "one-node", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
307
- amountAtomic: amountAtomic.toString(), confirmations, operators: [...best.operators], agreedBy, checked: seen };
348
+ amountAtomic: amountAtomic.toString(), confirmations, operators: [...best.operators], agreedBy, checked: seen, failed };
308
349
  }
309
350
  if (confirmations < minConfirmations) {
310
351
  return { seen: false, state: "pending", why: "confirmations", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
311
- amountAtomic: amountAtomic.toString(), confirmations, needConfirmations: minConfirmations, agreedBy, checked: seen };
352
+ amountAtomic: amountAtomic.toString(), confirmations, needConfirmations: minConfirmations, agreedBy, checked: seen, failed };
312
353
  }
313
354
  return { seen: true, state: "arrived", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
314
355
  amountAtomic: amountAtomic.toString(), confirmations, needConfirmations: minConfirmations,
315
- operators: [...best.operators], agreedBy, checked: seen };
356
+ operators: [...best.operators], agreedBy, checked: seen, failed };
316
357
  }
317
358
 
318
359
  /**