Skip to content

Adding A Simple Solidity Modifier

Now that you know whats the purpose of a modifier, let's add a simple modifier and remove the code duplication:

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.10;

contract InheritanceModifierExample {

    mapping(address => uint) public tokenBalance;

    address owner;

    uint tokenPrice = 1 ether;

    constructor() {
        owner = msg.sender;
        tokenBalance[owner] = 100;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "You are not allowed");
        _;
    }

    function createNewToken() public onlyOwner {
        tokenBalance[owner]++;
    }

    function burnToken() public onlyOwner {
        tokenBalance[owner]--;
    }

    function purchaseToken() public payable {
        require((tokenBalance[owner] * tokenPrice) / msg.value > 0, "not enough tokens");
        tokenBalance[owner] -= msg.value / tokenPrice;
        tokenBalance[msg.sender] += msg.value / tokenPrice;
    }

    function sendToken(address _to, uint _amount) public {
        require(tokenBalance[msg.sender] >= _amount, "Not enough tokens");
        assert(tokenBalance[_to] + _amount >= tokenBalance[_to]);
        assert(tokenBalance[msg.sender] - _amount <= tokenBalance[msg.sender]);
        tokenBalance[msg.sender] -= _amount;
        tokenBalance[_to] += _amount;
    }

}

Re-Deploy the Smart Contract and Test

  1. Deploy the Contract with Account#1
  2. Purchase Tokens with Account#2
  3. Try to Burn with Account#2

It should error out.

Problem

Right now, we're doing two things in one Smart Contract:

The token logic and the owner functionality.

We can further simplify the Smart Contract by using an Owner Smart Contract and then extending the Functionality. Let's do that next...