@ninsei-labs/sdk 0.60.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +81 -18
  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 +6 -10
  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 +17 -42
  14. package/engine/core/finality.js +0 -4
  15. package/engine/core/format.js +1 -5
  16. package/engine/core/preSignGuards.js +0 -4
  17. package/engine/core/rfqSource.js +0 -3
  18. package/engine/core/sellWindow.js +1 -5
  19. package/engine/core/store.js +11 -7
  20. package/engine/core/swap.js +3 -7
  21. package/engine/evm/amounts.js +2 -6
  22. package/engine/evm/asyncRoute.js +3 -7
  23. package/engine/evm/auth.js +0 -4
  24. package/engine/evm/claimGas.js +2 -6
  25. package/engine/evm/dex.js +1 -5
  26. package/engine/evm/escrow.js +0 -4
  27. package/engine/evm/factory.js +1 -5
  28. package/engine/evm/fees.js +62 -4
  29. package/engine/evm/funding.js +73 -71
  30. package/engine/evm/gasReserve.js +10 -4
  31. package/engine/evm/index.js +7 -11
  32. package/engine/evm/injected.js +0 -4
  33. package/engine/evm/permit.js +0 -4
  34. package/engine/evm/prices.js +3 -4
  35. package/engine/evm/session.js +1 -5
  36. package/engine/mock/chain.js +0 -4
  37. package/engine/monero/address.js +4 -5
  38. package/engine/monero/arrivalRead.js +15 -2
  39. package/engine/monero/halvesSweep.js +0 -4
  40. package/engine/monero/keyImage.js +146 -0
  41. package/engine/monero/keys.js +1 -0
  42. package/engine/monero/mnemonic.js +2 -1
  43. package/engine/monero/node.js +1 -4
  44. package/engine/monero/scan.js +12 -2
  45. package/engine/monero/swapKeys.js +0 -4
  46. package/engine/monero/unlock.js +2 -6
  47. package/engine/monero/wallet.js +0 -3
  48. package/engine/recovery/recoveryFile.js +31 -89
  49. package/engine/recovery/restore.js +0 -4
  50. package/engine/sdk/bridge.js +24 -58
  51. package/engine/ui/dom.js +0 -4
  52. package/engine/ui/walletModal.js +0 -4
  53. package/index.d.ts +436 -42
  54. package/package.json +22 -3
  55. package/src/actions.mjs +72 -6
  56. package/src/addressGuard.mjs +16 -0
  57. package/src/codes.mjs +26 -9
  58. package/src/config.mjs +56 -3
  59. package/src/decline.mjs +23 -74
  60. package/src/engine.mjs +17 -26
  61. package/src/firmRequest.mjs +80 -0
  62. package/src/index.mjs +17 -28
  63. package/src/legs/cow.mjs +2 -2
  64. package/src/legs/evm.mjs +20 -12
  65. package/src/legs/kyber-spec.mjs +2 -2
  66. package/src/legs/kyber.mjs +1 -1
  67. package/src/legs/shape.mjs +1 -1
  68. package/src/legs/uniswaprelay.mjs +16 -4
  69. package/src/legs/uniswapx.mjs +29 -7
  70. package/src/levelsWalkSpec.mjs +1 -1
  71. package/src/lock.mjs +18 -37
  72. package/src/provider/envFile.mjs +3 -3
  73. package/src/provider/sign.mjs +3 -3
  74. package/src/public/evm.d.ts +84 -0
  75. package/src/public/evm.mjs +20 -0
  76. package/src/public/order.mjs +1 -1
  77. package/src/public/provider.mjs +1 -1
  78. package/src/public/recovery.d.ts +4 -3
  79. package/src/public/recovery.mjs +1 -1
  80. package/src/public/xmr.d.ts +2 -2
  81. package/src/quoteEip712Spec.mjs +4 -4
  82. package/src/quotes.mjs +52 -11
  83. package/src/recovery-key.mjs +7 -3
  84. package/src/relayClaim.mjs +17 -3
  85. package/src/relayFirmClient.mjs +4 -0
  86. package/src/relayQuote.mjs +1 -0
  87. package/src/sim.mjs +1 -1
  88. package/src/swap-flow.mjs +28 -41
  89. package/src/swaps.mjs +217 -123
  90. package/src/sweep-inputs.mjs +61 -0
  91. package/src/sweep-reconcile.mjs +71 -0
  92. package/src/sweep-restore.mjs +38 -9
  93. package/src/sweep.mjs +164 -10
  94. package/src/version.mjs +1 -1
  95. package/src/wallet.mjs +1 -1
  96. package/src/xmr-arrival.mjs +1053 -57
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,
@@ -0,0 +1,80 @@
1
+ // A FIRM REQUEST'S DEADLINES, FROM THE MAKER'S SIGNED WINDOW AND THE CHAIN'S CLOCK.
2
+ //
3
+ // The maker publishes `readyMinSeconds..readyMaxSeconds` and `settlementMinSeconds..settlementMaxSeconds`; the client
4
+ // must place `readyBy` and `t1` inside those ranges, not on their edges. The node later judges the request by its own
5
+ // clock, which is later than the chain block the card read, so the lower edge needs more room than the upper one.
6
+ import { SdkError } from "./errors.mjs";
7
+ import { readReadyWindow } from "./readyWindow.mjs";
8
+
9
+ export const READY_MARGIN_SEC = 150;
10
+ export const DEADLINE_MARGIN_SEC = 60;
11
+
12
+ const int = (value) => {
13
+ const n = Number(value);
14
+ return Number.isSafeInteger(n) ? n : null;
15
+ };
16
+
17
+ const inside = (min, max, margin) => (max - min >= 2 * margin
18
+ ? min + margin
19
+ : min + Math.floor((max - min) / 2));
20
+
21
+ const readyInside = (min, max) => {
22
+ const room = max - min;
23
+ if (room < 2 * DEADLINE_MARGIN_SEC) return min + Math.floor(room / 2);
24
+ return min + Math.min(READY_MARGIN_SEC, room - DEADLINE_MARGIN_SEC);
25
+ };
26
+
27
+ /**
28
+ * Pick the one signed window for a market, side and Monero network. A missing or ambiguous match is a refusal, never
29
+ * the first window on the list: two networks for the same market are a real case, and picking the wrong one changes
30
+ * the order's Monero network.
31
+ */
32
+ export function firmWindowFor({ features, side, market, xmrNetwork } = {}) {
33
+ if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
34
+ if (side !== "ask" && side !== "bid") throw new SdkError("bad-input", { field: "side" });
35
+ if (typeof market !== "string" || !market) throw new SdkError("bad-input", { field: "market" });
36
+ if (typeof xmrNetwork !== "string" || !xmrNetwork) throw new SdkError("bad-input", { field: "xmrNetwork" });
37
+ if (!Array.isArray(features.firmWindows)) throw new SdkError("bad-input", { field: "features.firmWindows" });
38
+ const matches = features.firmWindows.filter((entry) => entry && entry.market === market && entry.side === side
39
+ && entry.xmrNetwork === xmrNetwork);
40
+ if (matches.length !== 1) {
41
+ throw new SdkError("bad-input", { field: "features.firmWindows",
42
+ why: matches.length ? "duplicate-window" : "window", market, side, xmrNetwork });
43
+ }
44
+ return readReadyWindow(matches[0], { side, field: "features.firmWindows" });
45
+ }
46
+
47
+ /**
48
+ * The deadlines for one signed window at the chain's `chainNow` (Unix seconds): `readyBy` and `t1`, in chain seconds.
49
+ * The margins are the same ones the site used: 150 s from the lower readiness edge, 60 s from the upper readiness
50
+ * edge and from both settlement edges.
51
+ */
52
+ export function firmDeadlines(window, chainNow) {
53
+ const ready = readReadyWindow(window);
54
+ const now = int(chainNow);
55
+ if (now === null || now <= 0) throw new SdkError("bad-input", { field: "chainNow" });
56
+ const settleMin = int(ready.settlementMinSeconds);
57
+ const settleMax = int(ready.settlementMaxSeconds);
58
+ if (settleMin === null || settleMax === null || settleMin <= 0 || settleMax < settleMin) {
59
+ throw new SdkError("bad-input", { field: "features.firmWindows", why: "settlement" });
60
+ }
61
+ const readyBy = now + readyInside(ready.readyMinSeconds, ready.readyMaxSeconds);
62
+ const t1 = readyBy + inside(settleMin, settleMax, DEADLINE_MARGIN_SEC);
63
+ if (!(t1 > readyBy)) throw new SdkError("bad-input", { field: "features.firmWindows", why: "deadlines" });
64
+ return { readyBy, t1 };
65
+ }
66
+
67
+ /**
68
+ * The firm-request builder: one window, selected by market, side and Monero network, and its deadlines on the chain
69
+ * clock. The caller spreads `readyBy`/`t1` into the order it then gives to `quotes.firmRelay`.
70
+ */
71
+ export function firmRequest({ features, side, market, xmrNetwork, chainNow } = {}) {
72
+ const window = firmWindowFor({ features, side, market, xmrNetwork });
73
+ return Object.freeze({
74
+ market,
75
+ side,
76
+ xmrNetwork,
77
+ window,
78
+ ...firmDeadlines(window, chainNow),
79
+ });
80
+ }
package/src/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // THE SDK ENTRY POINT. Assembles the facades and holds rules common to all: no DOM, no texts, no windows.
2
- import { buildConfig } from "./config.mjs";
2
+ import { buildConfig, escrowOverrideOf } from "./config.mjs";
3
3
  import { factoryCodesForChain, implementationCodesForChain } from "./factoryPolicy.mjs";
