Skip to content

Instantly share code, notes, and snippets.

@nhancv
Last active October 30, 2021 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nhancv/7d221c6679f99154208b0643977b5d6c to your computer and use it in GitHub Desktop.
Save nhancv/7d221c6679f99154208b0643977b5d6c to your computer and use it in GitHub Desktop.
TRC20 Token Client
import TronWeb from 'tronweb'
interface TRC20Token {
name(): {call()},
symbol(): {call()},
decimals(): {call()},
totalSupply(): {call()},
balanceOf(address: string): {call()}
transfer(toAddress: string, amount: number): {send(any)}
}
export default class TRC20TokenClient {
async start(): Promise<any> {
this.sendTRC20Token('TW4hHzQWhkDPe4yVGUerbo1wdsKCJEBhcV', 0.1)
}
/**
* Send Token fund
* @param recipientAddress
* @param tokenAmount
*/
async sendTRC20Token(recipientAddress: string, tokenAmount: number = 1): Promise<any | null> {
try {
const mainNetProvider = 'https://api.trongrid.io';
const testNetProvider = 'https://api.shasta.trongrid.io';
const netProvider = testNetProvider;
const HttpProvider = TronWeb.providers.HttpProvider; // Optional provider, can just use a url for the nodes instead
const fullNode = new HttpProvider(`${netProvider}`); // Full node http endpoint
const solidityNode = new HttpProvider(`${netProvider}`); // Solidity node http endpoint
const eventServer = `${netProvider}`; // Contract events http endpoint
const privateKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const tronWeb = new TronWeb(
fullNode,
solidityNode,
eventServer,
privateKey
);
const ownerAddress = tronWeb.address.fromPrivateKey(privateKey);
console.log({ownerAddress});
const contractAddressHex = tronWeb.address.toHex("TARCZ9Bw53DdsZ5eLYwc1GhfEkBAJsoFsv");
const contractInstance: TRC20Token = await tronWeb.contract().at(contractAddressHex);
const args = {
callValue: 0,
shouldPollResponse: true
};
const name = await contractInstance.name().call();
console.log({name});
const symbol = await contractInstance.symbol().call();
console.log({symbol});
const decimals = await contractInstance.decimals().call();
console.log({decimals});
const totalSupply = await contractInstance.totalSupply().call();
console.log({totalSupply: totalSupply.toString(10)});
const balanceOf = await contractInstance.balanceOf(ownerAddress).call();
console.log({balanceOf: balanceOf.balance.toString(10)});
let balanceOfrecipientAddress = await contractInstance.balanceOf(recipientAddress).call();
console.log({balanceOfrecipientAddress: balanceOfrecipientAddress.balance.toString(10)});
const amount = tokenAmount * Math.pow(10, decimals);
//{
// block: 1330340,
// timestamp: 1579589196000,
// contract: 'TARCZ9Bw53DdsZ5eLYwc1GhfEkBAJsoFsv',
// name: 'Transfer',
// transaction: '8158dda44af6f3f1ae2e65eb5d69787707f4e1ac7a1512b69cae8552e82065be',
// result: {
// _from: '41cba6374124b2320e7ff309033ecba4be5f81b2ea',
// _value: '100000',
// _to: '41dc6c365f620cef5fc9949bc008d362c711e9c3fc'
// },
// resourceNode: 'fullNode',
// unconfirmed: true
// }
contractInstance['Transfer']().watch((err, event) => {
if (err) return console.error('Error with "method" event:', err);
if (event) { // some function
console.log(event);
}
});
const transfer = await contractInstance.transfer(recipientAddress, amount).send(args);
console.log({transfer}); // { transfer: { success: true } }
balanceOfrecipientAddress = await contractInstance.balanceOf(recipientAddress).call();
console.log({balanceOfrecipientAddress: balanceOfrecipientAddress.balance.toString(10)});
return transfer.success;
} catch (e) {
Log.error(e);
return null;
}
}
}
@EvanXzj
Copy link

EvanXzj commented May 13, 2020

can I create an unsigned tx(trc20 token tranfser) first, and then sign the transaction with privateKey, and then broadcast the signed transaction?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment