I want to use TronWeb to send trc20 token. Whether I need to use contract().at() to do this? It means I need to treat trc20 token just as smart contract?
Asked
Active
Viewed 4,379 times
3 Answers
1
first things first, to clarify every token on any network (not just tron) has its own smart contract that has been published to the network
here is the code to get your account balance and another to transfer USDT
don't forget to init the code with your private key and network endpoints
note that you need tron energy and bandwidth to perform a transaction you can read about them using this link
const CONTRACT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
async function getBalance(account) {
const {
abi
} = await tronWeb.trx.getContract(CONTRACT);
const contract = tronWeb.contract(abi.entrys, CONTRACT);
const balance = await contract.methods.balanceOf(account).call();
console.log("balance:", balance.toString());
}
async function transferUSDT(destination, amount) {
const {
abi
} = await tronWeb.trx.getContract(CONTRACT);
const contract = tronWeb.contract(abi.entrys, CONTRACT);
const resp = await contract.methods.transfer(destination, amount).send();
console.log("transfer:", resp);
}
1
First step - init your tronWeb instance:
const tronWeb = new TronWeb({
headers: {
'TRON-PRO-API-KEY': 'XXXXXXXXX-f915-XXXX-b320-7b67c4ecef9d'
},
fullHost: 'https://api.shasta.trongrid.io',
// privateKey: DEFAULT_PRIVATE_KEY, // you can specify default key
});
Then, get contract entry instance:
async function initContract(contractAddress: string, privateKey: string) {
// I prefer to specify the key here, because I work with multiple private keys
tronWeb.setPrivateKey(privateKey);
return this.tronWeb.contract().at(contractAddress);
}
Finally, send TRC20 tokens function:
async function sendTokenTransaction(privateKeyFrom: string, to: string, value: number, contractAddress: string): Promise<string | null> {
try {
const contract = await initContract(contractAddress, privateKeyFrom);
const hash = await contract.transfer(to, value).send();
return hash;
} catch (err) {
console.log(`sendTokenTransaction: ${err}`);
}
return null;
}
Example for sending 1 USDT (shasta network):
// https://shasta.tronscan.org/#/contract/TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs
const usdtContractAddress = "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
const privateKey = "478XXXXXXX851B9163263A90E126F8758133504602BEB669AA613D64ADB9D390";
const to = "TH3JABY4URcbpenmXhYyfi8smvSp1niyX2";
sendTokenTransaction(privateKey, to, 1_000_000, usdtContractAddress);
Official documentation link

zemil
- 3,235
- 2
- 24
- 33
0
When you init the tronweb compnent with private key ,you could use the contract().at()
tronWeb = new TronWeb(
'https://api.nileex.io/',
'https://api.nileex.io/',
'https://event.nileex.io/',
'your privateKey'
);

akin
- 21
- 1
- 5