Using Truffle to Create and Deploy Smart Contracts

Gustavo (Gus) Guimaraes
2 min readMay 13, 2017

--

On my last post I went through the steps to deploy the smart contracts the hard way on one’s own Ethereum private blockchain. This one I am going to show the straightforwardness of doing so with Truffle, the de-facto framework to publish smart contracts on Ethereum.

Let’s start by installing truffle

$ npm install -g truffle

Ensure that it is installed

$ truffle
Truffle v3.2.1 - a development framework for Ethereum
Usage: truffle <command> [options]Commands:
init Initialize new Ethereum project with example contracts and tests
...

Then create the project

$ mkdir storage_smart_contract_example
$ cd storage_smart_contract_example
$ truffle init

You will see that truffle created the file structure to us. Go to the contracts folder and create Storage.sol file and then write the code for the smart contract in it.

pragma solidity ^0.4.8;contract Storage {
uint256 storedData;
function set(uint256 data) {
storedData = data;
}
function get() constant returns (uint256) {
return storedData;
}
}

Now go to the migrations/2_deploy_contracts.js and modify it to look like as follows:

var Storage = artifacts.require("./Storage.sol");module.exports = function(deployer) {
deployer.deploy(Storage);
};

Now that we got the basic set up on we need to deploy it to a blockchain. On my previous post I ran my own private network which information on how to do it is found here. For simplistic sake, let’s use testrpc which does the job well for testing development purposes.

On a separate tab, type these commands

$ npm install -g ethereumjs-testrpc$ testrpcEthereumJS TestRPC v3.0.3Available Accounts
==================
...

Then back on the tab where you have the Truffle project run

$ truffle compile
$ truffle migrate

Aaaand the contract is deployed.

Let’s check if we are able to call the contract functions.

$ truffle consoletruffle(development)> Storage.deployed().then(instance => instance.get.call()).then(result => storeData = result){ [String: '0'] s: 1, e: 0, c: [ 0 ] }truffle(development)> storeData.toString()
'0'

Alright, let’s see now we if can set storeData to be value 42.

truffle(development)> Storage.deployed().then(instance => instance.set.sendTransaction(42)).then(result => newStorageData = result)
'0xc5e2f9c9da4cf9f563c8e59073d5b6ca9458f112a6dcfc14aaea7c16a99422d4'
truffle(development)> Storage.deployed().then(instance => instance.get.call()).then(result => storeData = result)
{ [String: '42'] s: 1, e: 1, c: [ 42 ] }
truffle(development)> storeData.toString()
'42'

That it is.

I wrote the code for this blog post in this github repo for reference: https://github.com/gustavoguimaraes/storage_contract_example

--

--