You are on page 1of 7

Follow Sign in Get started

HOME FILTER ▼ ABOUT ITNEXT WRITE FOR ITNEXT MEETUP SUMMIT LINKIT

Alt Street Follow


We are Blockchain and Cryptocurrency experts.
Mar 4 · 7 min read

Create your rst Ethereum dAPP with


Web3 and Vue.JS (Part 1)
Click here to share this article on LinkedIn »

Welcome to yet another tutorial! In this tutorial we’ll dive into creating a
simple reactive decentralized application using Ethereum, Web3js, VueJS and
Vuex. You will likely need some understanding of javascript and web
applications to really enjoy this tutorial. If you don’t know Vue don’t worry,
we will cover the basics brie y while making our application.

Our application will be a simple one. A user will be able to bet ethers on a
number between 1 and 10. When the user guesses correctly he gets his payout
x10 (minus the cut for the house).

In this rst part we will go over our project setup and the creation of our
smart contract. In the second part we’ll introduce the web3js API and
VueJS/Vuex and in part three we’ll connect the dots and connect our
application to our contract. Follow along, enjoy the ride, it’s gonna be great.

Here’s what our nal application will look like:

Our nal application

. . .

Prerequisites
Due to the simplicity of the project we will not be using tru e. We will write
and deploy our smart contract onto a test net with MetaMask and Remix
(https://remix.ethereum.org).

The rst thing we’ll need is nodeJS and NPM, get them here and follow the
installation steps for your OS: https://nodejs.org/en/. To check if node has
installed correctly run the following commands in a terminal window:

node -v
npm -v
Next up, get metamask if you do not have it already: https://metamask.io/

Our last prerequisite is vue-cli, this will help us easily set up a VueJS project:

npm i vue-cli -g

. . .

Project set-up
We will write and deploy our simple smart contract using remix and deploy it
to the Ropsten test net through our metamask add-on. All we need to interact
with it in our front-end application is the contract address and ABI (An ABI
de nes how data structures or computational routines are accessed in
machine code).

Our front-end will be a vueJS application that we will generate by using the
vue-cli. We’ll also be using web3 to communicate with our contract. To create
the backbone for our client application follow these easy steps:

1. Open up a terminal and change directory to where you want to create the
app.

2. In the terminal window type the following command to create our project
and go through the wizard by spamming ‘enter’:

vue init webpack betting-dapp

3. Now we will go into our project folder and install web3, vuex and font-
awesome:

cd betting-dapp
npm i web3@^0.20.0 vuex font-awesome -s
//To start the dummy project generated by the vue-cli use 'npm
start'

*We are not using web3 1.0.0 beta because it is not compatible with MetaMask as
of writing.*

. . .

Writing our Smart Contract


Before we start writing code like headless chickens we must rst analyze
which components we need:

1. We need to know the owner of the contract and have an access modi er
(we will leave changing owner out of it for simplicity)

2. The owner of the contract can destroy the contract and retrieve the
balance

3. A user can bet a number between 1–10

4. The owner needs to be able to set a minimum bet amount and house edge
on contract creation (not changeable after creating for simplicity)
Steps one and two are very easy, we’ve also added comments so you have no
trouble following along. Fire up Remix and let’s get to work (gist link at the
end of article):

pragma solidity ^0.4.10;

contract Ownable {
address owner;
function Ownable() public {
//Set owner to who creates the contract
owner = msg.sender;
}

//Access modifier
modifier Owned {
require(msg.sender == owner);

}
}

contract Mortal is Ownable {


//Our access modifier is present, only the contract creator can
use this function
function kill() public Owned {
selfdestruct(owner);
}
}

First we create the contract Ownable, it’s constructor function Ownable() will
be called upon creation and set the state variable ‘owner’ to the address of the
creator. We also de ne an access modi er that will throw an exception when
the caller of a function we attach it to is not the contract owner.

We pass on this functionality into our Mortal contract (Mortal inherits from
Ownabe). This has one function that allows the contract owner (access
modi er) to destroy the contract and send the remaining funds back to him.

Did you manage to get this far? You’re doing great! We’re almost ready with
our contract.

Now for step 3 and 4 we will create our Casino contract:

The rst thing we’ll need is a minBet and houseEdge that can be set upon
contract creating. This is done by passing parameters to the constructor
Casino(). We will make our constructor payable so we can preload our
contract with some Ether on deployment. We’ll implement our fallback
already as well:

contract Casino is Mortal{


uint minBet;
uint houseEdge; //in %

//true+amount or false+0
event Won(bool _status, uint _amount);

function Casino(uint _minBet, uint _houseEdge) payable public {


require(_minBet > 0);
require(_houseEdge <= 100);
minBet = _minBet;
houseEdge = _houseEdge;
}

function() public { //fallback


revert();
}
}

This won’t do much yet so next up we’ll add our function to bet a number.
This function will generate a random number (not in a secure way!), then
calculate and send the amount won. So below your fallback function add the
following:

function bet(uint _number) payable public {


require(_number > 0 && _number <= 10);
require(msg.value >= minBet);
uint winningNumber = block.number % 10 + 1;
if (_number == winningNumber) {
uint amountWon = msg.value * (100 — houseEdge)/10;
if(!msg.sender.send(amountWon)) revert();
emit Won(true, amountWon);
} else {
emit Won(false, 0);
}
}

To generate a random number between 1–10 we take the current block


number and take the modulus (division remainder) of the current block
number. This will always result in a number between 0–9 so if we add 1 to it
we will get a “random” number between 1–10.

Example: if we deploy our contract on remix with the javascript VM in a fresh


incognito window and call the bet function after deployment we will always
get 2 as winning number. This is because the rst block is #1. The modulus of
1 is 1, adding 1 to that gives 2.

** Note that this is not truly random as it is easy to predict the next block number.
To learn more about randomness in solidity please check out
https://www.youtube.com/watch?v=3wY5PRliphE.

To calculate the amount won we are simply calculating a multiplier:

bet * (100 — houseEdge)/10

if the house edge is 0 our multiplier will be 10; if the house edge is 10% the
multiplier will be 9.

Lastly we will add a function for the owner to check the balance of the
contract, ideally we would want to add a withdrawal function for the owner
as well but we’ll leave that out for now. Below your bet function add the
following few lines:

function checkContractBalance() Owned public view returns(uint) {


return address(this).balance
}

Great work! The contract is now ready for testing!

. . .

Testing our contract in remix


In remix at the top right corner click the run tab. Make sure environment is
set to Javascript VM. In the value eld enter 20 and select Ether from the
dropdown next to it instead of Wei. This will preload our contract with 20 Eth
on deployment. Below that, next to the create button enter our constructor
parameters _minBet and _houseEdge (eg. 100000 wei and 10% houseEdge).
Once done it should look like this:
Before clicking ‘create’ it should looks like this.

Now click the create button, the contract instance should appear in the
bottom right of your screen now. There will be four functions visible, to check
everything went okay click on getContractBalance(). It should return
20000000000000000000, which is the 20 ether we sent to it converted to
wei. You will also see that your balance (next to account in the top right) will
now be a little less than 80 ether.

After clicking ‘create’ contract balance should be 20*1e18 wei

Ok great! Everything should work. Like mentioned before, when using the
javascript VM, the rst block will always be 1, so the rst winning number
will always be 2. We can test this out by entering 1 ether in the value eld and
passing in 2 as an argument to bet.
When pressing bet we should see our balance go up again, in the console click
details and scroll to ‘logs’. We should see an event that we have won:

We just won 9 ether !

Alright! Our contract works. In the next episode we’ll deploy our contract on
the Ropsten test network and retrieve the contract address and ABI for use in
our client application. Until then !

Check out PART 2 !

As always you’re welcome to leave a tip if you enjoy our tutorials, thanks for
reading and sticking through if you got this far!

ETH — 0x6d31cb338b5590adafec46462a1b095ebdc37d50

Full contract code:


https://gist.github.com/anonymous/9bd71a676e6f96f096b14a8afe6e368b

UPDATE: Updated calling events with emit pre x and typecasting this to
address type to get the balance member(solidity 0.4.21 release)

. . .

Looking to build your idea? We o er Ethereum proof of concept and crowdsale


development services.

Alt Street - Blockchain Consultants


Blockchain proof of concepts and Token sales
altstreet.io

Ethereum Blockchain Software Development Web Development Smart Contracts

Like what you read? Give Alt Street a round of applause.


From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.

482 2

Alt Street Follow ITNEXT Follow


We are Blockchain and ITNEXT is a platform for
Cryptocurrency experts. IT developers & software
engineers to share
knowledge, connect,
collaborate, learn and
experience next-gen
technologies.

More from ITNEXT More from ITNEXT More from ITNEXT


face-api.js — JavaScript API for Here's Why Mapping a Dynamic Programming vs Divide-
Face Recognition in the Browser… Constructed Array Doesn't Work… and-Conquer
with tensor ow.js in JavaScript
Vincent Mühler 5.4K Shawn Reisner 5.3K Oleksii Trekhleb 2.2K
8 min read 4 min read 10 min read

Responses

Write a response…

Show all responses


Never miss a story from ITNEXT, when you sign up for Medium.
GET UPDATES
Learn more

You might also like