[Ethereum] Calling “balanceOf” in a contract from another contract that imports it. Expected 1 Got 0

contract-developmenterc-20erc-721openzeppelinsolidity

I have an ERC20 contract that calls BalanceOf in a ERC721 contract;

In my ERC20 contract;

import "./NFT.sol";

    contract ERC20 {
    
     NFT public nft;
    
     constructor (NFT _nftAddress) public {
      nft = _nftAddress;
    }
    function getNFTBalance(address _nftOwner) public view returns (uint256 result){
           nft.balanceOf(_nftOwner);
           return result;
       }

I'm using the ERC721PresetMinterPauserAutoId from OpenZeppelin

My NFT contract import ERC21.sol

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

In the ERC721.sol the BalanceOf function;

function balanceOf(address owner) public view override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");

        return _holderTokens[owner].length();
    }

This is how I pass the contract address on deployment in 2_deploy_contracts.js

module.exports = async function(deployer) {
  // deploying the ERC20 Token
  const accounts = await web3.eth.getAccounts();

  await deployer.deploy(Token);

  // deploying the NFT
  const NFT_NAME = "ID Exclusivity Token";
  const NFT_SYMBOL = "IDET";
  const NFT_API = "https://example.com/nft/api/token/"

  await deployer.deploy(NFT, NFT_NAME, NFT_SYMBOL, NFT_API)

  .then( async () => {
    nftContractAddress = NFT.address;
    console.log('NFT ADDRESS : ',nftContractAddress)
    const feeAccount = accounts[0];
    const feePercent = 10;
    //Deploying Exchange with the NFT address
    await deployer.deploy(Exchange, nftContractAddress, feeAccount, feePercent);
  })
};

I can confirm that the address is the right one with the console log.

Once deployed, in truffle console:

nft = await NFT.deployed()

await nft.mint("0x851ffbF315d9d32E8DBE75b10B1E0b8C030320cf")

exchange = await Exchange.deployed()

await exchange.getNFTBalance("0x851ffbF315d9d32E8DBE75b10B1E0b8C030320cf") // return 0

await nft.balanceOf("0x851ffbF315d9d32E8DBE75b10B1E0b8C030320cf") // return 1

Best Answer

I was returning a result that i assumed was 0 by default.

Changed the function to;

 function getNFTBalance(address _owner) public view returns (uint256){
        
       return nft.balanceOf(_owner);
   }

Getting the right balance now

Related Topic