@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/actions.mjs CHANGED
@@ -9,6 +9,7 @@
9
9
  // claiming it is revealing your own half (irreversible), for refunding the same reveal. The transaction still
10
10
  // looks successful.
11
11
  import { SdkError } from "./errors.mjs";
12
+ import { ERROR_CODES } from "./codes.mjs";
12
13
  // THE DEAL FLOW IS NOW A PACKAGE MODULE, NOT AN ENGINE FILE (#32, wave 3): www/js/core/swap-flow.js moved to
13
14
  // sdk/src/swap-flow.mjs. The actions therefore call the module directly instead of reaching it through the
14
15
  // mirror - there is exactly one implementation, and it lives here.
@@ -44,13 +45,76 @@ const requestOrFail = (request, extra) => {
44
45
  return request;
45
46
  };
46
47
 
47
- // The engine's refusal arrives as text; a CODE goes out. Texts are the interface's business, the core speaks in codes.
48
+ // A WALLET ERROR IS NOT A CONTRACT REVERT. EIP-1193 providers report a refusal, a missing permission, another
49
+ // chain or a busy request with numeric codes; the old wrapper turned all of them into `contract-reverted`. The
50
+ // interface then told the person the escrow had refused a transaction it never saw. A real revert is recognised
51
+ // by the receipt, a revert-shaped error, or the message - and only then leaves as `contract-reverted`.
52
+ const codeOfError = (error) => error && (error.code || (error.data && error.data.originalError && error.data.originalError.code));
53
+ const messageOfError = (error) => String((error && error.message) || error || "");
54
+ const isProviderError = (error) => {
55
+ const code = codeOfError(error);
56
+ return typeof code === "number" || (typeof code === "string" && !ERROR_CODES.includes(code));
57
+ };
58
+ const actionFailure = (error, step) => {
59
+ // ERRORS ALREADY NAMED BY THE SDK KEEP THEIR CODE. The flow and the chain guards speak the same vocabulary;
60
+ // wrapping them a second time would erase `why` and turn a named refusal into a generic one.
61
+ if (error instanceof SdkError) throw error;
62
+ if (typeof (error && error.code) === "string" && ERROR_CODES.includes(error.code)) {
63
+ throw new SdkError(error.code, { ...(error.params || {}), step });
64
+ }
65
+ const code = codeOfError(error);
66
+ const message = messageOfError(error);
67
+ const receiptStatus = error && error.receipt && error.receipt.status;
68
+ const explicitReject = code === 4001 || code === "ACTION_REJECTED"
69
+ || /user rejected|user denied|rejected by user|denied by user|action_rejected/i.test(message);
70
+ // A NAMED REVERT WINS OVER A MESSAGE THAT MENTIONS "revert"; a wallet's own 4001 wins over generic
71
+ // revert-shaped text, so a localized "cannot be reverted" refusal is not blamed on the escrow.
72
+ const namedRevert = code === "contract-reverted" || code === 3
73
+ || receiptStatus === 0 || receiptStatus === "0x0" || receiptStatus === "0";
74
+ if (namedRevert) throw new SdkError("contract-reverted", { step, why: "revert" });
75
+ // 4001 IS THE PERSON'S DECISION, not a chain answer. A textual rejection is accepted as the same event
76
+ // because some injected providers send no numeric code.
77
+ if (explicitReject) throw new SdkError("wallet-rejected", { step });
78
+ // REVERT DATA ONLY COUNTS AFTER A REFUSAL. A 4001/ACTION_REJECTED error may carry arbitrary provider data;
79
+ // it is still the person's decision, not an escrow answer.
80
+ if ((error && typeof error.data === "string" && error.data.startsWith("0x")) || /execution reverted|revert/i.test(message)) {
81
+ throw new SdkError("contract-reverted", { step, why: "revert" });
82
+ }
83
+ // A DETERMINISTIC WALLET REFUSAL HAS ITS OWN CODE. No gas is a wallet-side state, not a transport failure:
84
+ // retrying the same transaction will fail the same way until the account is funded.
85
+ if (code === "INSUFFICIENT_FUNDS" || /insufficient funds/i.test(message)) {
86
+ throw new SdkError("insufficient-funds", { step });
87
+ }
88
+ // 4902 IS A WALLET THAT DOES NOT KNOW THE CHAIN. It is a wallet-side refusal with its own existing code, not
89
+ // a wrong contract answer.
90
+ if (code === 4902 || /unrecognized chain|not added|unknown chain/i.test(message)) {
91
+ throw new SdkError("wrong-chain", { vm: "evm", step, why: "unknown-chain" });
92
+ }
93
+ // THE WALLET IS NOT USABLE FOR THIS REQUEST. 4100 has no permission for the account, -32002 already has a
94
+ // request open, and a transport failure never reached a node. Keep one wallet-side code and name the reason.
95
+ if (code === 4100) throw new SdkError("wallet-not-connected", { step, why: "unauthorized" });
96
+ if (code === -32002 || /already pending|already processing/i.test(message)) {
97
+ throw new SdkError("wallet-not-connected", { step, why: "request-pending" });
98
+ }
99
+ if (isProviderError(error)) {
100
+ throw new SdkError("wallet-not-connected", { step, why: "transport", providerCode: code ?? null });
101
+ }
102
+ // AN UNCLASSIFIED FAILURE IS NOT A REVERT. The old fallback claimed the escrow refused; that is a statement
103
+ // about the chain we cannot make from an error we did not classify.
104
+ throw new SdkError("unknown", { step, why: "unclassified" });
105
+ };
106
+
107
+ // THE SAME CLASSIFIER FOR THE FUNDING PATH. `actionFailure` throws because the actions wrapper wants that shape;
108
+ // funding needs the named error as a value so it can rethrow it after its own pending-record cleanup.
109
+ export const walletError = (error, step) => {
110
+ try { actionFailure(error, step); }
111
+ catch (named) { return named; }
112
+ return new SdkError("unknown", { step, why: "unclassified" });
113
+ };
114
+
48
115
  const withCodes = async (step, work) => {
49
116
  try { return await work(); }
50
- catch (error) {
51
- if (error && typeof error.code === "string") throw error;
52
- throw new SdkError("contract-reverted", { step });
53
- }
117
+ catch (error) { actionFailure(error, step); }
54
118
  };
