Transferring ERC20 tokens across accounts – Aarthi Kannan – Medium

Transferring ERC20 tokens across accounts – Aarthi Kannan – Medium

I have been going through a couple of frustrating weeks trying to create simple workflows that help transfer ERC20 tokens to merchants to process payments from customers. There aren’t enough structured ‘help repositories’ to enable budding programmers to get the job done quickly. I thought of creating this article to help folks who are trying to figure out which methods to use for this workflow.

One of the first things I learnt is that the ERC20 contract is the main holder of all sums and balances. Customers and merchants who deals with a virtual token of a particular type have their ownership information registered with the contract. This means that transferring tokens to anyone other than the contract itself simply modifies ‘account balance’ values via the contract for the sender and the receiver. Any entity that wishes to know their account details need to call the contract methods to get them using balanceOf().

Let’s say one entity wishes to transfer tokens to another entity (a customer wants to pay tokens to a merchant for a purchase, for instance), you can use the sendSignedTransaction call to achieve this. Here is an excerpt:

Few key elements in the code need to be noted…

We are transferring from ‘fromAcct’ to ‘toAcct’ a value of ‘amount’. To enable this, we create a raw transaction.

var rawTransaction = ;

The ‘to’ field refers to the address of the deployed contract that we are requesting to execute the token transfer. This is different from the ‘toAcct’ who is the payee.

The ‘data’ field refers to the method call we request the contract to execute i.e. the ‘transfer’ method in the contract with explicit arguments encoded as ‘toAcct’, and the ‘amount’ to be transferred to ‘toAcct’.

Next we sign the transaction using the private key of the payer, which is analogous to getting the payer’s approval to transfer money from the payer’s account to payee’s.

var privKey = Buffer.from(thisweb3.utils.hexToBytes(<private_key_in_hex_format>));tx.sign(privKey);

Finally, this is followed by a call to the sendSignedTransaction to execute the call.

const receipt = await thisweb3.eth.sendSignedTransaction(‘0x’ + serializedTx.toString(‘hex’));:

This was tested with a private quorum network. Testbed info:

node: 10.5.x
web3: 1.0.0-beta.34
truffle: 4.1.14

Hope this helps.

Published at Sun, 17 Mar 2019 15:03:03 +0000

Spread the word. Share this post!

Leave a comment