개발자 문서
TronWeb으로 Tron 에너지 임대 (Node.js): 코드 예제
Node.js에서 TronWeb을 사용하여 Tron 에너지를 임대합니다. 4 TRX를 전송하고 API를 통해 65,000 에너지를 청구한 후 USDT를 70% 저렴하게 전송합니다. 오류 처리를 포함한 복사하여 붙여넣을 수 있는 코드입니다.
API 결제 주소
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
이 주소로 TRX를 전송합니다. 귀하의 트랜잭션 해시는 에너지 위임을 청구하는 데 사용됩니다.
TronWeb을 사용한 완전한 Node.js 통합입니다. 각 단계는 프로젝트에 복사할 수 있는 독립적인 코드 블록입니다. 전체 엔드투엔드 예제는 맨 아래에 있습니다.
필수 사항: Node.js 18+,
tronweb 설치됨 (npm install tronweb), 자금이 있는 Tron 지갑.
흐름
API 키 없음. 가입 없음. 코드는 TronEnergy 결제 주소로 온체인에서 TRX를 전송하고, 소유권을 증명하는 메시지에 서명한 후 위임을 청구합니다. 에너지는 약 3초 내에 도착합니다. 그 후 코드는 위임된 에너지를 사용하여 USDT를 전송합니다.
가격은 선형입니다: TRX당 16,250 에너지. 최소 주문 4 TRX (65,000 에너지 — 표준 USDT 전송 1회), 최대 1,000 TRX (16.25M 에너지). 전송하는 금액이 정확히 반환되는 에너지의 양을 결정합니다 — 티어나 패키지가 없습니다. 단일 표준 전송의 경우 4를 전송합니다. 새 지갑 전송의 경우 8을 전송합니다. 배치 작업의 경우 더 많이 전송합니다. 아래 코드는
trxAmount 변수를 사용하므로 한 곳에서 변경할 수 있습니다.
단계별
1. 설정
설정
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. TRX 전송
결제 전송
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. 위임 요청하기
위임 수령
// 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. USDT 전송
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);
오류 처리
오류 처리
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;
}
}
전체 예제
이 코드를 파일에 복사하고 환경 변수를 설정한 뒤 실행합니다. 스크립트는 TRX를 전송하고 메시지에 서명한 후, 재시도 로직과 함께 위임을 요청하고 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);
항상 서명을 포함합니다. 이는 TRX를 전송한 지갑이 당신임을 증명합니다. 서명이 없으면 API가 요청을 거부합니다
missing_signature.