Enabling Token Transfers

Mar 12, 2024 11:28:29 PM

Allowing Balance Transfers

The last method we need to add to our smart contract is the transfer method. This method is used to transfer tokens from one account to another.

The transfer method is not the same as the Transfer event. The transfer method is used to transfer tokens, while the Transfer event is used to notify the network and other applications about the transfer.

The transfer Method

The standard defines the transfer as follows:

The first two parameters are the and the receiver of the tokens. The third parameter is the amount of tokens to transfer. The last parameter is an optional parameter that can be used to send additional data. This field is used to send metadata about the transfer.

The transfer method must return a boolean value. It must return true if the transfer was successful and false otherwise.

Implementing the transfer Method

Let’s create a transfer method in our smart contract. Open the contract file and add the following code:

Making a Transfer

Run the transfer method by pressing Run. Select the first account as the first parameter and the second account as the second parameter. Set the amount to 100 and press enter.

Make sure that the Transfer event was fired. You can see the event in the output. The event contains the sender, the receiver, and the amount of tokens transferred. The event is also stored in the and can be retrieved by other applications.

Lastly, use the balanceOf method to check the balances of the accounts. Use the second account as the parameter. The method should return 100.

Next, let’s understand the details of the transfer method.