Javascript Function to Send Trx based on TronWeb

in #tron4 years ago

Sending TRX coin on TRON blockchain is easy. We can use the TronWeb library and here is the Javascript function to send Trx to a Tron wallet address:

async function sendTrx(fromAddress, toAddress, amount, privateKey, AppKey) {
  let headers = null;
  if (AppKey) {
      headers = { "TRON-PRO-API-KEY": AppKey };
  }
  const tronWeb = new TronWeb({
      fullHost: 'https://api.shasta.trongrid.io',
      headers: headers,   
      privateKey: privateKey,
  });
  const tradeobj = await tronWeb.transactionBuilder.sendTrx(
        tronWeb.address.toHex(toAddress),
        amount * 1000 * 1000,
        tronWeb.address.toHex(fromAddress)
  );
  const signedtxn = await tronWeb.trx.sign(
        tradeobj,
        privateKey
  );
  const receipt = await tronWeb.trx.sendRawTransaction(
        signedtxn
  );
  return receipt;
}

Example usage:

(async function() {
    const fromAddress = "TL.....";
    const toAddress = "TN.....";
    const amount = 1.2;
    const privateKey = "key";
    const AppKey = "Tron Pro API Key - Optional";
    await sendTrx(fromAddress, toAddress, amount, privateKey, AppKey);
})();

You can sign up on TronGrid and get 3 free api key if you need more quota of API usage. For testnets such as Shasta or Nile, you don't need the Tron Pro API key.

Reposted to blog

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 60472.73
ETH 1579.34
USDT 1.00
SBD 0.42