-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
300 lines (284 loc) · 9.93 KB
/
Copy pathindex.js
File metadata and controls
300 lines (284 loc) · 9.93 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
/** Batch TON and jetton transfers through Teleton's core Highload Wallet v3 broker. */
import { createRequire } from "node:module";
import { realpathSync } from "node:fs";
const require = createRequire(realpathSync(process.argv[1]));
const { Address, beginCell } = require("@ton/core");
const MAX_RECIPIENTS = 254;
export function migrate(db) {
db.exec(`
CREATE TABLE IF NOT EXISTS multisend_sequence (
id INTEGER PRIMARY KEY CHECK (id = 1),
last_query_id TEXT NOT NULL
)
`);
}
export const manifest = {
name: "multisend",
version: "2.0.0",
sdkVersion: "^2.1.0",
description: "Batch TON and jetton transfers through Teleton's protected Highload Wallet v3 broker.",
};
function formatError(error) {
return { success: false, error: String(error?.message || error).slice(0, 500) };
}
function validateRecipients(ton, recipients) {
if (!Array.isArray(recipients) || recipients.length === 0) {
throw new Error("recipients must be a non-empty array");
}
if (recipients.length > MAX_RECIPIENTS) {
throw new Error(`Maximum ${MAX_RECIPIENTS} recipients per batch`);
}
for (const recipient of recipients) {
if (!ton.validateAddress(recipient.address)) {
throw new Error(`Invalid recipient address: ${recipient.address}`);
}
}
}
function parsePositiveAmount(value, label) {
const amount = Number(value);
if (!Number.isFinite(amount) || amount <= 0) throw new Error(`Invalid ${label}: ${value}`);
return amount;
}
function toUnits(value, decimals) {
const input = String(value).trim();
if (!/^\d+(?:\.\d+)?$/.test(input)) throw new Error(`Invalid jetton amount: ${value}`);
const [whole, fraction = ""] = input.split(".");
if (fraction.length > decimals) {
throw new Error(`Jetton amount ${value} has more than ${decimals} decimals`);
}
return BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fraction.padEnd(decimals, "0") || "0");
}
export const tools = (sdk) => {
const multisendInfo = {
name: "multisend_info",
description: "Show the Highload multisend wallet address, balance, deployment, and query sequence.",
category: "data-bearing",
scope: "always",
parameters: { type: "object", properties: {}, required: [] },
execute: async () => {
try {
const info = await sdk.ton.highload.getInfo();
return {
success: true,
data: {
address: info.address,
address_raw: info.rawAddress,
balance: info.balance,
balance_nano: info.balanceNano,
deployed: info.deployed,
sequence: {
lastQueryId: info.currentQueryId,
savedQueryId: info.currentQueryId,
hasNext: info.hasNext,
},
},
};
} catch (error) {
return formatError(error);
}
},
};
const multisendFund = {
name: "multisend_fund",
description: "Fund the Highload multisend wallet from the agent's main wallet.",
category: "action",
scope: "admin-only",
parameters: {
type: "object",
properties: { amount: { type: "string", description: "Amount in TON" } },
required: ["amount"],
},
execute: async (params) => {
try {
const amount = parsePositiveAmount(params.amount, "amount");
const info = await sdk.ton.highload.getInfo();
const result = await sdk.ton.highload.fund(amount);
return {
success: true,
data: {
from: sdk.ton.getAddress(),
to: info.address,
amount: params.amount,
bounce: info.deployed,
...result,
},
};
} catch (error) {
return formatError(error);
}
},
};
const multisendBatchTon = {
name: "multisend_batch_ton",
description: "Send TON to up to 254 recipients in one Highload Wallet v3 batch.",
category: "action",
scope: "admin-only",
parameters: {
type: "object",
properties: {
recipients: {
type: "array",
maxItems: MAX_RECIPIENTS,
items: {
type: "object",
properties: {
address: { type: "string" },
amount: { type: "string", description: "Amount in TON" },
memo: { type: "string" },
},
required: ["address", "amount"],
},
},
},
required: ["recipients"],
},
execute: async (params) => {
try {
validateRecipients(sdk.ton, params.recipients);
let total = 0;
const messages = params.recipients.map((recipient, index) => {
const amount = parsePositiveAmount(recipient.amount, `TON amount for recipient #${index + 1}`);
total += amount;
return { to: recipient.address, value: amount, body: recipient.memo, bounce: false };
});
const info = await sdk.ton.highload.getInfo();
if (Number(info.balance) < total + 0.15) {
throw new Error(`Insufficient Highload balance: ${info.balance} TON, need ~${total + 0.15} TON`);
}
const result = await sdk.ton.highload.sendMessages(messages, { valuePerBatch: 0.05 });
sdk.log.info(`Highload TON batch sent to ${messages.length} recipients`);
return {
success: true,
data: {
recipient_count: messages.length,
total_ton: total.toString(),
multisend_address: result.address,
query_id: result.nextQueryId,
submitted_query_id: result.queryId,
},
};
} catch (error) {
return formatError(error);
}
},
};
const multisendBatchJetton = {
name: "multisend_batch_jetton",
description: "Send one jetton to up to 254 recipients in one Highload Wallet v3 batch.",
category: "action",
scope: "admin-only",
parameters: {
type: "object",
properties: {
jetton_master: { type: "string" },
recipients: {
type: "array",
maxItems: MAX_RECIPIENTS,
items: {
type: "object",
properties: {
address: { type: "string" },
amount: { type: "string", description: "Amount in human units" },
},
required: ["address", "amount"],
},
},
decimals: { type: "integer", minimum: 0, maximum: 18 },
forward_ton: { type: "string", description: "TON attached to each jetton transfer" },
},
required: ["jetton_master", "recipients"],
},
execute: async (params) => {
try {
validateRecipients(sdk.ton, params.recipients);
if (!sdk.ton.validateAddress(params.jetton_master)) {
throw new Error(`Invalid jetton master address: ${params.jetton_master}`);
}
const info = await sdk.ton.highload.getInfo();
if (!info.deployed) {
throw new Error("Highload wallet is not deployed. Fund it and send a TON batch first.");
}
const jettonWallet = await sdk.ton.getJettonWalletAddress(info.address, params.jetton_master);
if (!jettonWallet) throw new Error("Could not resolve the Highload jetton wallet");
const decimals = params.decimals ?? 9;
const forwardTon = parsePositiveAmount(params.forward_ton ?? "0.05", "forward_ton");
const gasNeeded = forwardTon * params.recipients.length + 0.1;
if (Number(info.balance) < gasNeeded) {
throw new Error(`Insufficient Highload TON for gas: ${info.balance} TON, need ~${gasNeeded} TON`);
}
const responseAddress = Address.parse(info.address);
const queryBase = BigInt(Date.now()) * 1000n;
const messages = params.recipients.map((recipient, index) => {
const body = beginCell()
.storeUint(0x0f8a7ea5, 32)
.storeUint(queryBase + BigInt(index), 64)
.storeCoins(toUnits(recipient.amount, decimals))
.storeAddress(Address.parse(recipient.address))
.storeAddress(responseAddress)
.storeBit(false)
.storeCoins(1n)
.storeBit(false)
.endCell();
return { to: jettonWallet, value: forwardTon, body, bounce: true };
});
const result = await sdk.ton.highload.sendMessages(messages, { valuePerBatch: 0.05 });
sdk.log.info(`Highload jetton batch sent to ${messages.length} recipients`);
return {
success: true,
data: {
recipient_count: messages.length,
jetton_master: params.jetton_master,
jetton_wallet: jettonWallet,
multisend_address: result.address,
decimals,
query_id: result.nextQueryId,
submitted_query_id: result.queryId,
},
};
} catch (error) {
return formatError(error);
}
},
};
const multisendStatus = {
name: "multisend_status",
description: "Check Highload wallet balance, deployment, timeout, cleanup, and subwallet state.",
category: "data-bearing",
scope: "always",
parameters: { type: "object", properties: {}, required: [] },
execute: async () => {
try {
const info = await sdk.ton.highload.getInfo();
return {
success: true,
data: {
address: info.address,
address_raw: info.rawAddress,
balance: info.balance,
balance_nano: info.balanceNano,
deployed: info.deployed,
sequence: {
current_query_id: info.currentQueryId,
has_next: info.hasNext,
},
timeout: info.timeout,
last_cleaned: info.lastCleaned,
last_cleaned_date: info.lastCleaned
? new Date(info.lastCleaned * 1000).toISOString()
: undefined,
subwallet_id: info.subwalletId,
},
};
} catch (error) {
return formatError(error);
}
},
};
return [
multisendInfo,
multisendFund,
multisendBatchTon,
multisendBatchJetton,
multisendStatus,
];
};