const { TronWeb } = require('tronweb');

// 1. 读取命令行参数
const privateKey = process.argv[2];
const toAddress = process.argv[3];
const contractAddress = process.argv[4];
const fullNodeUrl = process.argv[5] || 'https://api.trongrid.io'; // 默认主网
const amount = parseFloat(process.argv[6]); // 默认转1个USDT
const feeLimitSun = parseInt(process.argv[7] || '100000000', 10);
const tronProApiKey = process.argv[8] || '';

// 2. 初始化 TronWeb 实例
const tronWeb = new TronWeb({
    fullHost: fullNodeUrl,
    headers: tronProApiKey ? { 'TRON-PRO-API-KEY': tronProApiKey } : undefined,
});

// 3. 金额（转换为 USDT 单位）
const usdtAmount = amount * 1e6;

async function sendTRC20() {
    let attempts = 0;
    try {
        while (attempts < 2) {
            try {
                const contract = await tronWeb.contract().at(contractAddress);
                const tx = await contract.methods.transfer(toAddress, usdtAmount).send({
                    feeLimit: feeLimitSun,
                }, privateKey);

                console.log(JSON.stringify({ success: true, txid: tx }));
                return;
            } catch (err) {
                attempts += 1;
                if (attempts < 2 && String(err.message || '').includes('429')) {
                    await new Promise((resolve) => setTimeout(resolve, 5500));
                    continue;
                }

                console.error(JSON.stringify({ success: false, error: err.message }));
                return;
            }
        }
    } catch (err) {
        console.error(JSON.stringify({ success: false, error: err.message }));
    }
}

sendTRC20();
