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:
Initialization:
We start by importing the
Web3
library and initializing aweb3
instance 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
contract
instance which will be used to interact with the smart contract on the BSC blockchain.
getTokenURI
Function:This asynchronous function takes a
tokenId
as its argument.Inside the function, we use
contract.methods.tokenURI(tokenId).call()
to call thetokenURI
function 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
getTokenURI
function with a specifictokenId
to 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