How to add custom attributes (on-chain) in ERC721 token?
Asked Answered
G

1

5

i'm learning solidity using Openzeppelin Framework.

Currently i'm using the ERC721 Preset Contract (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol)

I would like to add custom attributes for each token minted in order to store some important data on the blockchain (i would not use for certain attributes the REST API, but i prefer to write them on the chain).

Each token will have different data.

string: Name
string: Surname
bytes32: 0x63383a61613a62323a30373a63383a323020

Is it possible to do it creating some new functions (without editing the mint function), allowing only the addresses that have the minter role?

Gastroenterostomy answered 29/3, 2021 at 14:42 Comment(0)
A
6

Yes.

You can create a mapping between the tokenId and whatever you want it to have. Let's call it name.

mapping(uint256 => string) name;

If you have a lot of attributes, you can do a mapping of a struct.

    struct Character {
        uint256 strength;
        uint256 dexterity;
        uint256 constitution;
        uint256 intelligence;
        uint256 wisdom;
        uint256 charisma;
        uint256 experience;
        string name;
    }

    Character[] public characters;

    mapping(uint256 => uint256) tokenIdToCharacterIndex;

Then, just make sure to update your tokenURI to include the on-chain attributes so that they show up in NFT marketplaces.

Autocrat answered 29/3, 2021 at 15:10 Comment(3)
Thanks a lot @patrick-collins for you reply. I just add your code on my contract, but i don't see how to add data to this struct, after i mint a new token.Gastroenterostomy
That’s a separate questions feel free to make that one next.Autocrat
For others who may come here - ya its right there in the code but doen't hurt mentoning here. There is a method _beforeTokenTransfer(address(0), to, tokenId); which the default mint method calls, which you can override and do your data generation and storage for the token that is being minted.Phoenician

© 2022 - 2024 — McMap. All rights reserved.