Skip to content

Contract Example

Let's start with a simple token-like Smart Contract. Mind, this is not an ERC20 Token contract. Its much simpler than that, and this code sample is only here to demonstrate how modifiers and inheritance works!

Copy the following contract over to Remix to follow along

//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;
    }

    function createNewToken() public {
        require(msg.sender == owner, "You are not allowed");
        tokenBalance[owner]++;
    }

    function burnToken() public {
        require(msg.sender == owner, "You are not allowed");
        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;
    }

}

Try the Smart Contract

What does the contract do? Let's give it a try! Head over to the Deploy and Run Transactions tab.

  1. Select Account#1 from the Accounts Dropdown
  2. Deploy the Contract

Buy Tokens

  1. Switch over to Account #2
  2. Enter 1 into the value field
  3. Select "Ether" from the Dropdown
  4. Buy 1 Token for 1 Ether by hitting the purchase button

Get the Token Balance

Now lets look if you have the right balance. Copy your address, fill it into the input field for "tokenBalance" and see if the balance is 1:

Burn Tokens

Now lets see what happens if you stay on Account#2 and try to burn tokens:

  1. Try to burn with Account #2
  2. Observe the Error message
  3. Which is coming from the require statement

Problem

Right now we have several similar require statements. They are all testing if a specific address called the smart contract. To avoid code duplication and make it easier to change this from a single place, we can use modifiers:

//other code
modifier onlyOnwer {
    require(msg.sender == owner, "You are not allowed");
    _;
}
//...

Let's add this to the contract...


Last update: May 4, 2022