@ninsei-labs/sdk 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +56 -5
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/halfenc.js +6 -6
  6. package/engine/core/config.js +17 -38
  7. package/engine/core/format.js +1 -1
  8. package/engine/core/sellWindow.js +1 -1
  9. package/engine/core/store.js +11 -3
  10. package/engine/core/swap.js +3 -3
  11. package/engine/evm/amounts.js +2 -2
  12. package/engine/evm/asyncRoute.js +3 -3
  13. package/engine/evm/dex.js +1 -1
  14. package/engine/evm/factory.js +1 -1
  15. package/engine/evm/fees.js +62 -0
  16. package/engine/evm/funding.js +71 -66
  17. package/engine/evm/gasReserve.js +10 -0
  18. package/engine/evm/index.js +2 -2
  19. package/engine/evm/prices.js +3 -0
  20. package/engine/evm/session.js +1 -1
  21. package/engine/monero/address.js +4 -2
  22. package/engine/monero/arrivalRead.js +15 -2
  23. package/engine/monero/keyImage.js +146 -0
  24. package/engine/monero/keys.js +1 -0
  25. package/engine/monero/mnemonic.js +2 -1
  26. package/engine/monero/node.js +1 -0
  27. package/engine/monero/scan.js +12 -2
  28. package/engine/recovery/recoveryFile.js +31 -85
  29. package/engine/sdk/bridge.js +21 -51
  30. package/index.d.ts +412 -19
  31. package/package.json +20 -2
  32. package/src/actions.mjs +72 -6
  33. package/src/addressGuard.mjs +16 -0
  34. package/src/codes.mjs +26 -9
  35. package/src/config.mjs +56 -3
  36. package/src/decline.mjs +23 -74
  37. package/src/firmRequest.mjs +80 -0
  38. package/src/index.mjs +17 -28
  39. package/src/legs/cow.mjs +2 -2
  40. package/src/legs/evm.mjs +20 -12
  41. package/src/legs/kyber-spec.mjs +2 -2
  42. package/src/legs/kyber.mjs +1 -1
  43. package/src/legs/shape.mjs +1 -1
  44. package/src/legs/uniswaprelay.mjs +16 -4
  45. package/src/legs/uniswapx.mjs +29 -7
  46. package/src/levelsWalkSpec.mjs +1 -1
  47. package/src/lock.mjs +18 -37
  48. package/src/provider/envFile.mjs +3 -3
  49. package/src/provider/sign.mjs +3 -3
  50. package/src/public/evm.d.ts +84 -0
  51. package/src/public/evm.mjs +20 -0
  52. package/src/public/order.mjs +1 -1
  53. package/src/public/provider.mjs +1 -1
  54. package/src/public/recovery.d.ts +3 -2
  55. package/src/public/recovery.mjs +1 -1
  56. package/src/public/xmr.d.ts +2 -2
  57. package/src/quoteEip712Spec.mjs +4 -4
  58. package/src/quotes.mjs +52 -11
  59. package/src/recovery-key.mjs +7 -3
  60. package/src/relayFirmClient.mjs +4 -0
  61. package/src/relayQuote.mjs +1 -0
  62. package/src/sim.mjs +1 -1
  63. package/src/swap-flow.mjs +22 -32
  64. package/src/swaps.mjs +63 -56
  65. package/src/sweep-inputs.mjs +61 -0
  66. package/src/sweep-reconcile.mjs +71 -0
  67. package/src/sweep-restore.mjs +38 -9
  68. package/src/sweep.mjs +164 -10
  69. package/src/version.mjs +1 -1
  70. package/src/wallet.mjs +1 -1
  71. package/src/xmr-arrival.mjs +1041 -43
package/src/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
package/src/lock.mjs CHANGED
@@ -1,35 +1,24 @@
1
1
  // LOCKING THE FUNDS: TERMS FIRST, THEN SENDING.
2
2
  //
