-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecuteTransfer.js
More file actions
483 lines (414 loc) · 14.9 KB
/
executeTransfer.js
File metadata and controls
483 lines (414 loc) · 14.9 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
const { ethers } = require("ethers");
const fs = require("fs");
require("dotenv").config();
/**
* Execute Approve and TransferFrom Script
*
* This script:
* 1. Reads configuration from JSON file (with private keys)
* 2. Logs balances and allowance before transactions
* 3. Executes approve transaction (from wallet approves spender)
* 4. Executes transferFrom transaction (spender sends from -> to)
*
* Usage:
* cd hedera-transfer-from/
* npm install
* node executeTransfer.js --config ./transfer-config.json
*
* Config file format:
* {
* "token": "0x...",
* "from": { "address": "0x...", "privateKey": "0x..." },
* "spender": { "address": "0x...", "privateKey": "0x..." },
* "to": "0x...",
* "amount": "1000000",
* "rpcUrl": "https://testnet.hashio.io/api",
* "chainId": 296
* }
*/
// ERC20 ABI for the functions we need
const ERC20_ABI = [
// ERC20 basics
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
"function balanceOf(address) view returns (uint256)",
"function allowance(address owner, address spender) view returns (uint256)",
"function totalSupply() view returns (uint256)",
// ERC20 write functions
"function approve(address spender, uint256 amount) returns (bool)",
"function transferFrom(address from, address to, uint256 amount) returns (bool)",
"function transfer(address to, uint256 amount) returns (bool)",
];
// Default network configuration (Hedera Testnet)
const DEFAULT_RPC_URL = "https://testnet.hashio.io/api";
const DEFAULT_CHAIN_ID = 296;
function formatAmount(amount, decimals) {
return ethers.utils.formatUnits(amount, decimals);
}
/**
* Load config from JSON file
*/
function loadConfigFile(configPath) {
if (!fs.existsSync(configPath)) {
throw new Error(`Config file not found: ${configPath}`);
}
const content = fs.readFileSync(configPath, "utf8");
const config = JSON.parse(content);
// Validate required fields
const requiredFields = ["token", "from", "spender", "to", "amount"];
for (const field of requiredFields) {
if (!config[field]) {
throw new Error(`Missing required field in config: ${field}`);
}
}
// Validate from has address and privateKey
if (!config.from.address || !config.from.privateKey) {
throw new Error('Config "from" must have "address" and "privateKey"');
}
// Validate spender has address and privateKey
if (!config.spender.address || !config.spender.privateKey) {
throw new Error('Config "spender" must have "address" and "privateKey"');
}
return config;
}
/**
* Print example config file
*/
function printExampleConfig() {
const example = {
token: "0x0000000000000000000000000000000000001234",
from: {
address: "0x0000000000000000000000000000000000005678",
privateKey: "0x_YOUR_FROM_PRIVATE_KEY_HERE",
},
spender: {
address: "0x0000000000000000000000000000000000009abc",
privateKey: "0x_YOUR_SPENDER_PRIVATE_KEY_HERE",
},
to: "0x000000000000000000000000000000000000def0",
amount: "1000000000000000000",
rpcUrl: "https://testnet.hashio.io/api",
chainId: 296,
};
console.log("\nExample config file (transfer-config.json):\n");
console.log(JSON.stringify(example, null, 2));
console.log("\nNote: Private keys should be in hex format with 0x prefix");
}
/**
* Wait for transaction with logging
*/
async function waitForTransaction(tx, description) {
console.log(`\n⏳ ${description}...`);
console.log(` Transaction hash: ${tx.hash}`);
const receipt = await tx.wait();
if (receipt.status === 1) {
console.log(` ✅ Transaction confirmed in block ${receipt.blockNumber}`);
console.log(` Gas used: ${receipt.gasUsed.toString()}`);
} else {
console.log(` ❌ Transaction failed!`);
}
return receipt;
}
async function main() {
// Parse command line arguments
const args = process.argv.slice(2);
let configPath = null;
for (let i = 0; i < args.length; i++) {
if (args[i] === "--config" && i + 1 < args.length) {
configPath = args[i + 1];
i++;
} else if (args[i] === "--example") {
printExampleConfig();
process.exit(0);
} else if (args[i] === "--help" || args[i] === "-h") {
console.log(`
Execute Approve and TransferFrom Script
This script executes two transactions:
1. Approve: The 'from' wallet approves 'spender' to spend tokens
2. TransferFrom: The 'spender' transfers tokens from 'from' to 'to'
Usage:
node executeTransfer.js --config <CONFIG_FILE>
Options:
--config <file> Path to JSON config file with transfer params and private keys
--example Print example config file format
--help, -h Show this help message
Config File Format:
{
"token": "0x...", // Token contract address
"from": {
"address": "0x...", // Address that owns the tokens
"privateKey": "0x..." // Private key to sign approve tx
},
"spender": {
"address": "0x...", // Address authorized to transfer
"privateKey": "0x..." // Private key to sign transferFrom tx
},
"to": "0x...", // Recipient address
"amount": "1000000", // Amount in smallest units (wei)
"rpcUrl": "${DEFAULT_RPC_URL}", // RPC endpoint (optional)
"chainId": ${DEFAULT_CHAIN_ID} // Chain ID (optional)
}
Examples:
# Execute transfer with config file
node executeTransfer.js --config ./transfer-config.json
# Show example config
node executeTransfer.js --example
`);
process.exit(0);
}
}
// Validate arguments
if (!configPath) {
console.error("Error: Must provide --config <CONFIG_FILE>");
console.error("Usage: node executeTransfer.js --config <CONFIG_FILE>");
console.error("Use --help for more information");
process.exit(1);
}
// Load configuration
const config = loadConfigFile(configPath);
const rpcUrl = config.rpcUrl || DEFAULT_RPC_URL;
const chainId = config.chainId || DEFAULT_CHAIN_ID;
const tokenAddress = config.token;
const fromAddress = config.from.address;
const fromPrivateKey = config.from.privateKey;
const spenderAddress = config.spender.address;
const spenderPrivateKey = config.spender.privateKey;
const toAddress = config.to;
const transferAmount = ethers.BigNumber.from(config.amount);
console.log("\n" + "=".repeat(80));
console.log("EXECUTE APPROVE AND TRANSFERFROM");
console.log("=".repeat(80));
// Setup provider
const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
try {
const network = await provider.getNetwork();
console.log(`\n📡 Network: ${network.name} (Chain ID: ${network.chainId})`);
console.log(` RPC URL: ${rpcUrl}`);
if (network.chainId !== chainId) {
console.warn(
`⚠️ Warning: Expected chain ID ${chainId}, got ${network.chainId}`
);
}
} catch (e) {
console.error(`Error connecting to network: ${e.message}`);
process.exit(1);
}
// Setup wallets
const fromWallet = new ethers.Wallet(fromPrivateKey, provider);
const spenderWallet = new ethers.Wallet(spenderPrivateKey, provider);
// Verify wallet addresses match config
if (fromWallet.address.toLowerCase() !== fromAddress.toLowerCase()) {
console.error(
`Error: From wallet address mismatch. Expected ${fromAddress}, got ${fromWallet.address}`
);
process.exit(1);
}
if (spenderWallet.address.toLowerCase() !== spenderAddress.toLowerCase()) {
console.error(
`Error: Spender wallet address mismatch. Expected ${spenderAddress}, got ${spenderWallet.address}`
);
process.exit(1);
}
// Connect to token contract
const tokenReadOnly = new ethers.Contract(tokenAddress, ERC20_ABI, provider);
const tokenFromSigner = tokenReadOnly.connect(fromWallet);
const tokenSpenderSigner = tokenReadOnly.connect(spenderWallet);
try {
// Get token info
const [name, symbol, decimals] = await Promise.all([
tokenReadOnly.name(),
tokenReadOnly.symbol(),
tokenReadOnly.decimals(),
]);
console.log(`\n📄 Token Contract: ${tokenAddress}`);
console.log(` Name: ${name}`);
console.log(` Symbol: ${symbol}`);
console.log(` Decimals: ${decimals}`);
// Transfer parameters
console.log(`\n💸 Transfer Parameters:`);
console.log(` From (owner): ${fromAddress}`);
console.log(` Spender: ${spenderAddress}`);
console.log(` To (recipient): ${toAddress}`);
console.log(
` Amount: ${formatAmount(transferAmount, decimals)} ${symbol} (${transferAmount.toString()} wei)`
);
// ========================================
// PRE-TRANSACTION STATE
// ========================================
console.log("\n" + "-".repeat(80));
console.log("PRE-TRANSACTION STATE");
console.log("-".repeat(80));
// Get balances and allowance
const [
fromBalance,
spenderBalance,
toBalance,
currentAllowance,
fromEthBalance,
spenderEthBalance,
] = await Promise.all([
tokenReadOnly.balanceOf(fromAddress),
tokenReadOnly.balanceOf(spenderAddress),
tokenReadOnly.balanceOf(toAddress),
tokenReadOnly.allowance(fromAddress, spenderAddress),
provider.getBalance(fromAddress),
provider.getBalance(spenderAddress),
]);
console.log(`\n💰 Token Balances:`);
console.log(
` From (${fromAddress}): ${formatAmount(fromBalance, decimals)} ${symbol}`
);
console.log(
` Spender (${spenderAddress}): ${formatAmount(spenderBalance, decimals)} ${symbol}`
);
console.log(
` To (${toAddress}): ${formatAmount(toBalance, decimals)} ${symbol}`
);
console.log(`\n⛽ ETH/HBAR Balances (for gas):`);
console.log(
` From: ${ethers.utils.formatEther(fromEthBalance)} HBAR`
);
console.log(
` Spender: ${ethers.utils.formatEther(spenderEthBalance)} HBAR`
);
console.log(`\n🔐 Current Allowance:`);
console.log(
` ${fromAddress} -> ${spenderAddress}: ${formatAmount(currentAllowance, decimals)} ${symbol}`
);
// Check if from has enough balance
if (fromBalance.lt(transferAmount)) {
console.error(
`\n❌ Error: Insufficient balance. From has ${formatAmount(fromBalance, decimals)} ${symbol}, need ${formatAmount(transferAmount, decimals)} ${symbol}`
);
process.exit(1);
}
// ========================================
// STEP 1: APPROVE TRANSACTION
// ========================================
console.log("\n" + "-".repeat(80));
console.log("STEP 1: APPROVE TRANSACTION");
console.log("-".repeat(80));
console.log(`\n📝 Approving ${spenderAddress} to spend ${formatAmount(transferAmount, decimals)} ${symbol} from ${fromAddress}`);
const approveTx = await tokenFromSigner.approve(
spenderAddress,
transferAmount
);
const approveReceipt = await waitForTransaction(
approveTx,
"Waiting for approve transaction"
);
if (approveReceipt.status !== 1) {
console.error("\n❌ Approve transaction failed!");
process.exit(1);
}
// Verify allowance after approve
const newAllowance = await tokenReadOnly.allowance(
fromAddress,
spenderAddress
);
console.log(
`\n New allowance: ${formatAmount(newAllowance, decimals)} ${symbol}`
);
// ========================================
// STEP 2: TRANSFERFROM TRANSACTION
// ========================================
console.log("\n" + "-".repeat(80));
console.log("STEP 2: TRANSFERFROM TRANSACTION");
console.log("-".repeat(80));
console.log(`\n📝 Spender (${spenderAddress}) transferring ${formatAmount(transferAmount, decimals)} ${symbol}`);
console.log(` From: ${fromAddress}`);
console.log(` To: ${toAddress}`);
const transferFromTx = await tokenSpenderSigner.transferFrom(
fromAddress,
toAddress,
transferAmount
);
const transferFromReceipt = await waitForTransaction(
transferFromTx,
"Waiting for transferFrom transaction"
);
if (transferFromReceipt.status !== 1) {
console.error("\n❌ TransferFrom transaction failed!");
process.exit(1);
}
// ========================================
// POST-TRANSACTION STATE
// ========================================
console.log("\n" + "-".repeat(80));
console.log("POST-TRANSACTION STATE");
console.log("-".repeat(80));
// Get final balances and allowance
const [
finalFromBalance,
finalSpenderBalance,
finalToBalance,
finalAllowance,
] = await Promise.all([
tokenReadOnly.balanceOf(fromAddress),
tokenReadOnly.balanceOf(spenderAddress),
tokenReadOnly.balanceOf(toAddress),
tokenReadOnly.allowance(fromAddress, spenderAddress),
]);
console.log(`\n💰 Final Token Balances:`);
console.log(
` From (${fromAddress}): ${formatAmount(finalFromBalance, decimals)} ${symbol}`
);
console.log(
` Spender (${spenderAddress}): ${formatAmount(finalSpenderBalance, decimals)} ${symbol}`
);
console.log(
` To (${toAddress}): ${formatAmount(finalToBalance, decimals)} ${symbol}`
);
console.log(`\n🔐 Final Allowance:`);
console.log(
` ${fromAddress} -> ${spenderAddress}: ${formatAmount(finalAllowance, decimals)} ${symbol}`
);
// Summary of changes
console.log("\n" + "-".repeat(80));
console.log("BALANCE CHANGES");
console.log("-".repeat(80));
const fromChange = finalFromBalance.sub(fromBalance);
const toChange = finalToBalance.sub(toBalance);
console.log(
`\n From: ${fromChange.isNegative() ? "" : "+"}${formatAmount(fromChange, decimals)} ${symbol}`
);
console.log(
` To: ${toChange.isNegative() ? "" : "+"}${formatAmount(toChange, decimals)} ${symbol}`
);
// ========================================
// SUMMARY
// ========================================
console.log("\n" + "=".repeat(80));
console.log("SUMMARY");
console.log("=".repeat(80));
console.log("\n✅ TRANSFER COMPLETED SUCCESSFULLY");
console.log(`\n Approve TX: ${approveTx.hash}`);
console.log(` TransferFrom TX: ${transferFromTx.hash}`);
console.log(
`\n Transferred: ${formatAmount(transferAmount, decimals)} ${symbol}`
);
console.log(` From: ${fromAddress}`);
console.log(` To: ${toAddress}`);
console.log("\n" + "=".repeat(80));
} catch (error) {
console.error("\n❌ Error during execution:", error.message);
// Try to decode revert reason if available
if (error.data) {
console.error(" Revert data:", error.data);
}
if (error.reason) {
console.error(" Reason:", error.reason);
}
if (error.code) {
console.error(" Error code:", error.code);
}
process.exit(1);
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error("Script failed:", error);
process.exit(1);
});