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.
- Select Account#1 from the Accounts Dropdown
- Deploy the Contract
Buy Tokens
- Switch over to Account #2
- Enter 1 into the value field
- Select āEtherā from the Dropdown
- 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:
- Try to burn with Account #2
- Observe the Error message
- 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ā¦