0

I'm new to solidity and just confused about the return value of a uint from my deployed contract I have written the contract like this:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

// import ERC721 standard
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

// inherit from the ERC721 library to make it compliant
contract NFT is ERC721URIStorage {
    // keep track of tokens created also works as the a tokenID whenever a new token is minted
    uint public tokenCount;

    constructor() ERC721("EOR NFT", "EOR"){}

    function mint(string memory _tokenURI) external returns(uint){
        tokenCount += 1;
        // msg.sender comes from the ingerited ERC721 contract and is the wallet address of the
        // account that is calling this function.
        _safeMint(msg.sender, tokenCount);
        _setTokenURI(tokenCount, _tokenURI);
        return(tokenCount);
    }
}

and have deployed successfully to a local blockchain using hardhat, to test it I us hardhad console and grab the contract and public tokenCount with this:

const contract = await ethers.getContractAt("NFT", "0x5FC8d32690cc91D4c39d9d3abcBD16989F875707");
const tokenCount = await contract.tokenCount();
tokenCount

I'm expecting it to give me:

BigNumber {Value:"0"}

but its giving me this:

BigNumber { _hex: '0x01', _isBigNumber: true }

How do I get a normal number from my contract and not that wierd _hex value?

thanks team!

2 Answers 2

2

Everything should be documented in the ethers BigNumber documentation.

If you really want a js type number you can use :

tokenCount.toNumber();

But that's unsafe, as the returned value can be too big to be safely represented in JavaScript. If you want to do mathematical operations on it stick to the BigNumber type.

For display in base 10, the recommended use would be :

tokenCount.toString()
0

I had also facing the same problem, try this:

async function getBalance() {
try {
  const data = await readContract({
    address: contractAddress,
    abi: contractABI,
    functionName: 'balanceOf',
    args: [address],
  })
  console.log("Contract: ", data);

  const balanceHex = data._hex;
  const balanceBigNumber = ethers.BigNumber.from(balanceHex);
  const balanceDecimal = ethers.utils.formatEther(balanceBigNumber);
  const change = balanceDecimal * 10**18;
  setBalance(change);
} catch (error) {
  console.log(error);
}
}

getBalance();

Make sure to install ethers.js in your project.

1
  • You shouldn't access internal data. It could change between version.
    – Ismael
    Feb 16, 2023 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.