Transfers
In this tutorial you'll learn how to implement NFT transfers as defined in the core standards into your smart contract.
We will define two methods for transferring NFTs:
nft_transfer
: that transfers ownership of an NFT from one account to anothernft_transfer_call
: that transfers an NFT to a "receiver" and calls a method on the receiver's account
nft_transfer
is a simple transfer between two user, while nft_transfer_call
allows you to attach an NFT to a function call
Introduction
Up until this point, you've created a simple NFT smart contract that allows users to mint tokens and view information using the enumeration standards. Today, you'll expand your smart contract to allow for users to not only mint tokens, but transfer them as well.
As we did in the minting tutorial, let's break down the problem into multiple subtasks to make our lives easier. When a token is minted, information is stored in 3 places:
- tokens_per_owner: set of tokens for each account.
- tokens_by_id: maps a token ID to a
Token
object. - token_metadata_by_id: maps a token ID to its metadata.
Let's now consider the following scenario. If Benji owns token A and wants to transfer it to Mike as a birthday gift, what should happen? First of all, token A should be removed from Benji's set of tokens and added to Mike's set of tokens.
If that's the only logic you implement, you'll run into some problems. If you were to do a view
call to query for information about that token after it's been transferred to Mike, it would still say that Benji is the owner.
This is because the contract is still mapping the token ID to the old Token
object that contains the owner_id
field set to Benji's account ID. You still have to change the tokens_by_id
data structure so that the token ID maps to a new Token
object which has Mike as the owner.
With that being said, the final process for when an owner transfers a token to a receiver should be the following:
- Remove the token from the owner's set.
- Add the token to the receiver's set.
- Map a token ID to a new
Token
object containing the correct owner.
You might be curious as to why we don't edit the token_metadata_by_id
field. This is because no matter who owns the token, the token ID will always map to the same metadata. The metadata should never change and so we can just leave it alone.
At this point, you're ready to move on and make the necessary modifications to your smart contract.
Modifications to the contract
Let's start our journey in the nft-contract-skeleton/src/nft_core.rs
file.