TokenURI function
how you can use web3.js to call the tokenURI function from an ERC-721 compliant smart contract and retrieve the URI for a specific token ID:
JavaScript Code:
const Web3 = require('web3');
const web3 = new Web3('https://bsc-dataseed.binance.org/');
const contractABI = [...]; // The ABI of your ERC-721 contract
const contractAddress = '0x511B52B473aB081B08E98F679501492eBBaB509f';
const contract = new web3.eth.Contract(contractABI, contractAddress);
async function getTokenURI(tokenId) {
try {
const uri = await contract.methods.tokenURI(tokenId).call();
console.log(`URI for token ID ${tokenId}:`, uri);
return uri;
} catch (error) {
console.error("Error fetching token URI:", error);
}
}
const tokenId = 123; // Replace with your desired token ID
getTokenURI(tokenId);Initialization:
We start by importing the
Web3library and initializing aweb3instance with an BSC node URL.We then define the ABI (Application Binary Interface) of our ERC-721 contract and the contract's address. The ABI allows us to interact with the contract's functions.
Using the ABI and address, we create a
contractinstance which will be used to interact with the smart contract on the BSC blockchain.
getTokenURIFunction:This asynchronous function takes a
tokenIdas its argument.Inside the function, we use
contract.methods.tokenURI(tokenId).call()to call thetokenURIfunction from the smart contract. This returns the URI associated with the providedtokenId.If successful, the URI is logged to the console and returned. If there's an error (e.g., the token doesn't exist), an error message is logged.
Function Call:
Finally, we call the
getTokenURIfunction with a specifictokenIdto retrieve and log its associated URI.
When you run this code, it will connect to the BSC blockchain, query the smart contract for the URI of the specified token ID, and then print the URI to the console.
Last updated