-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
799 lines (711 loc) · 23.7 KB
/
Copy pathindex.js
File metadata and controls
799 lines (711 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/**
* DeDust plugin -- DEX on TON
*
* Browse pools, search assets, view trades, get prices, estimate swaps,
* and execute on-chain swaps on the DeDust protocol through SDK v2.
*/
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const API_BASE = "https://api.dedust.io";
// ---------------------------------------------------------------------------
// Shared API helper
// ---------------------------------------------------------------------------
async function dedustFetch(path, opts = {}) {
const url =
typeof path === "string" && path.startsWith("http")
? path
: new URL(path, API_BASE);
const res = await fetch(url, {
...opts,
signal: AbortSignal.timeout(15000),
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(
`DeDust API error: ${res.status} ${text.slice(0, 200)}`
);
}
return res.json();
}
// ---------------------------------------------------------------------------
// Asset cache (5-minute TTL via sdk.storage)
// ---------------------------------------------------------------------------
let _sdk = null;
async function getAssets() {
const cached = _sdk?.storage?.get("dedust_assets");
if (cached) return cached;
// Direct URL avoids 301 redirect from api.dedust.io/v2/assets
const res = await fetch("https://assets.dedust.io/list.json", {
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new Error(`DeDust API error: ${res.status}`);
const data = await res.json();
_sdk?.storage?.set("dedust_assets", data, { ttl: 5 * 60 * 1000 });
return data;
}
function findAssetDecimals(assets, type, address) {
if (type === "native") {
const a = assets.find((a) => a.type === "native");
return a?.decimals ?? 9;
}
if (!address) return 9;
const a = assets.find(
(a) => a.type === "jetton" && a.address === address
);
return a?.decimals ?? 9;
}
function formatAmount(raw, decimals) {
if (!raw) return "0";
const s = String(raw);
if (decimals === 0) return s;
const padded = s.padStart(decimals + 1, "0");
const intPart = padded.slice(0, padded.length - decimals);
const fracPart = padded.slice(padded.length - decimals).replace(/0+$/, "");
return fracPart ? `${intPart}.${fracPart}` : intPart;
}
// ---------------------------------------------------------------------------
// Tool 1: dedust_assets
// ---------------------------------------------------------------------------
const dedustAssets = {
name: "dedust_assets",
description:
"Search or list tokens available on DeDust by symbol name or address. Returns token metadata including address, name, symbol, decimals, image, and type.",
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
search: {
type: "string",
description:
'Token symbol (e.g. "USDT", "TON") or address (e.g. "EQCxE6...")',
},
},
required: ["search"],
},
execute: async (params) => {
try {
const search = (params.search ?? "").trim();
if (!search) throw new Error("search parameter is required");
const assets = await getAssets();
const isAddress =
search.includes(":") ||
search.startsWith("EQ") ||
search.startsWith("UQ") ||
search.length > 30;
let results;
if (isAddress) {
results = assets.filter(
(a) => a.address && a.address.toLowerCase() === search.toLowerCase()
);
} else {
const q = search.toLowerCase();
results = assets.filter(
(a) =>
(a.symbol && a.symbol.toLowerCase().includes(q)) ||
(a.name && a.name.toLowerCase().includes(q))
);
}
if (results.length === 0) {
return { success: false, error: "No assets found for: " + search };
}
const data = results.slice(0, 20).map((a) => ({
type: a.type,
address: a.address ?? null,
name: a.name,
symbol: a.symbol,
decimals: a.decimals,
image: a.image ?? null,
}));
return { success: true, data };
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 2: dedust_pools
// ---------------------------------------------------------------------------
const dedustPools = {
name: "dedust_pools",
description:
"List top DeDust liquidity pools sorted by reserves, volume, or fees. Optionally filter by token symbol or address.",
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
search: {
type: "string",
description:
"Filter pools by token symbol or address (optional)",
},
limit: {
type: "integer",
description: "Number of results (1-50, default 10)",
minimum: 1,
maximum: 50,
},
sort_by: {
type: "string",
enum: ["reserves", "volume", "fees"],
description: 'Sort by metric (default: "reserves")',
},
},
},
execute: async (params) => {
try {
const limit = params.limit ?? 10;
const sortBy = params.sort_by ?? "reserves";
const search = (params.search ?? "").trim().toLowerCase();
// Fetch assets for symbol resolution and decimals
const assets = await getAssets();
const assetMap = new Map();
for (const a of assets) {
if (a.type === "native") {
assetMap.set("native", a);
} else if (a.address) {
assetMap.set(a.address, a);
}
}
// Fetch pools-lite (much smaller than /v2/pools)
const pools = await dedustFetch("/v2/pools-lite");
// Parse asset strings from pools-lite format: "native" or "jetton:EQ..."
function parsePoolAsset(assetStr) {
if (assetStr === "native") return { type: "native", address: null };
if (typeof assetStr === "string" && assetStr.startsWith("jetton:")) {
return { type: "jetton", address: assetStr.slice(7) };
}
return { type: "unknown", address: null };
}
// Filter
let filtered = pools;
if (search) {
filtered = pools.filter((p) => {
if (!Array.isArray(p.assets)) return false;
return p.assets.some((assetStr) => {
const parsed = parsePoolAsset(assetStr);
if (parsed.address && parsed.address.toLowerCase().includes(search)) return true;
const meta = parsed.type === "native"
? assetMap.get("native")
: assetMap.get(parsed.address);
if (meta) {
return (
(meta.symbol && meta.symbol.toLowerCase().includes(search)) ||
(meta.name && meta.name.toLowerCase().includes(search))
);
}
return false;
});
});
}
// Sort
const sortFn = (a, b) => {
const getVal = (pool) => {
if (sortBy === "reserves") {
return (BigInt(pool.reserves?.[0] ?? "0") + BigInt(pool.reserves?.[1] ?? "0"));
}
if (sortBy === "volume") {
return (BigInt(pool.volume?.[0] ?? "0") + BigInt(pool.volume?.[1] ?? "0"));
}
if (sortBy === "fees") {
return (BigInt(pool.fees?.[0] ?? "0") + BigInt(pool.fees?.[1] ?? "0"));
}
return 0n;
};
const va = getVal(a);
const vb = getVal(b);
if (vb > va) return 1;
if (vb < va) return -1;
return 0;
};
filtered.sort(sortFn);
const result = filtered.slice(0, limit).map((p) => {
const assetsParsed = (p.assets ?? []).map(parsePoolAsset);
const symbols = assetsParsed.map((a) => {
if (a.type === "native") return "TON";
const meta = assetMap.get(a.address);
return meta?.symbol ?? a.address?.slice(0, 10) ?? "?";
});
const decimals = assetsParsed.map((a) => {
if (a.type === "native") return 9;
const meta = assetMap.get(a.address);
return meta?.decimals ?? 9;
});
return {
address: p.address,
type: p.type,
pair: symbols.join("/"),
reserves: [
formatAmount(p.reserves?.[0], decimals[0]),
formatAmount(p.reserves?.[1], decimals[1]),
],
volume_24h: [
formatAmount(p.volume?.[0], decimals[0]),
formatAmount(p.volume?.[1], decimals[1]),
],
fees_24h: [
formatAmount(p.fees?.[0], decimals[0]),
formatAmount(p.fees?.[1], decimals[1]),
],
tradeFee: p.tradeFee,
};
});
return { success: true, data: { pools: result, count: result.length } };
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 3: dedust_pool_trades
// ---------------------------------------------------------------------------
const dedustPoolTrades = {
name: "dedust_pool_trades",
description:
"Get recent trades for a specific DeDust pool by its address.",
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
pool_address: {
type: "string",
description: "Pool contract address",
},
limit: {
type: "integer",
description: "Number of trades to return (1-100, default 20)",
minimum: 1,
maximum: 100,
},
},
required: ["pool_address"],
},
execute: async (params) => {
try {
const addr = params.pool_address;
const limit = params.limit ?? 20;
const trades = await dedustFetch(
`/v2/pools/${encodeURIComponent(addr)}/trades?page_size=${limit}`
);
if (!Array.isArray(trades) || trades.length === 0) {
return { success: true, data: { trades: [], count: 0 } };
}
// Get assets for decimals
const assets = await getAssets();
const result = trades.map((t) => {
const inType = t.assetIn?.type ?? "unknown";
const outType = t.assetOut?.type ?? "unknown";
const inAddr = t.assetIn?.address ?? null;
const outAddr = t.assetOut?.address ?? null;
const inDecimals = findAssetDecimals(assets, inType, inAddr);
const outDecimals = findAssetDecimals(assets, outType, outAddr);
return {
sender: t.sender,
asset_in: inType === "native" ? "TON" : inAddr,
asset_out: outType === "native" ? "TON" : outAddr,
amount_in: formatAmount(t.amountIn, inDecimals),
amount_out: formatAmount(t.amountOut, outDecimals),
time: t.createdAt,
lt: t.lt,
};
});
return { success: true, data: { trades: result, count: result.length } };
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 4: dedust_pool_info
// ---------------------------------------------------------------------------
const dedustPoolInfo = {
name: "dedust_pool_info",
description:
"Get detailed info for a specific DeDust pool including metadata, reserves, volume, fees, and trade fee.",
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
pool_address: {
type: "string",
description: "Pool contract address",
},
},
required: ["pool_address"],
},
execute: async (params) => {
try {
const addr = params.pool_address;
// Fetch metadata and full pool data in parallel
const [metadata, allPools] = await Promise.all([
dedustFetch(`/v2/pools/${encodeURIComponent(addr)}/metadata`),
dedustFetch("/v2/pools-lite"),
]);
const pool = allPools.find((p) => p.address === addr);
if (!pool) {
return { success: false, error: "Pool not found: " + addr };
}
const assets = await getAssets();
// Parse assets from pools-lite format
function parsePoolAsset(assetStr) {
if (assetStr === "native") return { type: "native", address: null };
if (typeof assetStr === "string" && assetStr.startsWith("jetton:")) {
return { type: "jetton", address: assetStr.slice(7) };
}
return { type: "unknown", address: null };
}
const assetsParsed = (pool.assets ?? []).map(parsePoolAsset);
const symbols = assetsParsed.map((a) => {
if (a.type === "native") return "TON";
const meta = assets.find((x) => x.address === a.address);
return meta?.symbol ?? a.address?.slice(0, 10) ?? "?";
});
const decimals = assetsParsed.map((a) => {
if (a.type === "native") return 9;
const meta = assets.find((x) => x.address === a.address);
return meta?.decimals ?? 9;
});
return {
success: true,
data: {
address: pool.address,
name: metadata?.name ?? null,
type: pool.type,
tradeFee: pool.tradeFee,
pair: symbols.join("/"),
assets: assetsParsed.map((a, i) => ({
type: a.type,
address: a.address,
symbol: symbols[i],
decimals: decimals[i],
})),
reserves: [
formatAmount(pool.reserves?.[0], decimals[0]),
formatAmount(pool.reserves?.[1], decimals[1]),
],
volume_24h: [
formatAmount(pool.volume?.[0], decimals[0]),
formatAmount(pool.volume?.[1], decimals[1]),
],
fees_24h: [
formatAmount(pool.fees?.[0], decimals[0]),
formatAmount(pool.fees?.[1], decimals[1]),
],
totalSupply: pool.totalSupply,
},
};
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 5: dedust_jetton_info
// ---------------------------------------------------------------------------
const dedustJettonInfo = {
name: "dedust_jetton_info",
description:
"Get jetton (token) metadata, top holders, and top traders from DeDust.",
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
address: {
type: "string",
description: "Jetton minter address (e.g. EQCxE6...)",
},
},
required: ["address"],
},
execute: async (params) => {
try {
const addr = params.address;
// Fetch all three in parallel
const [metadata, holders, topTraders] = await Promise.all([
dedustFetch(`/v2/jettons/${encodeURIComponent(addr)}/metadata`),
dedustFetch(`/v2/jettons/${encodeURIComponent(addr)}/holders`),
dedustFetch(`/v2/jettons/${encodeURIComponent(addr)}/top-traders`),
]);
const decimals = metadata?.decimals ?? 9;
const topHolders = (Array.isArray(holders) ? holders : [])
.slice(0, 10)
.map((h) => ({
owner: h.owner,
balance: formatAmount(h.balance, decimals),
}));
const traders = (Array.isArray(topTraders) ? topTraders : [])
.slice(0, 10)
.map((t) => ({
wallet: t.walletAddress,
volume: formatAmount(t.volume, decimals),
swaps: t.swaps,
}));
return {
success: true,
data: {
address: addr,
name: metadata?.name ?? null,
symbol: metadata?.symbol ?? null,
decimals,
image: metadata?.image ?? null,
description: metadata?.description ?? null,
top_holders: topHolders,
top_traders: traders,
},
};
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 6: dedust_prices
// ---------------------------------------------------------------------------
const dedustPrices = {
name: "dedust_prices",
description:
'Get prices and liquidity data for tokens from DeDust CoinGecko tickers. Use token addresses or "native" for TON.',
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
tokens: {
type: "array",
items: { type: "string" },
description:
'Token addresses to look up. Use "native" for TON. (e.g. ["native", "EQCxE6..."])',
},
},
required: ["tokens"],
},
execute: async (params) => {
try {
if (!Array.isArray(params.tokens) || params.tokens.length === 0) {
throw new Error("tokens must be a non-empty array");
}
const TON_ZERO_ADDR = "EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c";
// Normalize addresses: "native" -> TON zero address
const lookupAddrs = params.tokens.map((t) =>
t === "native" ? TON_ZERO_ADDR : t
);
const tickers = await dedustFetch("/v2/gcko/tickers");
if (!Array.isArray(tickers)) {
return { success: true, data: [] };
}
// Find tickers where base or target matches any requested token
const results = [];
const seen = new Set();
for (const addr of lookupAddrs) {
const addrLower = addr.toLowerCase();
const matching = tickers.filter((t) => {
const base = (t.base_currency ?? "").toLowerCase();
const target = (t.target_currency ?? "").toLowerCase();
return base === addrLower || target === addrLower;
});
// Take top tickers by liquidity for this token
matching.sort(
(a, b) =>
parseFloat(b.liquidity_in_usd ?? "0") -
parseFloat(a.liquidity_in_usd ?? "0")
);
for (const t of matching.slice(0, 3)) {
const key = t.ticker_id;
if (seen.has(key)) continue;
seen.add(key);
results.push({
ticker_id: t.ticker_id,
base: t.base_currency === TON_ZERO_ADDR ? "TON (native)" : t.base_currency,
target: t.target_currency === TON_ZERO_ADDR ? "TON (native)" : t.target_currency,
last_price: t.last_price,
base_volume: t.base_volume,
target_volume: t.target_volume,
liquidity_usd: t.liquidity_in_usd,
pool_id: t.pool_id,
});
}
}
return { success: true, data: results };
} catch (err) {
return {
success: false,
error: String(err.message || err).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 7: dedust_swap_estimate
// ---------------------------------------------------------------------------
const dedustSwapEstimate = {
name: "dedust_swap_estimate",
description:
'Estimate a DeDust swap through the Teleton SDK transaction broker. Use "native" for TON or a jetton address.',
category: "data-bearing",
scope: "always",
parameters: {
type: "object",
properties: {
input_token: {
type: "string",
description: 'Input token address or "native" for TON',
},
output_token: {
type: "string",
description: 'Output token address or "native" for TON',
},
input_amount: {
type: "string",
description:
'Amount to swap in human-readable units (e.g. "10" for 10 TON)',
},
},
required: ["input_token", "output_token", "input_amount"],
},
execute: async (params) => {
try {
const amount = Number(params.input_amount);
if (!Number.isFinite(amount) || amount <= 0) {
throw new Error("input_amount must be a positive number");
}
const quote = await _sdk.ton.dex.quoteDeDust({
fromAsset: params.input_token === "native" ? "ton" : params.input_token,
toAsset: params.output_token === "native" ? "ton" : params.output_token,
amount,
slippage: 0.05,
});
if (!quote) throw new Error("No ready DeDust pool for this pair");
return {
success: true,
data: {
input_token: params.input_token,
output_token: params.output_token,
input_amount: params.input_amount,
estimated_output: quote.expectedOutput,
min_output: quote.minOutput,
trade_fee: quote.fee,
rate: quote.rate,
price_impact: quote.priceImpact ?? null,
pool_type: quote.poolType ?? null,
},
};
} catch (error) {
_sdk.log.error(`Swap estimate failed: ${String(error?.message ?? error)}`);
return {
success: false,
error: String(error?.message ?? error).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Tool 8: dedust_swap
// ---------------------------------------------------------------------------
const dedustSwap = {
name: "dedust_swap",
description:
'Execute a DeDust swap through the Teleton SDK transaction broker. Use "native" for TON and call dedust_swap_estimate first.',
category: "action",
scope: "admin-only",
parameters: {
type: "object",
properties: {
input_token: {
type: "string",
description: 'Input token address or "native" for TON',
},
output_token: {
type: "string",
description: 'Output token address or "native" for TON',
},
input_amount: {
type: "string",
description:
'Amount to swap in human-readable units (e.g. "10" for 10 TON)',
},
slippage: {
type: "number",
description:
"Slippage tolerance (0.05 = 5%, default 0.05, range 0.001-0.5)",
minimum: 0.001,
maximum: 0.5,
},
},
required: ["input_token", "output_token", "input_amount"],
},
execute: async (params) => {
try {
const amount = Number(params.input_amount);
if (!Number.isFinite(amount) || amount <= 0) {
throw new Error("input_amount must be a positive number");
}
const result = await _sdk.ton.dex.swapDeDust({
fromAsset: params.input_token === "native" ? "ton" : params.input_token,
toAsset: params.output_token === "native" ? "ton" : params.output_token,
amount,
slippage: params.slippage ?? 0.05,
});
return {
success: true,
data: {
input_token: params.input_token,
output_token: params.output_token,
input_amount: result.amountIn,
estimated_output: result.expectedOutput,
min_output: result.minOutput,
slippage: result.slippage,
tx_ref: result.txRef ?? null,
message: "Swap transaction confirmed by the Teleton transaction broker.",
},
};
} catch (error) {
_sdk.log.error(`Swap failed: ${String(error?.message ?? error)}`);
return {
success: false,
error: String(error?.message ?? error).slice(0, 500),
};
}
},
};
// ---------------------------------------------------------------------------
// Export
// ---------------------------------------------------------------------------
export const manifest = {
name: "dedust",
version: "1.0.0",
sdkVersion: "^2.0.0",
description: "DeDust DEX on TON — browse pools, search assets, view trades, get prices, and execute on-chain swaps.",
};
export const tools = (sdk) => {
_sdk = sdk;
return [
dedustAssets,
dedustPools,
dedustPoolTrades,
dedustPoolInfo,
dedustJettonInfo,
dedustPrices,
dedustSwapEstimate,
dedustSwap,
];
};