How to override _setupDecimals() function in OpenZeppelin

Viewed 104

How can override Opezeppelin default decimal point of 18. The documentation says the _setupDecimals() should be called from a constructor; what am I doing wrong.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

contract MyToken is ERC20 {

    uint8 _decimals;

    constructor() ERC20("MyToken", "MTK") {

         _decimals = 3;

         function _setupDecimals(uint8 decimals_) internal {
            _decimals = decimals_;
         }

        _mint(msg.sender, 5000 * 10 ** decimals());

    }
}
1 Answers

_setupDecimals() was available in the OpenZeppelin version 3 (docs, GitHub).

Your import statement imports the latest version of the OpenZeppelin library, which is currently v4. This one implements the decimals() function (docs, GitHub) that you can override.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

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

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