4
4
  import { createQuotes } from "./quotes.mjs";
5
5
  import { createPreflight } from "./preflight.mjs";
@@ -44,6 +44,7 @@ const normalizeOptions = (options) => {
44
44
  if (settlement.vm !== undefined && (typeof settlement.vm !== "string" || !settlement.vm)) {
45
45
  fail("bad-input", { field: "settlement.vm" });
46
46
  }
47
+ const escrowOverride = escrowOverrideOf(settlement);
47
48
  if (typeof o.xmrNetwork !== "string" || !o.xmrNetwork) fail("bad-input", { field: "xmrNetwork" });
48
49
  const mode = o.mode === undefined ? "live" : o.mode;
49
50
  if (mode !== "live" && mode !== "sim") fail("bad-input", { field: "mode", known: ["live", "sim"] });
@@ -83,10 +84,10 @@ const normalizeOptions = (options) => {
83
84
  // substitution: the calls go to the network whose address the registry returned. The shape is the same as the
84
85
  // lock seam: ({to, data}) -> hex.
85
86
  if (o.evmCall !== undefined && typeof o.evmCall !== "function") fail("bad-input", { field: "evmCall" });
86
- // THE CODE-READ SEAM (issue #103): ({address}) -> hex code, for the extcodehash check of the factory. Same
87
+ // THE CODE-READ SEAM: ({address}) -> hex code, for the extcodehash check of the factory. Same
87
88
  // rule as evmCall - a read brought from outside, not a substitution of the chain.
88
89
  if (o.evmCode !== undefined && typeof o.evmCode !== "function") fail("bad-input", { field: "evmCode" });
89
- // THE LOG-READ SEAM (issue #40): ({ address, topics, fromBlock, toBlock }) -> logs. Needed for the maker's
90
+ // THE LOG-READ SEAM: ({ address, topics, fromBlock, toBlock }) -> logs. Needed for the maker's
90
91
  // decline, which is the escrow's `Declined` EVENT - the escrow has no getter that names it, and `status()` reads
91
92
  // a decline and an ordinary refund the same way. By default the logs are read through the page's wallet, the
92
93
  // same provider the chain read uses. Same rule as evmCall: a READ of the escrow's own event, not a node
@@ -102,12 +103,12 @@ const normalizeOptions = (options) => {
102
103
  const a = o.allowedProviders;
103
104
  if (!Array.isArray(a) && typeof a !== "function") fail("bad-input", { field: "allowedProviders" });
104
105
  }
105
- // THE INTERFACE'S FACTORY POLICY (issue #103): an array of code hashes (extcodehash) the interface accepts.
106
+ // THE INTERFACE'S FACTORY POLICY: an array of code hashes (extcodehash) the interface accepts.
106
107
  // Like allowedProviders - a POLICY list, not proof; empty/absent means "no policy".
107
108
  if (o.knownFactoryCodes !== undefined && o.knownFactoryCodes !== null && !Array.isArray(o.knownFactoryCodes)) {
108
109
  fail("bad-input", { field: "knownFactoryCodes" });
109
110
  }
110
- // THE INTERFACE'S ESCROW-IMPLEMENTATION POLICY (issue #114): an array of code hashes of known implementations
111
+ // THE INTERFACE'S ESCROW-IMPLEMENTATION POLICY: an array of code hashes of known implementations
111
112
  // of the escrow - the code every order's clone delegatecalls. The client checks the pair (implementation,
112
113
  // implementationCodeHash) the factory carries, exactly as the factory does at creation; this list pins WHICH
113
114
  // builds the interface accepts. Same rule as knownFactoryCodes: a POLICY list, empty/absent means "no policy"
@@ -115,7 +116,7 @@ const normalizeOptions = (options) => {
115
116
  if (o.knownImplementationCodes !== undefined && o.knownImplementationCodes !== null && !Array.isArray(o.knownImplementationCodes)) {
116
117
  fail("bad-input", { field: "knownImplementationCodes" });
117
118
  }
118
- // THE INTERFACE'S ADDRESS DENYLIST (issue #16): policy, like allowedProviders - addresses the interface will not
119
+ // THE INTERFACE'S ADDRESS DENYLIST: policy, like allowedProviders - addresses the interface will not
119
120
  // trade to or from. An empty/absent list means "no check"; an entry that is not a string is a typo, not a silent
120
121
  // no-op. The SDK fetches nothing: the interface brings the list in.
121
122
  if (o.denylist !== undefined && o.denylist !== null) {
@@ -136,7 +137,7 @@ const normalizeOptions = (options) => {
136
137
  }
137
138
  }
138
139
  return {
139
- settlement: { chain: settlement.chain, vm: settlement.vm },
140
+ settlement: { chain: settlement.chain, vm: settlement.vm, escrow: escrowOverride },
140
141
  xmrNetwork: o.xmrNetwork,
141
142
  assetsBase: typeof o.assetsBase === "string" && o.assetsBase ? o.assetsBase : "/",
142
143
  mode,
@@ -173,28 +174,16 @@ export function createNinsei(options) {
173
174
  nodes: o.nodes,
174
175
  addNodes: o.addNodes,
175
176
  });
176
- // THE NETWORK'S PINS REACH THE CORE. The bridge passed them explicitly; a caller with default options did not,
177
- // so the factory policy was null and the quote could name any factory. An explicit caller list still wins.
177
+ // The network pins reach the core. An explicit caller list wins.
178
178
  const knownFactoryCodes = factoryCodesForChain({ chain: config.settlement.chain, knownFactoryCodes: o.knownFactoryCodes });
179
179
  const knownImplementationCodes = implementationCodesForChain({ chain: config.settlement.chain, knownImplementationCodes: o.knownImplementationCodes });
180
180
  const leg = legFor(config.settlement.vm);
181
181
  const wallet = createWallet({ settlement: config.settlement.chain, leg });
182
- // THE GUARDS READ THE NETWORK UNDER THE NAME evmNetwork, WHILE THE CONFIGURATION BUILDER RETURNS IT AS
183
- // settlement.chain (preflight.mjs: both chain.nativeSymbol and config.evmNetwork.id). The names diverged, and
184
- // ANY guard call failed with a TypeError - without a code, that is, not as a refusal but as a breakdown. A
185
- // live swap start was therefore impossible in principle: preflight is called as the first step of start. We
186
- // hand the guards a record of the same network under the name they expect; from outside it is the same config
187
- // as before.
182
+ // The guards read the network as evmNetwork. Pass the same network under both names.
188
183
  const preflight = createPreflight({ config: { ...config, evmNetwork: config.settlement.chain }, wallet, limits: config.limits });
189
184
  const sim = o.mode === "sim" ? createSim() : null;
190
- // THE STORAGE THE INTERFACE BROUGHT BECOMES THE CORE'S STORAGE: unfinished swaps and the agent session live
191
- // where the interface decided (browser storage, memory, a server). Without the option the core takes its
192
- // default: web storage if it is present in the environment, otherwise memory.
193
- // ONE CLIENT, ONE STORE. A second client with another adapter used to replace the module-wide store, so the
194
- // first client listed the second's swaps and could delete them. Even a client that brought no adapter binds the
195
- // current one, so a later explicit store cannot take it over.
196
- // ONE CLIENT, ONE STORE - WITHOUT A PROCESS-WIDE EXCLUSIVE BINDING. Each facade gets a store over its own
197
- // adapter; two clients with different storages coexist and neither can take over the other's records.
185
+ // The storage option becomes the core's storage. Without it the core uses web storage or memory.
186
+ // One client, one store: each facade gets a store over its own adapter.
198
187
  const store = engine.store.createStore(o.storage || engine.store.storage());
199
188
  // THE CHAIN READ AND THE ALLOW-LIST GO INTO THE QUOTE CHECK: without the read the signature certifies itself,
200
189
  // so the same evmCall seam the lock and the actions use is handed to the quotes too.
@@ -251,7 +240,7 @@ export function createNinsei(options) {
251
240
  // THE ORDER DEADLINES (t1, readyBy, termsHash) from the chain: the screen needs them to say whether the
252
241
  // person is in the dead zone.
253
242
  deadlines: (escrow) => orderFlow.orderDeadlines(escrow, orderDeps),
254
- // THE MAKER'S DECLINE, READ FROM THE ESCROW (issue #40): the `Declined` event, which is the on-chain fact
243
+ // THE MAKER'S DECLINE, READ FROM THE ESCROW: the `Declined` event, which is the on-chain fact
255
244
  // that tells a decline apart from an ordinary refund. The answer carries the state and the node's own token
256
245
  // and NOTHING ELSE - no reason, no category, no provider. `checked: false` means the chain was not read,
257
246
  // which is NOT the same as "the escrow did not decline".
@@ -261,16 +250,16 @@ export function createNinsei(options) {
261
250
  quotes: {
262
251
  // THE ONLY QUOTE PATH: one recovery key in, a signed orderQuote and the maker's view half out.
263
252
  firmRelay: (request) => quotes.firmRelay(request),
253
+ // The deadlines for one signed firm window, by market, side and Monero network on the chain's clock.
254
+ firmRequest: (request) => quotes.firmRequest(request),
264
255
  },
265
256
  // READING STATE WORKS, STARTING IS NAMED HONESTLY: list/get raise swaps from storage after a page reload;
266
257
  // start holds the step order and runs into the step that creates the record (stage 2).
267
258
  // THE MODE AND THE MONERO NETWORK GO INTO THE SWAP START: in the sandbox the counterparty's side is built by
268
259
  // a stand-in, on a live chain - only from the quote (a stand-in there would mean money against a
269
260
  // non-existent side), and the network is needed to build the shared Monero address.
270
- // THE CHAIN READER GOES INTO THE SWAP START: it will check the escrow address, the order state and the fee
271
- // before signing.
272
- // THE CHAIN READER GOES INTO THE SWAP START: it will check the escrow address, the order state and the fee
273
- // before signing. The Monero watch reads the chain through the same seam; there is no backend watcher.
261
+ // The chain reader goes into the swap start. It checks the escrow address, the order state and the fee before
262
+ // signing. The Monero watch uses the same seam; there is no backend watcher.
274
263
  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
264
  // THE LOG SEAM FOR THE DECLINE CHECK: the watch asks the escrow for its `Declined` event on every tick, so
276
265
  // a declined order stops the wait at once instead of running to `xmr-timeout`.
package/src/legs/cow.mjs CHANGED
@@ -137,7 +137,7 @@ export function cowOrderSubmission({ order, signature, owner, signingScheme = "e
137
137
 
138
138
  /**
139
139
  * THE PROVIDER'S PLAN. For an async provider the plan is the INTENT: the signed order that will be submitted, with
140
- * the typed data, the digest and the UID, plus what ends execution. Returns { ok, ... } - a value.
140
+ * the typed data, the digest and the UID, plus what ends execution. Returns { ok,... } - a value.
141
141
  */
142
142
  export function cowPlan(request = {}) {
143
143
  const intent = buildCowIntent(request);
@@ -234,7 +234,7 @@ export async function cowOrderStatus({ uid, chainId, fetchImpl = null, timeoutMs
234
234
  * with a timeout. Returns:
235
235
  * { ok: true, done: true, settled: true, status: "fulfilled" } - the swap settled;
236
236
  * { ok: true, done: true, settled: false, status: "cancelled" | "expired" } - the order is finally dead;
237
- * { ok: false, code: "cow-not-settled" | "cow-unreachable" | "cow-bad-response" | ... } - a NAMED refusal.
237
+ * { ok: false, code: "cow-not-settled" | "cow-unreachable" | "cow-bad-response" |... } - a NAMED refusal.
238
238
  * "Not settled in time" is its OWN code: "we did not wait long enough" is a state of the order, not a breakdown.
239
239
  * The clock and the sleep are injectable so the wait is testable without real time.
240
240
  */
package/src/legs/evm.mjs CHANGED
@@ -29,7 +29,15 @@ export const sameChain = (walletChainIdValue, chain) => {
29
29
  // match is checked by tools/check-sdk.mjs - it reads the engine's registry and fails if they diverge.
30
30
  export const BALANCE_OF_SELECTOR = "0x70a08231";
31
31
 
32
- const toMinimal = (hex) => {
32
+ const ETH_QUANTITY = /^0x(?:0|[1-9a-f][0-9a-f]*)$/i;
33
+ const ABI_WORD = /^0x[0-9a-fA-F]{64}$/;
34
+
35
+ // BALANCE ANSWERS HAVE EXACT FORMATS. A JSON-RPC ETH quantity and a 32-byte ABI word are different answers; anything
36
+ // else is unknown, never zero. `BigInt("")` is 0n, which is exactly why an empty or malformed answer must be refused
37
+ // before the conversion.
38
+ const toMinimal = (hex, kind) => {
39
+ if (typeof hex !== "string") return null;
40
+ if (kind === "eth" ? !ETH_QUANTITY.test(hex) : !ABI_WORD.test(hex)) return null;
33
41
  try {
34
42
  return BigInt(hex).toString(10);
35
43
  } catch {
@@ -50,10 +58,10 @@ export async function balances({ driver, address, tokens }) {
50
58
  let amount = null;
51
59
  try {
52
60
  if (token.address === null) {
53
- amount = toMinimal(await driver.request({ method: "eth_getBalance", params: [address, "latest"] }));
61
+ amount = toMinimal(await driver.request({ method: "eth_getBalance", params: [address, "latest"] }), "eth");
54
62
  } else {
55
63
  const data = BALANCE_OF_SELECTOR + addrWord(address);
56
- amount = toMinimal(await driver.request({ method: "eth_call", params: [{ to: token.address, data }, "latest"] }));
64
+ amount = toMinimal(await driver.request({ method: "eth_call", params: [{ to: token.address, data }, "latest"] }), "token");
57
65
  }
58
66
  } catch {
59
67
  amount = null;
@@ -101,25 +109,25 @@ const ROUTE_PROVIDERS = {
101
109
  },
102
110
  // COWSWAP - AN INTENT AUCTION: "async". The person signs an intent, and the settlement arrives LATER as a separate
103
111
  // transaction sent by someone else. Its record therefore carries `settled(...)` - what ends its execution (the
104
- // order book reporting the order settled or finally dead). The provider itself lives in ./cow.mjs.
112
+ // order book reporting the order settled or finally dead). The provider itself lives in./cow.mjs.
105
113
  cowswap: cowProvider,
106
114
  // KYBERSWAP LIMIT ORDER - A SECOND INTENT AUCTION, ALSO "async". Same role as CoW (the person signs an
107
115
  // order, someone else settles it later), a different book and contract. It is the LIQUIDITY leg: its order
108
- // trades ERC20 against ERC20 and settles WETH, not native coin (see the scope note in ./kyber.mjs). The
109
- // provider itself lives in ./kyber.mjs.
116
+ // trades ERC20 against ERC20 and settles WETH, not native coin (see the scope note in./kyber.mjs). The
117
+ // provider itself lives in./kyber.mjs.
110
118
  kyberswap: kyberProvider,
111
119
  // UNISWAPX - A THIRD INTENT AUCTION, ALSO "async". Same role as CoW (the person signs an order, someone else
112
120
  // settles it later) and the same native capability (an output may be the NATIVE sentinel), so it is a SECOND
113
121
  // native leg as well as a single native route. Unlike CoW, publishing needs the Uniswap Trading API and an API
114
- // key and the order is cosigned by Uniswap Labs (see the scope note in ./uniswapx.mjs). The provider itself
115
- // lives in ./uniswapx.mjs.
122
+ // key and the order is cosigned by Uniswap Labs (see the scope note in./uniswapx.mjs). The provider itself
123
+ // lives in./uniswapx.mjs.
116
124
  uniswapx: uniswapxProvider,
117
125
  // THE RELAYED UNISWAP ROUTE - A FOURTH INTENT AUCTION, ALSO "async", AND THE KEY-FREE ONE. Same role as CoW (the
118
126
  // person signs an order, someone else settles it later) and the same native capability (the relayed swap unwraps
119
127
  // to native), so it is a THIRD native leg as well as a single native route. Its discovery path is the point:
120
128
  // Uniswap's own relayer repository documents NO submission endpoint and NO gossip service for a signed relay
121
129
  // order, so this provider refuses that step BY NAME ("uniswap-relay-no-discovery") instead of inventing one (see
122
- // the scope note in ./uniswaprelay.mjs). The provider itself lives in ./uniswaprelay.mjs.
130
+ // the scope note in./uniswaprelay.mjs). The provider itself lives in./uniswaprelay.mjs.
123
131
  uniswaprelay: uniswapRelayProvider,
124
132
  };
125
133
 
@@ -134,7 +142,7 @@ export const routeProviderFor = (id) => ROUTE_PROVIDERS[id] || null;
134
142
  * synchronous would fund an escrow with nothing behind it - so it is refused BY NAME, with a `reason` token (the
135
143
  * same shape of refusal the level book uses), not assumed to be synchronous.
136
144
  *
137
- * Returns { ok: true, provider } or { ok: false, reason, ... } - a refusal as a VALUE, not an exception: the
145
+ * Returns { ok: true, provider } or { ok: false, reason,... } - a refusal as a VALUE, not an exception: the
138
146
  * caller keeps its own wording for the token.
139
147
  */
140
148
  export const requireSyncProvider = (id) => {
@@ -150,7 +158,7 @@ export const requireSyncProvider = (id) => {
150
158
  * THE GATE OF A PATH THAT ASSUMES AN ASYNCHRONOUS INTENT. The mirror of requireSyncProvider: it accepts a provider
151
159
  * whose swap settles in a LATER, separate action, and refuses by NAME - never silently - a provider that is
152
160
  * unknown, that is in fact synchronous, or that declares itself asynchronous without naming what ends execution
153
- * (`settled`). Refusals are VALUES: { ok: true, provider } or { ok: false, reason, ... }.
161
+ * (`settled`). Refusals are VALUES: { ok: true, provider } or { ok: false, reason,... }.
154
162
  */
155
163
  export const requireAsyncProvider = (id) => {
156
164
  const provider = routeProviderFor(id);
@@ -191,7 +199,7 @@ export const providerSettles = (provider) => (provider && provider.settles ? pro
191
199
  * CAN THIS PROVIDER CARRY A NATIVE NEED ALL THE WAY - a VALUE, by name.
192
200
  * { ok: true, settles: "native", provider } - it settles native: it can be the native leg;
193
201
  * { ok: false, reason: "settles-wrapped", settles, provider } - wrapped native only: a liquidity leg at most;
194
- * { ok: false, reason: "settles-unstated", settles: null, ... } - it does not say: refused, never assumed native.
202
+ * { ok: false, reason: "settles-unstated", settles: null,... } - it does not say: refused, never assumed native.
195
203
  */
196
204
  export const carriesNativeVerdict = (provider) => {
197
205
  const settles = providerSettles(provider);
@@ -51,7 +51,7 @@ export const KYBER_DOMAIN_NAME = ["Kyber", "DSLO", "Protocol"].join(" ");
51
51
  export const KYBER_DOMAIN_VERSION = "1";
52
52
 
53
53
  // The limit order contract that verifies the signature; identical on every network KyberSwap serves
54
- // (docs.kyberswap.com, "Contracts & Addresses": Ethereum, BSC, Arbitrum, Polygon, ... all DSLOProtocol 0xcab2...).
54
+ // (docs.kyberswap.com, "Contracts & Addresses": Ethereum, BSC, Arbitrum, Polygon,... all DSLOProtocol 0xcab2...).
55
55
  export const KYBER_LIMIT_ORDER_CONTRACT = "0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C";
56
56
 
57
57
  // The type strings, assembled from their fields so the order is the single source of truth here (as in DSOrderMixin).
@@ -106,7 +106,7 @@ const concat = (...arrays) => {
106
106
  return out;
107
107
  };
108
108
  // BYTES ARE ACCEPTED IN EITHER FORM: the order book returns some hex fields WITHOUT a 0x prefix and others WITH one
109
- // (docs.kyberswap.com, Taker API: signature, getMakerAmount, ... are returned without a 0x prefix; an empty value
109
+ // (docs.kyberswap.com, Taker API: signature, getMakerAmount,... are returned without a 0x prefix; an empty value
110
110
  // means empty bytes). Both are the same bytes, so both are accepted; an empty value is empty bytes.
111
111
  const hexToBytes = (hex) => {
112
112
  const h = String(hex === undefined || hex === null ? "" : hex).replace(/^0x/, "");
@@ -366,7 +366,7 @@ export async function kyberOrderStatus({ id, chainId, maker, fetchImpl = null, t
366
366
  * with a timeout. Returns:
367
367
  * { ok: true, done: true, settled: true, status: "filled" } - the swap settled;
368
368
  * { ok: true, done: true, settled: false, status: "cancelled" | "expired" } - the order is finally dead;
369
- * { ok: false, code: "kyber-not-settled" | "kyber-unreachable" | "kyber-bad-response" | ... } - a NAMED refusal.
369
+ * { ok: false, code: "kyber-not-settled" | "kyber-unreachable" | "kyber-bad-response" |... } - a NAMED refusal.
370
370
  * "Not settled in time" is its OWN code: "we did not wait long enough" is a state of the order, not a breakdown. The
371
371
  * clock and the sleep are injectable so the wait is testable without real time.
372
372
  */
@@ -16,7 +16,7 @@ export const SHAPES = [SYNC, ASYNC];
16
16
 
17
17
  /**
18
18
  * IS A PROVIDER COMPLETE - may a path trust it. An answer as a VALUE, not an exception: { ok: true, shape } or
19
- * { ok: false, reason, ... }.
19
+ * { ok: false, reason,... }.
20
20
  *
21
21
  * The rule that matters: an ASYNCHRONOUS provider MUST declare what ends its execution - `settled(...)`, a check
22
22
  * that reads the outcome and answers whether the swap has ended and with what. A provider that cannot say this is
@@ -307,13 +307,25 @@ export async function uniswapRelayStatus({ orderHash, chainId = null, reactor =
307
307
  if (!read.ok) return read;
308
308
  const logs = read.logs;
309
309
  if (!Array.isArray(logs)) return refusal("uniswap-relay-bad-response", { where: "logs", got: typeof logs });
310
- const ours = logs.filter((log) => {
310
+ const expectedAddress = String(target).toLowerCase();
311
+ const topicMatches = (log) => {
311
312
  if (!log || !Array.isArray(log.topics)) return false;
312
313
  const t0 = String(log.topics[0] || "").toLowerCase();
313
314
  const t1 = String(log.topics[1] || "").toLowerCase();
314
315
  return t0 === UNISWAPRELAY_EVENT_TOPIC0.toLowerCase() && t1 === String(orderHash).toLowerCase();
315
- });
316
- if (logs.length > 0 && ours.length === 0) return refusal("uniswap-relay-bad-response", { where: "logs", detail: "topics-mismatch" });
316
+ };
317
+ // THE REACTOR'S OWN EVENT, NOT JUST THE RIGHT TOPICS. A log from another contract, a removed log, or a log without
318
+ // an address is not this order's settlement; the read must not turn a foreign answer into `filled`.
319
+ const ours = logs.filter((log) => topicMatches(log)
320
+ && String(log.address || "").toLowerCase() === expectedAddress
321
+ && log.removed !== true);
322
+ if (logs.length > 0 && ours.length === 0) {
323
+ const relevant = logs.filter(topicMatches);
324
+ const detail = relevant.length === 0
325
+ ? "topics-mismatch"
326
+ : (relevant.some((log) => log.removed === true) ? "removed" : "foreign-address");
327
+ return refusal("uniswap-relay-bad-response", { where: "logs", detail });
328
+ }
317
329
  if (ours.length > 0) return { ok: true, status: UNISWAPRELAY_SETTLED_STATUS, log: ours[0] };
318
330
  // No event: still open, unless the deadline (unix seconds) has already passed.
319
331
  if (deadline !== null && deadline !== undefined) {
@@ -328,7 +340,7 @@ export async function uniswapRelayStatus({ orderHash, chainId = null, reactor =
328
340
  * hash exists or the order is finally dead, with a timeout. Returns:
329
341
  * { ok: true, done: true, settled: true, status: "filled" } - the reactor relayed the order;
330
342
  * { ok: true, done: true, settled: false, status: "expired" } - the deadline passed with no event;
331
- * { ok: false, code: "uniswap-relay-not-settled" | "uniswap-relay-unreachable" | ... } - a NAMED refusal.
343
+ * { ok: false, code: "uniswap-relay-not-settled" | "uniswap-relay-unreachable" |... } - a NAMED refusal.
332
344
  * This observes the REAL on-chain effect (the event), never an answer from a service. The clock and the sleep are
333
345
  * injectable so the wait is testable without real time.
334
346
  */
@@ -128,8 +128,14 @@ export function buildUniswapxIntent(request = {}) {
128
128
  if (!net) return { ...refusal("uniswapx-unknown-network", { chainId: Number.isFinite(chainId) ? chainId : null }), known: Object.keys(UNISWAPX_NETWORKS).map(Number) };
129
129
  const swapper = request.swapper;
130
130
  const recipient = request.recipient === undefined || request.recipient === null ? swapper : request.recipient;
131
+ const reactor = request.reactor === undefined || request.reactor === null ? net.reactor : request.reactor;
132
+ // THE REACTOR IS NOT A CALLER CHOICE ON THIS PATH. A different address would sign an order another reactor may
133
+ // accept, and the status read below is bound to the network's reactor. Refuse it by name rather than override.
134
+ if (!isAddress(reactor) || String(reactor).toLowerCase() !== String(net.reactor).toLowerCase()) {
135
+ return refusal("uniswapx-bad-order", { field: "reactor", expected: net.reactor });
136
+ }
131
137
  const order = {
132
- reactor: request.reactor === undefined || request.reactor === null ? net.reactor : request.reactor,
138
+ reactor,
133
139
  swapper,
134
140
  nonce: request.nonce,
135
141
  deadline: request.deadline,
@@ -222,9 +228,10 @@ export async function uniswapxSignOrder({ typedData, wallet, address = null } =
222
228
  * quote call - this provider does not fabricate it, and the cosigner is Uniswap Labs' (see the header). With no
223
229
  * submitter URL it refuses by name ("uniswapx-no-submitter"). The endpoint is NEVER guessed.
224
230
  */
225
- export async function submitUniswapxOrder({ quote = null, signature = null, routing = "DUTCH_V2", submitter = null, fetchImpl = null, timeoutMs = 20_000 } = {}) {
231
+ export async function submitUniswapxOrder({ quote = null, signature = null, routing = "DUTCH_V2", submitter = null, fetchImpl = null, timeoutMs = 20_000, orderHash = null } = {}) {
226
232
  if (typeof signature !== "string" || !/^0x[0-9a-fA-F]{130}$/.test(signature)) return refusal("uniswapx-bad-order", { field: "signature" });
227
233
  if (!quote || typeof quote !== "object") return refusal("uniswapx-bad-order", { field: "quote" });
234
+ if (orderHash !== null && orderHash !== undefined && !isHash(orderHash)) return refusal("uniswapx-bad-order", { field: "orderHash" });
228
235
  const target = submitter === undefined || submitter === null || submitter === "" ? null : String(submitter);
229
236
  if (!target) return refusal("uniswapx-no-submitter", { field: "submitter" });
230
237
  const http = createHttp({ apiBase: target, fetchImpl, timeoutMs });
@@ -240,13 +247,19 @@ export async function submitUniswapxOrder({ quote = null, signature = null, rout
240
247
  if (!res.ok) return refusal("uniswapx-refused", { status: res.status, stage: "submit" });
241
248
  const data = res.body && typeof res.body === "object" ? res.body : null;
242
249
  if (!data || typeof data.orderId !== "string" || data.orderId === "") return refusal("uniswapx-bad-response", { where: "submit", field: "orderId" });
250
+ // A SUBMITTER THAT RETURNS ANOTHER ORDER ID DID NOT PUBLISH OUR ORDER. The caller may pass the hash it signed;
251
+ // when it does, the service answer must name that exact order.
252
+ if (orderHash !== null && orderHash !== undefined
253
+ && String(data.orderId).toLowerCase() !== String(orderHash).toLowerCase()) {
254
+ return refusal("uniswapx-bad-response", { where: "submit", field: "orderId", expected: orderHash });
255
+ }
243
256
  const status = data.orderStatus;
244
257
  if (typeof status !== "string" || !UNISWAPX_STATUSES.includes(status)) return refusal("uniswapx-bad-response", { where: "submit", field: "orderStatus" });
245
258
  return { ok: true, orderId: data.orderId, orderStatus: status, requestId: typeof data.requestId === "string" ? data.requestId : null };
246
259
  }
247
260
 
248
261
  /**
249
- * READ ONE ORDER by its hash. GET /orders?orderHash=<hash> -> { orders: [ ... ] }. The entry's `orderStatus` must be
262
+ * READ ONE ORDER by its hash. GET /orders?orderHash=<hash> -> { orders: [... ] }. The entry's `orderStatus` must be
250
263
  * a known status word (else "uniswapx-bad-response"); an empty list means the service does not know the order
251
264
  * ("uniswapx-order-unknown") - never silence, never null.
252
265
  */
@@ -266,8 +279,17 @@ export async function uniswapxOrderStatus({ orderHash, chainId = null, fetchImpl
266
279
  if (!res.ok) return refusal("uniswapx-refused", { status: res.status, stage: "orders" });
267
280
  const orders = res.body && res.body.orders;
268
281
  if (!Array.isArray(orders)) return refusal("uniswapx-bad-response", { where: "orders" });
269
- const found = orders.find((o) => o && String(o.orderHash || "").toLowerCase() === String(orderHash).toLowerCase()) || orders[0] || null;
270
- if (!found) return refusal("uniswapx-order-unknown", { orderHash });
282
+ const matches = orders.filter((o) => o && String(o.orderHash || "").toLowerCase() === String(orderHash).toLowerCase());
283
+ // AN ANSWER WITH ANOTHER ORDER IS NOT OUR ORDER. The service can return a non-empty list with a different hash;
284
+ // falling back to orders[0] would turn that order's final status into ours. An empty list stays "unknown", but a
285
+ // non-empty list whose hashes do not match is a malformed answer.
286
+ if (matches.length === 0) {
287
+ return orders.length === 0
288
+ ? refusal("uniswapx-order-unknown", { orderHash })
289
+ : refusal("uniswapx-bad-response", { where: "orders", detail: "order-hash-mismatch" });
290
+ }
291
+ if (matches.length > 1) return refusal("uniswapx-bad-response", { where: "orders", detail: "ambiguous-order-hash" });
292
+ const found = matches[0];
271
293
  const status = found.orderStatus;
272
294
  if (typeof status !== "string" || !UNISWAPX_STATUSES.includes(status)) return refusal("uniswapx-bad-response", { where: "orderStatus", got: typeof status === "string" ? status : null });
273
295
  return { ok: true, status, order: found };
@@ -277,8 +299,8 @@ export async function uniswapxOrderStatus({ orderHash, chainId = null, fetchImpl
277
299
  * WHAT ENDS AN ASYNCHRONOUS PROVIDER'S EXECUTION - poll the order service until the order is settled or finally
278
300
  * dead, with a timeout. Returns:
279
301
  * { ok: true, done: true, settled: true, status: "filled" } - the swap settled;
280
- * { ok: true, done: true, settled: false, status: "expired" | "error" | "cancelled" | ... } - finally dead;
281
- * { ok: false, code: "uniswapx-not-settled" | "uniswapx-unreachable" | ... } - a NAMED refusal.
302
+ * { ok: true, done: true, settled: false, status: "expired" | "error" | "cancelled" |... } - finally dead;
303
+ * { ok: false, code: "uniswapx-not-settled" | "uniswapx-unreachable" |... } - a NAMED refusal.
282
304
  * "Not settled in time" is its OWN code: "we did not wait long enough" is a state of the order, not a breakdown.
283
305
  * The clock and the sleep are injectable so the wait is testable without real time.
284
306
  */
@@ -1,4 +1,4 @@
1
- // THE MAKER'S LEVEL SET: THE REFERENCE WALK OVER IT (issue #110, part B).
1
+ // THE MAKER'S LEVEL SET: THE REFERENCE WALK OVER IT.
2
2
  //
3
3
  // WHY. The maker sends the node a LEVEL SET - chunks of volume with their own prices - and the node computes a
4
4
  // firm price by WALKING it. The client (SDK) needs the same walk to show the same price before signing. This file