5SKY
  • ✨Introduction
  • Products
    • 🌌5SKY NFT Project
      • 5SKY LTI (Core)
      • Lottery Smart Contract
    • 🪙5SKY Token Project
      • Token Specifications
      • Tokenomics Explained
      • Token Features
      • Functions Overview
  • Getting Started
    • Create a Wallet
    • Overview of the 5SKY NFT
      • Connecting MetaMask
      • Connecting Trust Wallet
  • 💻DEVELOPERS
    • Decentralization & Transparent Commitment
      • Plan Structure
      • NFTData Structure
      • TokenURI function
      • Purchase function
      • Upgrade function
  • 🎇FAQ
    • 5Sky Ecosystem
    • NFT Project
    • LTI Smart Contract
    • Lottery Smart Contract
    • Token Project
  • ☎️Contact Us
    • Customer Support
    • Social Accounts & Communities
Powered by GitBook
On this page
  1. DEVELOPERS
  2. Decentralization & Transparent Commitment

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);

  1. Initialization:

    • We start by importing the Web3 library and initializing a web3 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.

  2. getTokenURI Function:

    • This asynchronous function takes a tokenId as its argument.

    • Inside the function, we use contract.methods.tokenURI(tokenId).call() to call the tokenURI function from the smart contract. This returns the URI associated with the provided tokenId.

    • 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.

  3. Function Call:

    • Finally, we call the getTokenURI function with a specific tokenId 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.

PreviousNFTData StructureNextPurchase function

Last updated 1 year ago

💻