简体   繁体   中英

How to get access to specific metadata of a ERC721 token

I would like to get n ERC721 token with a specific "dna". See the metadata below:

{
  "dna": "602472F",
  "name": "Test #1",
  "description": "My Collectibles",
  "image": "ipfs://QmasMm8v9WkU11BtnWsybDW6/1.png",
  "edition": 1,
  "attributes": [
    {
      "trait": "type",
      "value": "Fire"
    },
    {
      "trait_type": "Eyes",
      "value": "Black"
    }
  ]
}

I know how to access a token using tokenURI . Here is my code:

  string public uri;
  string public uriSuffix = ".json";

  function _baseURI() internal view virtual override returns (string memory) {
    return uri;
  }

  function tokenURI(uint256 _tokenId) public view virtual override returns (string memory){
    require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
      string memory currentBaseURI = _baseURI();
      return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : "";
    }

Now, how can I check if a token has the dna I am looking for? Should I get this info from Opensea API or from the solidity side?

Ps: All my.json and.png files are hosted in IPFS.

EVM contracts are not able to read offchain data (the JSON file) directly. You'd need to use an offchain app (or an oracle provider such as Chainlink) for that to feed the offchain data to the contract.

So it's much easier to just query the data from an offchain app.

Example using node.js and the web3 package for querying the contract:

const contract = new web3.eth.Contract(abiJson, contractAddress);
const tokenURI = await contract.methods.tokenURI(tokenId);
const contents = (await axios.get(tokenURI)).data;
return contents.dna;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM