@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
@@ -184,3 +184,87 @@ export interface ClaimGasGiftRequest {
184
184
 
185
185
  /** The claim cost the client requires, plus the reserve margin. The ONE computation of the gift size. */
186
186
  export declare function claimGasGiftWei(request?: ClaimGasGiftRequest): bigint | null;
187
+
188
+ /** The contract's fee ceiling: 200 basis points (2%). */
189
+ export declare const MAX_FEE_BPS: number;
190
+
191
+ /** `floor(amount * bps / 10000)`, the contract's fee formula. */
192
+ export declare function feeWeiFor(amountWei: string | number | bigint, feeBps: string | number | bigint): bigint;
193
+
194
+ /** The largest principal whose principal plus fee fits a buy's total. */
195
+ export declare function principalForTotal(totalWei: string | number | bigint, feeBps: string | number | bigint): bigint;
196
+
197
+ export interface FeeTerms {
198
+ readonly bps: number;
199
+ readonly feeWei: bigint;
200
+ readonly totalWei: bigint;
201
+ readonly recipient: string | null;
202
+ readonly feeOnTop: boolean;
203
+ readonly legacy: false;
204
+ }
205
+
206
+ /** The signed quote's fee: rate, amount, recipient and direction, cross-checked against the formula. */
207
+ export declare function feeTermsFromQuote(quote: Readonly<Record<string, unknown>>): FeeTerms;
208
+
209
+ export interface SalePayoutBeforeClaimRequest {
210
+ readonly amountWei: string | number | bigint;
211
+ readonly feeWei: string | number | bigint;
212
+ readonly claimTipWei?: string | number | bigint;
213
+ }
214
+
215
+ export interface SalePayoutBeforeClaim {
216
+ readonly amountWei: bigint;
217
+ readonly feeWei: bigint;
218
+ readonly claimTipWei: bigint;
219
+ /** `amount - fee - claimTip`, when another address sends the claim. */
220
+ readonly guaranteedMinimumWei: bigint;
221
+ /** `amount - fee`, when the seller sends the claim. */
222
+ readonly sellerClaimWei: bigint;
223
+ }
224
+
225
+ /** The two labelled figures before the claim; null when the signed amounts do not add up. */
226
+ export declare function salePayoutBeforeClaim(request: SalePayoutBeforeClaimRequest): SalePayoutBeforeClaim | null;
227
+
228
+ export interface SalePayoutAfterClaimRequest extends SalePayoutBeforeClaimRequest {
229
+ readonly claimed?: boolean;
230
+ readonly claimSucceeded?: boolean;
231
+ /** The contract's actual `msg.sender`, not `tx.from`. */
232
+ readonly sender?: string | null;
233
+ readonly claimer?: string | null;
234
+ }
235
+
236
+ export interface SalePayoutAfterClaim {
237
+ readonly outcome: "claimed" | "unknown";
238
+ /** The seller's amount actually paid; null when the outcome is not determined. */
239
+ readonly payoutWei: bigint | null;
240
+ }
241
+
242
+ /** The seller's payout after a claim, judged by the contract's `msg.sender`. */
243
+ export declare function salePayoutAfterClaim(request: SalePayoutAfterClaimRequest): SalePayoutAfterClaim;
244
+
245
+ /** The gas limit of `createOrderAndFund`, the funding deposit. */
246
+ export declare const GAS_CREATE_ORDER_AND_FUND: bigint;
247
+
248
+ export declare const ORDER_READY_GAS_LIMIT: bigint;
249
+ export declare const ORDER_REFUND_GAS_LIMIT: bigint;
250
+ export declare const ORDER_GAS_LIMIT: bigint;
251
+ export declare const ORDER_DEPOSIT_GAS_LIMIT: bigint;
252
+
253
+ /** What the mark and possible refund reserve; the deposit is opt-in through `depositGasLimit`. */
254
+ export interface OrderGasReserveRequest {
255
+ readonly gasPriceWei?: string | number | bigint | null;
256
+ readonly readyGasLimit?: string | number | bigint | null;
257
+ readonly refundGasLimit?: string | number | bigint | null;
258
+ readonly depositGasLimit?: string | number | bigint | null;
259
+ readonly extraFeeWei?: string | number | bigint | null;
260
+ }
261
+
262
+ export declare function orderGasReserveWei(request?: OrderGasReserveRequest): bigint | null;
263
+
264
+ /** The funding deposit's reserve: its gas limit times the maximum fee per gas. */
265
+ export interface FundingGasReserveRequest {
266
+ readonly gasLimit?: string | number | bigint | null;
267
+ readonly maxFeePerGasWei?: string | number | bigint | null;
268
+ }
269
+
270
+ export declare function fundingGasReserveWei(request?: FundingGasReserveRequest): bigint | null;
@@ -27,3 +27,23 @@ export {
27
27
  claimMaxFeePerGasWei,
28
28
  claimRequiredWei,
29
29
  } from "../../engine/evm/claimGas.js";
30
+
31
+ export {
32
+ MAX_FEE_BPS,
33
+ feeTermsFromQuote,
34
+ feeWeiFor,
35
+ principalForTotal,
36
+ salePayoutAfterClaim,
37
+ salePayoutBeforeClaim,
38
+ } from "../../engine/evm/fees.js";
39
+
40
+ export { GAS_CREATE_ORDER_AND_FUND } from "../../engine/evm/funding.js";
41
+
42
+ export {
43
+ ORDER_DEPOSIT_GAS_LIMIT,
44
+ ORDER_GAS_LIMIT,
45
+ ORDER_READY_GAS_LIMIT,
46
+ ORDER_REFUND_GAS_LIMIT,
47
+ fundingGasReserveWei,
48
+ orderGasReserveWei,
49
+ } from "../../engine/evm/gasReserve.js";
@@ -1,7 +1,7 @@
1
1
  // THE ORDER SIDE: what a signature commits to, and the quote types it commits under.
2
2
  //
3
3
  // The canonical context string, the commitment on a half key, the EIP-712 quote types and digests. Same rule
4
- // as ./xmr: names only, no second implementation, no browser.
4
+ // as./xmr: names only, no second implementation, no browser.
5
5
 
6
6
  export { ORDER_CONTEXT_VERSION, orderContextString } from "../../engine/atomic/orderContext.js";
7
7
  export { halfCommitmentHex } from "../../engine/atomic/orderHalfCommit.js";
@@ -1,6 +1,6 @@
1
1
  // THE PROVIDER SIDE, NODE ONLY: identity, signing and env files for the machine that runs the node.
2
2
  //
3
- // Separate entry, like ./adapters, because these helpers reach the filesystem and node:crypto. A browser
3
+ // Separate entry, like./adapters, because these helpers reach the filesystem and node:crypto. A browser
4
4
  // consumer must never pull them in, and a Node consumer gets them with one import.
5
5
  //
6
6
  // WHY THEY LIVE HERE. The demo's backend verifies a maker's quote and builds an allow list from the provider's
@@ -262,7 +262,7 @@ export declare function recoveryFileName(swapId?: string | null): string;
262
262
 
263
263
 
264
264
  // ---------------------------------------------------------------------------------------------------
265
- // ONE RECOVERY KEY PER BROWSER (sdk#79)
265
+ // ONE RECOVERY KEY PER BROWSER
266
266
  // ---------------------------------------------------------------------------------------------------
267
267
 
268
268
  /** The version of the stored/backup key record. */
@@ -412,7 +412,8 @@ export declare const ESCROW_EVENT_TOPICS: {
412
412
  readonly declined: string;
413
413
  };
414
414
 
415
- /** Read HalfRevealed, Ready and Declined for a list of escrows in one log request. */
415
+ /** Read HalfRevealed, Ready and Declined for a list of escrows in one log request. Only the requested escrows and
416
+ * current (non-removed) logs are returned. */
416
417
  export declare function readEscrowEvents(request: {
417
418
  escrows: readonly string[];
418
419
  evmLogs: (request: { address: readonly string[]; topics: (string | null)[][]; fromBlock: number | string; toBlock: number | string }) => Promise<unknown[]>;
@@ -21,7 +21,7 @@ export {
21
21
  validatePayload,
22
22
  } from "../../engine/recovery/recoveryFile.js";
23
23
 
24
- // ONE RECOVERY KEY FOR EVERY SWAP (sdk#79): the taker's key, its derivation, its file and the on-chain search.
24
+ // ONE RECOVERY KEY FOR EVERY SWAP: the taker's key, its derivation, its file and the on-chain search.
25
25
  export {
26
26
  RECOVERY_KEY_ALG,
27
27
  RECOVERY_KEY_DOMAIN_V2,
@@ -83,7 +83,7 @@ export declare function addressFromKeys(request: AddressPayloadRequest, deps: Ad
83
83
  * `ok: true, verified: false` with the reason named, never a false "checked". A refusal always names WHY.
84
84
  */
85
85
  export type AddressCheck =
86
- | { readonly ok: false; readonly reason: string }
86
+ | { readonly ok: false; readonly reason: string; readonly network?: MoneroNetwork; readonly expectedNetwork?: MoneroNetwork }
87
87
  | { readonly ok: true; readonly verified: false; readonly network: MoneroNetwork | null; readonly reason: string }
88
88
  | { readonly ok: true; readonly verified: true; readonly network: MoneroNetwork; readonly kind: MoneroAddressKind; readonly bytes: number };
89
89
 
@@ -475,7 +475,7 @@ export interface NodeProbeRefusal {
475
475
 
476
476
  /**
477
477
  * ASK A NODE FOR `get_info`: the height, the network it names, whether it is synchronized. Never throws - the
478
- * answer names the problem (`unreachable`, `timeout`, `nettype`, ...). `fetchImpl` is injected so a Node consumer
478
+ * answer names the problem (`unreachable`, `timeout`, `nettype`,...). `fetchImpl` is injected so a Node consumer
479
479
  * or a test can pass its own; `timeoutMs` abandons the request (8 seconds by default).
480
480
  */
481
481
  export declare function probeMoneroNode(options: {
@@ -11,7 +11,7 @@
11
11
  // (the chain check itself is a later stage; here both values are only bound).
12
12
  // registry - the maker registry named by the order. Bound now so a quote cannot be replayed
13
13
  // from one registry into another even before anyone reads `providerOf`.
14
- // cashier - the fee vault of the order (issue #103): the fee destination is part of the SIGNED
14
+ // cashier - the fee vault of the order: the fee destination is part of the SIGNED
15
15
  // terms, so the factory no longer mints one vault per maker and the fee is not
16
16
  // scattered across them. Bound so a relayer cannot retarget where the fee accrues.
17
17
  // locker, claimer, - the order conditions: the same terms the DLEQ context binds and the escrow's
@@ -28,12 +28,12 @@
28
28
  // chainId - bound in the domain AND in the message. A quote signed for one network does not
29
29
  // verify on another.
30
30
  // feeBps, fee, - the provider's commission: the rate, the amount in wei and the recipient. Shown to
31
- // feeRecipient the customer before signing (#76) and frozen by the signature afterwards.
31
+ // feeRecipient the customer before signing and frozen by the signature afterwards.
32
32
  // validUntil - the quote's own expiry, IN SECONDS (the order's readyBy/t1 and block.timestamp
33
33
  // scale): a quote past it is refused regardless of the price.
34
34
  // nonce - replay protection: the very same signed quote cannot be presented twice.
35
35
  // claimTip - the tip the escrow pays to whoever sends `claim`, out of the payout, in the same
36
- // transaction (#18). It is inside the signed set so a provider cannot raise it after the
36
+ // transaction. It is inside the signed set so a provider cannot raise it after the
37
37
  // taker has seen the quote. Zero means no tip and is the only value a buy uses.
38
38
  // commitHalfLocker, - the depositor's half commitment and two Monero points. They used to travel beside the
39
39
  // edPointLocker, quote, outside the signature: a taker could show one set and fund another escrow with
@@ -46,7 +46,7 @@ export const ORDER_QUOTE_DOMAIN_NAME = "NinseiEscrowFactory";
46
46
  export const ORDER_QUOTE_DOMAIN_VERSION = "1";
47
47
  // 10: the signed EIP-712 field set grew the depositor's half commitment and two Monero points. They used to be
48
48
  // factory arguments outside the signature, which let one quote fund an escrow with decoy locker fields.
49
- // 9: the signed EIP-712 field set grew `claimTip` (#18) - the tip a third-party sender of `claim` takes from the
49
+ // 9: the signed EIP-712 field set grew `claimTip` - the tip a third-party sender of `claim` takes from the
50
50
  // payout, covered by the provider's signature like every other condition.
51
51
  // 8: the field set grew `xmrAmount` (#110 step 3). This is the request-shape generation label, and it moves WITH the
52
52
  // field set (see the note above). The DOMAIN name and the domain version string are UNCHANGED by it: they name the
package/src/quotes.mjs CHANGED
@@ -11,7 +11,7 @@ import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
11
11
  import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
12
12
  import { requestFirmQuote } from "./relayFirmClient.mjs";
13
13
  import { predictEscrow } from "./predictEscrow.mjs";
14
- import { readReadyWindow } from "./readyWindow.mjs";
14
+ import { firmRequest as buildFirmRequest, firmWindowFor } from "./firmRequest.mjs";
15
15
  import { quoteLifeVerdict } from "./quotePolicy.mjs";
16
16
  // THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
17
17
  // remembered: a single wrong hex digit would call another function and return a zero address - and a zero
@@ -23,7 +23,7 @@ const bytesToHexQ = (bytes) => { let out = "0x"; for (const b of bytes) out += b
23
23
  const providerOfSelector = () => bytesToHexQ(keccak256(utf8("providerOf(address)")).slice(0, 4));
24
24
  const providerOfData = (key) => providerOfSelector() + "0".repeat(24) + String(key).toLowerCase().replace(/^0x/, "");
25
25
  // THE FACTORY IS READ FROM THE RECORD, NOT FROM SETTINGS: `factoryOf(provider)` answers the factory the
26
- // provider named in its record (#103). Selected by a COMPUTED selector, like providerOf.
26
+ // provider named in its record. Selected by a COMPUTED selector, like providerOf.
27
27
  const factoryOfSelector = () => bytesToHexQ(keccak256(utf8("factoryOf(address)")).slice(0, 4));
28
28
  const factoryOfData = (provider) => factoryOfSelector() + "0".repeat(24) + String(provider).toLowerCase().replace(/^0x/, "");
29
29
  const hexToBytesQ = (hex) => {
@@ -109,20 +109,40 @@ export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFe
109
109
  }
110
110
 
111
111
  export function createQuotes({ config, now = () => Date.now(), evmCall = null, evmCode = null, evmBlock = null,
112
- providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null, fetchImpl = null }) {
113
- // THE INTERFACE'S FACTORY POLICY (#103): the code hashes of factories it is willing to trade through
112
+ providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null, fetchImpl = null,
113
+ chunkOptions = null }) {
114
+ // THE INTERFACE'S FACTORY POLICY: the code hashes of factories it is willing to trade through
114
115
  // (extcodehash semantics = keccak256 of the runtime code). An EMPTY list is "no policy" (like
115
116
  // allowedProviders); a NON-EMPTY one refuses any factory whose code is not on it. Lower-cased once.
116
117
  const factoryPolicy = Array.isArray(knownFactoryCodes) && knownFactoryCodes.length
117
118
  ? knownFactoryCodes.map((h) => String(h).toLowerCase()).filter(Boolean)
118
119
  : null;
119
- // THE INTERFACE'S ESCROW-IMPLEMENTATION POLICY (#114): the code hashes of the escrow IMPLEMENTATION the
120
+ // THE INTERFACE'S ESCROW-IMPLEMENTATION POLICY: the code hashes of the escrow IMPLEMENTATION the
120
121
  // factory must lead to - the code every order's clone delegatecalls. Same rule as the factory policy: an
121
122
  // EMPTY list is "no policy" (then the pair is still read and the implementation's code must be non-empty).
122
123
  const implementationPolicy = Array.isArray(knownImplementationCodes) && knownImplementationCodes.length
123
124
  ? knownImplementationCodes.map((h) => String(h).toLowerCase()).filter(Boolean)
124
125
  : null;
126
+ // THE CHAIN'S CLOCK, NOT THE DEVICE'S. A quote is signed for a timestamp; a device clock behind the chain lets
127
+ // an expired quote pass. The block seam is optional for simulation/tests, where the injected clock is the only
128
+ // clock available.
129
+ const chainNowSec = async () => {
130
+ if (typeof evmBlock !== "function") return Math.floor(Number(now()) / 1000);
131
+ let block = null;
132
+ try { block = await evmBlock("latest"); } catch { fail("quote-unchecked", { step: "clock", why: "block-read-failed" }); }
133
+ const timestamp = block && Number(block.timestamp);
134
+ if (!Number.isSafeInteger(timestamp) || timestamp <= 0) fail("quote-unchecked", { step: "clock", why: "timestamp-missing" });
135
+ return timestamp;
136
+ };
125
137
  return {
138
+ /**
139
+ * THE DEADLINES OF A FIRM REQUEST. Places `readyBy` and `t1` inside the maker's signed window for this market,
140
+ * side and Monero network, measured from the chain's `chainNow`. It reads nothing and signs nothing.
141
+ */
142
+ firmRequest(request) {
143
+ return buildFirmRequest(request);
144
+ },
145
+
126
146
  /**
127
147
  * A firm quote through the relay, starting from the one recovery key.
128
148
  *
@@ -191,10 +211,23 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
191
211
  const markets = [...new Set(windows.map((entry) => entry.market).filter((value) => typeof value === "string" && value))];
192
212
  const market = request.market !== undefined ? String(request.market) : (markets.length === 1 ? markets[0] : null);
193
213
  if (!market) fail("bad-input", { field: "market" });
194
- const window = windows.find((entry) => entry.market === market) || null;
195
- if (!window) fail("quote-refused", { step: "features", why: "window" });
196
- const readyWindow = readReadyWindow(window, { side, field: "features.firmWindows" });
197
- const xmrNetwork = request.xmrNetwork !== undefined ? String(request.xmrNetwork) : window.xmrNetwork;
214
+ const requestedNetwork = request.xmrNetwork !== undefined && request.xmrNetwork !== null
215
+ ? String(request.xmrNetwork) : null;
216
+ const networks = [...new Set(windows.filter((entry) => entry && entry.market === market)
217
+ .map((entry) => entry.xmrNetwork).filter((value) => typeof value === "string" && value))];
218
+ if (requestedNetwork === null && networks.length !== 1) {
219
+ // TWO NETWORKS FOR ONE MARKET ARE A REAL CASE. Guessing the first would sign an order on the wrong Monero
220
+ // network; the caller must name the one its key uses.
221
+ fail("bad-input", { field: "xmrNetwork", why: "ambiguous" });
222
+ }
223
+ const xmrNetwork = requestedNetwork !== null ? requestedNetwork : networks[0];
224
+ let readyWindow;
225
+ try {
226
+ readyWindow = firmWindowFor({ features, side, market, xmrNetwork });
227
+ } catch (error) {
228
+ if (error && typeof error.code === "string") fail("quote-refused", { step: "features", why: "window", market, xmrNetwork });
229
+ throw error;
230
+ }
198
231
  if (!xmrNetwork) fail("bad-input", { field: "xmrNetwork" });
199
232
  if (request.xmrAmount === undefined || request.xmrAmount === null || request.xmrAmount === "") {
200
233
  fail("bad-input", { field: "xmrAmount" });
@@ -216,7 +249,10 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
216
249
  }
217
250
  const derived = takerHalvesV2({ mnemonic, chainId, factory: order.factory, salt });
218
251
  const derivation = { kind: "salt-v2", salt };
219
- const own = await buildOwnSideFromHalvesChunked(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
252
+ const own = await buildOwnSideFromHalvesChunked(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf },
253
+ chunkOptions || {});
254
+ const quoteNowSec = await chainNowSec();
255
+ if (!Number.isSafeInteger(quoteNowSec) || quoteNowSec <= 0) fail("quote-unchecked", { step: "clock", why: "timestamp-missing" });
220
256
  const xa = secp256k1.Point.fromHex(own.side.proof.XA);
221
257
  const clientHalf = {
222
258
  commitHalf: bytesToHexQ(keccak256(xa.toBytes(false).slice(1))),
@@ -228,6 +264,7 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
228
264
  partner: request.partner,
229
265
  fetchImpl: request.fetchImpl || fetchImpl,
230
266
  timeoutMs: request.timeoutMs,
267
+ now: quoteNowSec * 1000,
231
268
  features,
232
269
  terms: {
233
270
  market,
@@ -270,6 +307,7 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
270
307
  viewPoint: result.edViewPointLocker,
271
308
  viewHalf: derived.makerViewHalf,
272
309
  },
310
+ options: chunkOptions || {},
273
311
  });
274
312
  // THE ONE-TIME XMR ADDRESS IS DERIVED, NOT TAKEN FROM THE RELAY. Both sides must assemble it from the same
275
313
  // points: our spend/view halves from the recovery key, the node's spend point and view point from the answer.
@@ -373,7 +411,10 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
373
411
  // happen first; a quote that had 31 s on arrival has less by now, and showing a confirmation would waste the
374
412
  // person's time only to refuse at the lock. A sell (bid) is checked by its own expiry alone: its escrow is
375
413
  // already funded, so there is no local lock to prepare and no margin to reserve.
376
- const answerNowSec = Math.floor(Number(now()) / 1000);
414
+ // THE LIFE CHECK RUNS AFTER ALL THE WORK THE ANSWER NEEDS. The chain clock is read again: the proof, the
415
+ // predict and the registry reads took time, and a device clock behind the chain must not grant it back.
416
+ const answerNowSec = await chainNowSec();
417
+ if (!Number.isSafeInteger(answerNowSec) || answerNowSec <= 0) fail("quote-unchecked", { step: "clock", why: "timestamp-missing" });
377
418
  const life = quoteLifeVerdict({ validUntil: quote.validUntil, nowSec: answerNowSec, side });
378
419
  if (!life.ok) {
379
420
  fail("quote-too-short", { step: "answer", side,
@@ -483,7 +483,8 @@ export async function readEscrowEvents({ escrows, evmLogs, fromBlock = "earliest
483
483
  fromBlock,
484
484
  toBlock,
485
485
  });
486
- return decodeEscrowEvents(logs);
486
+ // The address filter is a request, not a guarantee. Keep only the escrows this call asked for.
487
+ return decodeEscrowEvents(logs, new Set(escrows.map((escrow) => escrow.toLowerCase())));
487
488
  }
488
489
 
489
490
  /**
@@ -502,16 +503,19 @@ export async function readEscrowEventsByTopic({ evmLogs, fromBlock = "earliest",
502
503
  return decodeEscrowEvents(logs);
503
504
  }
504
505
 
505
- function decodeEscrowEvents(logs) {
506
+ function decodeEscrowEvents(logs, allowedEscrows = null) {
506
507
  const events = [];
507
508
  for (const log of logs) {
508
509
  if (!log || typeof log !== "object") continue;
510
+ // A removed log is not current state. It may describe an event that a reorg took back.
511
+ if (log.removed === true) continue;
509
512
  const topics = Array.isArray(log.topics) ? log.topics : [];
510
513
  const topic0 = String(topics[0] || "").toLowerCase();
511
514
  const name = ESCROW_EVENT_NAMES.get(topic0);
512
515
  if (!name) continue;
513
516
  const escrow = String(log.address || "").toLowerCase();
514
517
  if (!ADDRESS_RE.test(escrow)) continue;
518
+ if (allowedEscrows !== null && !allowedEscrows.has(escrow)) continue;
515
519
  const common = { escrow, event: name, blockNumber: log.blockNumber ?? null, transactionHash: log.transactionHash || null,
516
520
  logIndex: log.logIndex ?? null };
517
521
  if (name === "HalfRevealed") {
@@ -766,7 +770,7 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
766
770
  else readersReason = probed.reason || "no-height-readers";
767
771
  }
768
772
  // THE ORDER IS NATIVE, AND THE PAYING TOKEN IS NOT ON THE CHAIN. The escrow receives the settlement network's
769
- // native coin (`amount` is wei); which token the person swapped into it (USDC, USDT, ...) belongs to the DEX/quote
773
+ // native coin (`amount` is wei); which token the person swapped into it (USDC, USDT,...) belongs to the DEX/quote
770
774
  // record, not to OrderCreated or the clone. `payToken: null` plus a reason is the honest answer here; an invented
771
775
  // "USDC" would be a claim the chain does not support.
772
776
  for (const order of found) {
@@ -40,6 +40,7 @@ export async function requestFirmQuote({
40
40
  fetchImpl = null,
41
41
  timeoutMs = 20_000,
42
42
  retryTimeouts = 1,
43
+ now = () => Date.now(),
43
44
  ...request
44
45
  } = {}) {
45
46
  const base = String(relayUrl === undefined || relayUrl === null ? "" : relayUrl).trim().replace(/\/+$/, "");
@@ -123,6 +124,9 @@ export async function requestFirmQuote({
123
124
  answer,
124
125
  features: request.features,
125
126
  request: built,
127
+ // THE VERIFICATION USES THE CALLER'S CLOCK. A real Date.now here turns a slow run into `quote-expired`
128
+ // even when the caller injected a fixed clock for the rest of the quote path.
129
+ now: typeof now === "function" ? now() : now,
126
130
  });
127
131
  const publishedRecipient = wireText(published.feeRecipient === undefined || published.feeRecipient === null ? "" : published.feeRecipient, "relay.feeRecipient").toLowerCase();
128
132
  const quoteRecipient = wireText(verified.quote.feeRecipient === undefined || verified.quote.feeRecipient === null ? "" : verified.quote.feeRecipient, "quote.feeRecipient").toLowerCase();
@@ -220,6 +220,7 @@ function checkOrderQuote(quote, terms, nowSec) {
220
220
  }
221
221
  if (fee !== (amount * BigInt(bps)) / 10000n) throw new SdkError("quote-refused", { step: "answer", why: "fee" });
222
222
  const validUntil = wireNumber(quote.validUntil, "quote.validUntil");
223
+ // A quote must expire before readyBy. After readyBy, its signed price must not authorize a new deposit.
223
224
  if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
224
225
  throw new SdkError("quote-expired", { step: "answer", validUntil: quote.validUntil });
225
226
  }
package/src/sim.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // SANDBOX: failure scenarios and time. Added on requirement 8 of issue #32 - the interface lays out failure
1
+ // SANDBOX: failure scenarios and time. Added on requirement 8 of - the interface lays out failure
2
2
  // screens without waiting for a live testnet.
3
3
  //
4
4
  // What is deliberately absent, and why: scenarios are applied by the ENGINE (`www/js/mock`, the scenario fields
package/src/swap-flow.mjs CHANGED
@@ -22,7 +22,7 @@
22
22
  //
23
23
  // WHY IT IS IN THE PACKAGE. The deal engine is business logic, so it belongs to the package (@ninsei-labs/sdk).
24
24
  // The page reaches it through ONE seam (its bridge) by module name. The engine modules it needs are read through
25
- // ./engine.mjs; what lives here is the RULES, not the crypto.
25
+ //./engine.mjs; what lives here is the RULES, not the crypto.
26
26
  import { SdkError } from "./errors.mjs";
27
27
  import * as engine from "./engine.mjs";
28
28
  // THE HALF'S COMMITMENT, COMPUTED LOCALLY. The escrow checks the low 160 bits of `keccak256(x||y)` of `half*G`
@@ -30,7 +30,7 @@ import * as engine from "./engine.mjs";
30
30
  // the half ever leaving this process.
31
31
  import { halfCommitmentHex } from "../engine/atomic/orderHalfCommit.js";
32
32
  import { keccak256, secp256k1 } from "./primitives.mjs";
33
- // THE MAKER'S DECLINE (issue #40) - the escrow's `Declined` event and the neutral vocabulary the state is
33
+ // THE MAKER'S DECLINE - the escrow's `Declined` event and the neutral vocabulary the state is
34
34
  // reported in. It is its own module because TWO surfaces ask the same question (this flow and the swaps watch)
35
35
  // and a second implementation of the same event would be a second truth about it.
36
36
  import { declinedFromLogs, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0 } from "./decline.mjs";
@@ -63,7 +63,7 @@ export function escrowFactoryAddress(chainSlug) {
63
63
  return address;
64
64
  }
65
65
 
66
- // THE INTERFACE FEE CASHIER (#103): the address comes from the network registry, like the factory. The factory
66
+ // THE INTERFACE FEE CASHIER: the address comes from the network registry, like the factory. The factory
67
67
  // no longer creates the cashier - it arrives in the ORDER TERMS, and without it no quote under the order can be
68
68
  // assembled.
69
69
  export function escrowCashierAddress(chainSlug) {
@@ -91,43 +91,32 @@ export async function runAtomicOrder({
91
91
  const cashier = escrowCashierAddress(chainSlug);
92
92
  const chain = chainById(chainSlug || DEFAULT_CHAIN);
93
93
 
94
- // THE DEADLINES AND THE SALT ARE DECIDED HERE, BEFORE THE PROOF, AND NOWHERE ELSE.
94
+ // The deadlines and the salt are decided here, before the proof. The proof is bound to the order terms, which
95
+ // include both. Funding must not choose a different set later: the counterparty would reject the proof, while the
96
+ // local side would look healthy.
95
97
  //
96
- // This is the very reason the context stopped being a string from the caller. The proof is bound to the order
97
- // terms, and the terms include the deadlines and the salt. While the funding module decided them - that is,
98
- // AFTER the computation - the proof was bound to one set of deadlines while a different set went into the
99
- // contract: the check would fail at the counterparty, and on our own side everything would look healthy.
100
- // The salt here is the same in meaning as before: it determines the escrow address, so repeating an order must
101
- // come with the previous salt, otherwise a second escrow is created instead of the same one.
98
+ // The salt determines the escrow address. A repeated order must use the previous salt, or it creates a second
99
+ // escrow instead of the same one.
102
100
  const nowSec = Math.floor(Date.now() / 1000);
103
101
  const readyBy = nowSec + readyWindowSeconds;
104
- // t1 IS THE WINDOW AFTER readyBy, NOT "from now" (issue #88): the owner's claim window equals an hour AFTER the
105
- // readiness deadline. The flat formula "now + claimWindowSeconds" at a 4-hour readyBy gave t1 EARLIER than
106
- // readyBy, that is, an order created already closed (this is what check-atomic-flow caught).
102
+ // t1 is the window after readyBy, not "from now". The claim window starts after the readiness deadline.
107
103
  const t1 = readyBy + claimWindowSeconds;
108
104
  const salt = providedSalt || newSecret();
109
105
 
110
- // THE CONTEXT IS ASSEMBLED FROM THE ORDER FIELDS - by the same code as the provider node's and any verifier's.
111
- // The provider's half is derived from THESE SAME terms, so its proof will agree only here.
112
- // ONE ORDER OBJECT - ONE SOURCE OF FIELDS. Both the proof context and the quote request to the provider are
113
- // assembled from it. A second copy of these fields would diverge exactly where it costs the most: the provider
114
- // would derive its half from one set of terms while the proof was computed over another.
106
+ // The context is assembled from the order fields by the same rule a provider or verifier uses. The proof binds to
107
+ // these terms, so there is one order object for the proof and the quote request. A second copy would diverge where
108
+ // it costs the most.
115
109
  //
116
- // THERE IS NO CLAIMER HERE, AND THAT IS FUNDAMENTAL. The contract pays whoever is recorded as claimer, and at
117
- // claim time the half is revealed by whoever claims. So only the PROVIDER can name the claimer: it holds the
118
- // half and its address must receive the money. While the application substituted its own value, the provider
119
- // got an order with a foreign address and could not claim the ETH for it - the half stayed with it while the
120
- // money went to someone else. That is why the claimer comes in the quote, and the context is assembled AFTER
121
- // the quote.
110
+ // There is no claimer here. The contract pays the recorded claimer, and at claim time the half is revealed by
111
+ // whoever claims. Only the provider can name the claimer: it holds the half and must receive the money. The claimer
112
+ // therefore comes in the quote, and the context is assembled after the quote.
122
113
  const orderBase = {
123
114
  chainId: chain.chainId, factory, cashier, locker,
124
115
  amount: String(amountWei), readyBy: String(readyBy), t1: String(t1), salt,
125
116
  asset: "XMR", // what the user receives; not part of the context (it follows from the pair and network)
126
117
  };
127
- // THERE IS NO HASHLOCK AND ENVELOPE HERE ANY MORE. Under the scheme of doc 27 the order carries BOTH half
128
- // commitments and BOTH public ed25519 points, and the half is published by the settlement itself
129
- // (claim/refund). The secret that used to be placed in the recovery file is now MY HALF: it is exactly what is
130
- // needed to claim the XMR.
118
+ // The order carries both half commitments and both public ed25519 points. Settlement publishes the half. The secret
119
+ // in the recovery file is my half: exactly what is needed to claim the XMR.
131
120
  const say = (stage, detail) => onStage?.(stage, detail);
132
121
  {
133
122
  // THE QUOTE FIRST, THEN YOUR OWN SIDE. The order of steps is set by the fact that the claimer is named by the
@@ -167,6 +156,7 @@ export async function runAtomicOrder({
167
156
  onProgress: (step) => say("verify", step.phase === "sum"
168
157
  ? `summing commitments: ${step.done} of ${step.total}`
169
158
  : `verifying DLEQ proof: ${step.done} of ${step.total}`),
159
+ ...(typeof deps.yieldTo === "function" ? { yieldTo: deps.yieldTo } : {}),
170
160
  };
171
161
  const mine = await buildSide(order, chunkOptions);
172
162
  say("half", "side-ready");
@@ -366,7 +356,7 @@ export async function orderStatus(escrow, deps = {}) {
366
356
  }
367
357
 
368
358
  /**
369
- * THE ESCROW'S `Declined` EVENT - THE MAKER'S OWN CLOSING OF A FUNDED ORDER (issue #40).
359
+ * THE ESCROW'S `Declined` EVENT - THE MAKER'S OWN CLOSING OF A FUNDED ORDER.
370
360
  *
371
361
  * WHY THE EVENT AND NOT `status()`. Read on its own, `status()` cannot tell a decline from an ordinary refund:
372
362
  * both set `refunded` and send the whole balance back to the locker. The escrow keeps NO getter that names a
@@ -539,7 +529,7 @@ async function simulateAction(escrow, data, what, deps) {
539
529
  // A DRY RUN MUST NOT HAND THE HALF TO THE RPC. `eth_call` goes to a public endpoint by default, so simulating
540
530
  // `claim(half)` or `refund(half)` publishes the half to a third party while the escrow is still open and the ETH
541
531
  // has not moved. Whoever keeps that call holds both halves of the Monero key when the person declines the
542
- // transaction in the wallet or the send never lands (sdk#291).
532
+ // transaction in the wallet or the send never lands.
543
533
  //
544
534
  // The simulation added exactly one check, and it is arithmetic: the half's point commitment must equal the
545
535
  // order's. The contract compares the LOW 160 BITS of `keccak256(x||y)` of `half*G`
@@ -573,7 +563,7 @@ async function assertHalfMatchesCommit(escrow, half, slot, what, deps) {
573
563
  // lied here: the current contract has NO hashlock field. Instead it has two half commitments -
574
564
  // commitHalfClaimer and commitHalfLocker (:74-75), and claim compares the half against the first (:217).
575
565
  // In production this is the second half of the Monero spend key, so claiming and revealing the half are one
576
- // action: the half is published by whoever claims, and it is also obtained by the other side (HalfRevealed, :222).
566
+ // action: the half is published by whoever claims, and it is also obtained by the other side (HalfRevealed,:222).
577
567
  export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {} }) {
578
568
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
579
569
  if (!halfClaimer) throw new SdkError("bad-input", { field: "halfClaimer" });
@@ -588,7 +578,7 @@ export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {
588
578
  // the order. No call carries the half until the send.
589
579
  await assertHalfMatchesCommit(escrow, halfClaimer, "commitHalfClaimer", "claim", deps);
590
580
  onStep?.("confirm-claim");
591
- // THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE (issue #127): the node lays exactly
581
+ // THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE: the node lays exactly
592
582
  // this limit into the gas gift. It is set explicitly and with a margin: claim has the same trap as order
593
583
  // creation - the wallet estimates gas over a state that no longer exists on the chain (the same reason is
594
584
  // named in the contract, NinseiEscrow.sol:137-138), and the call costs tens of thousands of gas.