Skip to content

Inhertiance with Solidity

Now its time to split up our Smart Contract into smaller pieces. We are going to do one Smart Contract that manages the ownership, and another one that does the Token logic:

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.10;

contract Owned {
    address owner;

    constructor() {
        owner = msg.sender;

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

contract InheritanceModifierExample is Owned {

    mapping(address => uint) public tokenBalance;

    uint tokenPrice = 1 ether;

    constructor() {
        tokenBalance[owner] = 100;

    function createNewToken() public onlyOwner {

    function burnToken() public onlyOwner {

    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;


You see, now we have two contracts in one file.

Multiple Contracts in One File

Be careful when compiling and deploying the contract to select the correct one from the dropdown:

Of course, its not ideal to have multiple contracts in one file. That's why we can also separate them and import contracts. Let's do that next!

Last update: May 4, 2022