Search code examples
htmljsonsoliditynft

Solidity NFT metadata loading issue


I am creating an NFT collection, and am testing on ropsten. I have my NFT metadata on my website for example boredApes.com/tokens/3.json but the issue is the contract goes to boredApes.com/tokens/3 and not the .json part. How should I change to contract to load this metadata. The current solidity function is

function _baseURI() internal pure override returns (string memory) { return "https://boredApes.com/tokens/"; }


Solution

  • The _baseURI() function sets just the beginning of the URI. You need to override the tokenURI() function as well, appending the .json string at the end of the returned URI.

    pragma solidity ^0.8;
    
    import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol";
    
    contract MyCollection is ERC721 {
        constructor() ERC721("MyCollection", "MyC") {
            _mint(msg.sender, 1);
        }
    
        function _baseURI() internal pure override returns (string memory) {
            return "https://boredApes.com/tokens/";
        }
    
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            // the `super` keyword references the parent function of the same name
            string memory uri = super.tokenURI(tokenId);
            return string(abi.encodePacked(uri, ".json"));
        }
    }