@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/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 };
@@ -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
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // src/public/recovery.mjs only NAMES what the engine already offers; these declarations NAME the same thing for a
5
5
  // TypeScript consumer. Every signature is copied from the module the barrel re-exports
6
- // (`engine/recovery/recoveryFile.js`, itself a generated byte-for-byte copy of the engine source), and a symbol
6
+ // (`engine/recovery/recoveryFile.js`, the SDK's engine source for the recovery envelope), and a symbol
7
7
  // the barrel does not re-export is not declared here.
8
8
  //
9
9
  // NO DOM AND NO ARGUMENTS: the module touches WebCrypto (`crypto.subtle`), `btoa`/`atob` and the text encoders,
@@ -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) {
@@ -11,6 +11,10 @@ const ADDRESS = /^0x[0-9a-f]{40}$/;
11
11
  const HALF = /^[0-9a-f]{64}$/;
12
12
  const TXID = /^0x[0-9a-f]{64}$/;
13
13
  const DECIMAL = /^(0|[1-9][0-9]*)$/;
14
+ // RELAY-LEVEL ANSWERS ARE NOT THE SENDER'S REFUSAL. A rate limit, a malformed request or a version/quote problem
15
+ // describes the hop, not the sender; the half may not have been forwarded. They keep the conservative unknown
16
+ // outcome so the sender's slot is still read, instead of marking that sender as refused for good.
17
+ const RELAY_LEVEL_CODES = new Set(["rate_limited", "bad_request", "unsupported_version", "no_quote"]);
14
18
 
15
19
  /**
16
20
  * THE RELAY ORIGIN, NORMALISED ONCE. A claim is bound to the origin that answered the quote, so a trailing slash
@@ -42,9 +46,11 @@ export function halfTextOf(value) {
42
46
  * POST the half to the relay that answered the quote.
43
47
  *
44
48
  * A refusal from the relay is `quote-refused` with the provider's own code kept in `params.code`; the provider's
45
- * message is deliberately NOT copied, because it is not this package's user-facing text. A lost answer is
46
- * `claim-unknown`: the claim may have been sent, so a second call must begin by reading the escrow, never by
47
- * assuming that nothing happened. Only a validated transaction hash is a success.
49
+ * message is deliberately NOT copied, because it is not this package's user-facing text. A relay-level answer
50
+ * (`rate_limited`, `bad_request`, `unsupported_version`, `no_quote`) is `claim-unknown`: it names the hop, not the
51
+ * sender, and the half may not have been forwarded. A lost answer is `claim-unknown`: the claim may have been sent,
52
+ * so a second call must begin by reading the escrow, never by assuming that nothing happened. Only a validated
53
+ * transaction hash is a success.
48
54
  */
49
55
  export async function postRelayClaim({
50
56
  relayUrl,
@@ -88,6 +94,10 @@ export async function postRelayClaim({
88
94
  if (code === "claim-unknown" || code === "claim_unknown") {
89
95
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-timeout", code, status: response.status, outcome: "unknown" });
90
96
  }
97
+ if (code && RELAY_LEVEL_CODES.has(code)) {
98
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
99
+ code, status: response.status, outcome: "unknown" });
100
+ }
91
101
  if (code && version === 1) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
92
102
  // AN UNVERSIONED NON-2XX IS NOT A REFUSAL WE CAN READ. The claim may still have been sent, so it is unknown.
93
103
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-status", status: response.status, outcome: "unknown" });
@@ -95,6 +105,10 @@ export async function postRelayClaim({
95
105
  if (!answer || version !== 1) {
96
106
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer", outcome: "unknown" });
97
107
  }
108
+ if (code && RELAY_LEVEL_CODES.has(code)) {
109
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
110
+ code, status: response.status, outcome: "unknown" });
111
+ }
98
112
  if (code) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
99
113
 
100
114
  // ONLY A REAL TRANSACTION HASH IS A CLAIM. A body without one leaves the outcome unknown, whether the claim never
@@ -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();