Skip to content

Importing Solidity Contracts

One great feature of Solidity is the ability to import contracts into other contracts.

Github Imports

Did you know? In Remix you can also directly import contracts from github repositories

Let's take the previous contract and split it up into two separate files:

Ownable.sol Token.sol

Create these two files in Remix and copy the following content into the files:

//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");
        _;
    }
}
//SPDX-License-Identifier: MIT

pragma solidity ^0.8.10;

import "./Ownable.sol";

contract Token is Owned {

    mapping(address => uint) public tokenBalance;

    uint tokenPrice = 1 ether;

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

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

}

Let's test this and head over to the Run Tab. You will see again several contracts in the dropdown.

If you select "Token" from the dropdown and deploy it, you'll get the same contract as in the beginning, but better:

  1. The Contracts are split up into smaller logical units
  2. With modifiers we have re-usable small components we can also use in contracts extending the base contract
  3. With separate files we created a better organization of code

Now, let's have a look what happens here behind the scenes!


Last update: May 4, 2022