Search code examples
node.jsethereumweb3jsbinancebinance-smart-chain

BEP-20 Token Transaction on NodeJs


Hi I'm just confused that how to transact BEP-20 Token(e.g: Binance-Peg BUSD-T). I have simply transact bnb in Binance Smart Chain with this code:

const tx = await web3.eth.accounts.signTransaction({
  to: '0xB1455f4721b32390f4b65F86D2Cd50e74FaD7A99',
  value: '500000000000000',
  gas: 2000000
}, 'SENDER_PRIVATE_KEY');
  
const transaction = await web3.eth.sendSignedTransaction(tx.rawTransaction);

And it work perfectly fine. But I just do absolutely anything to transact a token, for example I used web3.eth.Contract(abi, contract_addr) and then

await contract.methods.transfer(toAddress, '500000000000000000').send({ 
  from: '0xF9FF794700224fc9a1D6a30eb2A90d11eA1D82D1'
});

or with ethereumjs-tx package and ..., but none of them transact the token. I just need a sample code example or a well documented blog to tell me what should I do. Can anyone help me with that ?!!


Solution

  • In order to use the .send({from: ...}) method, you need to

    • Have the from account unlocked on your provider.

      OR

    • Add its private key to the web3 account wallet (docs)


    Ulocked provider account

    This approach is mostly used on local providers (e.g. Ganache) that fund and unlock some accounts by default.

    Keeping an unlocked account on a production provider is unwise, because anyone who queries the provider can send transactions.


    Web3 account wallet

    You need to pass the private key that generates the from address.

    web3.eth.accounts.wallet.add(privateKey);
    

    And then you can use the .send({from: ...}) method

    await contract.methods.transfer(toAddress, '500000000000000000').send({ 
      from: '0xF9FF794700224fc9a1D6a30eb2A90d11eA1D82D1'
    });