@ninsei-labs/sdk 0.59.0 → 0.61.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 (62) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +40 -8
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/dleq2.js +0 -4
  6. package/engine/atomic/halfenc.js +0 -4
  7. package/engine/atomic/halves.js +0 -4
  8. package/engine/atomic/order.js +0 -4
  9. package/engine/atomic/orderContext.js +0 -4
  10. package/engine/atomic/orderHalfCommit.js +0 -4
  11. package/engine/core/chainSource.js +0 -4
  12. package/engine/core/clock.js +0 -4
  13. package/engine/core/config.js +0 -4
  14. package/engine/core/deployments.generated.js +1 -17
  15. package/engine/core/finality.js +0 -4
  16. package/engine/core/format.js +0 -4
  17. package/engine/core/preSignGuards.js +0 -4
  18. package/engine/core/rfqSource.js +0 -3
  19. package/engine/core/sellWindow.js +0 -4
  20. package/engine/core/store.js +0 -4
  21. package/engine/core/swap.js +0 -4
  22. package/engine/evm/amounts.js +0 -4
  23. package/engine/evm/asyncRoute.js +0 -4
  24. package/engine/evm/auth.js +0 -4
  25. package/engine/evm/claimGas.js +2 -6
  26. package/engine/evm/dex.js +0 -4
  27. package/engine/evm/escrow.js +0 -4
  28. package/engine/evm/factory.js +0 -4
  29. package/engine/evm/fees.js +0 -4
  30. package/engine/evm/funding.js +2 -5
  31. package/engine/evm/gasReserve.js +0 -4
  32. package/engine/evm/index.js +5 -9
  33. package/engine/evm/injected.js +0 -4
  34. package/engine/evm/permit.js +0 -4
  35. package/engine/evm/prices.js +0 -4
  36. package/engine/evm/session.js +0 -4
  37. package/engine/mock/chain.js +0 -4
  38. package/engine/monero/address.js +0 -3
  39. package/engine/monero/halvesSweep.js +0 -4
  40. package/engine/monero/node.js +0 -4
  41. package/engine/monero/swapKeys.js +0 -4
  42. package/engine/monero/unlock.js +2 -6
  43. package/engine/monero/wallet.js +0 -3
  44. package/engine/recovery/recoveryFile.js +0 -4
  45. package/engine/recovery/restore.js +0 -4
  46. package/engine/sdk/bridge.js +3 -7
  47. package/engine/ui/dom.js +0 -4
  48. package/engine/ui/walletModal.js +0 -4
  49. package/index.d.ts +89 -36
  50. package/package.json +3 -2
  51. package/src/engine.mjs +17 -26
  52. package/src/index.mjs +1 -1
  53. package/src/predictEscrow.mjs +25 -0
  54. package/src/public/recovery.d.ts +1 -1
  55. package/src/quotes.mjs +2 -5
  56. package/src/relayClaim.mjs +17 -3
  57. package/src/relayFirmClient.mjs +18 -0
  58. package/src/swap-flow.mjs +7 -10
  59. package/src/swaps.mjs +349 -76
  60. package/src/sweep.mjs +9 -2
  61. package/src/version.mjs +1 -1
  62. package/src/xmr-arrival.mjs +61 -41
