Working with Solidity imports

A quick smart contract example

A simple smart contract to say hello.

I was helping a fellow Consensys Academy student and figured I'd post this quick smart contract example.

The question revolved around imports in Solidity. Remix, the online IDE for Solidity development can bring in libraries from github which is a nifty feature. The problem is your contract while working in Truffle will be just a tad bit different due to working on your local dev box.

Here is the example for Remix:

Notice the import line calling out to github.com

Copy to Remix [https://remix.ethereum.org]

pragma solidity ^0.4.24;

import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";


contract Greeter is Ownable {

    string greet = "Hello";

    constructor() public {
        owner = msg.sender;
    }

    function getGreeting() view public returns (string) {
        return greet;
    }

    function changeGreeting(string _newGreeting) public returns (bool) {
        require(msg.sender == owner);
        greet = _newGreeting;
        return true;
    }

}

Now, on your local dev box you will use the following contract instead:

First go into your project and install the OpenZeppelin npm module:

npm install openzeppelin-solidity

Then in your smart contract change the import line like below. This points to the folder structure within node_modules.

pragma solidity ^0.4.24;

import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';


contract Greeter is Ownable {

    string greet = "Hello";

    constructor() public {
        owner = msg.sender;
    }

    function getGreeting() view public returns (string) {
        return greet;
    }

    function changeGreeting(string _newGreeting) public returns (bool) {
        require(msg.sender == owner);
        greet = _newGreeting;
        return true;
    }

}

See the readme for OpenZeppelin for more information:

https://github.com/OpenZeppelin/openzeppelin-solidity