@ninsei-labs/sdk 0.56.1 → 0.57.2

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 (55) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +17 -4
  4. package/THIRD_PARTY_NOTICES.md +174 -0
  5. package/assets/vendors/MANIFEST.json +1 -5
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +17 -24
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/swap.js +7 -7
  12. package/engine/evm/asyncRoute.js +1 -1
  13. package/engine/evm/claimGas.js +2 -1
  14. package/engine/evm/escrow.js +13 -8
  15. package/engine/evm/factory.js +11 -6
  16. package/engine/evm/funding.js +8 -3
  17. package/engine/evm/index.js +2 -4
  18. package/engine/evm/session.js +3 -3
  19. package/engine/monero/scan.js +101 -22
  20. package/engine/recovery/restore.js +8 -8
  21. package/engine/sdk/bridge.js +2 -5
  22. package/index.d.ts +48 -11
  23. package/package.json +4 -2
  24. package/src/actions.mjs +8 -5
  25. package/src/codes.mjs +5 -0
  26. package/src/config.mjs +1 -0
  27. package/src/engine.mjs +6 -6
  28. package/src/feeEstimate.mjs +11 -4
  29. package/src/http.mjs +4 -1
  30. package/src/index.mjs +1 -1
  31. package/src/legs/kyber.mjs +23 -0
  32. package/src/lock.mjs +1 -0
  33. package/src/order.mjs +108 -20
  34. package/src/primitives.mjs +4 -5
  35. package/src/probes.mjs +9 -3
  36. package/src/public/networks.d.ts +45 -0
  37. package/src/public/networks.mjs +10 -1
  38. package/src/public/xmr.mjs +1 -1
  39. package/src/quotes.mjs +97 -23
  40. package/src/recovery-key.mjs +32 -14
  41. package/src/relayFeatures.mjs +25 -13
  42. package/src/relayFirmClient.mjs +33 -7
  43. package/src/relayQuote.mjs +87 -10
  44. package/src/relayView.mjs +3 -3
  45. package/src/swap-flow.mjs +100 -58
  46. package/src/swaps.mjs +234 -64
  47. package/src/sweep-restore.mjs +8 -4
  48. package/src/sweep.mjs +5 -1
  49. package/src/version.mjs +1 -1
  50. package/src/xmr-arrival.mjs +55 -24
  51. package/assets/vendors/atomic/atomic-browser.js +0 -24
  52. package/engine/atomic/order-client.js +0 -56
  53. package/engine/atomic/order-worker.js +0 -156
  54. package/engine/evm/asyncExec.js +0 -577
  55. package/engine/evm/asyncLegs.js +0 -308