package/index.d.ts CHANGED
@@ -54,7 +54,8 @@ export interface NinseiOptions {
54
54
  /** "live" - real nodes and chain; "sim" - a sandbox (mocks, accelerated time, failure scenarios). */
55
55
  mode?: "live" | "sim";
56
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; a per-call `fetchImpl` still wins. */
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`. */
58
59
  fetch?: FetchLike;
59
60
  /** The clock. In "sim" the SDK uses it to accelerate time. */
60
61
  now?: () => number;
@@ -168,9 +169,24 @@ export interface NinseiOptions {
168
169
  createRecord?: (request: StartRequest) => Promise<SwapRecord> | SwapRecord;
169
170
  }
170
171
 
172
+ /** One durable sender attempt on a sell record, written before the relay POST. This is a diagnostic journal,
173
+ * not a set of senders that must be skipped on a later call. The journal is append-only and is not pruned by the
174
+ * SDK; a host may trim old entries, but must keep the latest `sending`/`unknown` one for its slot wait. */
175
+ export interface StoredClaimAttempt {
176
+ readonly sender: string;
177
+ readonly at?: number;
178
+ readonly outcome: "sending" | "refused" | "unknown" | "unconfirmed" | "claimed";
179
+ readonly code?: string | null;
180
+ readonly params?: Readonly<Record<string, unknown>> | null;
181
+ readonly txid?: string | null;
182
+ }
183
+
171
184
  /** The result of assembling the swap record: the record itself, your own side and what is missing. */
172
185
  export interface SwapRecord {
173
- readonly swap: Readonly<Record<string, unknown>>;
186
+ readonly swap: Readonly<Record<string, unknown>> & {
187
+ /** The ordered claim attempts; absent on records written before the journal existed. */
188
+ readonly claimAttempts?: readonly StoredClaimAttempt[];
189
+ };
174
190
  /** Our side of the order: halves, points, the proof and the encryption key. The shape is set by the builder. */
175
191
  readonly side: unknown;
176
192
  /** What the record is missing: for a start that is the counterparty's half (`counterparty-half`). */
@@ -558,6 +574,8 @@ export interface FirmRelayAnswer {
558
574
  }>;
559
575
  /** The relay origin that answered. `startSell` stores it for the later no-wallet claim. */
560
576
  readonly relayUrl: string;
577
+ /** The sender `GET /v1/relay` publishes for claims; null when the relay did not name one. */
578
+ readonly claimSender: string | null;
561
579
  readonly relay: string | null;
562
580
  readonly offered: number | null;
563
581
  readonly forwarded: Readonly<Record<string, unknown>> | null;
@@ -666,24 +684,29 @@ export interface SwapsApi {
666
684
  * sender. `claimSenders` is the client's ordered list - the relay's own sender first, then the listed makers -
667
685
  * sent one at a time through the relay (`POST /v1/claims/{sender}/{escrow}`). Each sender gets a 15-30 s slot; a
668
686
  * refusal moves on, a txid or unknown answer is followed by reading the escrow, and only `claimed` on chain is
669
- * success. When the list is exhausted the result is `claim-yourself` with the time left before `t1`.
687
+ * success. A later call starts from the first sender again; a previous `sending`/`unknown` entry is waited out
688
+ * for its slot and retried, so a temporary refusal or a restart is recoverable. When the list is exhausted the
689
+ * result is `claim-yourself` with the time left before `t1`.
670
690
  *
671
- * The deal's maker and its quote-key owner are refused before the half leaves the client. No wallet is created or
672
- * used and no chain transaction is signed. `relayUrl` may restate the stored origin; a different origin is refused.
691
+ * The claim window is read with the escrow's chain clock (`evmBlock`), not the device clock. Without a readable
692
+ * clock the result is `claim-window` / `unreadable` and no half leaves the client. The same applies to an escrow
693
+ * read that fails before any POST; after an earlier attempt it remains `claim-unknown`. The deal's maker and its
694
+ * quote-key owner are refused before the half leaves the client. No wallet is created or used and no chain
695
+ * transaction is signed. `relayUrl` may restate the stored origin; a different origin is refused.
673
696
  */
674
697
  claimViaRelay(request: RelayClaimRequest): Promise<RelayClaimResult>;
675
698
  /**
676
- * WAIT FOR THE XMR TO ARRIVE at the order's joint address. The polling uses the same request as the page's
677
- * (GET /swaps/{id}), the rate and the timeout - from `config.limits` and overridable here.
678
- * It arrived - the FACT is returned (the amount, the confirmations, the txid); we did not wait - a refusal with
679
- * the CODE `xmr-timeout`, separate from the others: "the wait expired" is a state of the money, not a breakdown.
699
+ * WAIT FOR THE XMR TO ARRIVE at the order's joint address. The polling is the client's own `verify` walk; there
700
+ * is no backend status call. The rate and the timeout come from `config.limits` and are overridable here.
701
+ * It arrived - the FACT is returned (the amount, the confirmations, the txid, and the joint Monero address); we did
702
+ * not wait - a refusal with the CODE `xmr-timeout`, separate from the others: "the wait expired" is a state of the
703
+ * money, not a breakdown.
680
704
  * XMR ON THE ADDRESS BUT LOCKED BY `unlock_time` is a THIRD answer with its own code `xmr-locked` (the boundary,
681
705
  * a height or a date, is in `params.until`): locked funds are NOT an arrival, and nothing is signed under them.
682
706
  * IF `expect` AND `wallet` ARE PASSED, then after the arrival the ready mark (actions.markReady) is called with
683
- * THESE expectations: the slot check against the chain stands in it before the signature. Without them the step
684
- * names the next one (`next: "mark-ready"`) and signs nothing.
685
- * THE MAKER DECLINED - THE WAIT STOPS AT ONCE (issue #40): the escrow's `Declined` event and the service's
686
- * `declined` + `compliance` status are BOTH asked on every tick, and either one ends the wait with
707
+ * THESE expectations and the EVM escrow: the slot check against the chain stands in it before the signature.
708
+ * Without them the step names the next one (`next: "mark-ready"`) and signs nothing.
709
+ * THE MAKER DECLINED - THE WAIT STOPS AT ONCE (issue #40): the escrow's `Declined` event ends the wait with
687
710
  * `SwapDeclinedWatch` instead of running to `xmr-timeout` about an order whose ETH is already back. Nothing is
688
711
  * signed, and the decline is written into the record, so every later read of the swap reports the same state.
689
712
  */
@@ -820,6 +843,8 @@ export interface XmrArrivalRequest {
820
843
  readonly fromHeight?: number | null;
821
844
  readonly nowSec?: number;
822
845
  readonly timeoutMs?: number;
846
+ /** The transport for node and witness reads; absent - the client's `fetch`, otherwise the global fetch. */
847
+ readonly fetch?: FetchLike;
823
848
  }
824
849
 
825
850
  /** The slice check's extra input: independent witnesses that serve witness-v1. */
@@ -849,6 +874,10 @@ export interface XmrWitnessShadowReading {
849
874
  };
850
875
  readonly checked: readonly Record<string, unknown>[];
851
876
  readonly failed: readonly Record<string, unknown>[];
877
+ /** One opinion per operator: seen/txid/height/blockHash/amount/locked. */
878
+ readonly observations: readonly Record<string, unknown>[];
879
+ /** Same-operator and cross-operator contradictions, plus contradictions against the exact reading. */
880
+ readonly disagreements: readonly Record<string, unknown>[];
852
881
  }
853
882
 
854
883
  /** The exact verdict and the slice reading, side by side. This is not a swap decision. */
@@ -968,11 +997,10 @@ export interface SellStartRequest {
968
997
  /** The verified `quotes.firmRelay` answer for the bid side. */
969
998
  readonly offer: FirmRelayAnswer;
970
999
  /**
971
- * Optional legacy single sender stored for a no-ETH claim. The ordered list passed to `claimViaRelay` is the
972
- * authority; this scalar is only a one-element fallback for callers written before the list existed. A sender
973
- * naming the deal's maker or its quote-key owner is refused.
1000
+ * Optional ordered senders stored for a no-ETH claim. An explicit list replaces the relay-published sender;
1001
+ * the published sender is used only when no list is passed. The old scalar is retired.
974
1002
  */
975
- readonly claimSender?: string;
1003
+ readonly claimSenders?: readonly string[];
976
1004
  /** The twelve-word key; required only when no key is stored yet. */
977
1005
  readonly recoveryKey?: string | { readonly mnemonic: string };
978
1006
  /** The recovery file's passphrase. In memory; the interface puts it on disk if it deems fit. */
@@ -995,8 +1023,8 @@ export interface SellStart {
995
1023
  readonly xmrAmount: string;
996
1024
  readonly claimTip: string | null;
997
1025
  readonly orderQuote: Readonly<Record<string, unknown>> | null;
998
- /** The legacy single sender stored by `startSell`, or null when the client supplies the list at claim time. */
999
- readonly claimSender: string | null;
1026
+ /** The ordered senders stored by `startSell`; empty when the client supplies the list at claim time. */
1027
+ readonly claimSenders: readonly string[];
1000
1028
  readonly readyWindow: ReadyWindow | null;
1001
1029
  readonly resumed: boolean;
1002
1030
  readonly next: "send-xmr";
@@ -1013,23 +1041,23 @@ export interface SellClaimRequest {
1013
1041
  /**
1014
1042
  * THE NO-WALLET CLAIM'S INPUTS. `id` names the sell record made by `startSell`; the escrow, half and signed tip
1015
1043
  * come from it. `claimSenders` is the client's ordered list: the relay's own sender first, then the listed makers.
1016
- * Each entry is checked for the deal's maker and its quote-key owner. The old scalar `claimSender` is accepted as a
1017
- * one-element fallback for callers written before the list. `relayUrl` is optional and may only repeat the origin
1018
- * stored with the record - a foreign origin is refused.
1044
+ * Each entry is checked for the deal's maker and its quote-key owner. The old scalar `claimSender` is retired and
1045
+ * refused by name. `relayUrl` is optional and may only repeat the origin stored with the record - a foreign origin
1046
+ * is refused. A second call is allowed after a refusal or an unknown answer: the journal is diagnostic and the
1047
+ * sender list is walked from the beginning once any previous slot ends.
1019
1048
  */
1020
1049
  export interface RelayClaimRequest {
1021
1050
  readonly id: string;
1022
1051
  /** Ordered senders. Tried one at a time; the first that lands a claim on chain wins. */
1023
1052
  readonly claimSenders?: readonly string[];
1024
- /** One-element fallback for a caller written before `claimSenders`; may never name the deal's maker. */
1025
- readonly claimSender?: string;
1026
1053
  readonly relayUrl?: string;
1027
1054
  /** One sender's slot; clamped to 15-30 s. Default 20 s. */
1028
1055
  readonly slotMs?: number;
1029
- /** How often the escrow is read during a slot. Default 2 s. */
1056
+ /** How often the escrow is read during a slot; clamped to at least 250 ms. Default 2 s. */
1030
1057
  readonly pollMs?: number;
1031
- readonly fetchImpl?: typeof fetch;
1058
+ /** HTTP timeout per sender; capped at 120 s. Default 20 s. */
1032
1059
  readonly timeoutMs?: number;
1060
+ readonly fetchImpl?: typeof fetch;
1033
1061
  }
1034
1062
 
1035
1063
  /** One sender's outcome in a list claim. */
@@ -1047,7 +1075,6 @@ export interface RelayClaimed {
1047
1075
  readonly id: string;
1048
1076
  /** The sender whose slot found the claim; null when the escrow already read claimed before the first POST. */
1049
1077
  readonly provider: string | null;
1050
- readonly claimSender: string | null;
1051
1078
  readonly escrow: string;
1052
1079
  readonly relayUrl: string;
1053
1080
  /** The txid when an answer carried one; `null` when the claim was found on chain without it. */
@@ -1060,10 +1087,29 @@ export interface RelayClaimed {
1060
1087
  /** No sender landed the claim. The seller must send `sellClaim` before `t1`. */
1061
1088
  export interface RelayClaimYourself {
1062
1089
  readonly state: "claim-yourself";
1063
- readonly reason: "senders-exhausted" | "escrow-refunded";
1090
+ readonly reason: "senders-exhausted";
1091
+ readonly id: string;
1092
+ readonly provider: null;
1093
+ readonly escrow: string;
1094
+ readonly relayUrl: string;
1095
+ readonly txid: null;
1096
+ readonly from: null;
1097
+ readonly tipWei: string;
1098
+ readonly t1: number | null;
1099
+ readonly secondsLeft: number | null;
1100
+ readonly tried: readonly RelayClaimAttempt[];
1101
+ }
1102
+
1103
+ /**
1104
+ * The half was not handed to any sender because the escrow's own claim window is not open. For a closed,
1105
+ * not-ready, margin or unfunded state the state is the answer; `unreadable` can be retried once the chain clock
1106
+ * and escrow state are readable again.
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";
1064
1111
  readonly id: string;
1065
1112
  readonly provider: null;
1066
- readonly claimSender: null;
1067
1113
  readonly escrow: string;
1068
1114
  readonly relayUrl: string;
1069
1115
  readonly txid: null;
@@ -1074,7 +1120,7 @@ export interface RelayClaimYourself {
1074
1120
  readonly tried: readonly RelayClaimAttempt[];
1075
1121
  }
1076
1122
 
1077
- export type RelayClaimResult = RelayClaimed | RelayClaimYourself;
1123
+ export type RelayClaimResult = RelayClaimed | RelayClaimYourself | RelayClaimWindow;
1078
1124
 
1079
1125
  export interface SellWatchRequest {
1080
1126
  /** The escrow predicted by the relay adapter. */
@@ -1087,14 +1133,18 @@ export interface SellWatchRequest {
1087
1133
 
1088
1134
  export interface SellWatchResult {
1089
1135
  readonly escrow: string;
1090
- readonly state: "ready" | "claim-open" | "claimed" | "refunded";
1136
+ readonly state: "ready" | "claim-open" | "claim-window-closed" | "claimed" | "refunded";
1091
1137
  readonly funded: boolean;
1092
1138
  readonly claimed: boolean;
1093
1139
  readonly refunded: boolean;
1094
1140
  /** `null` for a terminal claim/refund: the ready mark is not part of that answer. */
1095
1141
  readonly ready: boolean | null;
1096
- /** True when the escrow's readyBy has passed and no ready mark or terminal action was seen. */
1142
+ /** True when the escrow's readyBy has passed, t1 has not, and no ready mark or terminal action was seen. */
1097
1143
  readonly claimOpen: boolean;
1144
+ /** The order's deadline when the answer is about the claim window. */
1145
+ readonly t1?: number | null;
1146
+ /** Seconds from the observed clock to t1, when the answer is about the claim window. */
1147
+ readonly secondsLeft?: number | null;
1098
1148
  readonly balanceWei: string;
1099
1149
  readonly waitedMs: number;
1100
1150
  }
@@ -1102,7 +1152,8 @@ export interface SellWatchResult {
1102
1152
  export interface SwapWatchRequest {
1103
1153
  /** The local swap record identifier. */
1104
1154
  readonly id: string;
1105
- /** The escrow address for the ready mark (mandatory when `expect` and `wallet` are passed). */
1155
+ /** The escrow address for the ready mark. If the record already names an escrow, a different value is refused as
1156
+ * `bad-input` / `record-mismatch` rather than watched under the same id. */
1106
1157
  readonly escrow?: string;
1107
1158
  /** How often to ask the state. Default - `config.limits.watchPollMs`. */
1108
1159
  readonly pollMs?: number;
@@ -1117,7 +1168,8 @@ export interface SwapWatchRequest {
1117
1168
  /**
1118
1169
  * CLIENT-SIDE ARRIVAL CHECK (issue #85). With this the CLIENT decides: it reads the chain itself and `ready`
1119
1170
  * opens only when two operators agree. The backend's `seen` is then only a notification and does not open the
1120
- * button. Without it the watch keeps the service's answer.
1171
+ * button. `verify` is mandatory: without it the watch refuses with `bad-input`. `verify.address` must match the
1172
+ * record's `moneroAddress` when the record has one; a different address is `bad-input` / `record-mismatch`.
1121
1173
  */
1122
1174
  readonly verify?: Omit<XmrArrivalRequest, "minConfirmations">;
1123
1175
  /** The confirmation target before `ready`. Default - `config.limits.xmrConfirmations` (10). */
@@ -1159,8 +1211,9 @@ export interface SwapDeclinedWatch {
1159
1211
  export interface SwapWatch {
1160
1212
  readonly seen: true;
1161
1213
  readonly id: string;
1214
+ /** The joint Monero address the client checked - never the EVM escrow. */
1162
1215
  readonly address: string | null;
1163
- /** The watch state at the service (awaiting_funding | funded | ready | ...). */
1216
+ /** The legacy service status; null because the watch no longer asks a service. */
1164
1217
  readonly status: string | null;
1165
1218
  readonly expectedXmr: number | null;
1166
1219
  readonly receivedXmr: number;
@@ -1427,7 +1480,7 @@ export interface SweepRestoreRequest {
1427
1480
  */
1428
1481
  readonly trustedNode?: boolean;
1429
1482
  };
1430
- /** The fetch used for `get_block`; absent - the global fetch. */
1483
+ /** The fetch used for `get_block`; absent - the instance `fetch` from `createNinsei`, then the global fetch. */
1431
1484
  readonly fetchImpl?: typeof fetch;
1432
1485
  }
1433
1486
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@ninsei-labs/sdk",
3
- "version": "0.59.0",
3
+ "version": "0.61.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
7
7
  },
8
- "packageManager": "pnpm@12.11.2",
8
+ "packageManager": "pnpm@12.21.0",
9
9
  "description": "XMR <-> EVM swap engine: quotes, guards, order steps, recovery (no DOM, no user-facing strings)",
10
10
  "license": "(MIT AND LGPL-3.0-only)",
11
11
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "check:pack": "node tools/check.mjs --only=pack",
22
22
  "check:pack-teeth": "node tools/run-teeth-isolated.mjs tools/check-pack-teeth.mjs",
23
23
  "check:guard-teeth": "node tools/run-teeth-isolated.mjs tools/check-guard-teeth.mjs",
24
+ "check:claim-teeth": "node tools/run-teeth-isolated.mjs tools/check-claim-teeth.mjs",
24
25
  "check:secrets": "node tools/check.mjs --only=secrets",
25
26
  "check:vendor-bundles": "node tools/check.mjs --only=vendor-bundles",
26
27
  "check:dleq-vectors": "node tools/check-dleq-vectors.mjs",
package/src/engine.mjs CHANGED
@@ -1,18 +1,11 @@
1
- // THE ENGINE SEAM, NOW SELF-CONTAINED.
1
+ // THE ENGINE SEAM.
2
2
  //
3
- // The engine modules the core depends on are mirrored under sdk/engine/ - byte-for-byte copies kept in
4
- // sync by tools/build-sdk-engine.mjs and guarded by tools/check-sdk-engine.mjs. This file is the ONLY
5
- // place that knows where the engine lives; no other SDK module does.
3
+ // The engine modules live under engine/. This file is the only place that knows where they live; no other SDK
4
+ // module does. The SDK is the source of truth for these modules: do not regenerate them from another repository.
6
5
  //
7
- // WHY A VERIFIED MIRROR, NOT A MOVE. The very same modules are loaded by the demo page in the browser
8
- // (www/js), and the production web root is www/ alone - the sdk/ directory is not served there (see
9
- // tools/serve.mjs). Lifting the files out of www/js would 404 every engine import on the live site, and
10
- // dozens of repository checks read those sources by their www/js path. So the single source of truth
11
- // stays www/js and the SDK carries a copy: any drift reddens check-sdk-engine, so it cannot diverge
12
- // silently (the same rule build-sweep uses for the sweep/rfq copies).
13
- //
14
- // The mirror is generated - never edit sdk/engine/ by hand. Change www/js, then run:
15
- // node tools/build-sdk-engine.mjs
6
+ // The page reaches the same protocol rules through its own bridge, but the package does not depend on the page's
7
+ // source tree. A rule that would be copied into both places must live here, in the package, and the bridge must
8
+ // read it from the package.
16
9
  export * as config from "../engine/core/config.js";
17
10
  export * as guards from "../engine/core/preSignGuards.js";
18
11
  export * as restore from "../engine/recovery/restore.js";
@@ -32,27 +25,25 @@ export * as halfenc from "../engine/atomic/halfenc.js";
32
25
  // The engine's EVM layer: talking to the chain (order terms, sending, reading) - through this seam.
33
26
  export * as evm from "../engine/evm/index.js";
34
27
  // THE DEX LEG'S OWN GUARDS - THROUGH THE SAME SEAM. priceGateVerdict ("the price is not the market") and
35
- // dexLegVerdict (amount coverage + price) live in www/js/evm/dex.js and are re-exported here so a route provider
28
+ // dexLegVerdict (amount coverage + price) live in engine/evm/dex.js and are re-exported here so a route provider
36
29
  // that is NOT the declared Uniswap path (CoWSwap, an aggregator) applies THE SAME guards rather than lookalikes.
37
30
  export * as dex from "../engine/evm/dex.js";
38
- // THE DEAL ENGINE NO LONGER LIVES IN www/js (#32, wave 3): the order flow moved into the package
39
- // (sdk/src/swap-flow.mjs) and is declared in sdk/index.d.ts. The page reaches it through the bridge, so the
40
- // mirror no longer carries core/swap-flow.js - what stays in the seam is the ORDER QUOTE source and the shared
41
- // CLAIM GAS LIMIT that the moved flow reads through this same seam. The order side is built by engine/atomic/order.js.
31
+ // THE DEAL ENGINE LIVES IN THE PACKAGE: the order flow is sdk/src/swap-flow.mjs and is declared in sdk/index.d.ts.
32
+ // The page reaches it through the bridge. What stays in the seam is the ORDER QUOTE source and the shared CLAIM
33
+ // GAS LIMIT that the flow reads through this same seam. The order side is built by engine/atomic/order.js.
42
34
 
43
35
  export * as rfqSource from "../engine/core/rfqSource.js";
44
36
  export * as claimGas from "../engine/evm/claimGas.js";
45
37
  export * as escrow from "../engine/evm/escrow.js";
46
38
  export * as halvesSweep from "../engine/monero/halvesSweep.js";
47
- // MONERO ADDRESSES - THROUGH THE SAME MODULE THE DEMO USES. The format, the network prefixes and the address
48
- // check live in www/js/monero/address.js (checkAddress: base58 + keccak256 + network), and the page uses it
49
- // too. The wallet adapter needs exactly networkFromShape: its own address must belong to the network named by
50
- // the core, and that is checked by the same code, not by a private prefix table.
39
+ // MONERO ADDRESSES. The format, the network prefixes and the address check live in engine/monero/address.js
40
+ // (checkAddress: base58 + keccak256 + network); the page uses the same module through its bridge. The wallet
41
+ // adapter needs exactly networkFromShape: its own address must belong to the network named by the core, and that
42
+ // is checked by the same code, not by a private prefix table.
51
43
  export * as xmrAddress from "../engine/monero/address.js";
52
- // THE unlock_time RULE AND THE BLOCK READER - FROM THE SAME MIRROR, NOT A COPY. A second copy of "the output
53
- // is barred until a boundary" would be a second truth about money, so the rule lives under www/js
54
- // (monero/unlock.js) together with the Monero block parser (monero/scan.js), and the SDK reads them through
55
- // the engine mirror. check-sdk-engine reddens on any drift, so the two cannot diverge silently.
44
+ // THE unlock_time RULE AND THE BLOCK READER. A second copy of "the output is barred until a boundary" would be a
45
+ // second truth about money, so the rule lives in engine/monero/unlock.js together with the Monero block parser
46
+ // (engine/monero/scan.js), and the SDK reads them through the engine seam. There is no external source to drift from.
56
47
  export * as xmrUnlock from "../engine/monero/unlock.js";
57
48
  export * as xmrScan from "../engine/monero/scan.js";
58
49
  // THE ADDRESS AND ITS PUBLIC KEYS, for the arrival check: the view secret and spend key are bound to the address,
package/src/index.mjs CHANGED
@@ -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
 
@@ -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
+ }
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // src/public/recovery.mjs only NAMES what the engine already offers; these declarations NAME the same thing for a
5
5
  // TypeScript consumer. Every signature is copied from the module the barrel re-exports
6
- // (`engine/recovery/recoveryFile.js`, itself a generated byte-for-byte copy of the engine source), and a symbol
6
+ // (`engine/recovery/recoveryFile.js`, the SDK's engine source for the recovery envelope), and a symbol
7
7
  // the barrel does not re-export is not declared here.
8
8
  //
9
9
  // NO DOM AND NO ARGUMENTS: the module touches WebCrypto (`crypto.subtle`), `btoa`/`atob` and the text encoders,
package/src/quotes.mjs CHANGED
@@ -10,6 +10,7 @@ import { claimGasGiftWei } from "../engine/evm/claimGas.js";
10
10
  import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
11
11
  import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
12
12
  import { requestFirmQuote } from "./relayFirmClient.mjs";
13
+ import { predictEscrow } from "./predictEscrow.mjs";
13
14
  import { readReadyWindow } from "./readyWindow.mjs";
14
15
  import { quoteLifeVerdict } from "./quotePolicy.mjs";
15
16
  // THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
@@ -290,11 +291,7 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
290
291
  : { commitHalfLocker: nodeHalf.commitHalf, edPointLocker: nodeHalf.edPoint, edViewPointLocker: result.edViewPointLocker };
291
292
  let escrow = null;
292
293
  try {
293
- const predicted = await evmCall({
294
- to: quote.factory,
295
- data: engine.evm.encodePredict({ ...result.orderQuote, ...lockerHalf, signature: result.orderQuote.signature }),
296
- });
297
- escrow = engine.evm.decodeAddress(predicted);
294
+ escrow = await predictEscrow({ quote: result.orderQuote, lockerHalf, call: evmCall });
298
295
  } catch {
299
296
  fail("quote-escrow-unchecked", { step: "factory", why: "predict-failed", factory: quote.factory });
300
297
  }
@@ -11,6 +11,10 @@ const ADDRESS = /^0x[0-9a-f]{40}$/;
11
11
  const HALF = /^[0-9a-f]{64}$/;
12
12
  const TXID = /^0x[0-9a-f]{64}$/;
13
13
  const DECIMAL = /^(0|[1-9][0-9]*)$/;
14
+ // RELAY-LEVEL ANSWERS ARE NOT THE SENDER'S REFUSAL. A rate limit, a malformed request or a version/quote problem
15
+ // describes the hop, not the sender; the half may not have been forwarded. They keep the conservative unknown
16
+ // outcome so the sender's slot is still read, instead of marking that sender as refused for good.
17
+ const RELAY_LEVEL_CODES = new Set(["rate_limited", "bad_request", "unsupported_version", "no_quote"]);
14
18
 
15
19
  /**
16
20
  * THE RELAY ORIGIN, NORMALISED ONCE. A claim is bound to the origin that answered the quote, so a trailing slash
@@ -42,9 +46,11 @@ export function halfTextOf(value) {
42
46
  * POST the half to the relay that answered the quote.
43
47
  *
44
48
  * A refusal from the relay is `quote-refused` with the provider's own code kept in `params.code`; the provider's
45
- * message is deliberately NOT copied, because it is not this package's user-facing text. A lost answer is
46
- * `claim-unknown`: the claim may have been sent, so a second call must begin by reading the escrow, never by
47
- * assuming that nothing happened. Only a validated transaction hash is a success.
49
+ * message is deliberately NOT copied, because it is not this package's user-facing text. A relay-level answer
50
+ * (`rate_limited`, `bad_request`, `unsupported_version`, `no_quote`) is `claim-unknown`: it names the hop, not the
51
+ * sender, and the half may not have been forwarded. A lost answer is `claim-unknown`: the claim may have been sent,
52
+ * so a second call must begin by reading the escrow, never by assuming that nothing happened. Only a validated
53
+ * transaction hash is a success.
48
54
  */
49
55
  export async function postRelayClaim({
50
56
  relayUrl,
@@ -88,6 +94,10 @@ export async function postRelayClaim({
88
94
  if (code === "claim-unknown" || code === "claim_unknown") {
89
95
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-timeout", code, status: response.status, outcome: "unknown" });
90
96
  }
97
+ if (code && RELAY_LEVEL_CODES.has(code)) {
98
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
99
+ code, status: response.status, outcome: "unknown" });
100
+ }
91
101
  if (code && version === 1) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
92
102
  // AN UNVERSIONED NON-2XX IS NOT A REFUSAL WE CAN READ. The claim may still have been sent, so it is unknown.
93
103
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-status", status: response.status, outcome: "unknown" });
@@ -95,6 +105,10 @@ export async function postRelayClaim({
95
105
  if (!answer || version !== 1) {
96
106
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer", outcome: "unknown" });
97
107
  }
108
+ if (code && RELAY_LEVEL_CODES.has(code)) {
109
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
110
+ code, status: response.status, outcome: "unknown" });
111
+ }
98
112
  if (code) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
99
113
 
100
114
  // ONLY A REAL TRANSACTION HASH IS A CLAIM. A body without one leaves the outcome unknown, whether the claim never
@@ -139,12 +139,30 @@ export async function requestFirmQuote({
139
139
  || wireText(published.relayId, "relay.relayId") !== wireText(response.body.relay, "relay")) {
140
140
  throw new SdkError("quote-refused", { step: "relay-info", why: "relay" });
141
141
  }
142
+ // THE OPERATOR'S OWN CLAIM SENDER. `GET /v1/relay` publishes the address the relay submits claims from; it is the
143
+ // first entry in the seller's ordered list. A malformed value is refused here rather than handed to a claim path.
144
+ let claimSender = null;
145
+ const publishedSender = published.claimSender;
146
+ if (publishedSender !== undefined && publishedSender !== null) {
147
+ // A NON-STRING IS NOT AN ADDRESS. Check the type before any coercion: `String({toString: null})` throws before
148
+ // the refusal can be named, and the caller would see a raw TypeError instead of quote-refused/claim-sender.
149
+ if (typeof publishedSender !== "string") {
150
+ throw new SdkError("quote-refused", { step: "relay-info", why: "claim-sender" });
151
+ }
152
+ if (publishedSender.trim() !== "") {
153
+ claimSender = publishedSender.trim().toLowerCase();
154
+ if (!/^0x[0-9a-f]{40}$/.test(claimSender)) {
155
+ throw new SdkError("quote-refused", { step: "relay-info", why: "claim-sender" });
156
+ }
157
+ }
158
+ }
142
159
  return {
143
160
  ...verified,
144
161
  // THE ORIGIN THAT ANSWERED, KEPT FOR THE LATER CLAIM. The seller has no wallet, so the claim goes back to the
145
162
  // same relay through `swaps.claimViaRelay`; the record stores this value and a different origin is refused.
146
163
  relayUrl: base,
147
164
  relay: response.body.relay ?? null,
165
+ claimSender,
148
166
  offered: response.body.offered ?? null,
149
167
  forwarded: response.body.forwarded ?? null,
150
168
  answer,
package/src/swap-flow.mjs CHANGED
@@ -17,15 +17,12 @@
17
17
  // no such function - the payable constructor moves the money - and there is no envelope in the order. Nor
18
18
  // does the escrow have a separate funding function: an order is either born with money or not born at all.
19
19
  //
20
- // THE CRYPTOGRAPHY LIVES UNDER www/js/atomic/* (mirrored as ../engine/atomic/*) AND IS CALLED ONLY THROUGH
21
- // THE IN-PROCESS ORDER BUILDER. There is no crypto here - here is the order.
20
+ // THE CRYPTOGRAPHY LIVES UNDER engine/atomic/* AND IS CALLED ONLY THROUGH THE IN-PROCESS ORDER BUILDER.
21
+ // There is no crypto here - here is the order.
22
22
  //
23
- // WHY IT IS IN THE PACKAGE NOW. The page used to import this module straight from www/js/core/swap-flow.js; the
24
- // core (www/js, mirrored under ../engine/) was the second home of the deal flow. That is exactly the debt
25
- // issue #32 pays off: the deal engine is business logic, so it belongs to the package (@ninsei-labs/sdk), and
26
- // the page reaches it through ONE seam (www/js/sdk/bridge.js) by module name, not by pulling a file out of
27
- // www/js. The engine modules it needs are still read through the same verified mirror (./engine.mjs); what moved
28
- // is the RULES, not the crypto.
23
+ // WHY IT IS IN THE PACKAGE. The deal engine is business logic, so it belongs to the package (@ninsei-labs/sdk).
24
+ // The page reaches it through ONE seam (its bridge) by module name. The engine modules it needs are read through
25
+ // ./engine.mjs; what lives here is the RULES, not the crypto.
29
26
  import { SdkError } from "./errors.mjs";
30
27
  import * as engine from "./engine.mjs";
31
28
  // THE HALF'S COMMITMENT, COMPUTED LOCALLY. The escrow checks the low 160 bits of `keccak256(x||y)` of `half*G`
@@ -52,8 +49,8 @@ const {
52
49
  } = engine.escrow;
53
50
  // THE COUNTERPARTY GUARDS: whether a stand-in may be signed on this chain.
54
51
  const { liveOrderSlotsVerdict, counterpartyVerdict } = engine.guards;
55
- // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the mirror, so the page and
56
- // the package never keep a second copy of these rules.
52
+ // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the engine seam, so the page
53
+ // and the package never keep a second copy of these rules.
57
54
  const { orderContextString } = engine.orderContext;
58
55
  const { requestOrderQuote, checkOrderQuoteShape } = engine.rfqSource;
59
56
  const { CLAIM_GAS_LIMIT } = engine.claimGas;