1

I have the following functions

function balance() public view returns(uint152) {
        return uint152(IERC20(token).balanceOf(address(this)));
    }
    
    function balance1() public view returns(IERC20) {
        return IERC20(token);
    }

The first one throws the error mentioned in the title, but the second one works just fine. Can you please help me understand, why does the function needs to be payable when I'm just checking the balance of a certain token. Thank you.

1 Answer 1

0

balance() => you are doing an unnecessary (and wrong) conversion, since function balanceOf() from an ERC20 contract will return a uint256.

balance1() => in your example, this is actually returning the token address, not its balance.

So you probably should update your functions to:

contract Test {
    function balance() public view returns(uint256) {
        return IERC20(token).balanceOf(address(this));
    }
    
    function contractAddress() public pure returns(IERC20) {
        return IERC20(token);
    }
}
3
  • Thanks for the answer but it still didn't work. BTW when you're doing a conversion to a smaller number it just cuts the last bits of the original one(in this case 256-152 = 104 bits), so there was nothing wrong with it unless you're sure that your number is small enough not to lose information. Commented Mar 4, 2021 at 9:57
  • What is the error you get? which pragma version are you using? as for the conversion, it is quite risky assuming the number will be always smaller than a certain amount; if this condition is broken along the time for whichever reason, that function would become useless. In addition, for a view function that is not modifying the state, I don't see a reason for doing a conversion from a type that you know it is uint256. Commented Mar 4, 2021 at 10:52
  • It is for optimizing the gas price, and there is a guarantee, that it won't exceed those bits. Commented Mar 5, 2021 at 14:21

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.