Core
In this tutorial you'll learn how to implement the core standards into your smart contract. If you're joining us for the first time, feel free to clone this repo and checkout the 3.enumeration
branch to follow along.
git checkout 3.enumeration
If you wish to see the finished code for this Core tutorial, you can find it on the 4.core
branch.
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:
- tokensPerOwner: set of tokens for each account.
- tokensById: maps a token ID to a
Token
object. - tokenMetadataById: 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 tokensById
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 tokenMetadataById
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.