Anda di halaman 1dari 44

Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.

Global Open Versity


Blockchain DevOps Hands-on Labs Training Manual

Step-By-Step Guide Build & Deploy Ethereum Blockchain Smart


Contract
Kefa Rabah
Global Open Versity, Vancouver Canada
krabah@globalopenversity.org
www.globalopenversity.org

Table of Contents Page No.

STEP-BY-STEP GUIDE BUILD & DEPLOY ETHEREUM BLOCKCHAIN SMART CONTRACT 1

STEP-BY-STEP GUIDE BUILD AND DEPLOY ETHEREUM BLOCKCHAIN SMART CONTRACT 3

Introduction 3
A Quick Smart Contract Example: 3
What you’re Going to Learn 4

Part 1: Setting Up an Ethereum Node 4

Part 2: Establishing Our Own Private Ethereum Network 6


Step 1: Create Data Directory & .json file 6
Step 2: Start your Ethereum peer node. 8
Step 3: Display your Ethereum logs 9
Step 4: Import/Create an Account 9
Step 5: Set Default Account 10
Step 6: Start Private Mining 10
Step 7: Deleting Your Old Blockchain and Creating a New One 12

Part 3: Install Management Tools 12


Step 1: Installations of Tools 13
Step 2: Install Truffle 13
Step 3: Install Ganache 14
Step 4: Install Other Required Tools 14
Step 5: Install Lightweight http-server 15
Step 6: Install Remix 15
Step 7: Install MetaMask 17
Step 8: Install the Mist Browser 18
Step 9: Install the Ethereum Wallet 18
1. Download the Mist Browser & Connect to Our Private Network 19
2. Connecting Mist to our Private Network 19
3. The Basics of Mist 20

Part 4: Hands-on Solidity 24


Step 1: Working with Solidity 24

1
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Step 2: Functions & States 25


Step 3: Building out the Contract 25
Step 4: Let’s Test he Contract on RemixIDE 27

Part 5: Deploying Contracts in Mist 30


Step 1: Start Mist & Deploy our Contract 30

Part 6: Adding a Self-Destruct Function to our Smart Contract 36


Step 1: Updating our Contract File 36
Step 2: Let’s Send Some Ether… 41

A GOV Open Access Technical Academic Publications


Enhancing education & empowering people worldwide through eLearning in the 21st Century
2
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Global Open Versity


Cloud Computing Hands-on Labs Training Manual

Step-By-Step Guide Build and Deploy Ethereum Blockchain Smart


Contract
By Kefa Rabah, krabah@globalopenversity.org April 05, 2018 The Lake Institute

Introduction
So you want to build a smart contract? Perhaps you want to understand how they work, maybe you want
to build your own Dapp, maybe you want to launch the very first billion dollar ICO (sarcasm)... Regardless
of your intentions, learning how smart contracts work is invaluable. The Ethereum platform possesses
enormous potential to create Dapps that could change the way we interact on the web in the decades to
come. While Ethereum deploys smart contracts that work much like a standard blockchain transaction,
they yield a conditional statement that must be met before a function(s) is executed. Smart contracts can
be used for voting, crowdfunding, blind auctions, multi-signature wallets and MUCH more.
https://codeburst.io/build-your-first-ethereum-smart-contract-with-solidity-tutorial-94171d6b1c4b

A Quick Smart Contract Example:


With a smart contract many kinds of contractual clauses can be made partially or fully self-executing, self-
enforcing, or both. The main motive of smart contracts is to provide security that is better to traditional
contracts and to cut other transactional costs associated with traditional contracting.

Bob has his own scrap metal depot business in the United States; Eric is his iron scrap supplier. Eric is
based out of China. Bob and Eric have a GREAT business relationship. They trust each other and have
been doing business for a long time. Both have booming businesses, and Bob in particular sells out of iron
scrap on a routine basis. Bob deploys a contract where once his iron scrap inventory reaches a certain
range, he automatically sends an order out to Eric for X lbs of iron scrap at Y ether per ton. Eric agrees to
the arrangement and accepts Bob’s payment in ether right away. Eric gets to work right away and starts
fulfilling Bob’s order. Eric can exchange his ether at a local exchange online for Yuan for a tiny fee and it’ll
be processed instantaneously. Whether Eric decides to hold ether or convert to Yuan is his choice, but
either way he can now put this capital to work right away!

Both parties are ecstatic! Typically Bob has to contact his bank and request a money wire to be sent to
Eric’s bank in China. It typically takes ~48 hours to process the wire transfer, at which point Eric will have
to wait another few days for his bank to clear the payment. Not only that, Bob’s bank is going to charge
him a fee for wiring money to Eric… Time and money out the window. To make matters worse, both
parties have to deal with the headache of foreign exchange, turning the US Dollars into Chinese Yuan.

