What does it look like to override the decimals function?

What does it look like to override the decimal function? I tried this but got errors in remix: I’m trying zero decimals as practice.

pragma solidity 0.8.0;

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

contract MyToken is ERC20 {
	constructor () ERC20 ("MyToken", "MTK") {
		_mint(msg.sender, 1000000);
		function decimals() public view override returns (uint8) {
        return 0;
	}
}

in every other case, even when decimals are 18, you would do this right? or is 18 decimals implied if you don’t override the function?

pragma solidity 0.8.0;

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

contract MyToken is ERC20 {
	constructor () ERC20 ("MyToken", "MTK") {
		_mint(msg.sender, 1000000 * 10 ** 18);	
	}
}

any help is appreciated!

You're missing the closing brace in the constructor, but it's otherwise ok.

pragma solidity 0.8.0;

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

contract MyToken is ERC20 {
	constructor () ERC20 ("MyToken", "MTK") {
		_mint(msg.sender, 1000000);
	}

	function decimals() public view override returns (uint8) {
		return 0;
	}
}

18 decimals is the default number of decimals. But you still need to include ... * 10 ** 18 in your mint function call, because numbers of tokens are always expressed in terms of the smallest unit. This means "one token" is actually expressed as 10**18 tokens, or more generally 10**decimals. So in short, the snippet that you shared is correct.

2 Likes

got it, that makes sense.

Thank you!

I actually have one more question. I read that we no longer declare the totalSupply like this:

    contract ERC20FixedSupply is ERC20 {
        constructor() public {
            totalSupply += 1000;
            balances[msg.sender] += 1000;
        }
    }

Instead we do like in my first question, using the _mint function. To be clear, in a fixed supply contract the _mint function can’t be called again because it’s internal right? so it gets called once in the constructor and then can never be called again right? whereas in a non fixed supply contract I would make a function that then calls the _mint function, correct?

You can add a public mint function if you need the token to be mintable after deployment. Take a look at Contracts Wizard and see what it does when you toggle Mintable.

I just compiled this snippet in Remix and got a warning for the function mutability. As we do not evening read contract state so changing it from view to pure would be fine, right?

Yes that should be fine.

1 Like