3
- // The first half of the step is here - assembling and CHECKING the order terms BEFORE anything goes on-chain. The
4
- // rules are not ours: the contract sets them, and the engine already checks them (`www/js/evm/escrow.js`,
5
- // `orderTerms`). The core will not hold a copy of the rules: a copy would drift from the contract right where the
6
- // error shows up only as a rejected transaction.
3
+ // This module assembles and checks the order terms before anything goes on-chain. The contract sets the rules.
4
+ // The engine checks them; this module does not keep a second copy.
7
5
  //
8
- // WHAT IS HERE: both the assembly of the terms and the sending itself - it goes through the engine's EVM layer
9
- // (`fundOrder`), and the EVM wallet (the `send`/`receipt` role) comes from outside. What reads the chain is also a
10
- // seam: by default the engine's read, but the caller can substitute its own (as in actions.mjs).
6
+ // The send goes through the engine's EVM layer and the external wallet adapter. The chain read is a seam: the engine
7
+ // read by default, or a caller substitute.
11
8
  import { SdkError } from "./errors.mjs";
12
9
  import * as engine from "./engine.mjs";
13
- // THE DEAL FLOW IS A PACKAGE MODULE NOW (#32, wave 3): the registry address is read through it, exactly as
14
- // the actions read the order flow.
10
+ // The deal flow is a package module. The registry address is read through it, as the actions read the order flow.
15
11
  import * as flow from "./swap-flow.mjs";
16
12
  import { assertWalletChain } from "./chainGuard.mjs";
17
13
 
18
- // THE ORDER'S WORD-ADDRESSES ARE BROUGHT TO 0x HERE, AT THE BOUNDARY, NOT AT EVERY CALLER.
19
- //
20
- // The engine returns the points and commitments WITHOUT the 0x prefix (that is how www/js/atomic/halves.js stores
21
- // them), while the calldata encoder (www/js/evm/factory.js, word) REQUIRES the prefix and refuses "not a number
22
- // and not hex" on 64 digits without one. The page normalises them on its side (sdk/src/swap-flow.mjs, with0x)
23
- // for exactly this reason. The core must do the same ITSELF: otherwise every caller would repeat the
24
- // normalisation, and one forgetful one would break the signature with the encoder's raw error. The list is
25
- // exactly the fields encoded as bytes32 that do NOT enter the order context string (otherwise the normalisation
26
- // would drift from the proof, which is bound to the context): two half commitments and three ed25519 points.
14
+ // Bring these bytes32 fields to 0x form once, at the boundary. The encoder requires the prefix. These are the
15
+ // fields encoded as bytes32 that do not enter the order context string.
27
16
  const HEX_POLICY_FIELDS = ["commitHalfLocker", "commitHalfClaimer", "edPointLocker", "edPointClaimer", "edViewPointLocker"];
28
17
  const with0x = (v) => (typeof v === "string" && v && !/^0x/i.test(v) ? "0x" + v : v);
29
18
 
30
19
  /**
31
- * The order terms in canonical form: points and commitments - with the 0x prefix. One form for the check and for
32
- * sending - otherwise one thing would be checked and another encoded.
20
+ * The order terms in canonical form: points and commitments with the 0x prefix. One form for the check and for
21
+ * sending.
33
22
  */