3
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

What you’re Going to Learn


As the saying goes, “you have to crawl before you can walk”. Before we get to deploying our first contract
it’s important we learn a few basics. More importantly, I’d like to point out that Ethereum’s platform
launched in 2016. While still in its infancy, now is the perfect time to start learning about smart contracts.

In this tutorial we’re going to learn about:


• Ethereum Nodes
• Building A Private Blockchain Network
• MetaMask Browser Plug In
• Mist Browser
• Ethereum Wallet
• Web3 Ethereum JavaScript API
• Remix Web Browser IDE
• Geth (Go Ethereum) Command Line Interface
• Solidity Programming Language

Important: If at any point you run into an issue with running a program, try launching it as administrator by
right clicking on it and selecting “Run as administrator”.

Part 1: Setting Up an Ethereum Node


In the simplest form, an Ethereum node is any device that is running the Ethereum protocol (blockchain).
While nodes are typically running on desktops & laptops, development for mobile is ongoing. When we
connect to the Ethereum protocol we are on the Ethereum blockchain network and are running a node. By
running an Ethereum node we can connect to other nodes in the network, have direct access to the
blockchain, and even do things like mine blocks, send transactions, and deploy smart contracts.

Smart contracts on Ethereum network run on something called Ethereum Virtual Machine (EVM) which for
visualization purposes is similar to JVM in Java. The Decentralized Applications (DApps) running on the
Ethereum network are nothing more than a bunch of Complex Smart Contracts.

Nodes are written in Go (Go Ethereum/Geth), C++, and Python. In this tutorial we’re going to stick to the
most popular of the three, Go. Important to also note that by downloading Geth we are downloading the
ENTIRE Ethereum blockchain. That said; make sure you have ~35GBs of storage on your hard drive
before continuing.

1. Visit the Go Ethereum website and install Geth: Visit here: https://geth.ethereum.org/downloads/

2. Download the latest release of Geth (currently 1.8.2) for Windows, make sure you download the 64-bit
version.

3. Once your download is complete, double-click the installer and click “I Agree” to accept the license.

4
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