55
119
 
56
120
  export function createActions({ call = null, blockTime = null } = {}) {
@@ -74,7 +138,9 @@ export function createActions({ call = null, blockTime = null } = {}) {
74
138
  const tx = from ? { to, data, from } : { to, data };
75
139
  const result = await provider.request({ method: "eth_call", params: [tx, "latest"] });
76
140
  if (typeof result !== "string" || !result.startsWith("0x")) {
77
- throw new SdkError("contract-reverted", { surface: "actions.read" });
141
+ // A MALFORMED `eth_call` ANSWER IS A NODE FAILURE, NOT A WALLET STATE. `unknown` keeps it out of both
142
+ // `contract-reverted` and the wallet-side codes; the reason names what was wrong.
143
+ throw new SdkError("unknown", { surface: "actions.read", why: "bad-answer" });
78
144
  }
79
145
  return result;
80
146
  };
@@ -0,0 +1,16 @@
1
+ // ONE ADDRESS CHECK FOR EVERY PATH THAT CAN MOVE MONEY.
2
+ //
3
+ // `checkAddress` answers the shape, the checksum and the network. A caller that forgets it used to be able to send
4
+ // XMR to a malformed address or to another Monero network; `sweep.sign` and `swaps.start` now share this boundary.
5
+ import { SdkError } from "./errors.mjs";
6
+ import { checkAddress } from "../engine/monero/address.js";
7
+
8
+ export async function checkAddressOrThrow(address, network, field) {
9
+ const shape = await checkAddress(address, network ? { expectNetwork: network } : {});
10
+ if (shape.ok === true) return;
11
+ // THE NETWORK IS A FIELD, NOT A SENTENCE. The refusal still carries the human reason for the caller, but the
12
+ // decision uses the actual network reported by `checkAddress`; editing its wording cannot reclassify the error.
13
+ const wrongNetwork = shape.network !== undefined && network !== null
14
+ && network !== undefined && shape.network !== network;
15
+ throw new SdkError(wrongNetwork ? "wrong-chain" : "bad-input", { field, why: shape.reason || null });
16
+ }
package/src/codes.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // CODE TABLES. The single place where the codes are named: they are read by the SDK, by the check and by the README.
2
2
  //
3
3
  // Why codes and not texts: wording, translations and tone are the interface's business. The core must name a
4
- // state so that it can be translated and coloured without parsing a string (issue #32, requirement 2).
4
+ // state so that it can be translated and coloured without parsing a string.
5
5
 
6
6
  export const STEP_CODES = [
7
7
  "awaiting_funding",
@@ -13,7 +13,7 @@ export const STEP_CODES = [
13
13
  "swept",
14
14
  ];
15
15
 
16
- // `declined` IS A TERMINAL STATE OF ITS OWN (issue #40): the maker refused a funded order, so the whole balance -
16
+ // `declined` IS A TERMINAL STATE OF ITS OWN: the maker refused a funded order, so the whole balance -
17
17
  // the fee included - is already back in the depositor's wallet and NO half was revealed. It is told apart from
18
18
  // `refunded_eth`, which is the depositor taking the ETH back and DOES reveal a half (src/decline.mjs).
19
19
  // `xmr_returned` WAS DECLARED HERE AND IS GONE (it had no writer anywhere): the maker's reclaim of the XMR does
@@ -51,7 +51,7 @@ export const ERROR_CODES = [
51
51
  "wrong-account",
52
52
  "quote-unavailable",
53
53
  "quote-refused",
54
- // A NODE'S ADDRESS DENYLIST REFUSAL (issue #16): the maker's node answers {ok:false, code:"denied-address", why}
54
+ // A NODE'S ADDRESS DENYLIST REFUSAL: the maker's node answers {ok:false, code:"denied-address", why}
55
55
  // before it prices the order, and that refusal reaches the app under THIS code - WITHOUT the node's `why` text
56
56
  // and WITHOUT the address, because the interface shows the person its own neutral message. It is its own code,
57
57
  // not "quote-refused": the advice to the interface differs ("this address is barred" vs "the quote was refused").
@@ -80,7 +80,7 @@ export const ERROR_CODES = [
80
80
  "quote-key-unknown",
81
81
  "quote-provider-mismatch",
82
82
  "quote-provider-not-allowed",
83
- // THE FACTORY THAT WILL VERIFY THE QUOTE AND WHERE ITS FEE GOES (issue #103). The factory is taken from
83
+ // THE FACTORY THAT WILL VERIFY THE QUOTE AND WHERE ITS FEE GOES. The factory is taken from
84
84
  // the provider's REGISTRY RECORD and its CODE is checked against the interface's known builds (extcodehash):
85
85
  // quote-factory-unchecked - no way to read the factory / its code, so the claim stays unproven;
86
86
  // quote-factory-unknown - the record names no factory (zero);
@@ -103,7 +103,7 @@ export const ERROR_CODES = [
103
103
  // THE CLAIM WAS POSTED BUT NO REAL ANSWER CAME BACK. A timeout, a reset or a body without a usable transaction
104
104
  // hash leaves the outcome UNKNOWN: the relay may have sent the claim, and the half is already out of the client.
105
105
  // It is NOT `server-unavailable` (which would invite a blind retry) and NOT a success: the caller must read the
106
- // escrow before doing anything else. `params.why` names the lost part (`answer-lost`, `answer-txid`, ...).
106
+ // escrow before doing anything else. `params.why` names the lost part (`answer-lost`, `answer-txid`,...).
107
107
  "claim-unknown",
108
108
  // THE TRANSACTION WAS SENT BUT THE RECEIPT DOES NOT PROVE AN ESCROW: no receipt yet, no expected OrderCreated,
109
109
  // or a receipt from another factory. The tx hash is the handle for a retry read; nothing was saved as funded.
@@ -112,12 +112,12 @@ export const ERROR_CODES = [
112
112
  // money, not a breakdown and not an empty response: mixing it with other refusals, the interface could not
113
113
  // tell "not arrived yet" from "broken".
114
114
  "xmr-timeout",
115
- // XMR IS ON THE ADDRESS BUT BARRED BY THE TRANSACTION'S unlock_time (issue #84). Distinct from `xmr-timeout`:
115
+ // XMR IS ON THE ADDRESS BUT BARRED BY THE TRANSACTION'S unlock_time. Distinct from `xmr-timeout`:
116
116
  // that one means "nothing arrived within the wait", this one means "money is there and CANNOT be spent until a
117
117
  // height or a date". Marking ready under it would hand the escrow to the maker for funds he cannot be paid from -
118
118
  // so the core refuses with its own code, and the `until` boundary travels in params.
119
119
  "xmr-locked",
120
- // THE XMR ARRIVAL CHECK ON TWO NODES (issue #85). The decision "the XMR arrived" is made by the client, and a
120
+ // THE XMR ARRIVAL CHECK ON TWO NODES. The decision "the XMR arrived" is made by the client, and a
121
121
  // single node is a single truth that can lie. Each code names a different reason the button must stay closed:
122
122
  // xmr-nodes-disagree - a synced node has no such transaction in that block or a different block hash there;
123
123
  // xmr-no-nodes - every node in the list is unreachable, so nothing can be confirmed;
@@ -135,7 +135,19 @@ export const ERROR_CODES = [
135
135
  // normal transfer.
136
136
  "sweep-fee-too-high",
137
137
  "sweep-fee-unknown",
138
- // CLAIM GAS FOR THE XMR SELLER (issue #78). The seller comes from Monero and has no coin on the EVM side to pay
138
+ // THE WITHDRAWAL HAS NO COMPLETE SCAN OR NEEDS MORE THAN ONE TRANSACTION. Signing without a completed restore
139
+ // is a blind spend; a split sweep pays several fees and turns one withdrawal into several transactions.
140
+ "sweep-scan-incomplete",
141
+ "sweep-split",
142
+ // THE SIGNED TRANSACTION AND THE VERIFIED UNSPENT SET MUST NAME THE SAME INPUTS. A signed set that cannot be
143
+ // read is unknown; a set that differs is refused before relay.
144
+ "sweep-inputs-changed",
145
+ "sweep-inputs-unknown",
146
+ // THE WITHDRAWAL WAS SENT BUT THE WALLET DID NOT CONFIRM THE RESULT. A throw or an answer without a transaction
147
+ // id leaves the signed set in the open session. The caller must check the chain before signing again; the same
148
+ // token must not relay that set twice.
149
+ "sweep-relay-unknown",
150
+ // CLAIM GAS FOR THE XMR SELLER. The seller comes from Monero and has no coin on the EVM side to pay
139
151
  // for the claim, so the maker may send it - but only when asked for, and only after the core has CONFIRMED the
140
152
  // gas actually arrived. The three codes name the three states the interface must not blur together:
141
153
  // gas-refused-by-maker - the maker declines to pay the claim gas, and the refusal is shown BEFORE the deal;
@@ -205,6 +217,11 @@ export const ERROR_META = Object.freeze({
205
217
  "insufficient-funds": { retryable: false, side: "wallet" },
206
218
  "sweep-fee-too-high": { retryable: false, side: "chain" },
207
219
  "sweep-fee-unknown": { retryable: true, side: "chain" },
220
+ "sweep-scan-incomplete": { retryable: true, side: "chain" },
221
+ "sweep-split": { retryable: false, side: "wallet" },
222
+ "sweep-inputs-changed": { retryable: false, side: "chain" },
223
+ "sweep-inputs-unknown": { retryable: false, side: "wallet" },
224
+ "sweep-relay-unknown": { retryable: false, side: "chain" },
208
225
  "gas-refused-by-maker": { retryable: false, side: "provider" },
209
226
  "gas-not-arrived": { retryable: true, side: "chain" },
210
227
  "gas-too-little": { retryable: false, side: "provider" },
@@ -260,7 +277,7 @@ export const KIND_TO_CHECK = {
260
277
  "t1-not-after-ready-by": "deadline",
261
278
  "ready-window-too-short": "deadline",
262
279
  "claim-window-too-short": "deadline",
263
- // A DEADLINE TOO FAR AHEAD (issue #88 - a concurrent edit in this tree): the order's t1 is a year away, and the
280
+ // A DEADLINE TOO FAR AHEAD: the order's t1 is a year away, and the
264
281
  // ETH cannot be returned until then. It shares the `deadline` code with the other two extremes.
265
282
  "deadline-too-far": "deadline",
266
283
  // escrow state
package/src/config.mjs CHANGED
@@ -61,7 +61,7 @@ const chainConfig = (chain) => ({
61
61
  // refuses an answer whose `cashier` is not this network's vault, and the funding path fills the order terms
62
62
  // from the same projection. A projection that drops the field leaves a client built from a network NAME with
63
63
  // no vault at all, so every relay quote ends as `no-pinned-cashier` - a defect in the profile, not in the
64
- // answer (sdk#291). Nothing else fills these fields: the projection is the one place both facades read.
64
+ // answer. Nothing else fills these fields: the projection is the one place both facades read.
65
65
  escrow: chain.escrow ? {
66
66
  address: chain.escrow.address || null,
67
67
  mode: chain.escrow.mode || null,
@@ -88,7 +88,7 @@ const chainConfig = (chain) => ({
88
88
  // carry a client for the old node's HTTP surface: those routes were retired, and a client that still names them
89
89
  // would silently make every request against a service that no longer exists.
90
90
 
91
- // THE MONERO NODES THE ARRIVAL IS CHECKED AGAINST. Defaults are the list verified on 2026-10-02 (issue #85):
91
+ // THE MONERO NODES THE ARRIVAL IS CHECKED AGAINST. Defaults are the list verified on 2026-10-02:
92
92
  // mainnet - four public nodes of different operators; stagenet - our node and the one independent public node.
93
93
  // `ready` opens only when two nodes of DIFFERENT operators agree on the block (see sdk/src/xmr-arrival.mjs), so
94
94
  // the list is a list of WITNESSES, not of equal endpoints.
@@ -107,6 +107,11 @@ export const DEFAULT_XMR_NODES = Object.freeze({
107
107
  { url: "https://xmr-stagenet.ninsei.finance", operator: "Ninsei" },
108
108
  { url: "https://stagenet.xmr.kernal.eu:38089", operator: "kernal.eu" },
109
109
  ],
110
+ // TESTNET AND REGTEST HAVE NO PUBLIC NODES OF OURS. The network is accepted, and the map is present but empty:
111
+ // a caller can name its own list through `nodes` or `addNodes`; an empty list is not a typo and not a fallback to
112
+ // stagenet. Without this key, even a valid testnet node list was refused as `unknown`.
113
+ testnet: [],
114
+ fakechain: [],
110
115
  });
111
116
 
112
117
  const nodeEntryOk = (raw) => (typeof raw === "string" && raw)
@@ -117,7 +122,12 @@ const nodesArrayOk = (a) => Array.isArray(a) && a.every(nodeEntryOk);
117
122
  const nodesOf = (options, selected) => {
118
123
  const custom = options && options.nodes;
119
124
  const extra = options && options.addNodes;
120
- const out = { mainnet: [...DEFAULT_XMR_NODES.mainnet], stagenet: [...DEFAULT_XMR_NODES.stagenet] };
125
+ const out = {
126
+ mainnet: [...DEFAULT_XMR_NODES.mainnet],
127
+ stagenet: [...DEFAULT_XMR_NODES.stagenet],
128
+ testnet: [...DEFAULT_XMR_NODES.testnet],
129
+ fakechain: [...DEFAULT_XMR_NODES.fakechain],
130
+ };
121
131
  if (custom !== undefined && custom !== null) {
122
132
  if (nodesArrayOk(custom)) {
123
133
  if (!(selected in out)) fail("bad-input", { field: "nodes", network: selected });
@@ -178,10 +188,53 @@ const endpointsOf = (raw, options) => {
178
188
  };
179
189
  };
180
190
 
191
+ export function escrowOverrideOf(settlement) {
192
+ const raw = settlement && settlement.escrow;
193
+ if (raw === undefined || raw === null) return null;
194
+ if (!settlement || settlement.chain !== "local-anvil") {
195
+ fail("bad-input", { field: "settlement.escrow", why: "only-local-anvil" });
196
+ }
197
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("bad-input", { field: "settlement.escrow" });
198
+ const address = String(raw.address || "");
199
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
200
+ fail("bad-input", { field: "settlement.escrow.address" });
201
+ }
202
+ const text = (field) => {
203
+ if (raw[field] === undefined || raw[field] === null) return null;
204
+ if (typeof raw[field] !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(raw[field])) {
205
+ fail("bad-input", { field: "settlement.escrow." + field });
206
+ }
207
+ return raw[field];
208
+ };
209
+ if (raw.implementationCodeHash !== undefined && raw.implementationCodeHash !== null) {
210
+ if (typeof raw.implementationCodeHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(raw.implementationCodeHash)) {
211
+ fail("bad-input", { field: "settlement.escrow.implementationCodeHash" });
212
+ }
213
+ }
214
+ if (raw.deploymentBlock !== undefined && raw.deploymentBlock !== null
215
+ && (typeof raw.deploymentBlock !== "number" || !Number.isSafeInteger(raw.deploymentBlock) || raw.deploymentBlock < 0)) {
216
+ fail("bad-input", { field: "settlement.escrow.deploymentBlock" });
217
+ }
218
+ return {
219
+ address,
220
+ cashier: text("cashier"),
221
+ registry: text("registry"),
222
+ implementationCodeHash: raw.implementationCodeHash === undefined ? null : raw.implementationCodeHash,
223
+ deploymentBlock: raw.deploymentBlock === undefined || raw.deploymentBlock === null ? null : raw.deploymentBlock,
224
+ };
225
+ }
226
+
181
227
  export function buildConfig(options) {
182
228
  const chains = engine.config.CHAINS.map(chainConfig);
183
229
  const chosen = chains.find((c) => c.id === options.settlement.chain) || null;
184
230
  if (!chosen) fail("bad-input", { field: "settlement.chain", known: chains.map((c) => c.id) });
231
+ // A LOCAL CHAIN'S ADDRESSES ARE CREATED, NOT CONSTANT. The caller may hand the deployment that its own anvil
232
+ // just produced; the address, cashier and implementation pin then travel with the network into quotes, funding and
233
+ // the arrival read. The override is deliberately local-anvil only: a public network's pins stay reviewed data.
234
+ const override = escrowOverrideOf(options.settlement);
235
+ if (override) {
236
+ chosen.escrow = { ...(chosen.escrow || {}), ...override };
237
+ }
185
238
  const rawChain = engine.config.CHAINS.find((c) => c.id === options.settlement.chain) || {};
186
239
  const watch = watchOf(options);
187
240
  const endpoints = endpointsOf(rawChain, options);
package/src/decline.mjs CHANGED
@@ -1,37 +1,17 @@
1
- // THE MAKER'S DECLINE: A STATE OF ITS OWN, TOLD APART FROM AN ORDINARY REFUND.
1
+ // THE MAKER'S DECLINE.
2
2
  //
3
- // WHAT HAPPENS ON THE CHAIN. A maker who refuses a funded purchase - after screening the deposited ETH, say -
4
- // calls `decline()` on the escrow. The contract sets `refunded`, emits `Declined(claimer)` and sends the whole
5
- // balance, the fee included, back to the locker. NO half is revealed: there is nothing to recover, and nobody
6
- // assembles a Monero key from a declined order.
3
+ // A decline is a maker closing a funded order. The escrow sets `refunded`, emits `Declined(claimer)` and returns the
4
+ // balance to the locker. No half is revealed.
7
5
  //
8
- // WHY `status()` IS NOT ENOUGH TO SEE IT. `escrow.status()` answers four words - funded, claimed, refunded,
9
- // balance - and a decline reads exactly like an ordinary refund there: `refunded` is set and the money is back.
10
- // The two are not the same event, though. An ordinary refund is the depositor (or whoever holds their half)
11
- // taking the ETH back when the maker did not claim; it REVEALS THE DEPOSITOR'S HALF (`HalfRevealed(half, false)`)
12
- // so the maker can still take their XMR. A decline is the MAKER closing the order in the depositor's favour and
13
- // reveals nothing. On screen the two want different things said and different buttons hidden, so the SDK tells
14
- // them apart instead of reporting "refunded" for both.
6
+ // `status()` shows the same `refunded` state as an ordinary refund. The SDK reads the `Declined` event or the node's
7
+ // `declined` status with code `compliance` to tell them apart.
15
8
  //
16
- // THE TWO SOURCES, AND EITHER ONE IS ENOUGH:
17
- // 1) THE ESCROW'S `Declined` EVENT (the chain) - `declinedFromLogs`. The escrow has no getter for a decline
18
- // (there is no `declined()` view), so the event is the on-chain fact that names it; it is read through the
19
- // same read seam as every other chain read - an `eth_getLogs` over the escrow's address.
20
- // 2) THE NODE'S SWAP STATUS `declined` WITH THE CODE `compliance` (the wire) - `declinedFromStatus`. Those ARE
21
- // the two fields the node returns and nothing else, so BOTH are required: the bare word without its code is
22
- // not the state the node names, and guessing at it would put a category on a refusal that carries none.
23
- //
24
- // WHAT IS DELIBERATELY NOT CARRIED: a reason, a category, a provider. The node returns only `compliance` on
25
- // purpose - it does not name who declined or why - so the SDK reports the state, the node's own single token and
26
- // which reader saw it, AND NOTHING ELSE (see DECLINE_FIELDS below). The sentence a person reads is the
27
- // interface's: this package holds no user-facing string, and a decline is no exception.
9
+ // The SDK reports the state, the node's token and the reader. It does not invent a reason, a category or a provider.
28
10
  import { SdkError } from "./errors.mjs";
29
11
  import { keccak256 } from "./primitives.mjs";
30
12
  import * as engine from "./engine.mjs";
31
13
 
32
- // THE EVENT, AND ONLY IT. The signature is assembled from its parts and hashed HERE, once, exactly as Solidity
33
- // does it: keccak256("Declined(address)"). The topic is exported so a caller filters logs with it rather than
34
- // deriving it a second time - a second copy of the same event would be a second truth about it.
14
+ // The event signature is assembled once and hashed as Solidity does. Callers filter logs with the exported topic.
35
15
  export const DECLINE_EVENT_NAME = "Declined";
36
16
  export const DECLINE_EVENT_SIGNATURE = () => `${DECLINE_EVENT_NAME}(${["address"].join(",")})`;
37
17
 
@@ -42,33 +22,21 @@ const hexOf = (bytes) => {
42
22
  };
43
23
 
44
24
  /**
45
- * keccak256("Declined(address)") - topic0 of a decline's log. The escrow indexes `claimer`, so a log emitted by the
46
- * current contracts also carries it in topic1; the event signature (and therefore topic0) does not change. Logs from
47
- * escrows deployed before the indexing carry the claimer in data instead, which is why this module matches only
48
- * topic0 and does not assume a claimer position.
25
+ * The `Declined(address)` topic. The current escrow indexes `claimer` in topic1. Older escrows put the claimer in
26
+ * data, so this module matches topic0 only.
49
27
  */
50
28
  export const DECLINED_TOPIC0 = hexOf(keccak256(DECLINE_EVENT_SIGNATURE()));
51
29
 
52
- // THE NODE'S OWN TWO FIELDS for a declined swap: `{ status: "declined", code: "compliance" }`. The code is the
53
- // node's single token, deliberately opaque: it says "a screening decision was taken", not by whom or on what.
30
+ // The node's two fields for a declined swap: `{ status: "declined", code: "compliance" }`. The code is opaque.
54
31
  export const DECLINED_STATUS = "declined";
55
32
  export const DECLINED_CODE = "compliance";
56
33
 
57
- // THE STATE'S OWN CODE - a `TerminalCode` (`index.d.ts`). The interface draws the decline screen from THIS, and
58
- // phrases the sentence itself; the package contributes the state and the code, not the words.
34
+ // The terminal state the interface draws from. The package supplies the state and the code, not the words.
59
35
  export const DECLINED_TERMINAL = "declined";
60
36
 
61
37
  /**
62
- * THE WHOLE SET OF FIELDS A DECLINE IS REPORTED WITH - and the list is short ON PURPOSE. Everything else would be
63
- * a reason, a category or a provider, and the node names none of those:
64
- * `declined` - what happened (true/false);
65
- * `terminal` - the state the interface draws from (`declined`, or null);
66
- * `code` - the node's own token, UNCHANGED, or null;
67
- * `source` - which reader saw it: `event` (the escrow) or `status` (the node). PROVENANCE, NOT A REASON:
68
- * it says where the SDK learned it, not why the maker refused;
69
- * `at` - when it was seen (epoch ms), or null;
70
- * `checked` - whether the chain was read at all. `false` means "not measured", which is NOT "no decline" - a
71
- * caller that blurs the two would read a maker's refusal as an ordinary refund.
38
+ * The fields of a decline report. Keep this list short. `source` is provenance, not a reason. `checked: false` means
39
+ * the chain was not read, which is not the same as "no decline".
72
40
  */
73
41
  export const DECLINE_FIELDS = ["declined", "terminal", "code", "source", "at", "checked"];
74
42
 
@@ -92,13 +60,8 @@ export const declineNone = ({ source = null, at = null, checked = true } = {}) =
92
60
  verdictOf({ declined: false, terminal: null, code: null, source, at, checked });
93
61
 
94
62
  /**
95
- * SOURCE 1 - THE ESCROW'S `Declined` EVENT. `logs` is what the log read answered: an ARRAY of log objects.
96
- * Anything that is not an array is a refusal (`bad-input`), never "no decline": an unread chain must not be
97
- * reported as an escrow that declined nothing.
98
- *
99
- * Only the FIRST TOPIC is compared (the event's own signature). A log from another address is skipped when the
100
- * answer carries one and the caller named the escrow; a log without an address is still matched, because the
101
- * request that produced it was filtered by address and dropping it would hide a real decline.
63
+ * The escrow's `Declined` event. `logs` must be an array. A log from another address is skipped when the caller named
64
+ * the escrow. A log without an address still matches because the read was filtered by address.
102
65
  */
103
66
  export function declinedFromLogs(logs, { escrow = null, at = null } = {}) {
104
67
  if (!Array.isArray(logs)) throw new SdkError("bad-input", { field: "logs", why: "not-array" });
@@ -113,13 +76,8 @@ export function declinedFromLogs(logs, { escrow = null, at = null } = {}) {
113
76
  }
114
77
 
115
78
  /**
116
- * SOURCE 2 - THE NODE'S SWAP STATUS. `{ status: "declined", code: "compliance" }`, in either of the two shapes
117
- * the wire carries it in: at the top level of the answer (the swap state a backend relays) or NESTED UNDER
118
- * `userStatus` (the field the maker API names it by). BOTH fields must be there and must be exactly these tokens;
119
- * anything else is not the state the node names, and a partial match is NOT a decline.
120
- *
121
- * A body that is not an object at all answers `checked: false` - there was nothing to read, which is not the same
122
- * as having read it and found no decline.
79
+ * The node's status. It accepts `{ status: "declined", code: "compliance" }` at the top level or under `userStatus`.
80
+ * Both fields must match. A body that is not an object answers `checked: false`.
123
81
  */
124
82
  export function declinedFromStatus(body, { at = null } = {}) {
125
83
  if (!body || typeof body !== "object") return declineNone({ source: "status", at, checked: false });
@@ -133,10 +91,8 @@ export function declinedFromStatus(body, { at = null } = {}) {
133
91
  }
134
92
 
135
93
  /**
136
- * BOTH SOURCES AT ONCE, AND EITHER ONE IS ENOUGH - the form the flow uses. The chain is asked first (the escrow's
137
- * own event is the stronger fact) and the wire second; a source that was not read is named as such (its own
138
- * verdict stays, with `source: null` when neither was read), and a body without the node's two fields does not
139
- * cancel a chain answer.
94
+ * Both sources. Either one is enough. The chain is read first and the wire second. A body without the node's fields
95
+ * does not cancel a chain answer.
140
96
  */
141
97
  export function declineOf({ logs = undefined, status = undefined, escrow = null, at = null } = {}) {
142
98
  const fromChain = Array.isArray(logs) ? declinedFromLogs(logs, { escrow, at }) : null;
@@ -149,14 +105,8 @@ export function declineOf({ logs = undefined, status = undefined, escrow = null,
149
105
  }
150
106
 
151
107
  /**
152
- * THE DEFAULT CHAIN LOG READER: `eth_getLogs` THROUGH THE PAGE'S WALLET - the same provider the engine's
153
- * `readContract` uses, so the wallet that reads is the wallet that will sign (the rule the whole chain-read seam
154
- * follows). It is a READ, not a node substitution: the address is the caller's escrow and the filter is the
155
- * decline's own topic.
156
- *
157
- * `fromBlock` is the caller's: a watch that knows the escrow's birth height scans from there instead of walking
158
- * the chain's whole history. An answer that is not an array is a REFUSAL - a node that answered something else
159
- * did not answer "no decline", and a caller must not read it as one.
108
+ * The default log reader: `eth_getLogs` through the page wallet, so the reader and the signer use the same provider.
109
+ * `fromBlock` is the caller's. An answer that is not an array is a refusal, not "no decline".
160
110
  */
161
111
  export async function readDeclinedLogs({ address, topics = [DECLINED_TOPIC0], fromBlock = "earliest", toBlock = "latest" } = {}) {
162
112
  if (typeof address !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(address)) throw new SdkError("bad-input", { field: "logs.address" });
@@ -172,9 +122,8 @@ export async function readDeclinedLogs({ address, topics = [DECLINED_TOPIC0], fr
172
122
  export const logReaderOf = (logs) => (typeof logs === "function" ? logs : readDeclinedLogs);
173
123
 
174
124
  /**
175
- * A BLOCK BOUNDARY AS THE NODE WANTS IT (hex quantity), for a caller that knows where its escrow was born.
176
- * A value that is not a whole, non-negative number is the fallback - the safe end of the chain, not an invented
177
- * block: scanning too far is slow, scanning too little misses the event.
125
+ * A block boundary as the node wants it. A value that is not a whole, non-negative number falls back to the safe end
126
+ * of the chain. Scanning too far is slow. Scanning too little misses the event.
178
127
  */
179
128
  export const blockBoundaryOf = (height, fallback = "earliest") => {
180
129
  const value = Number(height);
@@ -0,0 +1,80 @@
1
+ // A FIRM REQUEST'S DEADLINES, FROM THE MAKER'S SIGNED WINDOW AND THE CHAIN'S CLOCK.
2
+ //
3
+ // The maker publishes `readyMinSeconds..readyMaxSeconds` and `settlementMinSeconds..settlementMaxSeconds`; the client
4
+ // must place `readyBy` and `t1` inside those ranges, not on their edges. The node later judges the request by its own
5
+ // clock, which is later than the chain block the card read, so the lower edge needs more room than the upper one.
6
+ import { SdkError } from "./errors.mjs";
7
+ import { readReadyWindow } from "./readyWindow.mjs";
8
+
9
+ export const READY_MARGIN_SEC = 150;
10
+ export const DEADLINE_MARGIN_SEC = 60;
11
+
12
+ const int = (value) => {
13
+ const n = Number(value);
14
+ return Number.isSafeInteger(n) ? n : null;
15
+ };
16
+
17
+ const inside = (min, max, margin) => (max - min >= 2 * margin
18
+ ? min + margin
19
+ : min + Math.floor((max - min) / 2));
20
+
21
+ const readyInside = (min, max) => {
22
+ const room = max - min;
23
+ if (room < 2 * DEADLINE_MARGIN_SEC) return min + Math.floor(room / 2);
24
+ return min + Math.min(READY_MARGIN_SEC, room - DEADLINE_MARGIN_SEC);
25
+ };
26
+
27
+ /**
28
+ * Pick the one signed window for a market, side and Monero network. A missing or ambiguous match is a refusal, never
29
+ * the first window on the list: two networks for the same market are a real case, and picking the wrong one changes
30
+ * the order's Monero network.
31
+ */
32
+ export function firmWindowFor({ features, side, market, xmrNetwork } = {}) {
33
+ if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
34
+ if (side !== "ask" && side !== "bid") throw new SdkError("bad-input", { field: "side" });
35
+ if (typeof market !== "string" || !market) throw new SdkError("bad-input", { field: "market" });
36
+ if (typeof xmrNetwork !== "string" || !xmrNetwork) throw new SdkError("bad-input", { field: "xmrNetwork" });
37
+ if (!Array.isArray(features.firmWindows)) throw new SdkError("bad-input", { field: "features.firmWindows" });
38
+ const matches = features.firmWindows.filter((entry) => entry && entry.market === market && entry.side === side
39
+ && entry.xmrNetwork === xmrNetwork);
40
+ if (matches.length !== 1) {
41
+ throw new SdkError("bad-input", { field: "features.firmWindows",
42
+ why: matches.length ? "duplicate-window" : "window", market, side, xmrNetwork });
43
+ }
44
+ return readReadyWindow(matches[0], { side, field: "features.firmWindows" });
45
+ }
46
+
47
+ /**
48
+ * The deadlines for one signed window at the chain's `chainNow` (Unix seconds): `readyBy` and `t1`, in chain seconds.
49
+ * The margins are the same ones the site used: 150 s from the lower readiness edge, 60 s from the upper readiness
50
+ * edge and from both settlement edges.
51
+ */
52
+ export function firmDeadlines(window, chainNow) {
53
+ const ready = readReadyWindow(window);
54
+ const now = int(chainNow);
55
+ if (now === null || now <= 0) throw new SdkError("bad-input", { field: "chainNow" });
56
+ const settleMin = int(ready.settlementMinSeconds);
57
+ const settleMax = int(ready.settlementMaxSeconds);
58
+ if (settleMin === null || settleMax === null || settleMin <= 0 || settleMax < settleMin) {
59
+ throw new SdkError("bad-input", { field: "features.firmWindows", why: "settlement" });
60
+ }
61
+ const readyBy = now + readyInside(ready.readyMinSeconds, ready.readyMaxSeconds);
62
+ const t1 = readyBy + inside(settleMin, settleMax, DEADLINE_MARGIN_SEC);
63
+ if (!(t1 > readyBy)) throw new SdkError("bad-input", { field: "features.firmWindows", why: "deadlines" });
64
+ return { readyBy, t1 };
65
+ }
66
+
67
+ /**
68
+ * The firm-request builder: one window, selected by market, side and Monero network, and its deadlines on the chain
69
+ * clock. The caller spreads `readyBy`/`t1` into the order it then gives to `quotes.firmRelay`.
70
+ */
71
+ export function firmRequest({ features, side, market, xmrNetwork, chainNow } = {}) {
72
+ const window = firmWindowFor({ features, side, market, xmrNetwork });
73
+ return Object.freeze({
74
+ market,
75
+ side,
76
+ xmrNetwork,
77
+ window,
78
+ ...firmDeadlines(window, chainNow),
79
+ });
80
+ }