34
23
  export function canonicalTerms(request) {
35
24
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -42,7 +31,7 @@ export function canonicalTerms(request) {
42
31
  * The order terms for the contract. They are assembled by the engine, and its refusal (the deadlines the wrong
43
32
  * way, readyBy in the past) is turned into a CODE: texts are the interface's business, the core speaks in codes.
44
33
  */
45
- export function terms(request) {
34
+ export function terms(request, nowSec = null) {
46
35
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
47
36
  const need = ["locker", "claimer", "commitHalfLocker", "commitHalfClaimer", "edPointLocker", "edPointClaimer", "amount", "readyBy", "t1"];
48
37
  const missing = need.filter((k) => request[k] === undefined || request[k] === null || request[k] === "");
@@ -52,7 +41,8 @@ export function terms(request) {
52
41
  } catch (error) {
53
42
  // We will not parse ANOTHER's text: we name what the contract's rules check, and only if the deadlines are
54
43
  // actually violated. Otherwise - a general refusal on the terms.
55
- const seconds = Math.floor(Date.now() / 1000);
44
+ const seconds = Number.isSafeInteger(Number(nowSec)) && Number(nowSec) > 0
45
+ ? Number(nowSec) : Math.floor(Date.now() / 1000);
56
46
  if (Number(request.readyBy) <= seconds) throw new SdkError("bad-input", { field: "readyBy", why: "not-in-future" });
57
47
  if (Number(request.t1) <= Number(request.readyBy)) throw new SdkError("bad-input", { field: "t1", why: "not-after-readyBy" });
58
48
  throw new SdkError("bad-input", { field: "terms" });
@@ -87,7 +77,7 @@ export async function send(request, wallet, deps = {}) {
87
77
  // THE DEADLINES - HERE, BEFORE ANY SENDING, and on the form funding expects (`amountWei`, not `amount`: the
88
78
  // order terms and the sending have different names for the same field, and they must not be confused).
89
79
  const canonical = canonicalTerms(request);
90
- terms({ ...canonical, amount: canonical.amountWei });
80
+ terms({ ...canonical, amount: canonical.amountWei }, deps.nowSec);
91
81
  const evm = engine.evm;
92
82
  await assertWalletChain(wallet, canonical.chainId, "fund-order");
93
83
  // WHAT READS THE CHAIN IS ALSO A SEAM (as in actions.mjs): by default it is the engine's read, but the caller
@@ -98,6 +88,7 @@ export async function send(request, wallet, deps = {}) {
98
88
  return await evm.fundOrder({
99
89
  ...canonical,
100
90
  call: reader,
91
+ nowSec: Number.isSafeInteger(Number(deps.nowSec)) && Number(deps.nowSec) > 0 ? Number(deps.nowSec) : null,
101
92
  onPredicted: deps.onPredicted,
102
93
  send: (tx) => wallet.send({ ...tx, chainId: canonical.chainId, from: canonical.locker }),
103
94
  // NORMALISING THE RECEIPT ARGUMENT'S SHAPE - HERE, AT THE CORE'S BOUNDARY, NOT AT EVERY CALLER.
@@ -109,27 +100,17 @@ export async function send(request, wallet, deps = {}) {
109
100
  receipt: (arg) => wallet.receipt(typeof arg === "string" ? arg : (arg && typeof arg.hash === "string" ? arg.hash : arg)),
110
101
  });
111
102
  } catch (error) {
112
- // AN ALREADY-NAMED REASON PASSES AS IS: the adapter's and the reader's codes (wrong-chain, server-unavailable,
113
- // contract-reverted, bad-input) ARE the answer, and it must not be overridden.
103
+ // A named reason passes as is. The adapter and reader codes are the answer and must not be overridden.
114
104
  if (error && typeof error.code === "string") throw error;
115
- // THE REST USED TO HIDE BEHIND server-unavailable { step: "fund-order" }, and the real reason (the first live
116
- // run: "locker and claimer cannot coincide") never reached the caller. Now the reason is NAMED as a string
117
- // (briefly, without keys), and the code is chosen by it: transport - server-unavailable, order/data
118
- // validation - bad-input.
105
+ // Name the reason and choose the code by it: transport is server-unavailable, order or data is bad-input.
119
106
  const why = sanitizeWhy((error && error.message) || error);
120
107
  throw new SdkError(transportish(why) ? "server-unavailable" : "bad-input", { step: "fund-order", why });
121
108
  }
122
109
  }
123
110
 
124
111
  /**
125
- * The escrow factory address for a network: FROM THE NETWORK REGISTRY, by the same path as the rest of the core.
126
- * The registry is read through the deal-flow module (sdk/src/swap-flow.mjs, escrowFactoryAddress) - the core
127
- * keeps no SECOND table of addresses.
128
- *
129
- * PREVIOUSLY THE FUNCTION LOOKED IN THE WRONG MODULE (www/js/evm/escrow.js, which has no such function) and
130
- * ALWAYS returned null - that is, the seam stayed silent about the factory's absence, and the caller took the
131
- * address elsewhere. Now the absence of a factory for a network is a REFUSAL WITH A CODE naming the network, not
132
- * null.
112
+ * The escrow factory address for a network, read from the network registry through the deal-flow module. An unknown
113
+ * network is a refusal with a code, not null.
133
114
  */
134
115
  export function factoryOf(chainSlug) {
135
116
  let address = null;
@@ -9,14 +9,14 @@ import { join } from "node:path";
9
9
  import { tmpdir } from "node:os";
10
10
 
11
11
  // WHERE TO LOOK WHEN THE FLAG IS NOT GIVEN: the current directory (the command is run from the node tree), then rfq/ under it (the layout of the tree this node was cut from)
12
- // (the same run from the repository root), then .env - that is also a frequent name for a settings file. What was found
12
+ // (the same run from the repository root), then.env - that is also a frequent name for a settings file. What was found
13
13
  // is printed: a silent read of 'some' file is exactly the case where people later look for why the settings are wrong.
14
14
  //
15
15
  // ORDER: THE LOCAL FILE OUTRANKS THE PRODUCTION ONE. The local contour puts its settings BESIDE the production ones
16
- // (rfq.env.local), and while the search went from the plain name to .local, the developer tool picked up the production
16
+ // (rfq.env.local), and while the search went from the plain name to.local, the developer tool picked up the production
17
17
  // file: the wallet path /opt/ninsei/..., the production price feed and its age - and refused with 'nothing to price the order with' where
18
18
  // the settings were in place (the quote checks fell exactly on this, and `npm run payout` with them).
19
- // The reverse order can err in one direction only: on the server there is no .local file at all, and the production
19
+ // The reverse order can err in one direction only: on the server there is no.local file at all, and the production
20
20
  // one remains the only one. An explicit --env= still outranks everything.
21
21
  // THE `rfq/` PATH IS A SUPPORTED LAYOUT, NOT A COMMENT: the node tree keeps its settings in `rfq/`, while a
22
22
  // checkout run from the repository root has the same file one level down. The local file outranks the production
@@ -112,7 +112,7 @@ export function loadPrivateKey(keyFile) {
112
112
 
113
113
  // THE NODE'S PUBLIC KEY: THE ONE IT SIGNS WITH, AND NOT THE CONTENT OF THE FILE BESIDE IT (partner request to the node).
114
114
  //
115
- // WHY FROM THE LOADED KEY AND NOT FROM THE .pub FILE. The signature is made by the key the node read at start
115
+ // WHY FROM THE LOADED KEY AND NOT FROM THE.pub FILE. The signature is made by the key the node read at start
116
116
  // (loadPrivateKey), so ITS public key must go out: the file beside it could be left from a former
117
117
  // key, come from a backup or be substituted. A reader who took the key from the file would check the signature
118
118
  // with the wrong key and would take a live node for a foreign one.
@@ -125,14 +125,14 @@ export function publicKeyBase64From(publicKeyPem) {
125
125
  return createPublicKey(publicKeyPem).export({ type: "spki", format: "der" }).toString("base64");
126
126
  }
127
127
 
128
- // The SIGNING public key from a private PEM - with the same SPKI DER export as in the .pub file.
128
+ // The SIGNING public key from a private PEM - with the same SPKI DER export as in the.pub file.
129
129
  // createPublicKey accepts the PRIVATE PEM itself and derives the public key from it; a repeated call on a KeyObject
130
130
  // (createPublicKey(createPublicKey(pem))) refuses - "expected private", so there is NO nesting here.
131
131
  export function signingPublicKeyBase64(privateKeyPem) {
132
132
  return publicKeyBase64From(privateKeyPem);
133
133
  }
134
134
 
135
- // The content of the .pub file in the same form (base64 of SPKI DER), or the reason why it is absent.
135
+ // The content of the.pub file in the same form (base64 of SPKI DER), or the reason why it is absent.
136
136
  export function publicKeyFileBase64(pubFile) {
137
137
  if (!pubFile) return { key: null, why: "the path of the public key file is not known" };
138
138
  if (!existsSync(pubFile)) return { key: null, why: "the public key file is missing: " + pubFile };