我想使用TronWeb发送trc20令牌。我是否需要使用contract((.at((来执行此操作?这意味着我需要将trc20代币视为智能合约?
首先,要澄清任何网络上的每个令牌(不仅仅是tron(都有自己的智能合约,该合约已发布到网络
这是获取账户余额的代码,另一个是转账USDT 的代码
不要忘记用您的私钥和网络端点初始化代码
注意,执行事务需要tron能量和带宽你可以使用这个链接阅读他们
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);
}
第一步-初始化您的tronWeb实例:
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
});
然后,获取合同输入实例:
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);
}
最后,发送TRC20代币功能:
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;
}
发送1 USDT(shasta网络(的示例:
// https://shasta.tronscan.org/#/contract/TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs
const usdtContractAddress = "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
const privateKey = "478XXXXXXX851B9163263A90E126F8758133504602BEB669AA613D64ADB9D390";
const to = "TH3JABY4URcbpenmXhYyfi8smvSp1niyX2";
sendTokenTransaction(privateKey, to, 1_000_000, usdtContractAddress);
📍官方文档链接
当您用私钥初始化tronweb组件时,您可以使用contract((.at((
tronWeb = new TronWeb(
'https://api.nileex.io/',
'https://api.nileex.io/',
'https://event.nileex.io/',
'your privateKey'
);