@@ -1,308 +0,0 @@
1
- // GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/asyncLegs.js for the SDK package.
2
- // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
3
- // Everything below this header is identical to the source.
4
-
5
- // THE KYBERSWAP LIMIT ORDER LEG, EXECUTED ON THE PAGE - THE LIQUIDITY LEG OF A COMPOSED ROUTE.
6
- //
7
- // WHAT IT IS AND WHY THE ENGINE REACHES FOR IT AT ALL. KyberSwap Limit Order is an intent auction: the Maker signs
8
- // an EIP-712 order off-chain (no gas), the order is stored in KyberSwap's book, and a Taker settles it on chain
9
- // later. It is an ASYNCHRONOUS provider like CoWSwap - but its orders trade ERC20 against ERC20 and its API refuses
10
- // native coin as an order asset (error 4004), so it settles the WRAPPED native (WETH), not native. Our escrow is
11
- // funded with NATIVE coin, so this provider can never be the last mile: it is the LIQUIDITY leg, and reaching native
12
- // is a SECOND order on a native-capable provider (CoWSwap, evm/asyncExec.js). This module is the first leg.
13
- //
14
- // WHY HERE AND NOT IN THE PACKAGE. The page cannot import the package's sources (they pull bare npm specifiers and
15
- // the DOM-free package never sees the page wallet); it reaches the core only through a built bundle whose surface is
16
- // fixed. So the provider's CONTRACT (the EIP-712 order fields, the domain, the order book paths, the status
17
- // vocabulary, the refusal codes) is repeated here - exactly as the CoW contract is repeated in evm/asyncExec.js -
18
- // and the agreement of the two is a CHECK (tools/check-async-route-compose.mjs compares every constant against
19
- // sdk/src/legs/kyber.mjs and sdk/src/legs/kyber-spec.mjs), never a promise in a comment.
20
- //
21
- // NO NEW DEPENDENCY: the transport is the page's fetch, the signature is the wallet's own eth_signTypedData_v4,
22
- // and the typed data comes FROM THE ORDER BOOK'S sign-message endpoint (validated against this spec before it is
23
- // trusted). Nothing is trusted to a library.
24
- //
25
- // EVERY FAILURE IS A NAMED VALUE ({ ok: false, code }), never silence and never a funded deal with no swap behind it.
26
-
27
- // THE ORDER BOOK: one base URL for every chain (docs.kyberswap.com, "Base URL: https://limit-order.kyberswap.com").
28
- export const KYBER_LEG_ORDERBOOK = "https://limit-order.kyberswap.com";
29
- // The venue name, assembled from parts (a single multi-word literal would read as user-facing text to the SDK).
30
- export const KYBER_LEG_VENUE = ["KyberSwap", "Limit", "Order"].join(" ");
31
-
32
- // THE EIP-712 DOMAIN AND THE VERIFYING CONTRACT - DSLOProtocol, identical on every network KyberSwap serves
33
- // (docs.kyberswap.com, "Contracts & Addresses"; sdk/src/legs/kyber-spec.mjs).
34
- export const KYBER_LEG_DOMAIN_NAME = ["Kyber", "DSLO", "Protocol"].join(" ");
35
- export const KYBER_LEG_DOMAIN_VERSION = "1";
36
- export const KYBER_LEG_CONTRACT = "0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C";
37
-
38
- // THE ORDER FIELDS AND THEIR TYPES, IN PROTOCOL ORDER - DSOrderMixin.LIMIT_ORDER_TYPEHASH. The order IS the protocol:
39
- // a reordered or retyped field still produces a valid signature and is refused by the contract, so the field list is
40
- // pinned against sdk/src/legs/kyber-spec.mjs (KYBER_ORDER_FIELDS) by the check.
41
- export const KYBER_LEG_ORDER_FIELDS = [
42
- ["salt", "uint256"],
43
- ["makerAsset", "address"],
44
- ["takerAsset", "address"],
45
- ["maker", "address"],
46
- ["receiver", "address"],
47
- ["allowedSender", "address"],
48
- ["makingAmount", "uint256"],
49
- ["takingAmount", "uint256"],
50
- ["feeConfig", "uint256"],
51
- ["makerAssetData", "bytes"],
52
- ["takerAssetData", "bytes"],
53
- ["getMakerAmount", "bytes"],
54
- ["getTakerAmount", "bytes"],
55
- ["predicate", "bytes"],
56
- ["interaction", "bytes"],
57
- ];
58
-
59
- // THE ENDPOINTS (docs.kyberswap.com, "Limit Order API" endpoint index and the Maker API reference).
60
- export const KYBER_LEG_SIGN_MESSAGE_PATH = "/write/api/v1/orders/sign-message";
61
- export const KYBER_LEG_CREATE_PATH = "/write/api/v1/orders";
62
- export const KYBER_LEG_MAKER_ORDERS_PATH = "/read-ks/api/v1/orders";
63
-
64
- // THE STATUS VOCABULARY (Maker API "Get List Of Orders By Maker" `status` enum). `active` and `closed` are umbrella
65
- // FILTER values; an item `status` is one of the concrete ones. A status outside this set is not "probably fine" - it
66
- // is "kyber-bad-response".
67
- export const KYBER_LEG_STATUSES = ["active", "open", "partially_filled", "cancelling", "closed", "filled", "cancelled", "expired"];
68
- export const KYBER_LEG_FINAL_STATUSES = ["filled", "cancelled", "expired"];
69
- export const KYBER_LEG_SETTLED_STATUS = "filled";
70
- export const KYBER_LEG_OPEN_STATUSES = ["open", "partially_filled", "cancelling"];
71
- // The buckets queried while waiting for an outcome: `active` covers open/partially_filled/cancelling, `closed`
72
- // covers filled/cancelled/expired.
73
- export const KYBER_LEG_STATUS_BUCKETS = ["active", "closed"];
74
-
75
- // THE NAMED REFUSALS. Every one is a VALUE ({ ok: false, code }), never null: a caller can always tell unreachable
76
- // from refused from not-settled-yet.
77
- export const KYBER_LEG_REFUSAL_CODES = [
78
- "kyber-unknown-network", // the chain has no order book here
79
- "kyber-bad-order", // the order is incomplete or malformed - nothing to sign
80
- "kyber-sign-failed", // the wallet did not produce a signature
81
- "kyber-unreachable", // no answer from the order book (connection or timeout)
82
- "kyber-order-unknown", // the order book does not know this order id for this maker
83
- "kyber-refused", // the order book answered and did not accept (carries the status and its reason)
84
- "kyber-bad-response", // the answer is not the shape we know (including typed data that is not this spec)
85
- "kyber-not-settled", // the order stayed open until the timeout - "not yet", not "broken"
86
- ];
87
-
88
- const refusal = (code, params = {}) => ({ ok: false, code, params });
89
-
90
- const isAddress = (v) => /^0x[0-9a-fA-F]{40}$/.test(String(v || ""));
91
- const isPositive = (v) => { try { return BigInt(String(v)) > 0n; } catch { return false; } };
92
- const isSignature = (v) => /^0x[0-9a-fA-F]{130}$/.test(String(v || ""));
93
-
94
- const joinUrl = (base, path) => String(base || "").replace(/\/+$/, "") + path;
95
-
96
- // ONE JSON REQUEST. A thrown fetch is kyber-unreachable, an unreadable body is kyber-bad-response - never silence.
97
- async function ask({ fetchImpl, url, method = "GET", body = null, timeoutMs = 20_000 }) {
98
- const doFetch = fetchImpl || (typeof fetch === "function" ? fetch : null);
99
- if (!doFetch) return refusal("kyber-unreachable", { why: "no-fetch" });
100
- let timer = null;
101
- try {
102
- const options = { method, headers: body === null ? undefined : { "content-type": "application/json" } };
103
- if (body !== null) options.body = JSON.stringify(body);
104
- const signal = typeof AbortController === "function" ? new AbortController() : null;
105
- if (signal) { options.signal = signal.signal; timer = setTimeout(() => signal.abort(), timeoutMs); }
106
- const res = await doFetch(url, options);
107
- let text = null;
108
- try { text = await res.text(); } catch { text = null; }
109
- return { ok: true, status: Number(res.status), text };
110
- } catch (error) {
111
- return refusal("kyber-unreachable", { why: String((error && error.message) || error) });
112
- } finally {
113
- if (timer) clearTimeout(timer);
114
- }
115
- }
116
-
117
- /**
118
- * THE INTENT REQUEST: from what the person gives, build the body the order book's sign-message endpoint expects.
119
- * Returns { ok: true, params, expectedOutWei } or a named refusal. Pure - no network, no wallet. The order book
120
- * computes feeConfig/getMakerAmount/getTakerAmount/predicate itself; we only name the trade (token -> wrapped native).
121
- */
122
- export function kyberLegPlan(request = {}) {
123
- const maker = request.maker;
124
- const receiver = request.receiver === undefined || request.receiver === null ? maker : request.receiver;
125
- const params = {
126
- chainId: String(request.chainId),
127
- makerAsset: request.makerAsset,
128
- takerAsset: request.takerAsset,
129
- maker,
130
- receiver,
131
- makingAmount: String(request.makingAmount),
132
- takingAmount: String(request.takingAmount),
133
- expiredAt: request.expiredAt,
134
- };
135
- if (request.allowedSenders !== undefined && request.allowedSenders !== null) params.allowedSenders = request.allowedSenders;
136
- const missing = [];
137
- if (!Number.isInteger(Number(params.chainId))) missing.push("chainId");
138
- if (!isAddress(maker)) missing.push("maker");
139
- if (!isAddress(params.makerAsset)) missing.push("makerAsset");
140
- if (!isAddress(params.takerAsset)) missing.push("takerAsset");
141
- if (!isAddress(params.receiver)) missing.push("receiver");
142
- if (!isPositive(params.makingAmount)) missing.push("makingAmount");
143
- if (!isPositive(params.takingAmount)) missing.push("takingAmount");
144
- if (!Number.isInteger(Number(params.expiredAt))) missing.push("expiredAt");
145
- if (missing.length) return refusal("kyber-bad-order", { missing: [...new Set(missing)] });
146
- return { ok: true, chainId: Number(params.chainId), params, expectedOutWei: String(params.takingAmount) };
147
- }
148
-
149
- /**
150
- * ASK FOR THE UNSIGNED ORDER. POST sign-message -> { types, domain, primaryType, message }. The returned typed data
151
- * is VALIDATED against this spec before it is trusted: the domain must be Kyber's and this contract's, the chain must
152
- * be the order's, the Order types must be EXACTLY KYBER_LEG_ORDER_FIELDS, and the message must be complete. Typed
153
- * data that does not agree is a NAMED refusal (kyber-bad-response), never signed anyway.
154
- */
155
- export async function kyberLegUnsigned({ params, chainId = null, orderbook = null, fetchImpl = null, timeoutMs = 20_000 } = {}) {
156
- const id = Number(chainId !== null ? chainId : params && params.chainId);
157
- const base = orderbook ? String(orderbook).replace(/\/+$/, "") : KYBER_LEG_ORDERBOOK;
158
- if (!Number.isFinite(id)) return refusal("kyber-unknown-network", { chainId: null });
159
- if (!params || typeof params !== "object") return refusal("kyber-bad-order", { field: "params" });
160
- const res = await ask({ fetchImpl, url: joinUrl(base, KYBER_LEG_SIGN_MESSAGE_PATH), method: "POST", body: params, timeoutMs });
161
- if (!res.ok) return res;
162
- if (res.status >= 400) return refusal("kyber-refused", { status: res.status, stage: "sign-message", reason: null });
163
- let body = null;
164
- try { body = JSON.parse(res.text); } catch { body = null; }
165
- const data = body && body.data;
166
- if (!data || typeof data !== "object") return refusal("kyber-bad-response", { where: "sign-message" });
167
- const domain = data.domain || {};
168
- const message = data.message || {};
169
- const typeNames = (data.types && Array.isArray(data.types.Order)) ? data.types.Order.map((t) => (t ? t.name : "") + ":" + (t ? t.type : "")).join(",") : null;
170
- const expectedNames = KYBER_LEG_ORDER_FIELDS.map(([name, type]) => name + ":" + type).join(",");
171
- const domainOk = String(domain.name) === KYBER_LEG_DOMAIN_NAME
172
- && String(domain.version) === KYBER_LEG_DOMAIN_VERSION
173
- && Number(domain.chainId) === id
174
- && String(domain.verifyingContract || "").toLowerCase() === KYBER_LEG_CONTRACT.toLowerCase();
175
- if (!domainOk) return refusal("kyber-bad-response", { where: "sign-message", field: "domain" });
176
- if (typeNames !== expectedNames) return refusal("kyber-bad-response", { where: "sign-message", field: "types" });
177
- const missing = KYBER_LEG_ORDER_FIELDS.filter(([name]) => message[name] === undefined || message[name] === null || message[name] === "");
178
- if (missing.length) return refusal("kyber-bad-response", { where: "sign-message", missing: missing.map((m) => m[0]) });
179
- return {
180
- ok: true,
181
- chainId: id,
182
- orderbook: base,
183
- contract: KYBER_LEG_CONTRACT,
184
- salt: String(message.salt),
185
- message,
186
- typedData: { domain, types: data.types, primaryType: data.primaryType || "Order", message },
187
- };
188
- }
189
-
190
- /**
191
- * SIGN THE UNSIGNED ORDER THROUGH THE WALLET. The adapter's own signTypedData when present (it wraps
192
- * eth_signTypedData_v4), otherwise the same call through the wallet's EIP-1193 driver. A wallet that will not sign
193
- * is kyber-sign-failed, not a crash.
194
- */
195
- export async function kyberLegSign({ typedData, wallet = null, address = null } = {}) {
196
- if (!typedData || typeof typedData !== "object") return refusal("kyber-bad-order", { field: "typedData" });
197
- try {
198
- if (wallet && typeof wallet.signTypedData === "function") {
199
- const signature = await wallet.signTypedData(typedData);
200
- if (!isSignature(signature)) return refusal("kyber-sign-failed", { why: "bad-signature-shape" });
201
- return { ok: true, signature };
202
- }
203
- const driver = wallet && typeof wallet.driver === "function" ? wallet.driver() : wallet;
204
- if (driver && typeof driver.request === "function") {
205
- const from = address || (wallet && typeof wallet.address === "function" ? await wallet.address() : null);
206
- const signature = await driver.request({ method: "eth_signTypedData_v4", params: [from, JSON.stringify(typedData)] });
207
- if (!isSignature(signature)) return refusal("kyber-sign-failed", { why: "bad-signature-shape" });
208
- return { ok: true, signature };
209
- }
210
- return refusal("kyber-sign-failed", { why: "no-wallet" });
211
- } catch (error) {
212
- return refusal("kyber-sign-failed", { why: String((error && error.code) || (error && error.message) || error) });
213
- }
214
- }
215
-
216
- /**
217
- * SUBMIT THE SIGNED ORDER. POST write path -> { data: { id } }. The body carries the request plus the salt from the
218
- * sign-message response and the Maker's signature. Every failure is one of the named refusals above.
219
- */
220
- export async function kyberLegSubmit({ params, salt, signature, orderbook = null, chainId = null, fetchImpl = null, timeoutMs = 20_000 } = {}) {
221
- const base = orderbook ? String(orderbook).replace(/\/+$/, "") : KYBER_LEG_ORDERBOOK;
222
- if (!params || typeof params !== "object") return refusal("kyber-bad-order", { field: "params" });
223
- if (!isSignature(signature)) return refusal("kyber-bad-order", { field: "signature" });
224
- if (salt === undefined || salt === null || salt === "") return refusal("kyber-bad-order", { field: "salt" });
225
- const body = { ...params, salt: String(salt), signature };
226
- const res = await ask({ fetchImpl, url: joinUrl(base, KYBER_LEG_CREATE_PATH), method: "POST", body, timeoutMs });
227
- if (!res.ok) return res;
228
- if (res.status >= 400) return refusal("kyber-refused", { status: res.status, stage: "submit", reason: null });
229
- let parsed = null;
230
- try { parsed = JSON.parse(res.text); } catch { parsed = null; }
231
- const created = parsed && parsed.data;
232
- const id = created && created.id;
233
- if (!Number.isInteger(Number(id)) || Number(id) <= 0) return refusal("kyber-bad-response", { where: "submit", got: typeof id });
234
- return { ok: true, id: Number(id), chainId: Number.isFinite(Number(chainId)) ? Number(chainId) : null };
235
- }
236
-
237
- /**
238
- * READ ONE ORDER's status. GET maker orders by bucket; the order is looked up by id. A status word outside
239
- * KYBER_LEG_STATUSES is kyber-bad-response; an id found in neither bucket is kyber-order-unknown - never silence.
240
- */
241
- export async function kyberLegRead({ id, chainId, maker, orderbook = null, fetchImpl = null, timeoutMs = 20_000 } = {}) {
242
- const base = orderbook ? String(orderbook).replace(/\/+$/, "") : KYBER_LEG_ORDERBOOK;
243
- const chain = Number(chainId);
244
- if (!Number.isInteger(Number(id)) || Number(id) <= 0) return refusal("kyber-bad-order", { field: "id" });
245
- if (!isAddress(maker)) return refusal("kyber-bad-order", { field: "maker" });
246
- for (const bucket of KYBER_LEG_STATUS_BUCKETS) {
247
- const path = KYBER_LEG_MAKER_ORDERS_PATH + "?chainId=" + chain + "&maker=" + maker + "&status=" + bucket;
248
- const res = await ask({ fetchImpl, url: joinUrl(base, path), timeoutMs });
249
- if (!res.ok) return res;
250
- if (res.status >= 400) return refusal("kyber-refused", { status: res.status, stage: "orders" });
251
- let parsed = null;
252
- try { parsed = JSON.parse(res.text); } catch { parsed = null; }
253
- const orders = parsed && parsed.data && parsed.data.orders;
254
- if (!Array.isArray(orders)) return refusal("kyber-bad-response", { where: "orders" });
255
- const found = orders.find((o) => o && Number(o.id) === Number(id)) || null;
256
- if (found) {
257
- const status = found.status;
258
- if (typeof status !== "string" || !KYBER_LEG_STATUSES.includes(status)) return refusal("kyber-bad-response", { where: "status", got: typeof status === "string" ? status : null });
259
- return { ok: true, status, order: found, bucket };
260
- }
261
- }
262
- return refusal("kyber-order-unknown", { id: Number(id), maker });
263
- }
264
-
265
- /**
266
- * WHAT ENDS THIS LEG'S EXECUTION - poll the order book until the order is settled or finally dead, with a timeout.
267
- * { ok: true, done: true, settled: true, status: "filled" } - the leg settled (WETH delivered);
268
- * { ok: true, done: true, settled: false, status: "cancelled" | "expired" } - the order is finally dead;
269
- * { ok: false, code: "kyber-not-settled" | "kyber-unreachable" | ... } - a NAMED refusal.
270
- * "Not settled in time" is its own code: "we did not wait long enough" is a state of the order, not a breakdown. The
271
- * clock and the sleep are injectable, so the wait is testable without real time.
272
- */
273
- export async function kyberLegSettled({ id, chainId, maker, orderbook = null, fetchImpl = null, pollMs = 5_000, timeoutMs = 300_000, now = null, sleep = null, onTick = null } = {}) {
274
- if (!Number.isInteger(Number(id)) || Number(id) <= 0) return refusal("kyber-bad-order", { field: "id" });
275
- const clock = typeof now === "function" ? now : () => Date.now();
276
- const pause = typeof sleep === "function" ? sleep : (ms) => new Promise((r) => setTimeout(r, ms));
277
- const step = Number.isFinite(pollMs) && pollMs > 0 ? pollMs : 5_000;
278
- const limit = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 300_000;
279
- const startedAt = clock();
280
- let lastStatus = null;
281
- for (;;) {
282
- const read = await kyberLegRead({ id, chainId, maker, orderbook, fetchImpl });
283
- if (!read.ok) return read;
284
- lastStatus = read.status;
285
- if (typeof onTick === "function") onTick(lastStatus);
286
- if (KYBER_LEG_FINAL_STATUSES.includes(lastStatus)) {
287
- return { ok: true, done: true, settled: lastStatus === KYBER_LEG_SETTLED_STATUS, status: lastStatus, id: Number(id) };
288
- }
289
- if (clock() - startedAt >= limit) return { ...refusal("kyber-not-settled", { id: Number(id), status: lastStatus, waitedMs: clock() - startedAt }), status: lastStatus, id: Number(id) };
290
- await pause(step);
291
- }
292
- }
293
-
294
- // THE REFUSAL WORDS FOR THE SCREEN - by CODE, so a refusal is never an empty toast. Unknown codes are shown as-is.
295
- export const kyberLegRefusalWords = (result) => {
296
- const code = result && result.code ? String(result.code) : null;
297
- const map = {
298
- "kyber-unknown-network": "no KyberSwap liquidity provider serves this network",
299
- "kyber-bad-order": "the swap intent is incomplete and was not sent",
300
- "kyber-sign-failed": "the wallet did not sign the swap intent",
301
- "kyber-unreachable": "the KyberSwap order book could not be reached",
302
- "kyber-order-unknown": "the KyberSwap order book does not know this order",
303
- "kyber-refused": "the KyberSwap order book did not accept the order",
304
- "kyber-bad-response": "the KyberSwap order book answered in a shape we do not know",
305
- "kyber-not-settled": "the swap did not settle in time",
306
- };
307
- return map[code] || (code ? code : "the liquidity leg stopped");
308
- };