-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathton.gs
More file actions
355 lines (306 loc) · 11.3 KB
/
Copy pathton.gs
File metadata and controls
355 lines (306 loc) · 11.3 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
/**
* @file TON network module.
* Handles USDT balance retrieval and transaction history.
*
* TON address parsing is implemented without external libraries (previously used TonWeb ~38K lines).
* Address format: TEP-2 (https://github.com/ton-blockchain/TEPs/blob/master/text/0002-address.md)
*/
// ============================================================
// TON ADDRESS PARSER (replaces TonWeb.utils.Address)
// ============================================================
/**
* CRC16-CCITT (polynomial 0x1021, init 0).
* Used to validate the checksum of user-friendly TON addresses.
* @param {number[]} data - byte array
* @returns {number[]} - two CRC bytes [high, low]
*/
function _crc16(data) {
var POLY = 0x1021;
var reg = 0;
for (var i = 0; i < data.length + 2; i++) {
var byte = i < data.length ? data[i] : 0;
var mask = 0x80;
while (mask > 0) {
reg <<= 1;
if (byte & mask) reg += 1;
mask >>= 1;
if (reg > 0xFFFF) {
reg &= 0xFFFF;
reg ^= POLY;
}
}
}
return [Math.floor(reg / 256), reg % 256];
}
/**
* Converts a byte array to a hex string.
* @param {number[]} bytes
* @returns {string}
*/
function _bytesToHex(bytes) {
var hex = '';
for (var i = 0; i < bytes.length; i++) {
hex += ('00' + (bytes[i] & 0xFF).toString(16)).slice(-2);
}
return hex;
}
/**
* Parses a TON address (user-friendly base64 or raw "wc:hex") and returns the result.
*
* User-friendly format (48 base64url chars -> 36 bytes):
* [0] - tag (0x11 bounceable, 0x51 non-bounceable, +0x80 testnet)
* [1] - workchain (0x00 = basechain, 0xFF = masterchain/-1)
* [2..33] - 32-byte account hash
* [34..35] - CRC16-CCITT checksum
*
* @param {string} address - TON address
* @returns {{valid: boolean, hashHex: string, workchain: number, error: string}}
*/
function parseTONAddress(address) {
if (!address || typeof address !== 'string') {
return { valid: false, hashHex: '', workchain: 0, error: 'Empty address' };
}
address = address.trim();
// Raw format: "workchain:hex_hash"
if (address.indexOf(':') !== -1) {
var parts = address.split(':');
var wc = parseInt(parts[0], 10);
var hash = parts[1];
if (hash && /^[0-9a-fA-F]{64}$/.test(hash) && (wc === 0 || wc === -1)) {
return { valid: true, hashHex: hash.toLowerCase(), workchain: wc, error: '' };
}
return { valid: false, hashHex: '', workchain: 0, error: 'Invalid raw format' };
}
// User-friendly format: base64/base64url, 48 chars
if (address.length !== 48) {
return { valid: false, hashHex: '', workchain: 0, error: 'Length != 48 chars' };
}
var b64 = address.replace(/-/g, '+').replace(/_/g, '/');
var rawBytes;
try {
rawBytes = Utilities.base64Decode(b64);
} catch (e) {
return { valid: false, hashHex: '', workchain: 0, error: 'Base64 decode error: ' + e.message };
}
if (rawBytes.length !== 36) {
return { valid: false, hashHex: '', workchain: 0, error: 'Decoded ' + rawBytes.length + ' bytes, expected 36' };
}
// Convert to unsigned
var bytes = [];
for (var i = 0; i < rawBytes.length; i++) {
bytes.push(rawBytes[i] & 0xFF);
}
// Verify CRC16
var addrBytes = bytes.slice(0, 34);
var crcBytes = bytes.slice(34, 36);
var crcCalc = _crc16(addrBytes);
if (crcCalc[0] !== crcBytes[0] || crcCalc[1] !== crcBytes[1]) {
return { valid: false, hashHex: '', workchain: 0, error: 'CRC16 mismatch' };
}
// Tag
var tag = bytes[0];
if (tag & 0x80) {
tag = tag ^ 0x80;
}
if (tag !== 0x11 && tag !== 0x51) {
return { valid: false, hashHex: '', workchain: 0, error: 'Unknown tag: 0x' + tag.toString(16) };
}
// Workchain (signed byte)
var wc = bytes[1];
if (wc === 0xFF) wc = -1;
if (wc !== 0 && wc !== -1) {
return { valid: false, hashHex: '', workchain: 0, error: 'Unknown workchain: ' + wc };
}
// 32-byte hash
var hashHex = _bytesToHex(bytes.slice(2, 34));
return { valid: true, hashHex: hashHex, workchain: wc, error: '' };
}
// ============================================================
// PROJECT LOGIC
// ============================================================
/**
* Starts transaction tracking for the TON network.
* Uses the universal trackNetworkTransactions handler.
*/
function trackTONTransactions() {
const adapter = {
networkName: 'TON',
fetchTransactions: getUSDTTransactionsWithCorrectHash,
processTransaction: processTONTransaction
};
trackNetworkTransactions(adapter, []);
}
/**
* Processes a single TON transaction into a spreadsheet row format.
* @param {object} tx - Transaction object from getUSDTTransactionsWithCorrectHash.
* @param {string} address - Wallet address.
* @param {string} name - Wallet name.
* @param {Date} cutoffDate - Transactions before this date are ignored.
* @returns {Array<any>|null} Row data array or null.
*/
function processTONTransaction(tx, address, name, cutoffDate) {
const txDate = new Date(tx.timestamp * 1000);
if (txDate < cutoffDate) {
return null;
}
const value = parseFloat(tx.amount);
const income = tx.incoming ? value : null;
const outcome = !tx.incoming ? value : null;
return [txDate, income, outcome, name, 'TON', tx.hash.toLowerCase()];
}
/**
* Fetches transaction history from toncenter API and extracts USDT operations.
* @param {string} ownerAddress - Wallet address to check.
* @param {number} limit - Maximum number of transactions to request.
* @returns {Array<Object>} Array of parsed transactions.
*/
function getUSDTTransactionsWithCorrectHash(ownerAddress, limit = CONFIG.TON_CENTER_LIMIT) {
try {
Logger.log(`[INFO] Fetching events for TON address: ${ownerAddress}`);
const url = `https://toncenter.com/api/v3/events?account=${encodeURIComponent(ownerAddress)}&limit=${limit}`;
const options = {
"method": "GET",
"headers": {
"accept": "application/json",
"X-API-Key": CONFIG.TONCENTER_API_KEY
},
"muteHttpExceptions": true
};
const response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() !== 200) {
Logger.log(`[ERROR] Toncenter API error for ${ownerAddress}: ${response.getResponseCode()}`);
return [];
}
const data = JSON.parse(response.getContentText());
const events = data.events || [];
const usdtTransactions = [];
const ownerHex = convertAddressToHex(ownerAddress);
for (let event of events) {
if (!event.actions) continue;
for (let action of event.actions) {
if ((action.type === 'jetton_transfer' || action.type === 'jetton_swap') && action.details) {
const details = action.details;
let asset, amountRaw, sender, receiver;
// Handle jetton_transfer
if (action.type === 'jetton_transfer') {
asset = (details.asset || '').toLowerCase();
amountRaw = details.amount || '0';
sender = (details.sender || '').toLowerCase();
receiver = (details.receiver || '').toLowerCase();
}
// Handle jetton_swap
else if (action.type === 'jetton_swap') {
asset = (details.asset_out || '').toLowerCase();
amountRaw = details.dex_outgoing_transfer?.amount || '0';
sender = (details.sender || '').toLowerCase();
receiver = (details.dex_outgoing_transfer?.destination || '').toLowerCase();
}
const expectedUSDT = CONFIG.USDT_TON_MASTER_ADDRESS.toLowerCase();
if (asset === expectedUSDT) {
const amount = toTokenAmount(amountRaw, 6);
if (amount <= 0) continue;
// Extract hash part of addresses for comparison
const senderHash = sender.includes(':') ? sender.split(":").pop().toLowerCase() : convertAddressToHex(sender).toLowerCase();
const receiverHash = receiver.includes(':') ? receiver.split(":").pop().toLowerCase() : convertAddressToHex(receiver).toLowerCase();
const ownerHash = ownerHex.toLowerCase();
const isIncoming = receiverHash === ownerHash;
const isOutgoing = senderHash === ownerHash;
if (isIncoming || isOutgoing) {
let txHash = event.trace_id || action.trace_id || (action.transactions ? action.transactions[0] : '');
usdtTransactions.push({
timestamp: action.start_utime || event.start_utime,
hash: convertHashToHex(txHash),
amount: amount,
incoming: isIncoming,
from: sender,
to: receiver
});
}
}
}
}
}
usdtTransactions.sort((a, b) => b.timestamp - a.timestamp);
return usdtTransactions;
} catch (error) {
Logger.log(`[ERROR] Exception fetching TON transactions for address ${ownerAddress}: ${error.message}`);
return [];
}
}
/**
* Converts a TON address to its HEX representation (hash part).
* @param {string} address - Address in any format (user-friendly or raw).
* @returns {string} HEX hash part or empty string.
*/
function convertAddressToHex(address) {
if (!address) return '';
var result = parseTONAddress(address);
if (!result.valid) {
Logger.log('[WARN] Failed to convert TON address "' + address + '". Error: ' + result.error);
return '';
}
return result.hashHex;
}
/**
* Converts a hash from base64 to hex format.
* @param {string} hash - Hash in base64 or hex.
* @returns {string} Hash in hex format.
*/
function convertHashToHex(hash) {
if (!hash) return hash;
if (/^[0-9a-fA-F]+$/.test(hash)) {
return hash.toLowerCase();
}
try {
let normalBase64 = hash.replace(/-/g, '+').replace(/_/g, '/');
while (normalBase64.length % 4 !== 0) {
normalBase64 += '=';
}
const bytes = Utilities.base64Decode(normalBase64);
return bytes.map(byte => ('0' + (byte & 0xFF).toString(16)).slice(-2)).join('');
} catch (e) {
Logger.log(`[WARN] Failed to convert hash: ${hash}, error: ${e}`);
return hash.toLowerCase();
}
}
/**
* Gets the USDT balance on the TON network for the given address.
* @param {string} address - Wallet address.
* @returns {number} Balance in USDT.
*/
function getTONUSDTBalance(address) {
try {
if (!address) return 0;
const url = `https://toncenter.com/api/v3/jetton/wallets?owner_address=${encodeURIComponent(address)}&jetton_address=${encodeURIComponent(CONFIG.USDT_TON_MASTER_ADDRESS)}`;
const options = {
"method": "GET",
"headers": {
"accept": "application/json",
"X-API-Key": CONFIG.TONCENTER_API_KEY
},
"muteHttpExceptions": true
};
const response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() === 200) {
const data = JSON.parse(response.getContentText());
if (data.jetton_wallets && data.jetton_wallets.length > 0) {
const wallet = data.jetton_wallets[0];
return toTokenAmount(wallet.balance || '0', 6);
}
return 0; // API returned 200 but wallet not found — genuine zero balance
}
Logger.log(`[ERROR] Failed to get TON balance for ${address}: HTTP ${response.getResponseCode()}`);
return null;
} catch (error) {
Logger.log(`[ERROR] Failed to get TON balance for ${address}: ${error.message}`);
return null;
}
}
/**
* Validates a TON network address.
* @param {string} address Address in any format.
* @returns {boolean}
*/
function isValidTONAddress(address) {
return parseTONAddress(address).valid;
}