Lesson14: Getting "URI query for non-existing token " error at 23:28 while deploying DynamicSvg Nft on local network #2779
-
Mint.js const { ethers, network } = require("hardhat");
const { developmentChains } = require("../helper-hardhat-config");
module.exports = async function ({ getNamedAccounts }) {
const { deployer } = await getNamedAccounts();
//Basic NFT
const basicNft = await ethers.getContract("BasicNft", deployer);
const basicMintTx = await basicNft.mintNft();
await basicMintTx.wait(1);
console.log(`basic NFT index 0 has tokenURIL ${await basicNft.tokenURI(0)}`);
//Random IPFs NNNFT
const randomIpfsNft = await ethers.getContract("RandomIpfsNft", deployer);
const mintFee = await randomIpfsNft.getMintFee();
await new Promise(async (resolve, reject) => {
setTimeout(resolve, 300000);
randomIpfsNft.once("NftMinted", async function () {
resolve();
});
const randomIpfsNftMintTx = await randomIpfsNft.requestNft({
value: mintFee.toString(),
});
const randomIpfsNftMintTxReceipt = await randomIpfsNftMintTx.wait(1);
if (developmentChains.includes(network.name)) {
const requestId =
randomIpfsNftMintTxReceipt.events[1].args.requestId.toString();
const vrfCoordinatorV2Mock = await ethers.getContract(
"VRFCoordinatorV2Mock",
deployer
);
await vrfCoordinatorV2Mock.fulfillRandomWords(
requestId,
randomIpfsNft.address
);
}
});
console.log(
`Random Ipfs Nft index 0 tokneUri: ${await randomIpfsNft.tokenURI(0)}`
);
//Dynamic SVG Nft
const highValue = ethers.utils.parseEther("4000");
const dynamicSvgNft = await ethers.getContract("DynamicSvgNft", deployer);
const dynamicSvgNftMintTx = await dynamicSvgNft.mintNft(highValue.toString());
await dynamicSvgNftMintTx.wait(1);
console.log(
`Dynamic SVG NFT index 0 tokenURI: ${await dynamicSvgNft.tokenURI(0)}`
);
}; DeployDynamicSvg.js const { network, ethers } = require("hardhat");
const {
developmentChains,
networkConfig,
} = require("../helper-hardhat-config");
const { verify } = require("../utils/verify");
const fs = require("fs");
module.exports = async function ({ getNamedAccounts, deployments }) {
const { deploy, log } = deployments;
const { deployer } = await getNamedAccounts();
const chainId = network.config.chainId;
let ethUsdPriceFeedAddress;
if (developmentChains.includes(network.name)) {
const EthUsdAggregator = await ethers.getContract("MockV3Aggregator");
ethUsdPriceFeedAddress = EthUsdAggregator.address;
} else {
ethUsdPriceFeedAddress = networkConfig[chainId].ethUsdPriceFeed;
}
log("--------------------------------------------");
const lowSVG = await fs.readFileSync("./images/dynamicNft/frown.svg", {
encoding: "utf-8",
});
const highSVG = await fs.readFileSync("./images/dynamicNft/happy.svg", {
encoding: "utf-8",
});
args = [ethUsdPriceFeedAddress, lowSVG, highSVG];
const dynamicSvgNft = await deploy("DynamicSvgNft", {
from: deployer,
args: args,
log: true,
waitConfirmations: network.config.blockConfirmations || 1,
});
if (
!developmentChains.includes(network.name) &&
process.env.ETHERSCAN_API_KEY
) {
log("Verifying........");
await verify(dynamicSvgNft.address, args);
}
};
module.exports.tags = ["all", "dynamicsvg", "main"]; DynamicSvgNft.sol //SPDX-License-Identifier:MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "base64-sol/base64.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract DynamicSvgNft is ERC721 {
//mint
//store our SVG information somwhwere
//SomeLogicc tom say "Show X Image or Show Y imagw"
uint256 private s_tokenCounter;
string private i_lowImageURI;
string private i_highImageURI;
string private constant base64EncodedSvgPrefix =
"data:image/svg+xml;base64";
AggregatorV3Interface internal immutable i_priceFeed;
mapping(uint256 => int256) public s_tokenIdToHighValue;
event CreatedNFT(uint256 indexed tokenId, int256 highValue);
constructor(
address priceFeedAddress,
string memory lowSvg,
string memory highSvg
) ERC721("Dynamic SVG NFT", "DSN") {
s_tokenCounter = 0;
i_lowImageURI = svgToImageURI(lowSvg);
i_highImageURI = svgToImageURI(highSvg);
i_priceFeed = AggregatorV3Interface(priceFeedAddress);
}
function svgToImageURI(string memory svg)
public
pure
returns (string memory)
{
string memory svgBase64Encoded = Base64.encode(
bytes(string(abi.encodePacked(svg)))
);
return
string(abi.encodePacked(base64EncodedSvgPrefix, svgBase64Encoded));
}
function mintNft(int256 highValue) public {
s_tokenIdToHighValue[s_tokenCounter] = highValue;
s_tokenCounter = s_tokenCounter + 1;
_safeMint(msg.sender, s_tokenCounter);
emit CreatedNFT(s_tokenCounter, highValue);
}
function _baseURI() internal pure override returns (string memory) {
return "data:application/json;base64";
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "URI Ouery for nonexisting token");
// string memory imageURI = "hi!!";
// data:application/json;base64
(, int256 price, , , ) = i_priceFeed.latestRoundData();
string memory imageURI = i_lowImageURI;
if (price >= s_tokenIdToHighValue[tokenId]) {
imageURI = i_highImageURI;
}
return
string(
abi.encodePacked(
_baseURI(),
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name(),
'","description":"An NFT that changes based on chainlink Feed",',
'"attributes":[{"trait_type":"coolness","value":100}],"image":"',
imageURI
)
)
)
)
);
}
}
hardhatConfig.js require("@nomiclabs/hardhat-waffle");
require("@nomiclabs/hardhat-etherscan");
require("hardhat-deploy");
require("solidity-coverage");
require("hardhat-gas-reporter");
require("hardhat-contract-sizer");
require("dotenv").config();
const RINKEBY_RPC_URL = process.env.RINKEBY_RPC_URL || "https://eth-rinkeby";
const PRIVATE_KEY = process.env.PRIVATE_KEY || "0xkey";
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY || "key";
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY || "key";
const MAINNET_RPC_URL = process.env.MAINNET_RPC_URL;
const GOERLI_RPC_URL = process.env.GOERLI_RPC_URL;
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 31337,
blockconfirmations: 1,
forking: {
url: MAINNET_RPC_URL,
},
},
localhost: {
chainId: 31337,
},
goerli: {
url: GOERLI_RPC_URL,
accounts: [PRIVATE_KEY],
chainId: 5,
blockConfirmations: 6,
},
},
etherscan: {
// yarn hardhat verify --network <NETWORK> <CONTRACT_ADDRESS> <CONSTRUCTOR_PARAMETERS>
apiKey: {
rinkeby: ETHERSCAN_API_KEY,
},
},
gasReporter: {
enabled: false,
outputFile: "gas-report.txt",
noColors: true,
currency: "USD",
coinmarketcap: COINMARKETCAP_API_KEY,
token: "MATIC",
},
solidity: {
compilers: [
{
version: "0.8.7",
},
{ version: "0.8.0" },
{
version: "0.4.24",
},
{ version: "0.4.19" },
{ version: "0.6.12" },
{ version: "0.6.0" },
],
},
namedAccounts: {
deployer: {
default: 0,
},
player: {
default: 1,
},
},
mocha: {
timeout: 500000,
},
}; |
Beta Was this translation helpful? Give feedback.
Answered by
alymurtazamemon
Sep 22, 2022
Replies: 1 comment 1 reply
-
In this function; function mintNft(int256 highValue) public {
s_tokenIdToHighValue[s_tokenCounter] = highValue;
s_tokenCounter = s_tokenCounter + 1;
_safeMint(msg.sender, s_tokenCounter);
emit CreatedNFT(s_tokenCounter, highValue);
} You are increasing counter value before minting an NFT, so what going on behind the scene is that when you first time mint the NFT, it gets mint for tokenId 1 instead of 0, and that is the reason when you are trying to get the NFT with tokenId 0 in the mint script, it is reverting an error. Fix it and things will work smoothly. change it to this; function mintNft(int256 highValue) public {
s_tokenIdToHighValue[s_tokenCounter] = highValue;
_safeMint(msg.sender, s_tokenCounter);
emit CreatedNFT(s_tokenCounter, highValue);
s_tokenCounter = s_tokenCounter + 1;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ritesh798
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ritesh798
In this function;
You are increasing counter value before minting an NFT, so what going on behind the scene is that when you first time mint the NFT, it gets mint for tokenId 1 instead of 0, and that is the reason when you are trying to get the NFT with tokenId 0 in the mint script, it is reverting an error.
Fix it and things will work smoothly.
change it to this;