mantle-agent-kit-sdk 1.0.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/dist/index.cjs ADDED
@@ -0,0 +1,1479 @@
1
+ 'use strict';
2
+
3
+ var viem = require('viem');
4
+ var accounts = require('viem/accounts');
5
+ var chains = require('viem/chains');
6
+ var actions = require('viem/actions');
7
+ var axios6 = require('axios');
8
+ var CryptoJS = require('crypto-js');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var axios6__default = /*#__PURE__*/_interopDefault(axios6);
13
+ var CryptoJS__default = /*#__PURE__*/_interopDefault(CryptoJS);
14
+
15
+ var __defProp = Object.defineProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var sendTransaction = async (agent, to, amount) => {
21
+ const hash = await agent.client.sendTransaction({
22
+ to,
23
+ value: viem.parseEther(amount)
24
+ });
25
+ const receipt = await actions.getTransactionReceipt(agent.client, {
26
+ hash
27
+ });
28
+ return receipt;
29
+ };
30
+ async function checkAllowance(agent, tokenAddress, ownerAddress, spenderAddress) {
31
+ try {
32
+ const allowance = await agent.client.readContract({
33
+ address: tokenAddress,
34
+ abi: viem.erc20Abi,
35
+ functionName: "allowance",
36
+ args: [ownerAddress, spenderAddress]
37
+ });
38
+ return allowance;
39
+ } catch (error) {
40
+ console.error("Failed to query allowance:", error);
41
+ throw error;
42
+ }
43
+ }
44
+
45
+ // src/constants/okx/index.ts
46
+ var okx_exports = {};
47
+ __export(okx_exports, {
48
+ ETH_ADDRESS: () => ETH_ADDRESS,
49
+ baseUrl: () => baseUrl,
50
+ configs: () => configs
51
+ });
52
+ var configs = {
53
+ apiKey: process.env.OKX_API_KEY,
54
+ secretKey: process.env.OKX_SECRET_KEY,
55
+ apiPassphrase: process.env.OKX_API_PASSPHRASE,
56
+ projectId: process.env.OKX_PROJECT_ID
57
+ };
58
+ var baseUrl = "https://web3.okx.com/api/v6/";
59
+ var ETH_ADDRESS = "0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000";
60
+ function getHeaders(timestamp, method, requestPath, queryString = "", body = "") {
61
+ const { apiKey, secretKey, apiPassphrase, projectId } = configs;
62
+ if (!apiKey || !secretKey || !apiPassphrase || !projectId) {
63
+ throw new Error(
64
+ "Missing required environment variables for API authentication"
65
+ );
66
+ }
67
+ const stringToSign = timestamp + method + requestPath + (queryString || body);
68
+ return {
69
+ "Content-Type": "application/json",
70
+ "OK-ACCESS-KEY": apiKey,
71
+ "OK-ACCESS-SIGN": CryptoJS__default.default.enc.Base64.stringify(
72
+ CryptoJS__default.default.HmacSHA256(stringToSign, secretKey)
73
+ ),
74
+ "OK-ACCESS-TIMESTAMP": timestamp,
75
+ "OK-ACCESS-PASSPHRASE": apiPassphrase,
76
+ "OK-ACCESS-PROJECT": projectId
77
+ };
78
+ }
79
+
80
+ // src/utils/okx/getApproveTx.ts
81
+ async function getApproveTx(tokenAddress, amount, chainIndex) {
82
+ try {
83
+ const path = "dex/aggregator/approve-transaction";
84
+ const url = `${baseUrl}${path}`;
85
+ const params = {
86
+ chainIndex,
87
+ tokenContractAddress: tokenAddress,
88
+ approveAmount: amount
89
+ };
90
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
91
+ const requestPath = `/api/v6/${path}`;
92
+ const queryString = "?" + new URLSearchParams(params).toString();
93
+ const headers = getHeaders(timestamp, "GET", requestPath, queryString);
94
+ const response = await axios6__default.default.get(url, { params, headers });
95
+ if (response.data.code === "0") {
96
+ return response.data.data[0];
97
+ } else {
98
+ throw new Error(`API Error: ${response.data.msg || "Unknown error"}`);
99
+ }
100
+ } catch (error) {
101
+ console.error(
102
+ "Failed to get approval transaction data:",
103
+ error.message
104
+ );
105
+ throw error;
106
+ }
107
+ }
108
+ async function getGasLimit(fromAddress, toAddress, chainIndex, txAmount = "0", inputData = "") {
109
+ try {
110
+ const path = "dex/pre-transaction/gas-limit";
111
+ const url = `https://web3.okx.com/api/v6/${path}`;
112
+ const body = {
113
+ chainIndex,
114
+ fromAddress,
115
+ toAddress,
116
+ txAmount,
117
+ extJson: {
118
+ inputData
119
+ }
120
+ };
121
+ const bodyString = JSON.stringify(body);
122
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
123
+ const requestPath = `/api/v6/${path}`;
124
+ const headers = getHeaders(timestamp, "POST", requestPath, "", bodyString);
125
+ const response = await axios6__default.default.post(url, body, { headers });
126
+ if (response.data.code === "0") {
127
+ return response.data.data[0].gasLimit;
128
+ } else {
129
+ throw new Error(`API Error: ${response.data.msg || "Unknown error"}`);
130
+ }
131
+ } catch (error) {
132
+ console.error("Failed to get gas limit:", error.message);
133
+ throw error;
134
+ }
135
+ }
136
+
137
+ // src/utils/okx/approveToken.ts
138
+ async function approveToken(agent, tokenAddress, amount) {
139
+ const chainIndex = agent.chain === "mainnet" ? "5000" : "5003";
140
+ const walletAddress = agent.account.address;
141
+ const spenderAddress = "0x1f16A607a7f3F3044E477abFFc8BD33952cE306b";
142
+ const currentAllowance = await checkAllowance(
143
+ agent,
144
+ tokenAddress,
145
+ walletAddress,
146
+ spenderAddress
147
+ );
148
+ if (currentAllowance >= BigInt(amount)) {
149
+ console.log("Sufficient allowance already exists");
150
+ return { allowanceExists: true, data: null };
151
+ }
152
+ console.log("Insufficient allowance, approving tokens...");
153
+ const approveData = await getApproveTx(tokenAddress, amount, chainIndex);
154
+ const gasLimit = await getGasLimit(
155
+ walletAddress,
156
+ tokenAddress,
157
+ chainIndex,
158
+ "0",
159
+ approveData.data
160
+ );
161
+ const txObject = {
162
+ to: tokenAddress,
163
+ data: approveData.data,
164
+ gas: gasLimit
165
+ };
166
+ return { allowanceExists: false, data: txObject };
167
+ }
168
+ async function getSwapTransaction(fromTokenAddress, toTokenAddress, amount, userWalletAddress, chainIndex, slippagePercent = "0.5") {
169
+ try {
170
+ const path = "dex/aggregator/swap";
171
+ const url = `${baseUrl}${path}`;
172
+ const params = {
173
+ chainIndex,
174
+ fromTokenAddress,
175
+ toTokenAddress,
176
+ amount,
177
+ userWalletAddress,
178
+ slippage: slippagePercent
179
+ };
180
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
181
+ const requestPath = `/api/v6/${path}`;
182
+ const queryString = "?" + new URLSearchParams(params).toString();
183
+ const headers = getHeaders(timestamp, "GET", requestPath, queryString);
184
+ const response = await axios6__default.default.get(url, { params, headers });
185
+ if (response.data.code === "0") {
186
+ return response.data.data[0];
187
+ } else {
188
+ throw new Error(`API Error: ${response.data.msg || "Unknown error"}`);
189
+ }
190
+ } catch (error) {
191
+ console.error(
192
+ "Failed to get swap transaction data:",
193
+ error.message
194
+ );
195
+ throw error;
196
+ }
197
+ }
198
+
199
+ // src/tools/okx/swap.ts
200
+ async function executeSwap(agent, fromTokenAddress, toTokenAddress, amount, slippagePercent) {
201
+ const chainIndex = agent.chain === "mainnet" ? "5000" : "5003";
202
+ const walletAddress = agent.account.address;
203
+ if (fromTokenAddress !== ETH_ADDRESS) {
204
+ const approval = await approveToken(agent, fromTokenAddress, amount);
205
+ if (!approval.allowanceExists && approval.data) {
206
+ const approveTxHash = await agent.client.sendTransaction({
207
+ to: approval.data.to,
208
+ data: approval.data.data,
209
+ value: BigInt(0),
210
+ gas: BigInt(approval.data.gas)
211
+ });
212
+ console.log(`Approval tx sent: ${approveTxHash}`);
213
+ const approveReceipt = await agent.client.waitForTransactionReceipt({
214
+ hash: approveTxHash
215
+ });
216
+ console.log(`Approval confirmed: ${approveReceipt.status}`);
217
+ }
218
+ }
219
+ const swapData = await getSwapTransaction(
220
+ fromTokenAddress,
221
+ toTokenAddress,
222
+ amount,
223
+ walletAddress,
224
+ chainIndex,
225
+ slippagePercent
226
+ );
227
+ const txData = swapData.tx;
228
+ console.log("Swap TX data received");
229
+ const gasLimit = await getGasLimit(
230
+ walletAddress,
231
+ txData.to,
232
+ chainIndex,
233
+ txData.value || "0",
234
+ txData.data
235
+ );
236
+ console.log("Gas limit received");
237
+ const txHash = await agent.client.sendTransaction({
238
+ to: txData.to,
239
+ data: txData.data,
240
+ value: BigInt(txData.value || "0"),
241
+ gas: BigInt(gasLimit)
242
+ });
243
+ console.log(`Swap tx sent: ${txHash}`);
244
+ const swapReceipt = await agent.client.waitForTransactionReceipt({
245
+ hash: txHash
246
+ });
247
+ console.log(`Swap confirmed: ${swapReceipt.status}`);
248
+ return {
249
+ data: txHash
250
+ };
251
+ }
252
+
253
+ // src/constants/openocean/index.ts
254
+ var openocean_exports = {};
255
+ __export(openocean_exports, {
256
+ NATIVE_TOKEN_ADDRESS: () => NATIVE_TOKEN_ADDRESS,
257
+ OPENOCEAN_BASE_URL: () => OPENOCEAN_BASE_URL,
258
+ OPENOCEAN_CHAIN: () => OPENOCEAN_CHAIN,
259
+ OPENOCEAN_EXCHANGE_PROXY: () => OPENOCEAN_EXCHANGE_PROXY
260
+ });
261
+ var OPENOCEAN_BASE_URL = "https://open-api.openocean.finance/v4";
262
+ var OPENOCEAN_CHAIN = {
263
+ mainnet: "mantle",
264
+ testnet: "mantle"
265
+ // OpenOcean may not support testnet
266
+ };
267
+ var NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
268
+ var OPENOCEAN_EXCHANGE_PROXY = "0x6352a56caadC4F1E25CD6c75970Fa768A3304e64";
269
+
270
+ // src/helpers/openocean/index.ts
271
+ function getHeaders2(apiKey) {
272
+ const headers = {
273
+ "Content-Type": "application/json"
274
+ };
275
+ return headers;
276
+ }
277
+
278
+ // src/utils/openocean/getQuoteData.ts
279
+ async function getQuoteData(fromToken, toToken, amount, chain) {
280
+ try {
281
+ const chainName = OPENOCEAN_CHAIN[chain];
282
+ const url = `${OPENOCEAN_BASE_URL}/${chainName}/quote`;
283
+ const params = {
284
+ inTokenAddress: fromToken,
285
+ outTokenAddress: toToken,
286
+ amount,
287
+ gasPrice: "5"
288
+ // Default gas price in gwei
289
+ };
290
+ const response = await axios6__default.default.get(url, {
291
+ params,
292
+ headers: getHeaders2()
293
+ });
294
+ if (response.data.code === 200) {
295
+ return response.data.data;
296
+ } else {
297
+ throw new Error(`OpenOcean API Error: ${response.data.message || "Unknown error"}`);
298
+ }
299
+ } catch (error) {
300
+ console.error("Failed to get OpenOcean quote:", error.message);
301
+ throw error;
302
+ }
303
+ }
304
+ async function getSwapData(fromToken, toToken, amount, userAddress, slippage, chain) {
305
+ try {
306
+ const chainName = OPENOCEAN_CHAIN[chain];
307
+ const url = `${OPENOCEAN_BASE_URL}/${chainName}/swap`;
308
+ const params = {
309
+ inTokenAddress: fromToken,
310
+ outTokenAddress: toToken,
311
+ amount,
312
+ gasPrice: "5",
313
+ // Default gas price in gwei
314
+ slippage,
315
+ account: userAddress
316
+ };
317
+ const response = await axios6__default.default.get(url, {
318
+ params,
319
+ headers: getHeaders2()
320
+ });
321
+ if (response.data.code === 200) {
322
+ return response.data.data;
323
+ } else {
324
+ throw new Error(`OpenOcean API Error: ${response.data.message || "Unknown error"}`);
325
+ }
326
+ } catch (error) {
327
+ console.error("Failed to get OpenOcean swap data:", error.message);
328
+ throw error;
329
+ }
330
+ }
331
+
332
+ // src/tools/openocean/getQuote.ts
333
+ async function getOpenOceanQuote(agent, fromToken, toToken, amount) {
334
+ return await getQuoteData(fromToken, toToken, amount, agent.chain);
335
+ }
336
+ async function checkAllowance2(agent, tokenAddress, ownerAddress, spenderAddress) {
337
+ try {
338
+ const allowance = await agent.client.readContract({
339
+ address: tokenAddress,
340
+ abi: viem.erc20Abi,
341
+ functionName: "allowance",
342
+ args: [ownerAddress, spenderAddress]
343
+ });
344
+ return allowance;
345
+ } catch (error) {
346
+ console.error("Failed to query allowance:", error);
347
+ throw error;
348
+ }
349
+ }
350
+ async function approveToken2(agent, tokenAddress, spenderAddress, amount) {
351
+ const walletAddress = agent.account.address;
352
+ const currentAllowance = await checkAllowance2(
353
+ agent,
354
+ tokenAddress,
355
+ walletAddress,
356
+ spenderAddress
357
+ );
358
+ if (currentAllowance >= BigInt(amount)) {
359
+ console.log("Sufficient allowance already exists");
360
+ return { approved: true, txHash: null };
361
+ }
362
+ console.log("Insufficient allowance, approving tokens...");
363
+ const { encodeFunctionData: encodeFunctionData8 } = await import('viem');
364
+ const approveData = encodeFunctionData8({
365
+ abi: viem.erc20Abi,
366
+ functionName: "approve",
367
+ args: [spenderAddress, BigInt(amount)]
368
+ });
369
+ const gasEstimate = await agent.client.estimateGas({
370
+ account: agent.account,
371
+ to: tokenAddress,
372
+ data: approveData
373
+ });
374
+ const txHash = await agent.client.sendTransaction({
375
+ to: tokenAddress,
376
+ data: approveData,
377
+ value: BigInt(0),
378
+ gas: gasEstimate
379
+ });
380
+ console.log(`Approval tx sent: ${txHash}`);
381
+ const receipt = await agent.client.waitForTransactionReceipt({
382
+ hash: txHash
383
+ });
384
+ console.log(`Approval confirmed: ${receipt.status}`);
385
+ return { approved: true, txHash };
386
+ }
387
+
388
+ // src/tools/openocean/swap.ts
389
+ async function swapOnOpenOcean(agent, fromToken, toToken, amount, slippage = "1") {
390
+ const walletAddress = agent.account.address;
391
+ if (fromToken.toLowerCase() !== NATIVE_TOKEN_ADDRESS.toLowerCase()) {
392
+ await approveToken2(agent, fromToken, OPENOCEAN_EXCHANGE_PROXY, amount);
393
+ }
394
+ const swapData = await getSwapData(
395
+ fromToken,
396
+ toToken,
397
+ amount,
398
+ walletAddress,
399
+ slippage,
400
+ agent.chain
401
+ );
402
+ console.log("OpenOcean swap data received");
403
+ console.log(`Expected output: ${swapData.outAmount}`);
404
+ const txHash = await agent.client.sendTransaction({
405
+ to: swapData.to,
406
+ data: swapData.data,
407
+ value: BigInt(swapData.value || "0"),
408
+ gas: BigInt(swapData.estimatedGas)
409
+ });
410
+ console.log(`OpenOcean swap tx sent: ${txHash}`);
411
+ const receipt = await agent.client.waitForTransactionReceipt({
412
+ hash: txHash
413
+ });
414
+ console.log(`Swap confirmed: ${receipt.status}`);
415
+ return {
416
+ txHash,
417
+ outAmount: swapData.outAmount
418
+ };
419
+ }
420
+
421
+ // src/constants/oneinch/index.ts
422
+ var oneinch_exports = {};
423
+ __export(oneinch_exports, {
424
+ NATIVE_TOKEN_ADDRESS: () => NATIVE_TOKEN_ADDRESS2,
425
+ ONEINCH_BASE_URL: () => ONEINCH_BASE_URL,
426
+ ONEINCH_CHAIN_ID: () => ONEINCH_CHAIN_ID,
427
+ ONEINCH_ROUTER_ADDRESS: () => ONEINCH_ROUTER_ADDRESS,
428
+ configs: () => configs2
429
+ });
430
+ var ONEINCH_BASE_URL = "https://api.1inch.dev/swap/v6.0";
431
+ var ONEINCH_CHAIN_ID = {
432
+ mainnet: "5000",
433
+ // Mantle mainnet
434
+ testnet: "5003"
435
+ // Mantle testnet (may not be supported)
436
+ };
437
+ var NATIVE_TOKEN_ADDRESS2 = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
438
+ var ONEINCH_ROUTER_ADDRESS = "0x111111125421cA6dc452d289314280a0f8842A65";
439
+ var configs2 = {
440
+ apiKey: process.env.ONEINCH_API_KEY
441
+ // Optional: for higher rate limits
442
+ };
443
+
444
+ // src/helpers/oneinch/index.ts
445
+ function getHeaders3() {
446
+ const headers = {
447
+ "Content-Type": "application/json"
448
+ };
449
+ if (configs2.apiKey) {
450
+ headers["Authorization"] = `Bearer ${configs2.apiKey}`;
451
+ }
452
+ return headers;
453
+ }
454
+
455
+ // src/utils/oneinch/getSwapData.ts
456
+ async function getQuoteData2(fromToken, toToken, amount, chain) {
457
+ try {
458
+ const chainId = ONEINCH_CHAIN_ID[chain];
459
+ const url = `${ONEINCH_BASE_URL}/${chainId}/quote`;
460
+ const params = {
461
+ src: fromToken,
462
+ dst: toToken,
463
+ amount
464
+ };
465
+ const response = await axios6__default.default.get(url, {
466
+ params,
467
+ headers: getHeaders3()
468
+ });
469
+ return response.data;
470
+ } catch (error) {
471
+ console.error("Failed to get 1inch quote:", error.message);
472
+ throw error;
473
+ }
474
+ }
475
+ async function getSwapData2(fromToken, toToken, amount, userAddress, slippage, chain) {
476
+ try {
477
+ const chainId = ONEINCH_CHAIN_ID[chain];
478
+ const url = `${ONEINCH_BASE_URL}/${chainId}/swap`;
479
+ const params = {
480
+ src: fromToken,
481
+ dst: toToken,
482
+ amount,
483
+ from: userAddress,
484
+ slippage,
485
+ disableEstimate: "true"
486
+ // We'll estimate gas ourselves
487
+ };
488
+ const response = await axios6__default.default.get(url, {
489
+ params,
490
+ headers: getHeaders3()
491
+ });
492
+ return response.data;
493
+ } catch (error) {
494
+ console.error("Failed to get 1inch swap data:", error.message);
495
+ throw error;
496
+ }
497
+ }
498
+
499
+ // src/tools/oneinch/getQuote.ts
500
+ async function get1inchQuote(agent, fromToken, toToken, amount) {
501
+ return await getQuoteData2(fromToken, toToken, amount, agent.chain);
502
+ }
503
+
504
+ // src/tools/oneinch/swap.ts
505
+ async function swapOn1inch(agent, fromToken, toToken, amount, slippage = "1") {
506
+ const walletAddress = agent.account.address;
507
+ if (fromToken.toLowerCase() !== NATIVE_TOKEN_ADDRESS2.toLowerCase()) {
508
+ await approveToken2(agent, fromToken, ONEINCH_ROUTER_ADDRESS, amount);
509
+ }
510
+ const swapData = await getSwapData2(
511
+ fromToken,
512
+ toToken,
513
+ amount,
514
+ walletAddress,
515
+ slippage,
516
+ agent.chain
517
+ );
518
+ console.log("1inch swap data received");
519
+ console.log(`Expected output: ${swapData.dstAmount}`);
520
+ const gasEstimate = await agent.client.estimateGas({
521
+ account: agent.account,
522
+ to: swapData.tx.to,
523
+ data: swapData.tx.data,
524
+ value: BigInt(swapData.tx.value || "0")
525
+ });
526
+ const txHash = await agent.client.sendTransaction({
527
+ to: swapData.tx.to,
528
+ data: swapData.tx.data,
529
+ value: BigInt(swapData.tx.value || "0"),
530
+ gas: gasEstimate
531
+ });
532
+ console.log(`1inch swap tx sent: ${txHash}`);
533
+ const receipt = await agent.client.waitForTransactionReceipt({
534
+ hash: txHash
535
+ });
536
+ console.log(`Swap confirmed: ${receipt.status}`);
537
+ return {
538
+ txHash,
539
+ dstAmount: swapData.dstAmount
540
+ };
541
+ }
542
+
543
+ // src/constants/uniswap/index.ts
544
+ var uniswap_exports = {};
545
+ __export(uniswap_exports, {
546
+ DEFAULT_POOL_FEE: () => DEFAULT_POOL_FEE,
547
+ FACTORY_ADDRESS: () => FACTORY_ADDRESS,
548
+ FEE_TIERS: () => FEE_TIERS,
549
+ NATIVE_TOKEN_ADDRESS: () => NATIVE_TOKEN_ADDRESS3,
550
+ QUOTER_V2_ADDRESS: () => QUOTER_V2_ADDRESS,
551
+ SWAP_ROUTER_ADDRESS: () => SWAP_ROUTER_ADDRESS,
552
+ WMNT_ADDRESS: () => WMNT_ADDRESS
553
+ });
554
+ var SWAP_ROUTER_ADDRESS = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45";
555
+ var QUOTER_V2_ADDRESS = "0x61fFE014bA17989E743c5F6cB21bF9697530B21e";
556
+ var FACTORY_ADDRESS = "0x1F98431c8aD98523631AE4a59f267346ea31F984";
557
+ var WMNT_ADDRESS = "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8";
558
+ var NATIVE_TOKEN_ADDRESS3 = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
559
+ var FEE_TIERS = {
560
+ LOWEST: 100,
561
+ // 0.01%
562
+ LOW: 500,
563
+ // 0.05%
564
+ MEDIUM: 3e3,
565
+ // 0.3%
566
+ HIGH: 1e4
567
+ // 1%
568
+ };
569
+ var DEFAULT_POOL_FEE = FEE_TIERS.MEDIUM;
570
+ var quoterV2Abi = [
571
+ {
572
+ inputs: [
573
+ {
574
+ components: [
575
+ { name: "tokenIn", type: "address" },
576
+ { name: "tokenOut", type: "address" },
577
+ { name: "amountIn", type: "uint256" },
578
+ { name: "fee", type: "uint24" },
579
+ { name: "sqrtPriceLimitX96", type: "uint160" }
580
+ ],
581
+ name: "params",
582
+ type: "tuple"
583
+ }
584
+ ],
585
+ name: "quoteExactInputSingle",
586
+ outputs: [
587
+ { name: "amountOut", type: "uint256" },
588
+ { name: "sqrtPriceX96After", type: "uint160" },
589
+ { name: "initializedTicksCrossed", type: "uint32" },
590
+ { name: "gasEstimate", type: "uint256" }
591
+ ],
592
+ stateMutability: "nonpayable",
593
+ type: "function"
594
+ }
595
+ ];
596
+ var swapRouterAbi = [
597
+ {
598
+ inputs: [
599
+ {
600
+ components: [
601
+ { name: "tokenIn", type: "address" },
602
+ { name: "tokenOut", type: "address" },
603
+ { name: "fee", type: "uint24" },
604
+ { name: "recipient", type: "address" },
605
+ { name: "amountIn", type: "uint256" },
606
+ { name: "amountOutMinimum", type: "uint256" },
607
+ { name: "sqrtPriceLimitX96", type: "uint160" }
608
+ ],
609
+ name: "params",
610
+ type: "tuple"
611
+ }
612
+ ],
613
+ name: "exactInputSingle",
614
+ outputs: [{ name: "amountOut", type: "uint256" }],
615
+ stateMutability: "payable",
616
+ type: "function"
617
+ }
618
+ ];
619
+ function getTokenAddress(token) {
620
+ if (token.toLowerCase() === NATIVE_TOKEN_ADDRESS3.toLowerCase()) {
621
+ return WMNT_ADDRESS;
622
+ }
623
+ return token;
624
+ }
625
+ async function getUniswapQuoteData(agent, tokenIn, tokenOut, amountIn, fee = DEFAULT_POOL_FEE) {
626
+ try {
627
+ const result = await agent.client.simulateContract({
628
+ address: QUOTER_V2_ADDRESS,
629
+ abi: quoterV2Abi,
630
+ functionName: "quoteExactInputSingle",
631
+ args: [
632
+ {
633
+ tokenIn: getTokenAddress(tokenIn),
634
+ tokenOut: getTokenAddress(tokenOut),
635
+ amountIn: BigInt(amountIn),
636
+ fee,
637
+ sqrtPriceLimitX96: BigInt(0)
638
+ }
639
+ ]
640
+ });
641
+ const [amountOut, sqrtPriceX96After, , gasEstimate] = result.result;
642
+ return {
643
+ amountOut,
644
+ sqrtPriceX96After,
645
+ gasEstimate
646
+ };
647
+ } catch (error) {
648
+ console.error("Failed to get Uniswap quote:", error);
649
+ throw error;
650
+ }
651
+ }
652
+ function buildSwapCalldata(params, fee = DEFAULT_POOL_FEE) {
653
+ return viem.encodeFunctionData({
654
+ abi: swapRouterAbi,
655
+ functionName: "exactInputSingle",
656
+ args: [
657
+ {
658
+ tokenIn: getTokenAddress(params.tokenIn),
659
+ tokenOut: getTokenAddress(params.tokenOut),
660
+ fee,
661
+ recipient: params.recipient,
662
+ amountIn: BigInt(params.amountIn),
663
+ amountOutMinimum: BigInt(params.amountOutMinimum),
664
+ sqrtPriceLimitX96: BigInt(0)
665
+ }
666
+ ]
667
+ });
668
+ }
669
+
670
+ // src/tools/uniswap/getQuote.ts
671
+ async function getUniswapQuote(agent, fromToken, toToken, amount, fee = DEFAULT_POOL_FEE) {
672
+ return await getUniswapQuoteData(agent, fromToken, toToken, amount, fee);
673
+ }
674
+
675
+ // src/tools/uniswap/swap.ts
676
+ async function swapOnUniswap(agent, fromToken, toToken, amount, slippage = "0.5", fee = DEFAULT_POOL_FEE) {
677
+ const walletAddress = agent.account.address;
678
+ const isNativeIn = fromToken.toLowerCase() === NATIVE_TOKEN_ADDRESS3.toLowerCase();
679
+ const quote = await getUniswapQuoteData(agent, fromToken, toToken, amount, fee);
680
+ console.log(`Uniswap quote: ${quote.amountOut.toString()}`);
681
+ const slippageBps = Math.floor(parseFloat(slippage) * 100);
682
+ const amountOutMinimum = quote.amountOut * BigInt(1e4 - slippageBps) / BigInt(1e4);
683
+ if (!isNativeIn) {
684
+ await approveToken2(agent, fromToken, SWAP_ROUTER_ADDRESS, amount);
685
+ }
686
+ const calldata = buildSwapCalldata(
687
+ {
688
+ tokenIn: fromToken,
689
+ tokenOut: toToken,
690
+ amountIn: amount,
691
+ amountOutMinimum: amountOutMinimum.toString(),
692
+ recipient: walletAddress
693
+ },
694
+ fee
695
+ );
696
+ const gasEstimate = await agent.client.estimateGas({
697
+ account: agent.account,
698
+ to: SWAP_ROUTER_ADDRESS,
699
+ data: calldata,
700
+ value: isNativeIn ? BigInt(amount) : BigInt(0)
701
+ });
702
+ const txHash = await agent.client.sendTransaction({
703
+ to: SWAP_ROUTER_ADDRESS,
704
+ data: calldata,
705
+ value: isNativeIn ? BigInt(amount) : BigInt(0),
706
+ gas: gasEstimate
707
+ });
708
+ console.log(`Uniswap swap tx sent: ${txHash}`);
709
+ const receipt = await agent.client.waitForTransactionReceipt({
710
+ hash: txHash
711
+ });
712
+ console.log(`Swap confirmed: ${receipt.status}`);
713
+ return {
714
+ txHash,
715
+ amountOut: quote.amountOut.toString()
716
+ };
717
+ }
718
+
719
+ // src/constants/squid/index.ts
720
+ var squid_exports = {};
721
+ __export(squid_exports, {
722
+ DESTINATION_CHAINS: () => DESTINATION_CHAINS,
723
+ NATIVE_TOKEN_ADDRESS: () => NATIVE_TOKEN_ADDRESS4,
724
+ SQUID_BASE_URL: () => SQUID_BASE_URL,
725
+ SQUID_CHAIN_ID: () => SQUID_CHAIN_ID
726
+ });
727
+ var SQUID_BASE_URL = "https://api.squidrouter.com/v2";
728
+ var SQUID_CHAIN_ID = {
729
+ mainnet: 5e3,
730
+ // Mantle mainnet
731
+ testnet: 5003
732
+ // Mantle testnet
733
+ };
734
+ var DESTINATION_CHAINS = {
735
+ ethereum: 101,
736
+ arbitrum: 110,
737
+ optimism: 111,
738
+ polygon: 109,
739
+ base: 184,
740
+ bsc: 102,
741
+ avalanche: 106,
742
+ mantle: 5e3
743
+ };
744
+ var NATIVE_TOKEN_ADDRESS4 = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
745
+
746
+ // src/helpers/squid/index.ts
747
+ function getHeaders4(integratorId) {
748
+ const headers = {
749
+ "Content-Type": "application/json"
750
+ };
751
+ return headers;
752
+ }
753
+
754
+ // src/utils/squid/getRouteData.ts
755
+ async function getRouteData(fromToken, toToken, fromChain, toChain, amount, fromAddress, slippage = 1) {
756
+ const params = {
757
+ fromChain: fromChain.toString(),
758
+ toChain: toChain.toString(),
759
+ fromToken: fromToken.toLowerCase() === NATIVE_TOKEN_ADDRESS4.toLowerCase() ? "native" : fromToken,
760
+ toToken: toToken.toLowerCase() === NATIVE_TOKEN_ADDRESS4.toLowerCase() ? "native" : toToken,
761
+ fromAmount: amount,
762
+ fromAddress,
763
+ slippage: slippage.toString(),
764
+ enableForecast: false
765
+ };
766
+ const response = await axios6__default.default.get(`${SQUID_BASE_URL}/route`, {
767
+ params,
768
+ headers: getHeaders4()
769
+ });
770
+ return response.data;
771
+ }
772
+
773
+ // src/tools/squid/crossChainSwap.ts
774
+ async function crossChainSwapViaSquid(agent, fromToken, toToken, fromChain, toChain, amount, slippage = 1) {
775
+ const routeData = await getRouteData(
776
+ fromToken,
777
+ toToken,
778
+ fromChain,
779
+ toChain,
780
+ amount,
781
+ agent.account.address,
782
+ slippage
783
+ );
784
+ const transactionRequest = routeData.route.transactionRequest;
785
+ if (fromToken.toLowerCase() !== NATIVE_TOKEN_ADDRESS4.toLowerCase() && transactionRequest.targetAddress) {
786
+ await approveToken2(
787
+ agent,
788
+ fromToken,
789
+ transactionRequest.targetAddress,
790
+ amount
791
+ );
792
+ }
793
+ const hash = await agent.client.sendTransaction({
794
+ to: transactionRequest.targetAddress,
795
+ data: transactionRequest.data,
796
+ value: BigInt(transactionRequest.value || "0"),
797
+ gas: BigInt(transactionRequest.gasLimit || "0")
798
+ });
799
+ await agent.client.waitForTransactionReceipt({ hash });
800
+ return hash;
801
+ }
802
+ async function getSquidRoute(agent, fromToken, toToken, fromChain, toChain, amount, slippage = 1) {
803
+ return await getRouteData(
804
+ fromToken,
805
+ toToken,
806
+ fromChain,
807
+ toChain,
808
+ amount,
809
+ agent.account.address,
810
+ slippage
811
+ );
812
+ }
813
+
814
+ // src/constants/lendle/index.ts
815
+ var lendle_exports = {};
816
+ __export(lendle_exports, {
817
+ INTEREST_RATE_MODE: () => INTEREST_RATE_MODE,
818
+ LENDING_POOL: () => LENDING_POOL,
819
+ LENDING_POOL_ABI: () => LENDING_POOL_ABI,
820
+ LENDING_POOL_ADDRESSES_PROVIDER: () => LENDING_POOL_ADDRESSES_PROVIDER,
821
+ ORACLE: () => ORACLE,
822
+ PROTOCOL_DATA_PROVIDER: () => PROTOCOL_DATA_PROVIDER,
823
+ WMNT_ADDRESS: () => WMNT_ADDRESS2
824
+ });
825
+ var LENDING_POOL = {
826
+ mainnet: "0xCFa5aE7c2CE8Fadc6426C1ff872cA45378Fb7cF3",
827
+ testnet: "0x0000000000000000000000000000000000000000"
828
+ // Not deployed on testnet
829
+ };
830
+ var LENDING_POOL_ADDRESSES_PROVIDER = {
831
+ mainnet: "0xAb94Bedd21ae3411eB2698945dfCab1D5C19C3d4",
832
+ testnet: "0x0000000000000000000000000000000000000000"
833
+ };
834
+ var PROTOCOL_DATA_PROVIDER = {
835
+ mainnet: "0x552b9e4bae485C4B7F540777d7D25614CdB84773",
836
+ testnet: "0x0000000000000000000000000000000000000000"
837
+ };
838
+ var ORACLE = {
839
+ mainnet: "0x870c9692Ab04944C86ec6FEeF63F261226506EfC",
840
+ testnet: "0x0000000000000000000000000000000000000000"
841
+ };
842
+ var WMNT_ADDRESS2 = "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8";
843
+ var INTEREST_RATE_MODE = {
844
+ STABLE: 1,
845
+ VARIABLE: 2
846
+ };
847
+ var LENDING_POOL_ABI = [
848
+ {
849
+ inputs: [
850
+ { name: "asset", type: "address" },
851
+ { name: "amount", type: "uint256" },
852
+ { name: "onBehalfOf", type: "address" },
853
+ { name: "referralCode", type: "uint16" }
854
+ ],
855
+ name: "deposit",
856
+ outputs: [],
857
+ stateMutability: "nonpayable",
858
+ type: "function"
859
+ },
860
+ {
861
+ inputs: [
862
+ { name: "asset", type: "address" },
863
+ { name: "amount", type: "uint256" },
864
+ { name: "to", type: "address" }
865
+ ],
866
+ name: "withdraw",
867
+ outputs: [{ name: "", type: "uint256" }],
868
+ stateMutability: "nonpayable",
869
+ type: "function"
870
+ },
871
+ {
872
+ inputs: [
873
+ { name: "asset", type: "address" },
874
+ { name: "amount", type: "uint256" },
875
+ { name: "interestRateMode", type: "uint256" },
876
+ { name: "referralCode", type: "uint16" },
877
+ { name: "onBehalfOf", type: "address" }
878
+ ],
879
+ name: "borrow",
880
+ outputs: [],
881
+ stateMutability: "nonpayable",
882
+ type: "function"
883
+ },
884
+ {
885
+ inputs: [
886
+ { name: "asset", type: "address" },
887
+ { name: "amount", type: "uint256" },
888
+ { name: "rateMode", type: "uint256" },
889
+ { name: "onBehalfOf", type: "address" }
890
+ ],
891
+ name: "repay",
892
+ outputs: [{ name: "", type: "uint256" }],
893
+ stateMutability: "nonpayable",
894
+ type: "function"
895
+ },
896
+ {
897
+ inputs: [{ name: "user", type: "address" }],
898
+ name: "getUserAccountData",
899
+ outputs: [
900
+ { name: "totalCollateralETH", type: "uint256" },
901
+ { name: "totalDebtETH", type: "uint256" },
902
+ { name: "availableBorrowsETH", type: "uint256" },
903
+ { name: "currentLiquidationThreshold", type: "uint256" },
904
+ { name: "ltv", type: "uint256" },
905
+ { name: "healthFactor", type: "uint256" }
906
+ ],
907
+ stateMutability: "view",
908
+ type: "function"
909
+ },
910
+ {
911
+ inputs: [{ name: "asset", type: "address" }],
912
+ name: "getReserveData",
913
+ outputs: [
914
+ {
915
+ components: [
916
+ { name: "configuration", type: "uint256" },
917
+ { name: "liquidityIndex", type: "uint128" },
918
+ { name: "variableBorrowIndex", type: "uint128" },
919
+ { name: "currentLiquidityRate", type: "uint128" },
920
+ { name: "currentVariableBorrowRate", type: "uint128" },
921
+ { name: "currentStableBorrowRate", type: "uint128" },
922
+ { name: "lastUpdateTimestamp", type: "uint40" },
923
+ { name: "aTokenAddress", type: "address" },
924
+ { name: "stableDebtTokenAddress", type: "address" },
925
+ { name: "variableDebtTokenAddress", type: "address" },
926
+ { name: "interestRateStrategyAddress", type: "address" },
927
+ { name: "id", type: "uint8" }
928
+ ],
929
+ name: "",
930
+ type: "tuple"
931
+ }
932
+ ],
933
+ stateMutability: "view",
934
+ type: "function"
935
+ }
936
+ ];
937
+
938
+ // src/tools/lendle/supply.ts
939
+ async function lendleSupply(agent, tokenAddress, amount) {
940
+ const lendingPoolAddress = LENDING_POOL[agent.chain];
941
+ if (lendingPoolAddress === "0x0000000000000000000000000000000000000000") {
942
+ throw new Error(
943
+ `Lendle LendingPool not configured for ${agent.chain}. Only available on mainnet.`
944
+ );
945
+ }
946
+ const amountBigInt = BigInt(amount);
947
+ const isNative = tokenAddress.toLowerCase() === WMNT_ADDRESS2.toLowerCase();
948
+ if (!isNative) {
949
+ await approveToken2(agent, tokenAddress, lendingPoolAddress, amount);
950
+ }
951
+ const data = viem.encodeFunctionData({
952
+ abi: LENDING_POOL_ABI,
953
+ functionName: "deposit",
954
+ args: [tokenAddress, amountBigInt, agent.account.address, 0]
955
+ // referralCode = 0 (uint16)
956
+ });
957
+ const hash = await agent.client.sendTransaction({
958
+ to: lendingPoolAddress,
959
+ data,
960
+ value: isNative ? amountBigInt : 0n
961
+ });
962
+ await agent.client.waitForTransactionReceipt({ hash });
963
+ return hash;
964
+ }
965
+ async function lendleWithdraw(agent, tokenAddress, amount, to) {
966
+ const lendingPoolAddress = LENDING_POOL[agent.chain];
967
+ if (lendingPoolAddress === "0x0000000000000000000000000000000000000000") {
968
+ throw new Error(
969
+ `Lendle LendingPool not configured for ${agent.chain}. Only available on mainnet.`
970
+ );
971
+ }
972
+ const amountBigInt = BigInt(amount);
973
+ const toAddress = to || agent.account.address;
974
+ const data = viem.encodeFunctionData({
975
+ abi: LENDING_POOL_ABI,
976
+ functionName: "withdraw",
977
+ args: [tokenAddress, amountBigInt, toAddress]
978
+ });
979
+ const hash = await agent.client.sendTransaction({
980
+ to: lendingPoolAddress,
981
+ data
982
+ });
983
+ await agent.client.waitForTransactionReceipt({ hash });
984
+ return hash;
985
+ }
986
+ async function lendleBorrow(agent, tokenAddress, amount, interestRateMode = INTEREST_RATE_MODE.VARIABLE, onBehalfOf) {
987
+ const lendingPoolAddress = LENDING_POOL[agent.chain];
988
+ if (lendingPoolAddress === "0x0000000000000000000000000000000000000000") {
989
+ throw new Error(
990
+ `Lendle LendingPool not configured for ${agent.chain}. Only available on mainnet.`
991
+ );
992
+ }
993
+ const amountBigInt = BigInt(amount);
994
+ const onBehalfOfAddress = onBehalfOf || agent.account.address;
995
+ const data = viem.encodeFunctionData({
996
+ abi: LENDING_POOL_ABI,
997
+ functionName: "borrow",
998
+ args: [tokenAddress, amountBigInt, BigInt(interestRateMode), 0, onBehalfOfAddress]
999
+ // referralCode = 0 (uint16)
1000
+ });
1001
+ const hash = await agent.client.sendTransaction({
1002
+ to: lendingPoolAddress,
1003
+ data
1004
+ });
1005
+ await agent.client.waitForTransactionReceipt({ hash });
1006
+ return hash;
1007
+ }
1008
+ async function lendleRepay(agent, tokenAddress, amount, rateMode = INTEREST_RATE_MODE.VARIABLE, onBehalfOf) {
1009
+ const lendingPoolAddress = LENDING_POOL[agent.chain];
1010
+ if (lendingPoolAddress === "0x0000000000000000000000000000000000000000") {
1011
+ throw new Error(
1012
+ `Lendle LendingPool not configured for ${agent.chain}. Only available on mainnet.`
1013
+ );
1014
+ }
1015
+ const amountBigInt = BigInt(amount);
1016
+ const onBehalfOfAddress = onBehalfOf || agent.account.address;
1017
+ await approveToken2(agent, tokenAddress, lendingPoolAddress, amount);
1018
+ const data = viem.encodeFunctionData({
1019
+ abi: LENDING_POOL_ABI,
1020
+ functionName: "repay",
1021
+ args: [tokenAddress, amountBigInt, BigInt(rateMode), onBehalfOfAddress]
1022
+ });
1023
+ const hash = await agent.client.sendTransaction({
1024
+ to: lendingPoolAddress,
1025
+ data
1026
+ });
1027
+ await agent.client.waitForTransactionReceipt({ hash });
1028
+ return hash;
1029
+ }
1030
+
1031
+ // src/constants/agni/index.ts
1032
+ var agni_exports = {};
1033
+ __export(agni_exports, {
1034
+ FACTORY: () => FACTORY,
1035
+ FEE_TIERS: () => FEE_TIERS2,
1036
+ POSITION_MANAGER: () => POSITION_MANAGER,
1037
+ SWAP_ROUTER: () => SWAP_ROUTER,
1038
+ SWAP_ROUTER_ABI: () => SWAP_ROUTER_ABI
1039
+ });
1040
+ var FACTORY = {
1041
+ mainnet: "0x25780dc8Fc3cfBD75F33bFDAB65e969b603b2035",
1042
+ testnet: "0x0000000000000000000000000000000000000000"
1043
+ };
1044
+ var SWAP_ROUTER = {
1045
+ mainnet: "0x319B69888b0d11cEC22caA5034e25FfFBDc88421",
1046
+ testnet: "0x0000000000000000000000000000000000000000"
1047
+ };
1048
+ var POSITION_MANAGER = {
1049
+ mainnet: "0x218bf598d1453383e2f4aa7b14ffb9bfb102d637",
1050
+ testnet: "0x0000000000000000000000000000000000000000"
1051
+ };
1052
+ var SWAP_ROUTER_ABI = [
1053
+ {
1054
+ inputs: [
1055
+ {
1056
+ components: [
1057
+ { name: "tokenIn", type: "address" },
1058
+ { name: "tokenOut", type: "address" },
1059
+ { name: "fee", type: "uint24" },
1060
+ { name: "recipient", type: "address" },
1061
+ { name: "deadline", type: "uint256" },
1062
+ { name: "amountIn", type: "uint256" },
1063
+ { name: "amountOutMinimum", type: "uint256" },
1064
+ { name: "sqrtPriceLimitX96", type: "uint160" }
1065
+ ],
1066
+ name: "params",
1067
+ type: "tuple"
1068
+ }
1069
+ ],
1070
+ name: "exactInputSingle",
1071
+ outputs: [{ name: "amountOut", type: "uint256" }],
1072
+ stateMutability: "payable",
1073
+ type: "function"
1074
+ }
1075
+ ];
1076
+ var FEE_TIERS2 = {
1077
+ LOWEST: 100,
1078
+ // 0.01%
1079
+ LOW: 500,
1080
+ // 0.05%
1081
+ MEDIUM: 3e3,
1082
+ // 0.3%
1083
+ HIGH: 1e4
1084
+ // 1%
1085
+ };
1086
+
1087
+ // src/tools/agni/swap.ts
1088
+ async function agniSwap(agent, tokenIn, tokenOut, amountIn, slippagePercent = 0.5, feeTier = FEE_TIERS2.MEDIUM) {
1089
+ const swapRouterAddress = SWAP_ROUTER[agent.chain];
1090
+ if (swapRouterAddress === "0x0000000000000000000000000000000000000000") {
1091
+ throw new Error(`Agni SwapRouter not available on ${agent.chain}`);
1092
+ }
1093
+ const amountInBigInt = BigInt(amountIn);
1094
+ const deadline = BigInt(Math.floor(Date.now() / 1e3) + 1200);
1095
+ const amountOutMinimum = amountInBigInt * BigInt(1e4 - Math.floor(slippagePercent * 100)) / 10000n;
1096
+ await approveToken2(agent, tokenIn, swapRouterAddress, amountIn);
1097
+ const data = viem.encodeFunctionData({
1098
+ abi: SWAP_ROUTER_ABI,
1099
+ functionName: "exactInputSingle",
1100
+ args: [
1101
+ {
1102
+ tokenIn,
1103
+ tokenOut,
1104
+ fee: feeTier,
1105
+ recipient: agent.account.address,
1106
+ deadline,
1107
+ amountIn: amountInBigInt,
1108
+ amountOutMinimum,
1109
+ sqrtPriceLimitX96: 0n
1110
+ }
1111
+ ]
1112
+ });
1113
+ const hash = await agent.client.sendTransaction({
1114
+ to: swapRouterAddress,
1115
+ data
1116
+ });
1117
+ await agent.client.waitForTransactionReceipt({ hash });
1118
+ return hash;
1119
+ }
1120
+
1121
+ // src/constants/merchantmoe/index.ts
1122
+ var merchantmoe_exports = {};
1123
+ __export(merchantmoe_exports, {
1124
+ LB_FACTORY: () => LB_FACTORY,
1125
+ LB_QUOTER: () => LB_QUOTER,
1126
+ LB_ROUTER: () => LB_ROUTER,
1127
+ LB_ROUTER_ABI: () => LB_ROUTER_ABI,
1128
+ MOE_TOKEN: () => MOE_TOKEN
1129
+ });
1130
+ var LB_ROUTER = {
1131
+ mainnet: "0x013e138EF6008ae5FDFDE29700e3f2Bc61d21E3a",
1132
+ testnet: "0x0000000000000000000000000000000000000000"
1133
+ };
1134
+ var LB_FACTORY = {
1135
+ mainnet: "0xa6630671775c4EA2743840F9A5016dCf2A104054",
1136
+ testnet: "0x0000000000000000000000000000000000000000"
1137
+ };
1138
+ var LB_QUOTER = {
1139
+ mainnet: "0x501b8AFd35df20f531fF45F6f695793AC3316c85",
1140
+ testnet: "0x0000000000000000000000000000000000000000"
1141
+ };
1142
+ var MOE_TOKEN = "0x4515a45337f461a11ff0fe8abf3c606ae5dc00c9";
1143
+ var LB_ROUTER_ABI = [
1144
+ {
1145
+ inputs: [
1146
+ { name: "amountIn", type: "uint256" },
1147
+ { name: "amountOutMin", type: "uint256" },
1148
+ { name: "path", type: "uint256[]" },
1149
+ { name: "to", type: "address" },
1150
+ { name: "deadline", type: "uint256" }
1151
+ ],
1152
+ name: "swapExactTokensForTokens",
1153
+ outputs: [{ name: "amountOut", type: "uint256" }],
1154
+ stateMutability: "nonpayable",
1155
+ type: "function"
1156
+ }
1157
+ ];
1158
+
1159
+ // src/tools/merchantmoe/swap.ts
1160
+ async function merchantMoeSwap(agent, tokenIn, tokenOut, amountIn, slippagePercent = 0.5) {
1161
+ const routerAddress = LB_ROUTER[agent.chain];
1162
+ if (routerAddress === "0x0000000000000000000000000000000000000000") {
1163
+ throw new Error(`Merchant Moe LB Router not available on ${agent.chain}`);
1164
+ }
1165
+ const amountInBigInt = BigInt(amountIn);
1166
+ const deadline = BigInt(Math.floor(Date.now() / 1e3) + 1200);
1167
+ const amountOutMin = amountInBigInt * BigInt(1e4 - Math.floor(slippagePercent * 100)) / 10000n;
1168
+ await approveToken2(agent, tokenIn, routerAddress, amountIn);
1169
+ const path = [BigInt(tokenIn), BigInt(tokenOut)];
1170
+ const data = viem.encodeFunctionData({
1171
+ abi: LB_ROUTER_ABI,
1172
+ functionName: "swapExactTokensForTokens",
1173
+ args: [amountInBigInt, amountOutMin, path, agent.account.address, deadline]
1174
+ });
1175
+ const hash = await agent.client.sendTransaction({
1176
+ to: routerAddress,
1177
+ data
1178
+ });
1179
+ await agent.client.waitForTransactionReceipt({ hash });
1180
+ return hash;
1181
+ }
1182
+
1183
+ // src/constants/meth/index.ts
1184
+ var meth_exports = {};
1185
+ __export(meth_exports, {
1186
+ METH_TOKEN: () => METH_TOKEN
1187
+ });
1188
+ var METH_TOKEN = {
1189
+ mainnet: "0xcDA86A272531e8640cD7F1a92c01839911B90bb0",
1190
+ testnet: "0x0000000000000000000000000000000000000000"
1191
+ };
1192
+
1193
+ // src/tools/okx/getSwapQuote.ts
1194
+ var getSwapQuote = async (agent, from, to, amount, slippagePercentage) => {
1195
+ const chainIndex = agent.chain === "mainnet" ? "5000" : "5003";
1196
+ return getSwapTransaction(from, to, amount, chainIndex, slippagePercentage);
1197
+ };
1198
+
1199
+ // src/utils/x402/index.ts
1200
+ var DEFAULT_PLATFORM_URL = "https://mantle-x402.vercel.app";
1201
+ var cachedConfig = null;
1202
+ var validationPromise = null;
1203
+ function getPlatformBaseUrl() {
1204
+ if (typeof process !== "undefined" && process.env) {
1205
+ return process.env.PLATFORM_URL || process.env.NEXT_PUBLIC_PLATFORM_URL || DEFAULT_PLATFORM_URL;
1206
+ }
1207
+ return DEFAULT_PLATFORM_URL;
1208
+ }
1209
+ async function validateAppId(appId) {
1210
+ const baseUrl2 = getPlatformBaseUrl();
1211
+ const url = `${baseUrl2}/api/v1/validate?appId=${encodeURIComponent(appId)}`;
1212
+ const response = await fetch(url, {
1213
+ method: "GET",
1214
+ headers: { "Content-Type": "application/json" }
1215
+ });
1216
+ if (!response.ok) {
1217
+ if (response.status === 404) {
1218
+ throw new Error(
1219
+ "Platform: Project not found. Invalid APP_ID. Please check your APP_ID configuration."
1220
+ );
1221
+ }
1222
+ if (response.status === 401) {
1223
+ throw new Error(
1224
+ "Platform: Unauthorized. Invalid APP_ID. Please verify your APP_ID."
1225
+ );
1226
+ }
1227
+ throw new Error(
1228
+ `Platform: Validation failed: ${response.status} ${response.statusText}`
1229
+ );
1230
+ }
1231
+ const data = await response.json();
1232
+ if (!data.appId || !data.payTo || !data.network) {
1233
+ throw new Error("Platform: Invalid response - missing required fields");
1234
+ }
1235
+ if (data.status !== "ACTIVE") {
1236
+ throw new Error(
1237
+ `Platform: Project is not active. Current status: ${data.status}`
1238
+ );
1239
+ }
1240
+ return {
1241
+ appId: data.appId,
1242
+ name: data.name,
1243
+ payTo: data.payTo,
1244
+ network: data.network,
1245
+ status: data.status
1246
+ };
1247
+ }
1248
+ async function initializePlatform() {
1249
+ if (cachedConfig) {
1250
+ return cachedConfig;
1251
+ }
1252
+ if (validationPromise) {
1253
+ return validationPromise;
1254
+ }
1255
+ let appId;
1256
+ if (typeof process !== "undefined" && process.env) {
1257
+ appId = process.env.APP_ID || process.env.NEXT_PUBLIC_APP_ID;
1258
+ }
1259
+ if (!appId || typeof appId !== "string" || appId.trim().length === 0) {
1260
+ throw new Error(
1261
+ "APP_ID is required. Set it in your .env file:\nAPP_ID=your_app_id_here"
1262
+ );
1263
+ }
1264
+ validationPromise = validateAppId(appId.trim());
1265
+ try {
1266
+ cachedConfig = await validationPromise;
1267
+ return cachedConfig;
1268
+ } catch (error) {
1269
+ validationPromise = null;
1270
+ throw error;
1271
+ }
1272
+ }
1273
+ function getProjectConfig() {
1274
+ if (!cachedConfig) {
1275
+ throw new Error(
1276
+ "Platform not initialized. Call initializePlatform() first."
1277
+ );
1278
+ }
1279
+ return cachedConfig;
1280
+ }
1281
+
1282
+ // src/agent.ts
1283
+ var MNTAgentKit = class {
1284
+ account;
1285
+ client;
1286
+ chain;
1287
+ projectConfig;
1288
+ constructor(privateKey, chain) {
1289
+ this.account = accounts.privateKeyToAccount(privateKey);
1290
+ this.chain = chain;
1291
+ this.client = viem.createWalletClient({
1292
+ chain: chain == "mainnet" ? chains.mantle : chains.mantleSepoliaTestnet,
1293
+ transport: viem.http(),
1294
+ account: this.account
1295
+ }).extend(viem.publicActions);
1296
+ }
1297
+ /**
1298
+ * Initialize the agent with platform validation
1299
+ *
1300
+ * Validates APP_ID with the platform API.
1301
+ * Must be called after creating the agent instance.
1302
+ *
1303
+ * @returns The initialized agent instance
1304
+ * @throws Error if APP_ID is not set or validation fails
1305
+ *
1306
+ * @example
1307
+ * ```typescript
1308
+ * const agent = new MNTAgentKit(privateKey, "mainnet");
1309
+ * await agent.initialize(); // Validates APP_ID
1310
+ * ```
1311
+ */
1312
+ async initialize() {
1313
+ this.projectConfig = await initializePlatform();
1314
+ return this;
1315
+ }
1316
+ async sendTransaction(to, amount) {
1317
+ return await sendTransaction(this, to, amount);
1318
+ }
1319
+ // OKX DEX Aggregator
1320
+ async getSwapQuote(fromTokenAddress, toTokenAddress, amount, slippagePercentage = "0.5") {
1321
+ return await getSwapQuote(
1322
+ this,
1323
+ fromTokenAddress,
1324
+ toTokenAddress,
1325
+ amount,
1326
+ slippagePercentage
1327
+ );
1328
+ }
1329
+ async executeSwap(fromTokenAddress, toTokenAddress, amount, slippagePercentage = "0.5") {
1330
+ if (this.chain === "mainnet") {
1331
+ return await executeSwap(
1332
+ this,
1333
+ fromTokenAddress,
1334
+ toTokenAddress,
1335
+ amount,
1336
+ slippagePercentage
1337
+ );
1338
+ }
1339
+ }
1340
+ // OpenOcean DEX Aggregator
1341
+ async getOpenOceanQuote(fromToken, toToken, amount) {
1342
+ return await getOpenOceanQuote(this, fromToken, toToken, amount);
1343
+ }
1344
+ async swapOnOpenOcean(fromToken, toToken, amount, slippage = 0.5) {
1345
+ return await swapOnOpenOcean(
1346
+ this,
1347
+ fromToken,
1348
+ toToken,
1349
+ amount,
1350
+ slippage.toString()
1351
+ );
1352
+ }
1353
+ // 1inch DEX Aggregator
1354
+ async get1inchQuote(fromToken, toToken, amount) {
1355
+ return await get1inchQuote(this, fromToken, toToken, amount);
1356
+ }
1357
+ async swapOn1inch(fromToken, toToken, amount, slippage = 0.5) {
1358
+ return await swapOn1inch(
1359
+ this,
1360
+ fromToken,
1361
+ toToken,
1362
+ amount,
1363
+ slippage.toString()
1364
+ );
1365
+ }
1366
+ // Uniswap V3 DEX
1367
+ async getUniswapQuote(fromToken, toToken, amount) {
1368
+ return await getUniswapQuote(this, fromToken, toToken, amount);
1369
+ }
1370
+ async swapOnUniswap(fromToken, toToken, amount, slippage = 0.5) {
1371
+ return await swapOnUniswap(
1372
+ this,
1373
+ fromToken,
1374
+ toToken,
1375
+ amount,
1376
+ slippage.toString()
1377
+ );
1378
+ }
1379
+ // Lendle Lending Protocol
1380
+ async lendleSupply(tokenAddress, amount) {
1381
+ return await lendleSupply(this, tokenAddress, amount);
1382
+ }
1383
+ async lendleWithdraw(tokenAddress, amount, to) {
1384
+ return await lendleWithdraw(this, tokenAddress, amount, to);
1385
+ }
1386
+ async lendleBorrow(tokenAddress, amount, interestRateMode = 2, onBehalfOf) {
1387
+ return await lendleBorrow(
1388
+ this,
1389
+ tokenAddress,
1390
+ amount,
1391
+ interestRateMode,
1392
+ onBehalfOf
1393
+ );
1394
+ }
1395
+ async lendleRepay(tokenAddress, amount, rateMode = 2, onBehalfOf) {
1396
+ return await lendleRepay(this, tokenAddress, amount, rateMode, onBehalfOf);
1397
+ }
1398
+ // Agni Finance DEX (#1 on Mantle)
1399
+ async agniSwap(tokenIn, tokenOut, amountIn, slippagePercent = 0.5, feeTier) {
1400
+ return await agniSwap(
1401
+ this,
1402
+ tokenIn,
1403
+ tokenOut,
1404
+ amountIn,
1405
+ slippagePercent,
1406
+ feeTier
1407
+ );
1408
+ }
1409
+ // Merchant Moe DEX (#2 on Mantle)
1410
+ async merchantMoeSwap(tokenIn, tokenOut, amountIn, slippagePercent = 0.5) {
1411
+ return await merchantMoeSwap(
1412
+ this,
1413
+ tokenIn,
1414
+ tokenOut,
1415
+ amountIn,
1416
+ slippagePercent
1417
+ );
1418
+ }
1419
+ // mETH Protocol - Liquid Staking Token
1420
+ getMethTokenAddress() {
1421
+ return METH_TOKEN[this.chain];
1422
+ }
1423
+ // Squid Router Cross-chain
1424
+ async getSquidRoute(fromToken, toToken, fromChain, toChain, amount, slippage = 1) {
1425
+ return await getSquidRoute(
1426
+ this,
1427
+ fromToken,
1428
+ toToken,
1429
+ fromChain,
1430
+ toChain,
1431
+ amount,
1432
+ slippage
1433
+ );
1434
+ }
1435
+ async crossChainSwapViaSquid(fromToken, toToken, fromChain, toChain, amount, slippage = 1) {
1436
+ return await crossChainSwapViaSquid(
1437
+ this,
1438
+ fromToken,
1439
+ toToken,
1440
+ fromChain,
1441
+ toChain,
1442
+ amount,
1443
+ slippage
1444
+ );
1445
+ }
1446
+ };
1447
+
1448
+ exports.AgniConstants = agni_exports;
1449
+ exports.LendleConstants = lendle_exports;
1450
+ exports.METH_TOKEN = METH_TOKEN;
1451
+ exports.MNTAgentKit = MNTAgentKit;
1452
+ exports.MerchantMoeConstants = merchantmoe_exports;
1453
+ exports.MethConstants = meth_exports;
1454
+ exports.OKXConstants = okx_exports;
1455
+ exports.OneInchConstants = oneinch_exports;
1456
+ exports.OpenOceanConstants = openocean_exports;
1457
+ exports.SquidConstants = squid_exports;
1458
+ exports.UniswapConstants = uniswap_exports;
1459
+ exports.agniSwap = agniSwap;
1460
+ exports.approveToken = approveToken;
1461
+ exports.crossChainSwapViaSquid = crossChainSwapViaSquid;
1462
+ exports.executeSwap = executeSwap;
1463
+ exports.get1inchQuote = get1inchQuote;
1464
+ exports.getOpenOceanQuote = getOpenOceanQuote;
1465
+ exports.getProjectConfig = getProjectConfig;
1466
+ exports.getSquidRoute = getSquidRoute;
1467
+ exports.getUniswapQuote = getUniswapQuote;
1468
+ exports.initializePlatform = initializePlatform;
1469
+ exports.lendleBorrow = lendleBorrow;
1470
+ exports.lendleRepay = lendleRepay;
1471
+ exports.lendleSupply = lendleSupply;
1472
+ exports.lendleWithdraw = lendleWithdraw;
1473
+ exports.merchantMoeSwap = merchantMoeSwap;
1474
+ exports.sendTransaction = sendTransaction;
1475
+ exports.swapOn1inch = swapOn1inch;
1476
+ exports.swapOnOpenOcean = swapOnOpenOcean;
1477
+ exports.swapOnUniswap = swapOnUniswap;
1478
+ //# sourceMappingURL=index.cjs.map
1479
+ //# sourceMappingURL=index.cjs.map