Enabling Token Transfers

Apr 29, 2024 11:46:57 PM

NEP-17 Transfer Overview

The transfer method must be implemented following rules defined in the NEP-17 standard.

They are:

  • The transfer method must trigger the Transfer event, even if the value is 0.
  • The transfer method must check if the recipient is a smart contract and invoke the onNEP17Payment method if it is.
    • The callback should be called after triggering the Transfer event.
    • If the recipient wishes to refuse the transfer, it must throw an exception.
    • If the recipient doesn’t implement the onNEP17Payment method, an exception is thrown.
  • If the user doesn’t have enough funds, the transfer method must return False.
  • If the user is not authorized to transfer the funds, the transfer method must return False.
  • If the parameters are invalid, the transfer method must throw an exception.

The transfer method from the previous class already follows all these rules. We are going to refer to it in the next sections.

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 NEP-17 standard defines the transfer method signature as follows:

The first two parameters are the sender 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:

Coin.py

Making a Transfer

Run the transfer method by pressing Run. Select the dev1 account as the first parameter and dev2 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 blockchain and can be retrieved by other applications.

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

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