-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathairdrop.js
More file actions
410 lines (348 loc) · 14.4 KB
/
airdrop.js
File metadata and controls
410 lines (348 loc) · 14.4 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
require('dotenv').config();
const { Account, RpcProvider, Contract, uint256, cairo } = require('starknet');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
// Shared readline interface - will be set externally when used as module
let rl = null;
function setReadlineInterface(readlineInterface) {
rl = readlineInterface;
}
function getReadlineInterface() {
if (!rl) {
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
}
return rl;
}
function question(prompt) {
return new Promise((resolve) => {
getReadlineInterface().question(prompt, resolve);
});
}
// ERC20 ABI minimal pour transfer
const ERC20_ABI = [
{
name: 'transfer',
type: 'function',
inputs: [
{ name: 'recipient', type: 'felt' },
{ name: 'amount', type: 'Uint256' }
],
outputs: [{ name: 'success', type: 'felt' }],
stateMutability: 'external'
},
{
name: 'decimals',
type: 'function',
inputs: [],
outputs: [{ name: 'decimals', type: 'felt' }],
stateMutability: 'view'
}
];
function listHolderFiles() {
const holdersDir = path.join(__dirname, 'holders');
if (!fs.existsSync(holdersDir)) {
console.log('\nNo holders directory found!');
return [];
}
const files = fs.readdirSync(holdersDir).filter(f => f.endsWith('.json'));
if (files.length === 0) {
console.log('\nNo holder files found in holders directory!');
return [];
}
console.log('\n═══════════════════════════════════════');
console.log(' AVAILABLE HOLDER LISTS');
console.log('═══════════════════════════════════════');
files.forEach((file, index) => {
console.log(`${index + 1}. ${file}`);
});
console.log('═══════════════════════════════════════\n');
return files;
}
async function loadHolders(filename) {
const filePath = path.join(__dirname, 'holders', filename);
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
return data.items || [];
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function formatDuration(ms) {
const totalSeconds = Math.max(0, Math.round(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}m ${seconds.toString().padStart(2, '0')}s`;
}
async function airdropTokens() {
try {
// Vérifier les variables d'environnement
if (!process.env.STARKNET_ADDRESS || !process.env.STARKNET_PRIVATE_KEY) {
console.log('\n❌ Error: STARKNET_ADDRESS and STARKNET_PRIVATE_KEY must be set in .env file');
console.log('Copy .env.example to .env and fill in your wallet details.\n');
return;
}
// Liste les fichiers de holders
const files = listHolderFiles();
if (files.length === 0) return;
// Sélection du fichier
const fileChoice = await question('Select holder list (number): ');
const fileIndex = parseInt(fileChoice) - 1;
if (fileIndex < 0 || fileIndex >= files.length) {
console.log('Invalid selection.');
return;
}
const selectedFile = files[fileIndex];
console.log(`\nLoading holders from: ${selectedFile}`);
const holders = await loadHolders(selectedFile);
console.log(`Found ${holders.length} holders\n`);
// Adresse du token à envoyer
const tokenAddress = await question('Enter token address to send: ');
const normalizedTokenAddress = tokenAddress?.trim();
if (!normalizedTokenAddress || !normalizedTokenAddress.startsWith('0x')) {
console.log('Invalid token address.');
return;
}
// Quantité à envoyer par holder
const amountPerHolder = await question('Enter amount to send per holder (in token units): ');
const amount = parseFloat(amountPerHolder);
if (isNaN(amount) || amount <= 0) {
console.log('Invalid amount.');
return;
}
// Taille des batches pour le multicall
// Estimer le temps pour chaque option (7s par batch en moyenne)
const avgTimePerBatch = 7; // secondes
const estimateTime = (batchSize) => {
const batches = Math.ceil(holders.length / batchSize);
const totalSeconds = batches * avgTimePerBatch;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `~${minutes}m ${seconds}s (${batches} batches)`;
};
console.log('\nSelect batch size for multicall:');
console.log(`1. Small (25 transfers/batch) - Safer - ${estimateTime(25)}`);
console.log(`2. Medium (50 transfers/batch) - Recommended - ${estimateTime(50)}`);
console.log(`3. Large (75 transfers/batch) - Faster - ${estimateTime(75)}`);
console.log(`4. Very Large (100 transfers/batch) - Maximum speed - ${estimateTime(100)}`);
console.log('5. Custom');
const batchChoice = await question('Choice: ');
let MULTICALL_BATCH_SIZE;
switch (batchChoice.trim()) {
case '1':
MULTICALL_BATCH_SIZE = 25;
break;
case '2':
MULTICALL_BATCH_SIZE = 50;
break;
case '3':
MULTICALL_BATCH_SIZE = 75;
break;
case '4':
MULTICALL_BATCH_SIZE = 100;
break;
case '5':
const customSize = await question('Enter custom batch size: ');
MULTICALL_BATCH_SIZE = parseInt(customSize);
if (isNaN(MULTICALL_BATCH_SIZE) || MULTICALL_BATCH_SIZE <= 0) {
console.log('Invalid batch size, using default (50)');
MULTICALL_BATCH_SIZE = 50;
}
break;
default:
console.log('Invalid choice, using default (50)');
MULTICALL_BATCH_SIZE = 50;
}
// Confirmation
const totalBatches = Math.ceil(holders.length / MULTICALL_BATCH_SIZE);
console.log('\n═══════════════════════════════════════');
console.log(' AIRDROP SUMMARY');
console.log('═══════════════════════════════════════');
console.log(`Holders: ${holders.length}`);
console.log(`Token: ${normalizedTokenAddress}`);
console.log(`Amount per holder: ${amount}`);
console.log(`Total to distribute: ${amount * holders.length}`);
console.log(`Batch size: ${MULTICALL_BATCH_SIZE} transfers`);
console.log(`Total batches: ${totalBatches}`);
console.log(`From wallet: ${process.env.STARKNET_ADDRESS}`);
console.log('═══════════════════════════════════════\n');
const confirm = await question('Proceed with airdrop? (yes/no): ');
if (!confirm || confirm.trim().toLowerCase() !== 'yes') {
console.log('Airdrop cancelled.');
return;
}
// Initialiser le provider et le compte
const accountAddress = process.env.STARKNET_ADDRESS?.trim();
const privateKey = process.env.STARKNET_PRIVATE_KEY?.trim();
const rpcUrl = process.env.STARKNET_RPC_URL?.trim();
if (!rpcUrl) {
throw new Error('STARKNET_RPC_URL is not defined in .env');
}
if (!accountAddress || !privateKey) {
throw new Error('STARKNET_ADDRESS or STARKNET_PRIVATE_KEY is not defined in .env');
}
// Créer le provider avec la syntaxe v8
const provider = new RpcProvider({
nodeUrl: rpcUrl,
chainId: '0x534e5f4d41494e' // SN_MAIN
});
const account = new Account({
provider,
address: accountAddress,
signer: privateKey
});
// Initialiser le contrat token
const tokenContract = new Contract({
abi: ERC20_ABI,
address: normalizedTokenAddress,
providerOrAccount: account
});
// Récupérer les decimals du token
let decimals = 18;
try {
const decimalsResult = await tokenContract.decimals();
// Extraire la valeur si c'est un objet BigInt ou un nombre
if (typeof decimalsResult === 'bigint') {
decimals = Number(decimalsResult);
} else if (typeof decimalsResult === 'object' && decimalsResult !== null) {
// Si c'est un objet, essayer d'extraire la première propriété ou la valeur
const keys = Object.keys(decimalsResult);
if (keys.length > 0) {
decimals = Number(decimalsResult[keys[0]]);
} else {
decimals = Number(decimalsResult.toString());
}
} else {
decimals = Number(decimalsResult);
}
// Vérifier que decimals est valide
if (isNaN(decimals)) {
console.log('Could not parse decimals, using 18 as default\n');
decimals = 18;
}
} catch (error) {
console.log('Could not fetch decimals, using 18 as default\n');
console.log('Error:', error.message);
}
// Convertir le montant en wei
const amountWei = BigInt(Math.floor(amount * (10 ** decimals)));
const amountUint256 = uint256.bnToUint256(amountWei);
console.log(`\nStarting airdrop with multicall (${MULTICALL_BATCH_SIZE} transfers per batch)...\n`);
let successCount = 0;
let failCount = 0;
const failedRecipients = new Map(); // Track unique recipients from failed batches
// Diviser les holders en batches
const finalTotalBatches = Math.ceil(holders.length / MULTICALL_BATCH_SIZE);
const batchDurations = [];
for (let batchIndex = 0; batchIndex < finalTotalBatches; batchIndex++) {
const start = batchIndex * MULTICALL_BATCH_SIZE;
const end = Math.min(start + MULTICALL_BATCH_SIZE, holders.length);
const batchHolders = holders.slice(start, end);
console.log(`\n[Batch ${batchIndex + 1}/${finalTotalBatches}] Processing ${batchHolders.length} transfers (${start + 1}-${end})...`);
if (batchDurations.length > 0) {
const averageDuration = batchDurations.reduce((sum, duration) => sum + duration, 0) / batchDurations.length;
const remainingBatches = finalTotalBatches - batchIndex;
const etaMs = averageDuration * remainingBatches;
console.log(` Estimated time remaining: ~${formatDuration(etaMs)}`);
}
// Créer les calls pour le multicall
const calls = batchHolders.map(holder => ({
contractAddress: normalizedTokenAddress,
entrypoint: 'transfer',
calldata: [holder.holder, amountUint256.low, amountUint256.high]
}));
const batchStart = Date.now();
try {
// Exécuter le multicall
const tx = await account.execute(calls);
console.log(` ✓ Multicall transaction hash: ${tx.transaction_hash}`);
console.log(` Waiting for confirmation...`);
// Attendre la confirmation pour ce batch
await provider.waitForTransaction(tx.transaction_hash);
console.log(` ✓ Batch confirmed! ${batchHolders.length} transfers successful`);
successCount += batchHolders.length;
} catch (error) {
console.log(` ✗ Batch failed: ${error.message}`);
let newFailures = 0;
batchHolders.forEach((holder, indexInBatch) => {
if (holder?.holder && !failedRecipients.has(holder.holder)) {
failedRecipients.set(holder.holder, {
address: holder.holder,
amountTokens: amount,
amountWei: amountWei.toString(),
batch: batchIndex + 1,
position: start + indexInBatch + 1
});
newFailures++;
}
});
failCount += newFailures;
if (newFailures > 0) {
console.log(` Logged ${newFailures} recipients for retry (${failCount} total recorded).`);
} else {
console.log(' No new recipients added to retry list (possible duplicates).');
}
// En cas d'échec du batch, on peut optionnellement continuer avec les suivants
console.log(` Continuing with next batch...`);
}
const batchDuration = Date.now() - batchStart;
batchDurations.push(batchDuration);
const remainingBatchesAfterCurrent = finalTotalBatches - (batchIndex + 1);
if (remainingBatchesAfterCurrent > 0) {
const averageDuration = batchDurations.reduce((sum, duration) => sum + duration, 0) / batchDurations.length;
const etaMs = averageDuration * remainingBatchesAfterCurrent;
console.log(` Updated ETA: ~${formatDuration(etaMs)} remaining`);
}
}
let failedReportPath = null;
if (failedRecipients.size > 0) {
const failuresDir = path.join(__dirname, 'airdrop-failures');
if (!fs.existsSync(failuresDir)) {
fs.mkdirSync(failuresDir, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `${normalizedTokenAddress.slice(0, 10)}_${timestamp}.json`;
failedReportPath = path.join(failuresDir, filename);
const failurePayload = {
generatedAt: new Date().toISOString(),
tokenAddress: normalizedTokenAddress,
sourceHoldersFile: selectedFile,
decimals,
amountPerHolderTokens: amount,
amountPerHolderWei: amountWei.toString(),
failedCount: failedRecipients.size,
recipients: Array.from(failedRecipients.values())
};
fs.writeFileSync(failedReportPath, JSON.stringify(failurePayload, null, 2));
}
console.log('\n═══════════════════════════════════════');
console.log(' AIRDROP COMPLETE');
console.log('═══════════════════════════════════════');
console.log(`Successful: ${successCount}`);
console.log(`Failed (recorded): ${failCount}`);
if (failedReportPath) {
const relativePath = path.relative(process.cwd(), failedReportPath);
console.log(`Failed recipients saved to: ${relativePath}`);
} else {
console.log('No failed recipients to retry.');
}
console.log('═══════════════════════════════════════\n');
} catch (error) {
console.error('\n❌ Airdrop error:', error.message);
}
}
// Export pour utilisation dans index.js
module.exports = { airdropTokens, setReadlineInterface };
// Permettre l'exécution standalone
if (require.main === module) {
airdropTokens().then(() => {
if (rl) rl.close();
process.exit(0);
}).catch(error => {
console.error(error);
if (rl) rl.close();
process.exit(1);
});
}