user2447290
user2447290

Reputation:

How can I find out the token balance of an address?

I am using the contract from: https://bscscan.com/address/0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c#readContract

I have seen that it has a public variable which is:

mapping (address => uint) public balanceOf;

I am trying to call in my contract, but it is not very clear to me how to use it, if via interface or in what way

contract checkBalanceOf {
    mapping (address => uint) public  balanceOf;
    function balanceOf() public returns (uint256) {
        address  ERC20Address = targetInterface(0x18895B2a605CdAb301482d8F96E59FaDc17964C3);
        return ERC20Address.balanceOf(bankAddress);
    }

I was trying to apply the logic of this answer, but unlike, that this one does not have a public function

is posible call public view return deployed, from anther contract?

Upvotes: 0

Views: 2401

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43481

In order to check how many WBNB the bankAddress owns, and to perform the check from your own contract, your contract needs to:

  1. Define the balanceOf() function in an interface
  2. Instantiate the interface pointing to the WBNB contract address
  3. Call the WBNB function balanceOf() passing it the bankAddress
  4. Recommended: Wrap the call in a view function so that by default it uses a call, not a transaction, in some client apps.
pragma solidity ^0.8;

interface IBEP20 {
    // mind the `view` modifier
    function balanceOf(address _owner) external view returns (uint256);
}

contract checkBalanceOf {
    address bankAddress = address(0x123);

    // mind the `view` modifier
    function balanceOf() external view returns (uint256) {
        // creating a pointer to the WBNB contract
        IBEP20 WBNBContract = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);

        // getting balance of `bankAddress` on the WBNB contract
        return WBNBContract.balanceOf(bankAddress);
    }
}

Upvotes: 0

Related Questions