Solidity – How to Get the Decimals of ERC20 Token in Smart Contract

solidity

I have a smart contract which operates with an "external" ERC20 Token. For some calculations I need to access the decimal() function of the ERC20 Token.

In my contract I have the following line:

price = 200 * (10 ** token.decimals());

When I want to compile I get this error: TypeError: Member "decimals" not found or not visible after argument-dependent lookup in contract IERC20.

I initialize the "external" Token through the constructor:

IERC20 private token;

constructor(IERC20 _token) public {
    token = _token;
}

Does anyone know how to get access to the decimals of the token?

Best Answer

This will allow you to call decimals on every token which implements this method (either explicitly, or implicitly as a public variable):

contract IERC20Extented is IERC20 {
    function decimals() public view returns (uint8);
}

contract MyContract {
    IERC20Extented private token;

    constructor(IERC20Extented _token) public {
        token = _token;
    }

    ...
}

Be aware that decimals is primarily designated for off-chain use (typically in order to achieve nicer display of huge values).

Using it on-chain is rather unorthodox, so you might wanna consider that very carefully (i.e., think about your goal, and ask yourself why you need to use this value in order to achieve that goal).

Related Topic