2

I am looking to check token balance of some other contract into my own contract to see how many tokens of that contract are owned by my user.

Is this possible? If yes how to achieve it?

I tried this way

contract ERC20Interface {
function balanceOf(address whom) view public returns (uint);
}
2

You need to first create an interface of the functions you want to use which are created in the other contract balanceOf() in this case.

contract ERC20Interface {
    function balanceOf(address whom) view public returns (uint);
}

Then you need to instantiate the contract you want to use by its address.

ERC20Address = '0x...';
ERC20Interface ERC20Contract = ERC20Interface(ERC20Address);

Later, you can the methods of ERC20Contract which are written in your ERC20Interface, Just like shown below

ERC20Contract.balanceOf(msg.sender);
0

Instantiate the token contract interface and use it's balanceOf() function. This is the most common method to call a function in another contract.

Get the interface over here: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/IERC20.sol

This should give you the general idea.

import "./IERC20.sol";

contract MyContract {

  function myTokenBalance(address tokenContractAddress) public view returns(uint) {
    IERC20 token = IERC20(tokenContractAddress); // token is cast as type IERC20, so it's a contract
    return token.balanceOf(msg.sender);
  }
}

Hope it helps.

0

On-chain:

uint256 balance = erc20Contract.balanceOf(address(otherContract));

Off-chain using web3.js v0.x:

let balance = await erc20Contract.balanceOf(otherContract.address);

Off-chain using web3.js v1.x:

let balance = await erc20Contract.methods.balanceOf(otherContract._address);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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