TÀI LIỆU NHÂN VIÊN PHÁT TRIỂN
Thuê Tron Energy với TronWeb (Node.js): Ví Dụ Code
Thuê Tron Energy bằng TronWeb trên Node.js. Gửi 4 TRX, yêu cầu 65,000 năng lượng qua API, và gửi USDT với chi phí ít hơn 70%. Code sao chép được với xử lý lỗi.
ĐỊA CHỈ THANH TOÁN API
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
Gửi TRX đến địa chỉ này. Hash giao dịch của bạn được dùng để yêu cầu ủy quyền năng lượng.
Tích hợp Node.js hoàn chỉnh sử dụng TronWeb. Mỗi bước là một khối code độc lập bạn có thể sao chép vào dự án của mình. Ví dụ hoàn chỉnh từ đầu đến cuối ở dưới cùng.
Yêu cầu: Node.js 18+,
tronweb được cài đặt (npm install tronweb), một ví Tron có tài nguyên.
Quy Trình
Không có API key. Không cần đăng ký. Code của bạn gửi TRX trên chuỗi đến địa chỉ thanh toán TronEnergy, ký một tin nhắn chứng minh quyền sở hữu, rồi yêu cầu ủy quyền. Năng lượng sẽ đến trong khoảng 3 giây. Sau đó code của bạn gửi USDT bằng năng lượng ủy quyền.
Giá tính tuyến tính: 16,250 năng lượng trên TRX. Đơn hàng tối thiểu 4 TRX (65,000 năng lượng — một chuyển USDT tiêu chuẩn), tối đa 1,000 TRX (16.25M năng lượng). Số tiền bạn gửi xác định chính xác có bao nhiêu năng lượng quay trở lại — không có các bậc hay gói. Để chuyển tiêu chuẩn, gửi 4. Để chuyển ví mới, gửi 8. Để công việc hàng loạt, gửi thêm. Code bên dưới sử dụng một
trxAmount biến số bạn có thể thay đổi ở một nơi.
Từng Bước
1. Thiết lập
thiết lập
const { TronWeb } = require('tronweb'); // destructured: the default import is broken in v6
const tronWeb = new TronWeb({
fullHost: 'https://api.trongrid.io',
privateKey: process.env.TRON_PRIVATE_KEY,
});
const API = 'https://api.tronnrg.com';
const ADDR = 'TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx'; // API payment address
const USDT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
2. Gửi TRX
gửi thanh toán
const TRX_AMOUNT = 4; // Linear: 16,250 energy per TRX. Min 4, max 1000.
// 4 → 65k (standard) · 8 → 130k (new wallet) · 40 → 650k (10 transfers)
const payment = await tronWeb.trx.sendTransaction(ADDR, TRX_AMOUNT * 1e6);
console.log('Payment tx:', payment.txid);
3. Nhận ủy quyền năng lượng
yêu cầu ủy quyền năng lượng
// Sign: proves you are the sender
const msg = `${payment.txid}:${tronWeb.defaultAddress.base58}`;
const sig = await tronWeb.trx.signMessageV2(msg);
const delegation = await fetch(`${API}/delegate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tx_hash: payment.txid,
delegate_to: tronWeb.defaultAddress.base58,
signature: sig,
}),
}).then(r => r.json());
if (delegation.error) {
throw new Error(delegation.message);
}
console.log('Energy delegated:', delegation.energy); // TRX_AMOUNT × 16,250
4. Gửi USDT
gửi USDT
const contract = await tronWeb.contract().at(USDT);
const tx = await contract.transfer(
recipientAddress, Math.round(usdtAmount * 1e6)
).send({ feeLimit: 50_000_000 });
console.log('USDT sent:', tx);
Xử lý lỗi
xử lý lỗi
const result = await fetch(`${API}/delegate`, { ... })
.then(r => r.json());
if (result.error) {
switch (result.error) {
case 'payment_verification_failed':
// Payment not yet indexed on-chain. Wait 3s and retry.
break;
case 'hash_already_used':
// Already claimed. Don't retry.
break;
case 'signature_mismatch':
// Sender of TRX != signer of the message. Sign with the same key.
break;
case 'delegation_failed':
// Provider could not deliver. Retry or contact support with result.ref.
break;
}
}
Ví dụ hoàn chỉnh
Sao chép vào tập tin, đặt các biến môi trường của bạn và chạy. Script gửi TRX, ký thông điệp, nhận ủy quyền năng lượng với thử lại, rồi gửi USDT.
delegate-energy.js
const { TronWeb } = require('tronweb'); // destructured: default import is broken in v6
const tronWeb = new TronWeb({
fullHost: 'https://api.trongrid.io',
privateKey: process.env.TRON_PRIVATE_KEY,
});
const API = 'https://api.tronnrg.com';
const ADDR = 'TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx';
const USDT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
async function claimWithRetry(txHash, delegateTo, signature, retries = 3) {
for (let i = 0; i < retries; i++) {
const res = await fetch(`${API}/delegate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tx_hash: txHash, delegate_to: delegateTo, signature }),
}).then(r => r.json());
if (!res.error) return res;
if (res.error !== 'payment_verification_failed') throw new Error(res.message);
await new Promise(r => setTimeout(r, 3000));
}
throw new Error('Transaction not found after retries');
}
async function main() {
const recipient = 'TRecipientWallet';
const trxAmount = 4; // min 4, max 1000 — you get trxAmount × 16,250 energy
// 1. Send TRX (linear pricing: 16,250 energy per TRX)
const payment = await tronWeb.trx.sendTransaction(ADDR, trxAmount * 1e6);
console.log('Payment:', payment.txid);
// 2. Claim delegation
// Sign: proves you are the sender
const message = `${payment.txid}:${recipient}`;
const signature = await tronWeb.trx.signMessageV2(message);
const result = await claimWithRetry(payment.txid, recipient, signature);
console.log('Delegated:', result.energy, 'energy');
console.log('Delegation tx:', result.delegations[0].tx); // verify on TronScan
console.log('Ref:', result.ref);
// 3. Send USDT
const contract = await tronWeb.contract().at(USDT);
const tx = await contract.transfer(recipient, 10 * 1e6).send();
console.log('USDT sent:', tx);
}
main().catch(console.error);
Luôn bao gồm chữ ký. Nó chứng minh bạn là ví đã gửi TRX. Không có nó, API từ chối yêu cầu với
missing_signature.