Royalty
In this tutorial you'll continue building your non-fungible token (NFT) smart contract, and learn how to implement perpetual royalties into your NFTs. This will allow people to get a percentage of the purchase price when an NFT is sold.
Introduction
By now, you should have a fully fledged NFT contract, except for the royalties support.
To get started, go to the nft-contract-approval/
folder from our GitHub repository, or continue your work from the previous tutorials.
cd nft-contract-approval/
If you wish to see the finished code for this Royalty tutorial, you can find it in the nft-contract-royalty
folder.
Thinking about the problem
In order to implement the functionality, you first need to understand how NFTs are sold. In the previous tutorial, you saw how someone with an NFT could list it on a marketplace using the nft_approve
function by passing in a message that could be properly decoded. When a user purchases your NFT on the marketplace, what happens?
Using the knowledge you have now, a reasonable conclusion would be to say that the marketplace transfers the NFT to the buyer by performing a cross-contract call and invokes the NFT contract's nft_transfer
method. Once that function finishes, the marketplace would pay the seller for the correct amount that the buyer paid.
Let's now think about how this can be expanded to allow for a cut of the pay going to other accounts that aren't just the seller.
Expanding the current solution
Since perpetual royalties will be on a per-token basis, it's safe to assume that you should be changing the Token
and JsonToken
structs. You need some way of keeping track of what percentage each account with a royalty should have. If you introduce a map of an account to an integer, that should do the trick.
Now, you need some way to relay that information to the marketplace. This method should be able to transfer the NFT exactly like the old solution but with the added benefit of telling the marketplace exactly what accounts should be paid what amounts. If you implement a method that transfers the NFT and then calculates exactly what accounts get paid and to what amount based on a passed-in balance, that should work nicely.
This is what the royalty standards outlined. Let's now move on and modify our smart contract to introduce this behavior.
Modifications to the contract
The first thing you'll want to do is add the royalty information to the structs. Open the nft-contract-approval/src/metadata.rs
file and add royalty
to the Token
struct:
pub royalty: HashMap<AccountId, u32>,
Second, you'll want to add royalty
to the JsonToken
struct as well:
pub royalty: HashMap<AccountId, u32>,