@anywalletkit/protocol-swap2-kyberswap 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/README.md +98 -2
- package/dist/activity.cjs +196 -0
- package/dist/activity.cjs.map +1 -0
- package/dist/activity.d.cts +11 -0
- package/dist/activity.d.ts +11 -0
- package/dist/activity.js +10 -0
- package/dist/activity.js.map +1 -0
- package/dist/chunk-DEWODPQQ.js +430 -0
- package/dist/chunk-DEWODPQQ.js.map +1 -0
- package/dist/chunk-FWC6K553.js +21 -0
- package/dist/chunk-FWC6K553.js.map +1 -0
- package/dist/chunk-PIC4PYGN.js +32 -0
- package/dist/chunk-PIC4PYGN.js.map +1 -0
- package/dist/chunk-WOVGN3FL.js +184 -0
- package/dist/chunk-WOVGN3FL.js.map +1 -0
- package/dist/index.cjs +657 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +56 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.cjs +635 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +17 -0
- package/dist/protocol.d.ts +17 -0
- package/dist/protocol.js +10 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.cjs +613 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +31 -0
- package/dist/provider.d.ts +31 -0
- package/dist/provider.js +11 -0
- package/dist/provider.js.map +1 -0
- package/dist/router.cjs +204 -0
- package/dist/router.cjs.map +1 -0
- package/dist/router.d.cts +180 -0
- package/dist/router.d.ts +180 -0
- package/dist/router.js +39 -0
- package/dist/router.js.map +1 -0
- package/module.json +33 -0
- package/package.json +87 -3
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/protocol.ts
|
|
21
|
+
var protocol_exports = {};
|
|
22
|
+
__export(protocol_exports, {
|
|
23
|
+
KyberswapSwap2Protocol: () => KyberswapSwap2Protocol
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(protocol_exports);
|
|
26
|
+
var import_single = require("@anywalletkit/protocol-swap2-core/swap2/single");
|
|
27
|
+
var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
|
|
28
|
+
|
|
29
|
+
// src/provider.ts
|
|
30
|
+
var import_viem2 = require("viem");
|
|
31
|
+
var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
|
|
32
|
+
var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
33
|
+
var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
|
|
34
|
+
var import_provider = require("@anywalletkit/protocol-swap2-wrap/provider");
|
|
35
|
+
|
|
36
|
+
// src/activity.ts
|
|
37
|
+
var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
|
|
38
|
+
var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
|
|
39
|
+
|
|
40
|
+
// src/router.ts
|
|
41
|
+
var import_util = require("@anywalletkit/protocol-swap2-core/util");
|
|
42
|
+
var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
|
|
43
|
+
var import_swap2_assets = require("@anywalletkit/swap2-assets");
|
|
44
|
+
var import_viem = require("viem");
|
|
45
|
+
var KYBER_ROUTER_V2 = "0x6131B5fae19EA4f9D964eAc0408E4408b66337b5";
|
|
46
|
+
var KYBER_EXECUTOR = "0x8F10B468b06c6FD214B65F87778827F7D113f996";
|
|
47
|
+
var KYBER_ROUTER_V3 = "0x6868d319c8c9a78f7d39dc3602c5c917315132d7";
|
|
48
|
+
var KYBER_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
49
|
+
var ZERO = "0x0000000000000000000000000000000000000000";
|
|
50
|
+
var KYBER_CHAINS = Object.freeze({
|
|
51
|
+
1: { slug: "ethereum", name: "Ethereum", build: "generic" },
|
|
52
|
+
8453: { slug: "base", name: "Base", build: "generic" },
|
|
53
|
+
56: { slug: "bsc", name: "BNB Smart Chain", build: "generic" },
|
|
54
|
+
42161: { slug: "arbitrum", name: "Arbitrum", build: "generic" },
|
|
55
|
+
10: { slug: "optimism", name: "Optimism", build: "generic" },
|
|
56
|
+
137: { slug: "polygon", name: "Polygon", build: "generic" },
|
|
57
|
+
43114: { slug: "avalanche", name: "Avalanche", build: "generic" },
|
|
58
|
+
59144: { slug: "linea", name: "Linea", build: "generic" },
|
|
59
|
+
146: { slug: "sonic", name: "Sonic", build: "lite" },
|
|
60
|
+
80094: { slug: "berachain", name: "Berachain", build: "lite" },
|
|
61
|
+
130: { slug: "unichain", name: "Unichain", build: "lite" },
|
|
62
|
+
999: { slug: "hyperevm", name: "HyperEVM", build: "lite" },
|
|
63
|
+
9745: { slug: "plasma", name: "Plasma", build: "lite" },
|
|
64
|
+
143: { slug: "monad", name: "Monad", build: "lite" },
|
|
65
|
+
4326: { slug: "megaeth", name: "MegaETH", build: "lite" },
|
|
66
|
+
4663: { slug: "robinhood", name: "Robinhood Chain", build: "lite" },
|
|
67
|
+
5042: { slug: "arc", name: "Arc", build: "lite" },
|
|
68
|
+
99901: { slug: "elysium", name: "Elysium", build: "lite" }
|
|
69
|
+
});
|
|
70
|
+
function kyberChain(chainId) {
|
|
71
|
+
return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
|
|
72
|
+
}
|
|
73
|
+
function kyberNativeSwaps(chainId) {
|
|
74
|
+
return !!(0, import_swap2_assets.ccAssetByToken)(`eip155:${chainId}`, ZERO);
|
|
75
|
+
}
|
|
76
|
+
var KYBER_ROUTER_ABI = (0, import_viem.parseAbi)([
|
|
77
|
+
"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }",
|
|
78
|
+
"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }",
|
|
79
|
+
"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)"
|
|
80
|
+
]);
|
|
81
|
+
var KYBER_SWAP_SELECTOR = "0xe21fd0e9";
|
|
82
|
+
var KYBER_REFUSED_SELECTORS = Object.freeze({
|
|
83
|
+
"0x59e50fed": "swapGeneric",
|
|
84
|
+
"0x8af033fb": "swapSimpleMode"
|
|
85
|
+
});
|
|
86
|
+
var KYBER_FLAGS_ALLOWED = 0x200n;
|
|
87
|
+
var KyberTransactionError = class extends Error {
|
|
88
|
+
constructor(message) {
|
|
89
|
+
super(`kyberswap: ${message}`);
|
|
90
|
+
this.name = "KyberTransactionError";
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var fail = (message, reason) => (0, import_errors.withReason)(new KyberTransactionError(message), reason);
|
|
94
|
+
var notes = (0, import_errors.refusalNotes)();
|
|
95
|
+
var isAddr = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
|
|
96
|
+
var same = (a, b) => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();
|
|
97
|
+
var routerToken = (t) => same(t, ZERO) ? KYBER_NATIVE : t;
|
|
98
|
+
var named = (a) => isAddr(a) ? a : "something that is not an address";
|
|
99
|
+
var MAX_CALLDATA_BYTES = 64 * 1024;
|
|
100
|
+
function checkKyberTransaction(tx, expected) {
|
|
101
|
+
const chain = kyberChain(expected.chainId);
|
|
102
|
+
if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, "unsupported_pair");
|
|
103
|
+
if (same(tx.to, KYBER_ROUTER_V3)) throw fail("Kyber router V3 not supported yet", "policy_refused");
|
|
104
|
+
if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, "vault_mismatch");
|
|
105
|
+
if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {
|
|
106
|
+
throw fail("invalid receiver", "recipient_mismatch");
|
|
107
|
+
}
|
|
108
|
+
const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);
|
|
109
|
+
if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
|
|
110
|
+
if (same(expected.tokenIn, expected.tokenOut)) throw fail("same token in and out", "unsupported_pair");
|
|
111
|
+
if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail("invalid quote amounts", "price_check_failed");
|
|
112
|
+
if (typeof tx.data !== "string" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail("malformed calldata", "policy_refused");
|
|
113
|
+
if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail("calldata is larger than any routed swap", "policy_refused");
|
|
114
|
+
const selector = tx.data.slice(0, 10).toLowerCase();
|
|
115
|
+
const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : void 0;
|
|
116
|
+
if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, "policy_refused");
|
|
117
|
+
if (selector !== KYBER_SWAP_SELECTOR) throw fail("not a router swap() call", "policy_refused");
|
|
118
|
+
let x;
|
|
119
|
+
try {
|
|
120
|
+
const call = (0, import_viem.decodeFunctionData)({ abi: KYBER_ROUTER_ABI, data: tx.data });
|
|
121
|
+
x = call.args[0];
|
|
122
|
+
const again = (0, import_viem.encodeFunctionData)({ abi: KYBER_ROUTER_ABI, functionName: "swap", args: [x] });
|
|
123
|
+
if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error("non-canonical");
|
|
124
|
+
} catch {
|
|
125
|
+
throw fail("the calldata is not a canonical router swap() encoding", "policy_refused");
|
|
126
|
+
}
|
|
127
|
+
const d = x.desc;
|
|
128
|
+
if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, "vault_mismatch");
|
|
129
|
+
if (!same(x.approveTarget, ZERO)) throw fail("the swap asks the router to approve another contract", "policy_refused");
|
|
130
|
+
if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail("calldata swaps other tokens than requested", "policy_refused");
|
|
131
|
+
if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, "price_check_failed");
|
|
132
|
+
if (d.srcReceivers.length !== d.srcAmounts.length) throw fail("malformed input split", "policy_refused");
|
|
133
|
+
if (nativeIn) {
|
|
134
|
+
if (d.srcReceivers.length !== 0) throw fail("a native-coin swap must not split the input", "policy_refused");
|
|
135
|
+
if (tx.value !== expected.amountIn) throw fail("native value does not match the input", "price_check_failed");
|
|
136
|
+
} else {
|
|
137
|
+
if (tx.value !== 0n) throw fail("a token swap must not send the native coin", "price_check_failed");
|
|
138
|
+
const total = d.srcAmounts.reduce((s, a) => s + a, 0n);
|
|
139
|
+
if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, "price_check_failed");
|
|
140
|
+
}
|
|
141
|
+
if (same(d.dstReceiver, ZERO)) throw fail("the swap names no receiver", "recipient_mismatch");
|
|
142
|
+
if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, "recipient_mismatch");
|
|
143
|
+
if (d.minReturnAmount <= 0n) throw fail("the swap names no minimum", "price_check_failed");
|
|
144
|
+
if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, "price_check_failed");
|
|
145
|
+
if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail("calldata pays a fee receiver \u2014 this module charges none", "policy_refused");
|
|
146
|
+
if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, "policy_refused");
|
|
147
|
+
if (d.permit !== "0x") throw fail("calldata carries a permit", "policy_refused");
|
|
148
|
+
return { srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags };
|
|
149
|
+
}
|
|
150
|
+
function kyberMinimum(amountOut, bps) {
|
|
151
|
+
const m = amountOut * BigInt(1e4 - bps) / 10000n - 1n;
|
|
152
|
+
return m > 0n ? m : 0n;
|
|
153
|
+
}
|
|
154
|
+
function kyberApiSlippage(amountOut, bps) {
|
|
155
|
+
const floor = amountOut * BigInt(1e4 - bps) / 10000n;
|
|
156
|
+
for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
|
|
160
|
+
function kyberVerifyQuote(params, quote) {
|
|
161
|
+
if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
|
|
162
|
+
try {
|
|
163
|
+
const chainId = chainIdOf(params.sourceChain);
|
|
164
|
+
if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, "unsupported_pair");
|
|
165
|
+
const src = (0, import_util.sourceAssetOf)(params);
|
|
166
|
+
if (!src) return notes.note(`unknown source token ${params.sourceToken}`, "unsupported_pair");
|
|
167
|
+
if (quote.sourceAmount !== params.amountIn) return notes.note("the quote prices another amount", "price_check_failed");
|
|
168
|
+
const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
|
|
169
|
+
if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
|
|
170
|
+
if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
|
|
171
|
+
const bps = params.slippageBps;
|
|
172
|
+
if (bps !== void 0 && Number.isInteger(bps) && bps >= 0 && bps < 1e4 && min < kyberMinimum(out, bps)) {
|
|
173
|
+
return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
|
|
174
|
+
}
|
|
175
|
+
const tx = quote.txRequest;
|
|
176
|
+
if (!tx) return params.dry === false ? notes.note("the quote carries no router transaction", "policy_refused") : null;
|
|
177
|
+
if (!tx.to || !tx.data) return notes.note("the quote carries no router transaction", "policy_refused");
|
|
178
|
+
if (tx.approvalAddress !== void 0 && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note("the quote asks to approve another spender", "vault_mismatch");
|
|
179
|
+
checkKyberTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value ?? "0") }, {
|
|
180
|
+
chainId,
|
|
181
|
+
tokenIn: src.contract ? (0, import_viem.getAddress)(src.contract) : ZERO,
|
|
182
|
+
tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : (0, import_viem.getAddress)(params.destToken),
|
|
183
|
+
amountIn: BigInt(params.amountIn),
|
|
184
|
+
receiver: (0, import_viem.getAddress)(params.destAddress),
|
|
185
|
+
minAmountOut: min
|
|
186
|
+
});
|
|
187
|
+
return null;
|
|
188
|
+
} catch (e) {
|
|
189
|
+
const text = e instanceof Error ? e.message.replace(/^kyberswap: /, "") : String(e);
|
|
190
|
+
const info = (0, import_errors.refusalOf)(e);
|
|
191
|
+
return info ? notes.note(text, info) : text;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function routerFor(chain) {
|
|
195
|
+
return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
|
|
196
|
+
}
|
|
197
|
+
var kyberPins = Object.freeze({
|
|
198
|
+
callTargets: routerFor,
|
|
199
|
+
spenders: routerFor,
|
|
200
|
+
verifyQuote: kyberVerifyQuote,
|
|
201
|
+
reasonOf: (refusal2) => notes.reasonOf(refusal2)
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// src/activity.ts
|
|
205
|
+
var KYBERSWAP_MODULE = "@anywalletkit/protocol-swap2-kyberswap";
|
|
206
|
+
function describeKyberActivity(tx, ctx) {
|
|
207
|
+
if (!(0, import_util2.isEvm)(tx.chain) || !kyberChain((0, import_util2.evmRef)(tx.chain))) return null;
|
|
208
|
+
if (!(0, import_activity.matchesCall)(tx, [KYBER_ROUTER_V2], [KYBER_SWAP_SELECTOR])) return null;
|
|
209
|
+
return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: KYBERSWAP_MODULE, subtitle: `KyberSwap \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/provider.ts
|
|
213
|
+
var ZERO2 = "0x0000000000000000000000000000000000000000";
|
|
214
|
+
var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
|
|
215
|
+
var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
|
|
216
|
+
var DEFAULT_SLIPPAGE_BPS = 50;
|
|
217
|
+
var DEFAULT_TTL_MS = 3e4;
|
|
218
|
+
var DRY_CACHE_MS = 5e3;
|
|
219
|
+
var BUILD_DEADLINE_S = 20 * 60;
|
|
220
|
+
var ERROR_REASONS = {
|
|
221
|
+
4e3: "policy_refused",
|
|
222
|
+
4001: "policy_refused",
|
|
223
|
+
4002: "policy_refused",
|
|
224
|
+
4005: "policy_refused",
|
|
225
|
+
4007: "policy_refused",
|
|
226
|
+
40017: "policy_refused",
|
|
227
|
+
4008: "no_route",
|
|
228
|
+
40011: "no_route",
|
|
229
|
+
4009: "insufficient_liquidity",
|
|
230
|
+
4010: "insufficient_liquidity",
|
|
231
|
+
4011: "unsupported_pair",
|
|
232
|
+
4221: "unsupported_pair",
|
|
233
|
+
4222: "price_check_failed",
|
|
234
|
+
4227: "simulation_failed"
|
|
235
|
+
};
|
|
236
|
+
var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
|
|
237
|
+
var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
|
|
238
|
+
var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
|
|
239
|
+
var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
|
|
240
|
+
var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
|
|
241
|
+
var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
|
|
242
|
+
var apiToken = (t) => t === ZERO2 ? KYBER_NATIVE : t;
|
|
243
|
+
var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
|
|
244
|
+
var ERC20_READS = (0, import_viem2.parseAbi)(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
|
|
245
|
+
function revertData(e) {
|
|
246
|
+
const err = e;
|
|
247
|
+
const nested = err.data && typeof err.data === "object" ? err.data.data : void 0;
|
|
248
|
+
for (const v of [err.data, nested]) if (typeof v === "string" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v;
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
function kyberValueLossBps(amountInUsd, amountOutUsd) {
|
|
252
|
+
const num = (v) => typeof v === "string" && /^\d{1,15}(\.\d{1,30})?$/.test(v) ? Number(v) : null;
|
|
253
|
+
const vin = num(amountInUsd), vout = num(amountOutUsd);
|
|
254
|
+
if (vin === null || vout === null || vin <= 0 || vout <= 0) return null;
|
|
255
|
+
return Math.min(1e4, Math.max(0, Math.round((vin - vout) / vin * 1e4)));
|
|
256
|
+
}
|
|
257
|
+
function revertString(e) {
|
|
258
|
+
const data = revertData(e);
|
|
259
|
+
if (data) {
|
|
260
|
+
try {
|
|
261
|
+
const r = (0, import_viem2.decodeErrorResult)({ abi: [], data });
|
|
262
|
+
if (r.errorName === "Error" && typeof r.args?.[0] === "string") return r.args[0].slice(0, 200);
|
|
263
|
+
} catch {
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const m = e instanceof Error ? /execution reverted:?\s*([^\n]{1,160})/.exec(e.message) : null;
|
|
267
|
+
return m ? m[1] : null;
|
|
268
|
+
}
|
|
269
|
+
function kyberswapProvider(config = {}) {
|
|
270
|
+
const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
|
|
271
|
+
const clientId = config.clientId ?? "anywalletkit";
|
|
272
|
+
const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
|
|
273
|
+
const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;
|
|
274
|
+
const timeoutMs = config.timeoutMs ?? 1e4;
|
|
275
|
+
const enabledChains = config.enabledChains ? new Set(config.enabledChains) : null;
|
|
276
|
+
const headers = config.apiKey ? { "x-api-key": config.apiKey } : { "x-client-id": clientId };
|
|
277
|
+
const dryCache = /* @__PURE__ */ new Map();
|
|
278
|
+
const chainIdOf2 = (caip2) => {
|
|
279
|
+
if (!(0, import_util3.isEvm)(caip2)) return null;
|
|
280
|
+
const id = (0, import_util3.evmRef)(caip2);
|
|
281
|
+
return kyberChain(id) && (!enabledChains || enabledChains.has(id)) ? id : null;
|
|
282
|
+
};
|
|
283
|
+
async function rpc(chainId, method, params) {
|
|
284
|
+
let lastErr;
|
|
285
|
+
for (const url of config.rpcUrls?.[chainId] ?? []) {
|
|
286
|
+
try {
|
|
287
|
+
const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), signal: (0, import_util3.timeoutSignal)(12e3) });
|
|
288
|
+
if (!res.ok) {
|
|
289
|
+
const error = new Error(`HTTP ${res.status}`);
|
|
290
|
+
const info = (0, import_errors2.httpRefusal)(res.status, res.headers?.get?.("retry-after"));
|
|
291
|
+
throw info ? (0, import_errors2.withReason)(error, info) : error;
|
|
292
|
+
}
|
|
293
|
+
const body = await res.json();
|
|
294
|
+
if (body.error) throw Object.assign(new Error(body.error.message ?? "rpc error"), { rpc: true, data: body.error.data });
|
|
295
|
+
return body.result ?? null;
|
|
296
|
+
} catch (e) {
|
|
297
|
+
if (e.rpc) throw e;
|
|
298
|
+
lastErr = e;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
throw (0, import_errors2.withReason)(new Error(`kyberswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr ?? "none configured")})`), (0, import_errors2.refusalOf)(lastErr) ?? "upstream_unavailable");
|
|
302
|
+
}
|
|
303
|
+
async function api(url, init, signal) {
|
|
304
|
+
let res;
|
|
305
|
+
try {
|
|
306
|
+
res = await fetch(url, { ...init, headers: { ...headers, ...init.body ? { "content-type": "application/json" } : {} }, signal: signal ?? (0, import_util3.timeoutSignal)(timeoutMs) });
|
|
307
|
+
} catch (e) {
|
|
308
|
+
return { ok: false, why: `API unreachable (${e instanceof Error ? e.name : "error"})`, ...signal?.aborted ? {} : { info: "upstream_unavailable" } };
|
|
309
|
+
}
|
|
310
|
+
let body;
|
|
311
|
+
try {
|
|
312
|
+
const parsed = await res.json();
|
|
313
|
+
body = parsed && typeof parsed === "object" ? parsed : null;
|
|
314
|
+
} catch {
|
|
315
|
+
body = null;
|
|
316
|
+
}
|
|
317
|
+
if (res.status === 429) return { ok: false, why: "rate limited (HTTP 429)", info: (0, import_errors2.httpRefusal)(429, res.headers?.get?.("retry-after")) ?? "rate_limited" };
|
|
318
|
+
if (res.status === 401 || res.status === 403) return { ok: false, why: `API key rejected (HTTP ${res.status})`, info: (0, import_errors2.httpRefusal)(res.status) ?? "policy_refused" };
|
|
319
|
+
if (res.status === 404 && !body?.code) return { ok: false, why: "KyberSwap does not serve this chain (HTTP 404)", info: "unsupported_pair" };
|
|
320
|
+
if (!res.ok || body?.code !== 0) {
|
|
321
|
+
const code = typeof body?.code === "number" ? body.code : void 0;
|
|
322
|
+
const reason = errorReason(code) ?? (res.status >= 500 ? "upstream_unavailable" : void 0);
|
|
323
|
+
return { ok: false, why: `${code !== void 0 ? `error ${code}` : `HTTP ${res.status}`}${body?.message ? `: ${short(body.message)}` : ""}`, ...reason ? { info: reason } : {} };
|
|
324
|
+
}
|
|
325
|
+
if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
|
|
326
|
+
return { ok: true, data: body.data };
|
|
327
|
+
}
|
|
328
|
+
async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
|
|
329
|
+
const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
|
|
330
|
+
if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
|
|
331
|
+
if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
|
|
332
|
+
const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
|
|
333
|
+
if (!r.ok) return r;
|
|
334
|
+
const summary = r.data.routeSummary;
|
|
335
|
+
const router = r.data.routerAddress;
|
|
336
|
+
if (!summary || typeof summary !== "object") return { ok: false, why: "malformed API response (no route)", info: "upstream_unavailable" };
|
|
337
|
+
if (same2(router, KYBER_ROUTER_V3)) return { ok: false, why: "Kyber router V3 not supported yet", info: "policy_refused" };
|
|
338
|
+
if (!same2(router, KYBER_ROUTER_V2)) return { ok: false, why: "the route settles through another router than the pinned one", info: "vault_mismatch" };
|
|
339
|
+
if (!same2(summary.tokenIn, apiToken(tokenIn)) || !same2(summary.tokenOut, apiToken(tokenOut))) return { ok: false, why: "the route swaps other tokens than requested", info: "policy_refused" };
|
|
340
|
+
if (uint(summary.amountIn) !== amountIn) return { ok: false, why: "the route prices another amount", info: "price_check_failed" };
|
|
341
|
+
const fee = summary.extraFee;
|
|
342
|
+
if (fee !== void 0 && fee !== null) {
|
|
343
|
+
const amount = fee.feeAmount === "" || fee.feeAmount === void 0 ? 0n : uint(fee.feeAmount);
|
|
344
|
+
if (typeof fee !== "object" || amount !== 0n || fee.feeReceiver !== void 0 && fee.feeReceiver !== "") return { ok: false, why: "the route carries an integrator fee", info: "policy_refused" };
|
|
345
|
+
}
|
|
346
|
+
const amountOut = uint(summary.amountOut);
|
|
347
|
+
if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
|
|
348
|
+
const sources = [...new Set((summary.route ?? []).flat().map((h) => h?.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
|
|
349
|
+
return { ok: true, summary, amountOut, sources };
|
|
350
|
+
}
|
|
351
|
+
async function revertReason(chainId, sender, quoted, e) {
|
|
352
|
+
const text = revertString(e);
|
|
353
|
+
if (text && /return amount is not enough|min return/i.test(text)) {
|
|
354
|
+
return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
|
|
355
|
+
}
|
|
356
|
+
const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
|
|
357
|
+
if (lack) return (0, import_errors2.refusal)("simulation_failed", lack);
|
|
358
|
+
return (0, import_errors2.refusal)("simulation_failed", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : "revert"))}). Nothing was sent; refresh the quote.`);
|
|
359
|
+
}
|
|
360
|
+
async function inputShortfall(chainId, sender, quoted) {
|
|
361
|
+
const call = (0, import_viem2.decodeFunctionData)({ abi: KYBER_ROUTER_ABI, data: quoted.data });
|
|
362
|
+
const desc = call.args[0].desc;
|
|
363
|
+
const word = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null;
|
|
364
|
+
if (same2(desc.srcToken, KYBER_NATIVE)) {
|
|
365
|
+
const balance2 = word(await rpc(chainId, "eth_getBalance", [sender, "latest"]));
|
|
366
|
+
return balance2 !== null && balance2 < desc.amount ? `kyberswap: the wallet's balance is below the amount (${balance2} < ${desc.amount}). Nothing was sent.` : null;
|
|
367
|
+
}
|
|
368
|
+
const read = (data) => rpc(chainId, "eth_call", [{ to: desc.srcToken, data }, "latest"]);
|
|
369
|
+
const [balance, allowance] = (await Promise.all([
|
|
370
|
+
read((0, import_viem2.encodeFunctionData)({ abi: ERC20_READS, functionName: "balanceOf", args: [sender] })),
|
|
371
|
+
read((0, import_viem2.encodeFunctionData)({ abi: ERC20_READS, functionName: "allowance", args: [sender, KYBER_ROUTER_V2] }))
|
|
372
|
+
])).map(word);
|
|
373
|
+
if (balance != null && balance < desc.amount) return `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.`;
|
|
374
|
+
if (allowance != null && allowance < desc.amount) return "kyberswap: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.";
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
async function tokenSwapCheck(chainId, sender, token, amount, data) {
|
|
378
|
+
const word = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null;
|
|
379
|
+
const read = (call) => rpc(chainId, "eth_call", [{ to: token, data: call }, "latest"]);
|
|
380
|
+
const [balance, allowance] = (await Promise.all([
|
|
381
|
+
read((0, import_viem2.encodeFunctionData)({ abi: ERC20_READS, functionName: "balanceOf", args: [sender] })),
|
|
382
|
+
read((0, import_viem2.encodeFunctionData)({ abi: ERC20_READS, functionName: "allowance", args: [sender, KYBER_ROUTER_V2] }))
|
|
383
|
+
])).map(word);
|
|
384
|
+
if (balance == null || allowance == null) return { refusal: null, simulated: "none" };
|
|
385
|
+
if (balance < amount) return { refusal: null, simulated: "none" };
|
|
386
|
+
if (allowance >= amount) {
|
|
387
|
+
try {
|
|
388
|
+
await rpc(chainId, "eth_call", [{ from: sender, to: KYBER_ROUTER_V2, data, value: "0x0" }, "latest"]);
|
|
389
|
+
return { refusal: null, simulated: "swap" };
|
|
390
|
+
} catch (e) {
|
|
391
|
+
if (e.rpc) return { refusal: refuseRevert(revertString(e)), simulated: "swap" };
|
|
392
|
+
throw e;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const approve = (n) => ({ from: sender, to: token, data: (0, import_viem2.encodeFunctionData)({ abi: ERC20_READS, functionName: "approve", args: [KYBER_ROUTER_V2, n] }) });
|
|
396
|
+
const calls = [...allowance > 0n ? [approve(0n)] : [], approve(amount), { from: sender, to: KYBER_ROUTER_V2, data, value: "0x0" }];
|
|
397
|
+
let result;
|
|
398
|
+
try {
|
|
399
|
+
result = await rpc(chainId, "eth_simulateV1", [{ blockStateCalls: [{ calls }], validation: false }, "latest"]);
|
|
400
|
+
} catch {
|
|
401
|
+
return { refusal: null, simulated: "none" };
|
|
402
|
+
}
|
|
403
|
+
const out = (Array.isArray(result) ? result[0]?.calls : void 0) ?? [];
|
|
404
|
+
if (out.length !== calls.length || out.slice(0, -1).some((c) => c.status !== "0x1")) return { refusal: null, simulated: "none" };
|
|
405
|
+
const swap = out[out.length - 1];
|
|
406
|
+
if (swap.status === "0x1") return { refusal: null, simulated: "approve+swap" };
|
|
407
|
+
const err = { data: swap.error?.data ?? swap.returnData, message: typeof swap.error?.message === "string" ? swap.error.message : "" };
|
|
408
|
+
return { refusal: refuseRevert(revertString(Object.assign(new Error(err.message), { data: err.data }))), simulated: "approve+swap" };
|
|
409
|
+
}
|
|
410
|
+
function refuseRevert(why) {
|
|
411
|
+
return {
|
|
412
|
+
why: `the route does not execute on-chain right now${why ? ` (${short(why)})` : ""}`,
|
|
413
|
+
reason: why && /return amount is not enough/i.test(why) ? "price_check_failed" : "simulation_failed"
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
return {
|
|
417
|
+
name: "kyberswap",
|
|
418
|
+
describeActivity: describeKyberActivity,
|
|
419
|
+
supportsSameChain: true,
|
|
420
|
+
// The account's own estimate of the exact call, never the API's gas model.
|
|
421
|
+
ownGasEstimate: true,
|
|
422
|
+
enabled: () => config.enabled ?? true,
|
|
423
|
+
supportsChain: (caip2) => chainIdOf2(caip2) !== null,
|
|
424
|
+
supportsChainPair: (from, to) => from === to && chainIdOf2(from) !== null,
|
|
425
|
+
supportsRoute: (from, to) => {
|
|
426
|
+
if (from.chain !== to.chain) return false;
|
|
427
|
+
const id = chainIdOf2(from.chain);
|
|
428
|
+
if (id === null) return false;
|
|
429
|
+
const wrapped = Object.prototype.hasOwnProperty.call(import_provider.WRAPPED_NATIVE, id) ? import_provider.WRAPPED_NATIVE[id].address : null;
|
|
430
|
+
const isNative = (t) => /^0x0+$/.test(t) || same2(t, KYBER_NATIVE) || t === (0, import_swap2_assets2.ccAssetByToken)(from.chain, ZERO2)?.symbol;
|
|
431
|
+
const isWrapped = (t) => !!wrapped && (same2(t, wrapped) || t === import_provider.WRAPPED_NATIVE[id].symbol);
|
|
432
|
+
return !(isNative(from.token) && isWrapped(to.token) || isWrapped(from.token) && isNative(to.token));
|
|
433
|
+
},
|
|
434
|
+
async getQuote(params, signal) {
|
|
435
|
+
const refuse = (why, info) => {
|
|
436
|
+
params.onRefusal?.(`kyberswap: ${why}`, typeof info === "string" ? { reason: info } : info);
|
|
437
|
+
return null;
|
|
438
|
+
};
|
|
439
|
+
if (params.flex) return refuse("amount-flexible deposits are not supported", "unsupported_pair");
|
|
440
|
+
if (params.sourceChain !== params.destChain) return refuse("same-chain swaps only", "unsupported_pair");
|
|
441
|
+
const chainId = chainIdOf2(params.sourceChain);
|
|
442
|
+
if (chainId === null) return refuse(`KyberSwap is not enabled for ${params.sourceChain}`, "unsupported_pair");
|
|
443
|
+
const chain = kyberChain(chainId);
|
|
444
|
+
const src = (0, import_util3.sourceAssetOf)(params);
|
|
445
|
+
if (!src) return refuse(`unknown source token ${params.sourceToken}`, "unsupported_pair");
|
|
446
|
+
const tokenIn = src.contract ? (0, import_viem2.getAddress)(src.contract) : ZERO2;
|
|
447
|
+
const nativeOut = /^0x0+$/.test(params.destToken) || same2(params.destToken, KYBER_NATIVE);
|
|
448
|
+
if (!nativeOut && !isAddr2(params.destToken)) return refuse("destination token must be an EVM address", "unsupported_pair");
|
|
449
|
+
const tokenOut = nativeOut ? ZERO2 : (0, import_viem2.getAddress)(params.destToken);
|
|
450
|
+
if (tokenIn === tokenOut) return refuse("same token in and out", "unsupported_pair");
|
|
451
|
+
if ((tokenIn === ZERO2 || tokenOut === ZERO2) && !kyberNativeSwaps(chainId)) return refuse(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
|
|
452
|
+
let amountIn;
|
|
453
|
+
try {
|
|
454
|
+
amountIn = BigInt(params.amountIn);
|
|
455
|
+
} catch {
|
|
456
|
+
return refuse("amount is not an integer");
|
|
457
|
+
}
|
|
458
|
+
if (amountIn <= 0n) return refuse("amount must be positive");
|
|
459
|
+
const bps = params.slippageBps ?? slippageDefault;
|
|
460
|
+
if (!Number.isInteger(bps) || bps <= 0 || bps >= 2e3) return refuse("invalid slippage (KyberSwap accepts under 20%)", "price_check_failed");
|
|
461
|
+
let floor = 0n;
|
|
462
|
+
if (params.minAmountOut !== void 0) {
|
|
463
|
+
const f = uint(params.minAmountOut);
|
|
464
|
+
if (f === null) return refuse("minimum output is not an integer");
|
|
465
|
+
floor = f;
|
|
466
|
+
}
|
|
467
|
+
const dry = params.dry !== false;
|
|
468
|
+
if (!dry && !isAddr2(params.destAddress)) return refuse("recipient must be an EVM address", "recipient_mismatch");
|
|
469
|
+
if (!dry && !config.rpcUrls?.[chainId]?.length) return refuse(`no RPC configured for ${chain.name}: a KyberSwap swap is simulated before it is signed`, "upstream_unavailable");
|
|
470
|
+
let r;
|
|
471
|
+
if (dry) {
|
|
472
|
+
const key = `${chainId}|${tokenIn}|${tokenOut}|${amountIn}`;
|
|
473
|
+
const hit = dryCache.get(key);
|
|
474
|
+
if (hit && Date.now() - hit.at < DRY_CACHE_MS) r = await hit.value;
|
|
475
|
+
else {
|
|
476
|
+
const value2 = routes(chainId, tokenIn, tokenOut, amountIn, signal);
|
|
477
|
+
dryCache.set(key, { at: Date.now(), value: value2 });
|
|
478
|
+
if (dryCache.size > 64) {
|
|
479
|
+
for (const [k, v] of dryCache) if (Date.now() - v.at >= DRY_CACHE_MS) dryCache.delete(k);
|
|
480
|
+
}
|
|
481
|
+
r = await value2;
|
|
482
|
+
if (!r.ok) dryCache.delete(key);
|
|
483
|
+
}
|
|
484
|
+
} else r = await routes(chainId, tokenIn, tokenOut, amountIn, signal);
|
|
485
|
+
if (!r.ok) return refuse(r.why, r.info);
|
|
486
|
+
const apiBps = kyberApiSlippage(r.amountOut, bps);
|
|
487
|
+
if (apiBps === null) return refuse("the output is too small to carry a minimum", "amount_too_small");
|
|
488
|
+
const minOut = kyberMinimum(r.amountOut, apiBps);
|
|
489
|
+
if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
|
|
490
|
+
const base = {
|
|
491
|
+
provider: "kyberswap",
|
|
492
|
+
intentId: `kyberswap:${chainId}`,
|
|
493
|
+
depositAddress: "",
|
|
494
|
+
depositMemo: null,
|
|
495
|
+
sourceAmount: amountIn.toString(),
|
|
496
|
+
// KyberSwap's amountOut is the route's ceiling, not an average: the executed output came 1.5–7.4 bps under it.
|
|
497
|
+
destAmount: r.amountOut.toString(),
|
|
498
|
+
minDestAmount: minOut.toString(),
|
|
499
|
+
feeUsd: 0,
|
|
500
|
+
etaSeconds: 15,
|
|
501
|
+
reliability: 0.95,
|
|
502
|
+
validUntilMs: Date.now() + ttl
|
|
503
|
+
};
|
|
504
|
+
const providerData = {
|
|
505
|
+
amountOut: r.amountOut.toString(),
|
|
506
|
+
minOut: minOut.toString(),
|
|
507
|
+
apiSlippageBps: String(apiBps),
|
|
508
|
+
...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
|
|
509
|
+
...r.sources.length ? { sources: r.sources.join(",") } : {}
|
|
510
|
+
};
|
|
511
|
+
const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
|
|
512
|
+
if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
|
|
513
|
+
if (dry) {
|
|
514
|
+
return { ...base, providerData: tokenIn === ZERO2 ? providerData : { ...providerData, approvalAddress: KYBER_ROUTER_V2 } };
|
|
515
|
+
}
|
|
516
|
+
const receiver = (0, import_viem2.getAddress)(params.destAddress);
|
|
517
|
+
const signer = isAddr2(params.sender) ? params.sender : isAddr2(params.refundAddress) ? params.refundAddress : params.destAddress;
|
|
518
|
+
const sender = (0, import_viem2.getAddress)(signer);
|
|
519
|
+
const built = await api(`${baseUrl}/${chain.slug}/api/v1/route/build`, {
|
|
520
|
+
method: "POST",
|
|
521
|
+
body: JSON.stringify({
|
|
522
|
+
routeSummary: r.summary,
|
|
523
|
+
sender,
|
|
524
|
+
recipient: receiver,
|
|
525
|
+
slippageTolerance: apiBps,
|
|
526
|
+
deadline: Math.floor(Date.now() / 1e3) + BUILD_DEADLINE_S,
|
|
527
|
+
source: clientId
|
|
528
|
+
})
|
|
529
|
+
}, signal);
|
|
530
|
+
if (!built.ok) return refuse(`build: ${built.why}`, built.info);
|
|
531
|
+
const b = built.data;
|
|
532
|
+
if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
|
|
533
|
+
if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
|
|
534
|
+
const value = uint(b.transactionValue ?? "0");
|
|
535
|
+
if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
|
|
536
|
+
const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
|
|
537
|
+
let decoded;
|
|
538
|
+
try {
|
|
539
|
+
decoded = checkKyberTransaction(tx, { chainId, tokenIn, tokenOut, amountIn, receiver, minAmountOut: minOut > floor ? minOut : floor });
|
|
540
|
+
} catch (e) {
|
|
541
|
+
return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, "") : String(e), (0, import_errors2.refusalOf)(e));
|
|
542
|
+
}
|
|
543
|
+
let simulated = "swap";
|
|
544
|
+
if (tokenIn !== ZERO2) {
|
|
545
|
+
try {
|
|
546
|
+
const check = await tokenSwapCheck(chainId, sender, tokenIn, amountIn, tx.data);
|
|
547
|
+
if (check.refusal) return refuse(check.refusal.why, check.refusal.reason);
|
|
548
|
+
simulated = check.simulated;
|
|
549
|
+
} catch (e) {
|
|
550
|
+
return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, "") : String(e), (0, import_errors2.refusalOf)(e) ?? "upstream_unavailable");
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (tokenIn === ZERO2) {
|
|
554
|
+
try {
|
|
555
|
+
await rpc(chainId, "eth_call", [{ from: sender, to: KYBER_ROUTER_V2, data: tx.data, value: `0x${value.toString(16)}` }, "latest", { [sender]: { balance: `0x${(value + 10n ** 18n).toString(16)}` } }]);
|
|
556
|
+
} catch (e) {
|
|
557
|
+
if (e.rpc) {
|
|
558
|
+
const why = revertString(e);
|
|
559
|
+
return refuse(`the route does not execute on-chain right now${why ? ` (${short(why)})` : ""}`, why && /return amount is not enough/i.test(why) ? "price_check_failed" : "simulation_failed");
|
|
560
|
+
}
|
|
561
|
+
return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, "") : String(e), (0, import_errors2.refusalOf)(e) ?? "upstream_unavailable");
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return {
|
|
565
|
+
...base,
|
|
566
|
+
minDestAmount: decoded.minReturnAmount.toString(),
|
|
567
|
+
txRequest: {
|
|
568
|
+
to: KYBER_ROUTER_V2,
|
|
569
|
+
data: tx.data,
|
|
570
|
+
value: value.toString(),
|
|
571
|
+
chainId,
|
|
572
|
+
...tokenIn === ZERO2 ? {} : { approvalAddress: KYBER_ROUTER_V2 }
|
|
573
|
+
},
|
|
574
|
+
providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
|
|
575
|
+
};
|
|
576
|
+
},
|
|
577
|
+
/**
|
|
578
|
+
* Simulate the exact quoted transaction from the account at the latest block (approval in place) and refuse when
|
|
579
|
+
* it would revert or when no RPC answers — the API is not trusted, so an unsimulated swap is not sent.
|
|
580
|
+
* Only the quote's own transaction is simulated, never a caller's.
|
|
581
|
+
*/
|
|
582
|
+
async preflightDeposit(quote, tx) {
|
|
583
|
+
const chainId = Number(quote.intentId.split(":")[1]);
|
|
584
|
+
const sender = quote.providerData?.sender;
|
|
585
|
+
const quoted = quote.txRequest;
|
|
586
|
+
if (!kyberChain(chainId) || !isAddr2(sender)) throw (0, import_errors2.refusal)("policy_refused", "kyberswap: the quote is not an execution quote. Nothing was sent; refresh the quote.");
|
|
587
|
+
if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data ?? "", quoted.data) || !sameAmount(tx.value || "0", quoted.value ?? "0")) {
|
|
588
|
+
throw (0, import_errors2.refusal)("policy_refused", "kyberswap: the transaction is not the quoted swap. Nothing was sent; refresh the quote.");
|
|
589
|
+
}
|
|
590
|
+
try {
|
|
591
|
+
await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
|
|
592
|
+
} catch (e) {
|
|
593
|
+
if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
|
|
594
|
+
throw (0, import_errors2.withReason)(new Error("kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again."), (0, import_errors2.refusalOf)(e) ?? "upstream_unavailable");
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
async buildDeposit(quote) {
|
|
598
|
+
const tx = quote.txRequest;
|
|
599
|
+
if (!tx?.to || !tx.data) throw (0, import_errors2.refusal)("policy_refused", "swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)");
|
|
600
|
+
return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
|
|
601
|
+
},
|
|
602
|
+
async trackIntent(ref) {
|
|
603
|
+
if (!ref.sourceTxHash) return { state: "pending" };
|
|
604
|
+
const chainId = Number(ref.intentId.split(":")[1]);
|
|
605
|
+
if (!kyberChain(chainId) || !config.rpcUrls?.[chainId]?.length) return { state: "pending" };
|
|
606
|
+
try {
|
|
607
|
+
const receipt = await rpc(chainId, "eth_getTransactionReceipt", [ref.sourceTxHash]);
|
|
608
|
+
if (!receipt) return { state: "pending" };
|
|
609
|
+
return receipt.status === "0x1" ? { state: "completed", destTxHash: ref.sourceTxHash } : { state: "failed" };
|
|
610
|
+
} catch {
|
|
611
|
+
return { state: "pending" };
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/protocol.ts
|
|
618
|
+
var KyberswapSwap2Protocol = class extends import_single.SingleProviderSwap2 {
|
|
619
|
+
provider;
|
|
620
|
+
_kyber;
|
|
621
|
+
constructor(account, config) {
|
|
622
|
+
super(account, config);
|
|
623
|
+
this.provider = kyberswapProvider(config);
|
|
624
|
+
this._kyber = config;
|
|
625
|
+
}
|
|
626
|
+
chainSupported(caip2) {
|
|
627
|
+
if (!(0, import_util4.isEvm)(caip2)) return false;
|
|
628
|
+
const id = (0, import_util4.evmRef)(caip2);
|
|
629
|
+
return !!kyberChain(id) && (!this._kyber.enabledChains || this._kyber.enabledChains.includes(id)) && !!this._kyber.rpcUrls?.[id]?.length;
|
|
630
|
+
}
|
|
631
|
+
pairSupported(fromChain, toChain) {
|
|
632
|
+
return fromChain === toChain && this.chainSupported(fromChain);
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
//# sourceMappingURL=protocol.cjs.map
|