4. When done with installation, open up command prompt (I’ll be using Git Bash, which you can
 download from https://git-scm.com, and do make sure to add to PATH variables during installation)
and navigate to the Geth directory by typing "cd C:\Program Files\Geth":

 Fig. 1

5. Begin syncing to the Ethereum blockchain by typing “Geth”. Because this is your first sync you’ll
download the ENTIRE blockchain from other peers. This will take some time so get comfy…

Fig. 2

6. Excellent! You’re now running an Ethereum Node. Let the fun begin…

7. You’re done with this section.

5
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Part 2: Establishing Our Own Private Ethereum Network


Now that we have access to the Ethereum protocol via our node, we’re going to setup our own private
server to develop & deploy our smart contract. Note that none of this will actually be deployed on the
Ethereum blockchain, instead we’ll deploy on our own blockchain. We’ll start by initializing the very first
block in our blockchain, the genesis block ("genesis.json").

Step 1: Create Data Directory & .json file


1. Create a new folder on your desktop called “Private Chain”.

2. Open command prompt in this folder and create a data directory folder for our chaindata by typing
"mkdir chaindata", if you’re using git cmd or just add new folder from Windows. You can open a
command prompt in this folder by holding shift and right clicking, then select “open command window
here”.

3. Next, we need to create and save our ("genesis.json").block in our Private Chain folder, as the
genesis block will be used to initialize our private network and store data in the data directory folder
“chaindata”.

4. Open up notepad, copy & paste the code below into a new file called ("genesis.json").and save
this file in our Private Chain folder.

Learn more about ("genesis.json").parameters visit the link


below: https://ethereum.stackexchange.com/questions/2376/what-does-each-genesis-json-parameter-
mean

{
"coinbase" : "0x0000000000000000000000000000000000000001",
"difficulty" : "0x20000",
"extraData" : "",
"gasLimit" : "0x2fefd8",
"nonce" : "0x0000000000000042",
"mixhash" :
"0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash" :
"0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp" : "0x00",
"alloc": { "0xedeb444469a46300bcab856338d75fa589b86013": {"balance":
"111111111"},
"0x0000000000000000000000000000000000000002": {"balance": "222222222"}
},
"config": {
"chainId": 15,
"homesteadBlock": 0,
"eip155Block": 0,

6
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

"eip158Block": 0
}
}

Fig. 3

5. Now we want to initialize our private network in the chaindata directory by using our genesis.json
file. We’re going to tell Geth we want the data directory in the “chaindata” directory and where the
"genesis.json".file can be found (make sure "genesis.json".is NOT in chaindata folder) by
entering the code below into our command line pointing to the Private Chain folder. (or simply right-
click on the Private Chain folder on the Desktop and open with Git CMD to access Fig. 4.

geth --datadir=./chaindata/ init ./genesis.json

Fig. 4

Note: you should then see that the genesis state was successfully written.

7
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

6. Now we can start Geth and connect to our own private chain. As you will see the geth.ipc endpoint
socket connection will be opened and so will port 30303.

geth --datadir=./chaindata/

Fig. 5

Note: whenever we start Geth the IPC endpoint will open, which is used to process connections to
Geth with programs like MetaMask, Ethereum Wallet, Mist, or for opening the Geth Javascript API
console. We will discuss all of these next.

7. Done! We now have successfully established our very own private geth network!

8. You’re done with this section.

Step 2: Start your Ethereum peer node.


Networkid helps ensure the privacy of your network. You can use any number here (where we used
“15”), but other peers joining your network must use the same one.

8
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

geth --datadir=./chaindata/ --networkid 15 console 2>> myEth.log

1. From the terminal enter the following command

Output should look like this:

Fig. 6

Note: this is the geth JavaScript console. Any command with the symbol > should be typed here.

Step 3: Display your Ethereum logs


2. Open another terminal window

cd chaindata

Type

tail -f myEth.log

Output should look like this:

Step 4: Import/Create an Account


If you allocated ETH in the Genesis file, import the corresponding account by dragging the UTC file into
the "myDataDir/keystore" directory and skip to step 5.

From the geth console, we’ll need to create a new account and a new password by typing in
whatever you want. You will have to type your new password twice.

3. In the geth JavaScript console, create an account:

> personal.newAccount("<YOUR_PASSPHRASE>")

4. Type and enter password twice:

9
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

> personal.newAccount()

"0xedeb444469a46300bcab856338d75fa589b86013"

Note: do not forget this passphrase! You will be typing this a lot, so for this test network you can keep
it simple.

5. Save this address somewhere and exit by typing “exit” and hitting Enter.

Step 5: Set Default Account


6. Now from the geth console to check your default account run:

> eth.coinbase

Note: if this address is the same as the one from step 4, skip the rest of step 5.

OR
To set your default account, type

> miner.setEtherbase(web3.eth.accounts[0])

Step 6: Start Private Mining


Mining on the public Ethereum network is a complex task as its only feasible using GPUs, requiring an
OpenCL or CUDA enabled ethminer instance. For information on such a setup, please consult the
EtherMining subreddit and the Genoil miner repository.

In a private network setting however, a single CPU miner instance is more than enough for practical
purposes as it can produce a stable stream of blocks at the correct intervals without needing heavy
resources (consider running on a single thread, no need for multiple ones either).

7. From the geth console, check your balance, run:

10
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

> eth.getBalance(eth.coinbase)

8. To start mining from geth console, run:

> miner.start()

OR exit geth console.

Now start a geth instance for mining, run it with all your usual flags, extended by:

$ geth --datadir=./chaindata/ --networkid 15 --mine --minerthreads=1 --


etherbase=0x0000000000000000000000000000000000000001

Note: look at the terminal window; you should see some mining action in the logs. Check your
balance again and it should be higher.

9. You should see the mining process going soon, as shown in Fig. 7.

Fig. 7

Note: if it stops in this line

Done generating DAG for epoch 0

It means that you set the mining difficulty(the “difficulty” parameter in genesis file) too high so you may
have to wait longer.

11
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

10. After sometime you may run out memory in you don’t have sufficient memory in your system –
Blockchain mining operation is a memory intensive operation.

11. To end/stop mining, from the geth console type

> miner.stop()

12. You’re done with this section.

Step 7: Deleting Your Old Blockchain and Creating a New One


13. Execute these commands to clear out the old blockchain data and restart geth:

cd eth-data
rm -rf chaindata dapp history nodekey
cd ..

14. You’re done

Part 3: Install Management Tools


The tools we will use
The most prominent tools at the moments are:
• Truffle: A development environment, testing framework and asset pipeline for Ethereum. In other
words, it helps you develop smart contracts, publish them, and test them, among other things. You
can read the docs of the Truffle suite for more informations.
• Ganache: It was called TestRPC before, if you have read a tutorial from a few months ago, chances
are they use TestRPC with Truffle, but it was renamed upon the integration of TestRPC within the
Truffle Suite. What Ganache does is simple, it creates a virtual Ethereum blockchain, and it generates
some fake accounts that we will use during development.
• Mist: It’s a browser for decentralized web apps. It seeks to be the equivalent of Chrome or Firefox, but
for Dapps. It’s still insecure and you shouldn’t use it with untrusted dapps as of yet.

12
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

• Ethereum wallet: It’s a version of Mist, but only opens one single dapp, the Ethereum Wallet. Mist and
Ethereum Wallet are just UI fronts. And we need a core that will connect us to an Ethereum
blockchain(It could be the real Ethereum blockchain, or a test one).
• Geth: Is the core application on your computer that will connect you to a blockchain. It can also start a
new one (in our case we will create a local test blockchain), create contract, mine ether etc.

We will start by using Truffle and Ganache, and then use Truffle with geth and Mist.

Step 1: Installations of Tools


1. The requirements for this tutorial are that you know what is and how to use a command-line tool, and
you are a bit familiar with NPM, which we must download and install first. At the time of writing this
article, we used “node-v9.8.0-x64.exe”

Step 2: Install Truffle


2. Open up a command-line, and type the next part:

npm install -g truffle

3. If all is OK, then type command truffle,

13
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

4. If something goes wrong we advise you to read more on Truffle’s docs.

Let’s start Truffle


5. First, create a new folder, and type the next line:

truffle init

6. It will initialize an empty truffle project.

Step 3: Install Ganache


7. Then, install Ganache’s command-line interface:

npm install -g ganache-cli

8. If all is OK, then type command ganache-cli,

9. If you are unsure about something, here is Ganache’s Github page.

Note: there is a GUI for Ganache, but because we are such haxors, we will use the CLI.

Step 4: Install Other Required Tools


10. Next we need to install some of the tools required:

14
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

npm i -D webpack react react-dom babel-core babel-loader babel-preset-react


babel-preset-env css-loader style-loader json-loader web3@0.20.0

Note: these are all the tools that we need to create the front-end of the dapp. There are a lot of
dependencies because we’ll be creating a web application with the latest version of javascript and
React.js.

Mainly we installed webpack, react, babel and web3.

Note that we are installing the version 0.20.0 of web3 with web3@0.20.0 because the latest version
of web3, the 1.0 is still in beta and it’s unstable.

Step 5: Install Lightweight http-server


This a lightweight server that we’ll use to host your web app locally as you develop on localhost:8080.

11. Type the following command to install the server:

npm i -g http-server.

Step 6: Install Remix


12. Install npm and node.js (see https://docs.npmjs.com/getting-started/installing-node), then do:

13. Remix-ide has been published as an npm module:

npm install remix-ide -g

15
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Or if you want to clone the github repository:

git clone https://github.com/ethereum/remix-ide.git


cd remix-ide
npm install
npm run build && npm run serve

14. Start the Remix IDE

remix-ide

Note: Remix IDE requires Apache (http) server to be in place.

Note: the "ballot.sol" is a default file that come with Remix IDE. So go ahead and overwrite it.

15. To stop the server, issue ^C command:

16. You’re done with this section

16
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Developing Contract using Remix


17. Run npm start and open http://127.0.0.1:8080 in your browser.

18. Then open your text editor and start developing. The browser will automatically refresh when files
are saved.

Note: most of the time working with other modules (like debugger etc.) hosted in the Remix repository
is not needed. But in case changes have to be made in that repository too, the following command will
help you link Remix with your local remix-ide repository:

19. After npm install run also:

npm run pullremix

npm run linkremixcore

npm run linkremixlib

npm run linkremixsolidity

npm run linkremixdebugger

20. You’re done with this section

Step 7: Install MetaMask

What is MetaMask Exactly?


MetaMask is both an Ethereum browser and a wallet. Through MetaMask you can interact with Dapps and
smart contracts on the web without having to download the blockchain or install any software. You simply
add MetaMask to chrome as an extensions, create a wallet, and deposit ether. While currently only
available for Chrome, expect to see a launch for Firefox in the near future.

The biggest downfall to Metamask is that like any online wallet, you must trust MetaMask. The possibility
of MetaMask being hacked or leaking your private key does exists, for your information is stored online.

You can download MetaMask here:


https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en

17
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 8

Step 8: Install the Mist Browser


Mist is an electron application, meaning that its a desktop hybrid app with a web interface as well. This
allows for faster development and changes of the Mist interface and helps with the browser part of Mist.
Its important that you recognize Mist is in beta, so expect to run into a few issues here and there.
Mist is powerful in that it includes a Geth node that runs in the background upon launch; a connection to
the Ethereum blockchain is made right away. But because we want to practice developing a smart
contract, we are going to run a node on our private network and will not need Mist to connect to the
default Geth node.

Read more about Mist: https://github.com/ethereum/mist/wiki

Step 9: Install the Ethereum Wallet


The Ethereum Wallet is just a Mist implementation that can only access a single Dapp — the wallet dapp,
this is due to missing features in Mist. The Ethereum Wallet is written in pure HTML and Javascript code,
makes use of web3.js to manage your accounts, and runs inside of the Mist browser. You can also
download a standalone version if prefered. The wallet is not yet official released, bugs will exist.

Ethereum Wallet: https://github.com/ethereum/meteor-dapp-wallet

18
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

1. Download the Mist Browser & Connect to Our Private Network


Let’s take a second to download the Mist browser so we can connect with our private network. Navigate to
the Mist download page and download the latest version of the Mist installer —
 https://github.com/ethereum/mist/releases. At the time of writing, we downloaded file "Mist-installer-0-9-
3.exe". Double-click it, run, accept the license to complete the installation.

Feel free to open Mist and mess around with the UI to get a better feel for things, but we’ll be opening up
Mist shortly.

2. Connecting Mist to our Private Network


Now that we knocked out initializing our private network with the genesis block, we can open a command
line in our Private Chain folder and tell Geth to connect to our datadir.

1. Type the following command into command prompt:

geth --datadir=./chaindata/

Fig. 9

2. Geth will now start running and once we open Mist the geth.ipc endpoint will open; Mist will then
make the connection to our private network. Make sure Mist is connected by confirming "Private-
Net" exists in the upper right corner of the Mist launch window.

Fig. 9a
19
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 9b

Note: ignore “Looking for peers”, remember we’re on our own network so you’ll never connect to
any other peers.

3. The Basics of Mist


Let’s open up Mist and familiarize ourselves with a few things:

Fig. 10

20
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

1. From Fig. 10, at the top we can see our tool bar. Navigating to "Ethereum Node" under the
"Develop" tab will show that we are NOT connect to Geth, as it is grayed out — we’re running our
own network. Much like Chrome, under the "Develop" tab we can also access "Developer Tools"

Fig. 11

2. On the left side of the Mist browser we can see the various different tabs that are open, just like any
other browser. By clicking on the green box we are opening the Ethereum Wallet. The wallet is a
distributed application that makes it incredibly easy to interact with the JavaScript interface of Go
Ethereum.

3. As you can see we’re connected to the Ethereum wallet through https://wallet.ethereum.org/ , don’t
forget that Mist is simply a browser. From here we can do things like see past transactions, send
ether, and even deploy or watch contracts.

4. Under the “Wallets” tab we can see our accounts, add new accounts, create wallet contracts (like
single owner accounts, multi-signature wallet contracts, and even import wallets), and also examine
past transactions.

5. Let’s create an account by clicking “Add Account” (synonymous with “wallet”), then “Create new
account”, and enter a super safe password (even though this is an account on our private network
and will not be connected to the actual Ethereum network, it’s a good habit). Click “OK” and create
your wallet

21
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 12a

Fig. 12b

22
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 13

6. Under the “Send” tab we can send ether from one wallet to another, or even from a wallet to a
contract. As you can see below, before hitting send we’re given the option to set the gas (fee) for our
transaction. All transactions require some amount of gas to incentivize processing. Depending on how
fast we want to get the transaction processed and approved by the blockchain, we can adjust the
amount of gas, see Fig. 14.

23
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 14

7. Lastly, under the “Contracts” tab we can deploy new contracts, watch existing contracts, and watch
previously created tokens. Here is where we will create and deploy our “Hello World!” contract.

Part 4: Hands-on Solidity


For those of you familiar with Javascript I’m sure you’ll take notice to the overlaps with Solidity. Much like
JS, Solidity is a contract-oriented, high-level language that is designed to target the Ethereum Virtual
Machine (EVM). The code is statically typed, supports inheritance, libraries and complex user-defined
types among other features.

Step 1: Working with Solidity


1. In our “Hello World!” contract we’re going to create a state variable called counter and assign it a
starting value of 5. Then we’re going to create a function that increases our state variable by 1, a

24
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

function that decreases the variable by 1, a function that returns our counter, and lastly a function that
will destroy the contract.

2. The first bit of code that we’ll type into Remix is the source code version. At the time of writing this
Solidity 0.4.16 is the latest version that is recognized by Mist. We’re going to call this version by typing
at the top of our contract:

pragma solidity ^0.4.16;

The keyword pragma is called that way because generally pragmas are instructions for the compiler about
how to treat the source code.

More info on Solidity can be found here in the docs: https://solidity.readthedocs.io/en/develop/index.html

Step 2: Functions & States


Looking at the bare bones of a smart contract we can see that contracts are merely collections of code (its
functions) and data (its states) that correspond to a specific contract address on the blockchain.

3. For example, the line uint256 counter; sets the variable counter of type uint256 (unsigned integer of
256 bits). It can now be thought of as a single slot in a database that can be pulled by calling the
function of the code that manages the database. We can even set a value for the
variable counter while also setting the type as uint256.

uint256 counter = 5;

4. State variables are typically outside of functions, making them global variables, and usually are the
first few lines in our contract. We’ve now managed to set our variable counter as an uint256 and a
value of 5. If we want to call a function to increase the value of counter by 1, we’re going to create a
function (we’ll call it “add”) and tell it to add 1 to counter .

function add() public {


counter++;
}

After calling the function "add()", counter will have a value of 6.

Step 3: Building out the Contract


5. Let’s create our “Hello World!” contract by first creating a contract called such:

pragma solidity ^0.4.16;


contract HelloWorld {

25
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

6. We can now include that counter state variable that we talked about early. Remember, we’re going to
assigning this state variable as an unsigned integer of 256 bits (unsigned meaning that this type can
only be positive integers, not positive and negative. 256 bits in size is a design of the Ethereum Virtual
Machine). Oh yeah, also set it to a value of 5.

pragma solidity ^0.4.16;


contract HelloWorld {
uint256 counter = 5;

7. Go ahead and see if you can create 2 functions below this state variable assignment. We need 1). a
function that increases counter by 1 and 2), and a function that decreases the counter by 1.

pragma solidity ^0.4.16;


contract HelloWorld {

uint256 counter = 5; //state variable we assigned earlier


function add() public { //increases counter by 1
counter++;
}

function subtract() public { //decreases counter by 1


counter--;
}

Note: you’ll see from the code above that we assigned both functions the modifier public. Since
Solidity knows two kinds of function calls (internal ones that do not create an actual EVM call — also
called a "message call" — and external ones that do), there are four types of visibilities for
functions and state variables. Functions can be specified as
being external, public, internal or private, the default is public . Aside from the fact that
Remix will throw a warning message stating that no visibility is specified and it’s defaulting to public,
typing out the function visibility is a good habit to get into. It will allow us to better understand the
contract settings when evaluating our code.

8. We’re getting close, but not quite there. Our state variable can change depending on the function we
call, but we need a function that will output the value of counter. Try creating a function called
"getCounter()" that will return counter. This will be a read only action, so we need to tell our
function that we’ll be returning a constant. Additionally, when returning a state variable we must tell
our function the type that is being returned, in this case we’re returning a uint256 as discussed earlier.
26
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

pragma solidity ^0.4.16;


contract HelloWorld {

uint256 counter = 5; //state variable we assigned earlier


function add() public { //increases counter by 1
counter++;
}

function subtract() public { //decreases counter by 1


counter--;
}
function getCounter() public constant returns (uint256) {
return counter;
}
}

Note: while calling a functions on the Ethereum network will require a small amount of gas to be
spent, no gas is required when returning a constant function.

Awesome! So now we have a contract that allows us to change the value of our global variable counter .
We can also increase it by 1, decrease it by 1, and return the value of our counter whenever we want.
Let’s give it a whirl…

Copy and paste the contract code snippet into the Remixeditor
Remix is the tool that helps us write and compile smart contracts written in Solidity to bytecode (computer
generated gibberish) that Ethereum Virtual Machine can understand and process.

9. Start the Remix IDE

remix-ide

Note: Remix IDE requires Apache (http) server to be in place.

Step 4: Let’s Test he Contract on RemixIDE


10. So your code should be in Remix and “Auto compile” should be checked by default under the
“Compile” tab.

27
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 15

11. Make your way over to the “Run” tab.

Note: Default settings will have the environment set to JavaScript VM, an account will be selected,
gas limit will be 3000000, and your gas price & value will be 0.

Fig. 15

28
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

12. Click on “Create” under your “Run” tab. You should now see your contract created just like below.

Fig. 16

Notice the amount of ether on our account ticked down slightly from 100 after creating the contract.

13. Right off the bat you can see the 3 functions that we had created — “add”, “substract”, and
“getCounter”. You can also see that our state variable has a value assigned to it of 5. Now, click “add”
to increase our counter by 1. Then go ahead and click “getCounter” to call our newly
modified counter . You should see the value has been updated to 6. Try it again for “subtract”.

29
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 16

14. Give yourself a pat on the back. You just done did it. Contract created!

15. We’re done with this section.

Part 5: Deploying Contracts in Mist


Now that we’ve tested and confirmed our code in Remix, let’s start up Mist (make sure it’s connected to
the Private Network) and deploy it on our private network.

Note 1: before we can proceed any further, we need to have ether in our wallet. We can mine for
ether on our private network by running the miner. You can do this from the Geth JavaScript console.
Fortunately, we had done some mining in our previous Hands-on Labs, check it out from here:

Note 2: if not, then open up ANOTHER geth command prompt window pointing to your private
network folder (C:/users/name/desktop/privatenetwork3) and type geth attach . Hit
enter. You will see a Geth JavaScript console generated and you can now enter commands into Geth
directly. Let’s begin mining for some ether by typing miner.start();. You will see that the console
returns "null" and mining has begun! Take a look at your wallet on Mist, you’ll see increments of 5
ether continuously added to your wallet. You can stop the miner anytime by typing miner.stop();
in console…or you can continue to mine fake ether…whatever makes you happy!

Step 1: Start Mist & Deploy our Contract


1. Start Mist and Navigate to the “Contracts” tab of the Ethereum Wallet in Mist. (Note: as you can
observe from Fig. 17, we have sufficient ether rom both account 1 and 3).

30
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 17

2. Then select “Deploy New Contract” and paste our code from Remix into the source code box.

Fig. 18

31
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

3. Now move back to the “Contracts” tab, “Deploy New Contract”, make sure our code is in the
source code box. To the right of the source code box select "Hello World" as the contract to
deploy. as shown in Fig. 20.

Fig. 20

4. Next, scroll down and then click on the Deploy button, as shown in Fig. 21.

Fig. 21

5. After you have entered your password (Note: you the password you used when you initially installed
Mist), and then click on the SEND TRANSACTION button make your way back over to the wallets
tab. It will take a while to process the transaction.

32
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 22

6. When done processing the transaction, scroll down to “Latest Transactions” and you will see the
contract we just deployed. You’ll also notice that the contract shows 0 of 12 confirmations and is stuck
in a perpetual state of "creating contract".

Fig. 23

Note: the reason our contract hasn’t been fully created is that there are no miners on our network
confirming our newly deployed contract.

33
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

7. Start mining again in the Geth JavaScript console we opened earlier ( miner.start(); ), or open
geth console start mining:

$ geth --datadir=./chaindata/ --networkid 15 --mine --minerthreads=1 --


etherbase=0x0000000000000000000000000000000000000001

Fig. 24

8. Once we start mining again we will see that the number of confirmations will start to tick up, eventually
fully deploying our contract, as shown in Fig. 25.

Fig. 25

9. From Fig. 25, click on the contract name. From here we can do all sorts of things, as shown in Fig. 26.
That is, we can transfer ether to the contract, copy the contract address, generate a QR code to be
scanned, get the contracts interface (ABI), and even execute contract functions.

34
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 26

10. As you can see our “Hello World” contract is displaying our getCounter() function with the
counter state variable of 5. Make your way over to “select function” and select either "add" or
"subtract" function. Once selected, click on the “EXECUTE” button. Do not forget, we’re the only
ones on our private network so we need to confirm the transaction by running our miner!

Fig. 27

11. And there we have it! Our contract has executed the subtract function and returned a value of “4”, as
shown in Fig. 28. We now have a live smart contract on our private Ethereum blockchain network that
can be interacted with on Mist!

35
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 28

12. You’re done with this section.

13. Woooooosh – You’re done with this Hands-on Labs.

Part 6: Adding a Self-Destruct Function to our Smart Contract


As mentioned above, when contracts are deployed they are officially added to the Ethereum blockchain
and anyone with the contract address can interact with the contract, to a certain degree that is. What if we
as the owner decide we want to remove the contract from the blockchain? Fortunately, Solidity offers an
incredibly easy, maybe perhaps too easy, method for putting an end to the contract. We can perform the
selfdestruct operation. When we selfdestruct the contract, all remaining Ether stored at the
contract address is sent to a designated target and the contract is no more.

Step 1: Updating our Contract File


While we want to have the optionality for destroying the contract, we want to make sure that such
operation can only be performed by the creator of the contract. It could be CATASTROPHIC to neglect
assigning selfdestruct privileges to a certain person(s). We need to first tell our contract who the
owner of the contract is, which is the msg.sender . Go ahead and set the state variable owner as
msg.sender . Because the msg.sender is associated with an address, we also need to tell Solidity that
the state variable is going to be assigned as an address.

pragma solidity ^0.4.16;


contract HelloWorld {

uint256 counter = 5; //state variable we assigned earlier


address owner = msg.sender; //set owner as msg.sender
........
}

36
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

We’re going to call the self-destruct function “kill” and are also going to create a conditional if statement
to ensure that the person executing the kill function is in fact the owner. We will also set
selfdestruct(owner); to tell the contract to send all contract funds back to the owner of the contract.
Let’s also rename the "Hello_World.sol" to "Helow_World2.sol" for clarity purposes only, and the
contract to "HelloWorld2", respectively.

pragma solidity ^0.4.16;


contract HelloWorld2 {

uint256 counter = 5; //state variable we assigned earlier


address owner = msg.sender; //set owner as msg.sender
function add() public { //increases counter by 1
counter++;
}

function subtract() public { //decreases counter by 1


counter--;
}
function getCounter() public constant returns (uint256) {
return counter;
}
function kill() public { //self-destruct function,
if(msg.sender == owner) {
selfdestruct(owner);
}
}
}

We can now go back into Mist and redeploy a new contract with the kill() function added. To see the
kill() function in full force, we’re going to deploy the new contract, send ether to the contract, and then
initialize kill() and see our ether return back to our wallet. Likewise, we also need to create a function
that is executed whenever our contract receives Ether. In order to receive Ether, a fallback function must
be marked payable in the contract. If such a function does not exist, the contract cannot receive Ether. A
contract can have exactly one unnamed function, which is going to be the unnamed function that we’ll
mark as payable . Add the function below to our contract, the function can be placed below the kill()
function.

function () public payable {

1. Great, now our contract can receive Ether from any wallet that has the contract’s address! Go ahead
and select the "HelloWorld2" contact and then scroll down and click “Deploy” to deploy our new
contract and submit your password.

37
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 29

2. Do make sure your miner is running to confirm the transaction, if not, head back to geth console and
start the mining operation. (Note: remember to provide password when requested)

38
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 30a

Fig. 30b

3. Once complete, as shown in Fig. 31

Fig. 31

4. Go to ”Contract” tab, and then from here click the HelloWorld2 contract as shown in Fig. 32

39
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Fig. 32

5. Next, click on the “Copy address”, an shown in Fig. 33.

Fig. 33a

Note: you will get a warning message reminding you that you’re on a test network, select “copy
anyway”. You’ll alerted by copy complete alert!

Fig. 33b
The address we have copied:
0x811C82BaA192850878843b0F06F3A091089D3ED4

40
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Step 2: Let’s Send Some Ether…


6. Excellent, we’ve copied our contract’s address, which is:

0x811C82BaA192850878843b0F06F3A091089D3ED4

7. Now we can send over some Ether to test our kill() function. Click on the “Send” tab and copy the
contract address into the “TO” field. Enter in however much ether you’d like to send for this test, I’m
going to send over ~2,000 Ether, see Fig. 34.

Fig. 34a

Note: you know the routine by now…scroll down and click “SEND”, as shown in Fig. 34b. Next, turn
on your miner, and wait for the transaction to get processed.

Fig. 34b

41
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

Note: you may get a warning, that your transfer might not succeed as shown in Fig. 34c, just ignore
and proceed with the transaction anyway.

Fig. 34c

Note: the process should proceed as shown in Fig. 34d.

Fig. 34d

Note: when the process completes, you should notice that your Main account has -2,000, as shown in
Fig. 34e.

Fig. 34e

Note: nou should notice right away your wallet no longer holds the ether we sent to the contract.
Open the contract AGAIN under your “Contracts” tab, you’ll see that the contract now has ether
attached to it. Select the kill function under the “Select function” drop down and go ahead and self-
destruct that bad boy. Enter your password, crank that miner. After 12/12 confirmations have been

42
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Ethereum Blockchain Smart Contract v1.2

processed, your wallet will be restored with the Ether we sent to the contract. Now the contract is
inoperable, but the contract’s history does still exist on the blockchain.

Fig. 35

8. You’re done with this section.\

9. You’re also done with this Hands-on Labs.

Congratulations!
Congrats on finishing the tutorial and having deployed (and killed) your very first smart contract! There is a
lot that was covered here, surely something’s are still a bit of a head scratch. That’s okay! You now know
how to open a private network using Ethereum blockchain and mined some ether and setup a working
smart contract, write Solidity code, deploy in Mist & Remix, and interact with it. Lots of details and tools,
but hope that some of these made sense, and gave you a little more clarity on how blockchain smart
contract work. Plenty more to do and learn now that you know the basics.

A Creative Common Publication:

-----------------------------------------------
Kefa Rabah is the Founder of The Lake Institute. Kefa is knowledgeable in several fields of Science &
Technology, Information Security Compliance, Blockchain Technology, Distributed Ledger Technology
(DLT) and Project Management, and Renewable Energy Systems. He is also the founder of Global Open
Versity, a place to enhance your educating and career goals using the latest innovations and
technologies.

Fellow us on Twitter: The Lake Institute and Kefa Rabah

A Globalopenversity Open Access Technical Academic Publications


Delivering Cutting-edge Technology at your Fingertips in the 21st Century

43
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org

Anda mungkin juga menyukai