How to Code Ethereum DApps

The article introduces to you the Ethereum DApps development. We'll discover all tools you need to write your first DApp. From running your own blockchain inside Docker to interacting via js with a deployed smart contract
01 February 2018   7248

This article covers several subjects:

  • How to start and run private Ethereum node
  • How to write and compile your first smart contract
  • How to interact with smart contracts via Mist browser (ÐApp)

Before we start you got to have:

  • Installed Docker (Download page)
  • Mist wallet to work with ÐApp (Download Mist, we need exactly Mist, not Ethereum-Wallet-*)

All code we'll write you can find at github.com

How to start and run private

Ethereum node

We need a tool to run blockchain. The most popular option is Geth — Official golang implementation of the Ethereum protocol.

To run a Docker container with Geth we need to create the Dockerfile with content:

FROM ethereum/client-go
ADD ./genesis.json /root/

Our folder should contain a genesis.json file

{
    "config": {
        "chainId": 42,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
    "difficulty": "1",
    "gasLimit": "2500000",
    "alloc": {
    }
}

Let's inspect a few fields from genesis.json: chainId and difficulty.

chainId we need to identify our private blockchain. We already have some reserved values. For the main net (also called Frontier) we have 1. 2 and 3 also reserved (you can check it at github.com). We need to choose a new one to prevent future difficulties such as Geth will try to download blocks from existed blockchains and fails to validate it because other options are different.

difficulty is needed to define a minimum accepted value of difficulty. The difficulty will automatically adjust in order to follow rules: will raise if new blocks are created in less then 9 seconds or decrease if miners struggle to find a solution in less then 20 seconds. If we set 0, the rule will no longer be applied and Geth starts to create tens new blocks per second.

Let's create a new Docker image

$ docker build . -t private-net-docker

And now let's run the command to initialize the blockchain

$ docker run -v $(pwd):/root/ private-net-docker init /root/genesis.json

-v $(pwd):/root/ — will synchronise foler /root/ inside container with our current hosts machine

init /root/genesis.json — the command init we're passing to Geth with an argument

Right now we have an .ethereum/ folder with content:

.ethereum/
├── geth
│   ├── chaindata
│   │   ├── 000001.log
│   │   ├── CURRENT
│   │   ├── LOCK
│   │   ├── LOG
│   │   └── MANIFEST-000000
│   └── lightchaindata
│       ├── 000001.log
│       ├── CURRENT
│       ├── LOCK
│       ├── LOG
│       └── MANIFEST-000000
└── keystore

4 directories, 10 files

The geth folder contains blockchain files.

The keystore folder contains private keys encrypted by password. Let's generate a new wallet. More precisely a wallet it is just a private key because an address is a hash function from the public key (which is also a cryptographic function from a private key).

$ docker run -v $(pwd):/root/ -it private-net-docker account new The current command will ask you to type your passphrase and use it as a secret key to encrypt your wallet file.

Let's create a wallet

$ docker run -v (pwd):/root/ -it private-net-docker account new

Your new account is locked with a password. Please give a password. Do not forget this password.
Passphrase:
Repeat passphrase:
Address: {9bd431ec62f0d581872bc610f2b74f0b6eeb1d06}

If we take a look at our wallet file, we'll see (passphrase is "test"):

$ cat .ethereum/keystore/UTC--2018-01-24T17-32-52.514528177Z--9bd431ec62f0d581872bc610f2b74f0b6eeb1d06

{
    "address": "9bd431ec62f0d581872bc610f2b74f0b6eeb1d06",
    "crypto": {
        "cipher": "aes-128-ctr",
        "ciphertext": "f3ee7771de9862ce4e1ad1fdc46921d63294196f49192b4f174e629c7efeaa06",
        "cipherparams": {
            "iv": "e00fe4ef5de621b1292f5130b6ef461e"
        },
        "kdf": "scrypt",
        "kdfparams": {
            "dklen": 32,
            "n": 262144,
            "p": 1,
            "r": 8,
            "salt": "b3da6b0fc66c9d8254c7314ee844e2773b090c8e73b7efc845521d9b06a86d36"
        },
        "mac": "7f8825010ed6b0644127115ebdac7d80ff37fbdf34034dd5828fef124ed02e8b"
    },
    "id": "4c6b6254-b0fb-4f5c-86d6-ee1a7be68d05",
    "version": 3
}

On the current stage we have an initialised private blockchain and we've generated a wallet. It's time to run our blockchain' node to mine the first block. To mine any block we don't need transactions. We'll mine and still get the reward for the new block (except, of course, fees for handling transactions).

$ docker run -p 8545:8545 -p 8546:8546 -v $(pwd):/root/ private-net-docker --etherbase=0x<YOUR_ADDRESS> --networkid 42 --mine --minerthreads=1 --rpc --rpcaddr 0.0.0.0 --rpcapi "db,eth,net,web3,personal"

<YOUR_ADDRESS> should be replaced with generated address, in our case it will be etherbase=0x9bd431ec62f0d581872bc610f2b74f0b6eeb1d06

We are starting to see the messages

NFO [01-24|15:17:29] Starting mining operation

INFO [01-24|15:17:29] Commit new mining work number=1 txs=0 uncles=0 elapsed=208.389µs
INFO [01-24|15:17:33] Generating DAG in progress epoch=0 percentage=0 elapsed=2.717s
INFO [01-24|15:17:36] Generating DAG in progress epoch=0 percentage=1 elapsed=5.437s
INFO [01-24|15:17:39] Generating DAG in progress epoch=0 percentage=2 elapsed=8.048s
INFO [01-24|15:17:41] Generating DAG in progress epoch=0 percentage=3 elapsed=10.703s

The first block has been mined. Also, we're starting to see the messages about DAG generating (Directed Acyclic Graph). That graph required for "Proof of Work" conception. It needs to be generated every 30,000 blocks. The generation takes much power to compute. The data will be placed inside .ethash folder and takes around 1GB. The size will grow every 30,000 blocks.

Right now DAG files of the current Ethereum network are taking 2.29GB. After DAG has been generated, the geth node will start mine new blocks and also pre-generate next DAG for the 30,0001 block.

Our first smart contract

The general concept of smart contract is pretty simple if you're familiar with OOP (object-oriented programming). You can think of it like it is just a regular a class object and class object has a state (variables) and also has functions to work with this variables or call other classes.

You can call smart contract function by sending a transaction to its address with a special `data` argument. The data argument is formatted in a special way to produce an execution of smart contact's method with some arguments. It isn't required to transfer Ether, you can make an empty transfer transaction but just ensure to pay a fee to miners to handle the transaction. If a method of smart contract you want to execute is not modifying any variables, just return some value, you can call it via Geth's API without any fees. The language you choose to write smart contact should be compiled to bytecode that Ethereum VM (Virtual Machine) can run. The most popular language for that goal now is Solidity.

Our first smart contract

 

pragma solidity ^0.4.16;

contract Test {
    uint public id = 0;

    function getId() public view returns (uint id_counter) {
        return id;
    }

    function nextId() public {
        id++;
    }
}

What is going on here?

pragma solidity ^0.4.16; — we're defining compiler version

contract Test { — we're naming our "class"

uint public id = 0; — we're defining a class variable. Then we need to create some functions to access and change our variable.

function getId() public view returns (uint id_counter) { return id; }

public — scope (also can be internal)

view — function's type, view function are prohibiting to modify a state of the contract (type also can be pure, view, payable)

returns (uint id_counter) — declaration of function's return

function nextId() public { id++; } — that function are just adding 1 to the id variable.

Let's save smart contract to the test.sol file

Compilation

We're ready to compile our first smart contract. In order to do that, we need to install solidity compilator. Dockerfile

FROM ethereum/solc:stable

WORKDIR /srv/app/

ADD ./ /srv/app/

$ docker build . -t contract

Compilation

$ docker run -v $(pwd):/srv/app/ contract --optimize --abi --bin /srv/app/test.sol

Compile command's output

======= /srv/app/test.sol:Test =======

Binary:
606060405260008055341561001357600080fd5b60de806100216000396000f30060606040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416635d1ca6318114605757806361b8ce8c146079578063af640d0f14608b575b600080fd5b3415606157600080fd5b6067609b565b60405190815260200160405180910390f35b3415608357600080fd5b608960a1565b005b3415609557600080fd5b606760ac565b60005490565b600080546001019055565b600054815600a165627a7a72305820414c782c7578801973a19b44d5cd532afbdd32a894e2d2dc955a3da88db33b230029

Contract JSON ABI
[{"constant":true,"inputs":[],"name":"getId","outputs":[{"name":"id_counter","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"nextId","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"id","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]

We can see two blocks

Binary — smart contract's binary code

Contract JSON ABI — JSON interface to interact with a smart contract

Deploying

One way to deploy smart contract is using Mist wallet. By default, Mist is running its own version of Geth. In order to connect Mist to our node, we need to pass a few arguments. When we started the geth one of the arguments was --rpcapi "db,eth,net,web3,personal" — here we have defined modules we want to allow using with rpcapi. We need to be careful and disallow any external connections to our network with running geth.

Run Mist (Mac OS)

/Applications/Mist.app/Contents/MacOS/Mist --rpc http://localhost:8545 --swarmurl "null" Mist, страница кошелька The initial page it's a great example of decentralized application (DApp). Mist is just a browser with the special interface for a decentralized application. As an example, the wallet part is a DApp itself which is located at wallet.ethereum.org. To publish our first smart contract we should go to the contracts page (top right corner), then we need to click to the "DEPLOY NEW CONTRACT" link (keep on mind that it is just a DApp's interface). Then, on the deploy page, we need to change tab to the binary code publication, paste our binary code and click on the Deploy button. Mist, публикация спартконтракта After we will finish publishing contract we need to get its address. We have two ways to do it: in console, we can see the info about contract creation and its address

INFO [01-24|17:36:17] Submitted contract creation fullhash=0x5999b523138e2c6dd93b770f7d7d53a21e19a25848c3b1c2cc9b1a9255adc687 contract=0x82087D6c27994B4a88975610f19b6bE7A5125E9C

Also, we can go the main page of the wallet and check the transactions block on the bottom. Mist, публикация смартконтракта Right now we are running our Ethereum private node, we have done our first smart contract and have published it to our blockchain. It's time to create a decentralized application.

Decentralised application

What is a DApp? It's a frontend application that can send a request to the Geth API. If you open a DApp via Mist browser, Miss will provide a handy interface to interact with Geth. Then, Geth will interact with the blockchain to make a transaction or read the swarm's database.

Let's take a look at some examples how we can interact with Mist (or with Geth directly if we want to) by our code of frontend application. To do this we need to install web3 js library via npm. Then we'll use web3 to connect to the Geth. To perform transactions we also need to define our Ethereum address.

var Web3 = require('web3');

window.client = new Web3(web3.currentProvider);
window.coinbase = '0x9bd431ec62f0d581872bc610f2b74f0b6eeb1d06'

Next, we'll define function to call getID() smart contract's method .

var initContract = function () {
    var abi = [{ "constant": true, "inputs": [], "name": "getId", "outputs": [{ "name": "id_counter", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "nextId", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "id", "outputs": [{ "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }]
    var data = '606060405260008055341561001357600080fd5b60de806100216000396000f30060606040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416635d1ca6318114605757806361b8ce8c146079578063af640d0f14608b575b600080fd5b3415606157600080fd5b6067609b565b60405190815260200160405180910390f35b3415608357600080fd5b608960a1565b005b3415609557600080fd5b606760ac565b60005490565b600080546001019055565b600054815600a165627a7a72305820414c782c7578801973a19b44d5cd532afbdd32a894e2d2dc955a3da88db33b230029'

    return new window.client.eth.Contract(abi, '0x82087D6c27994B4a88975610f19b6bE7A5125E9C');
}

window.getId = function () {
    var contract = initContract();

    contract.methods.getId().call().then(function (data) {
        console.log(data);
        document.getElementById('res').innerHTML = data;
    });
}

We have defined two functions: window.getId() and initContract().

The initContract() function is defining data of our smart contract: JSON interface, code and address. It is required by the web3 lib to arrange requests to the geth's API.

The window.getId() function calls the getId() of smart contract and then will write the result to the console.

Ok, we have a general understanding what is going on here. Let's do some practice.

  1. First, clone the github repository
  2. Go to the dapp folder
  3. Run the $ docker build . -t dapp command
  4. Edit the file /src/app.js to write your address on the line 4 to coinbase and smart contract's address on the line 20 into the ' ' string
  5. Run the application
$ docker run -p 8080:8080 -v $(pwd):/srv/app/ dapp npm i
$ docker run -p 8080:8080 -v $(pwd):/srv/app/ dapp npm run start

Here is the final stage. Let's test that everything is working nicely. Open the page http://localhost:8080 in Mist browser and developer tools for that page.

Mist, инструменты разработчика

In console we can call the methods of our ÐApp: getId() и nextId().

Взаимодействие с DApp в Mist

Keep in mind that getId() will return 1 only after the transaction have been mined.

That's all.

We have successfully created a private Ethereum network, completed and compiled our first smart contract and wrote the decentralized application for it.

A few words about ICO. Tokens are the same smart contracts, i.e. classes with variables that are keeping track of the state. In order to create a smart contract which can call itself token, the smart contract should have methods with predefined names. You can find that names of methods in ERC20 standard. As an example, if you call a special function of smart contract and send some Ether, the function will increase a value of smart contract's variable.

Boris Kuznetsov, Senior Software Engineer at Evrone

Top Upcoming ICO 22nd - 28th July

Check the most interesting upcoming ICOs: CrowdPrecision, InsCoin for Knox Project, METOKEN, Vanig, Codex, Plentix, WAR FIELD
15 July 2018   61

CBOE Presindent recently warned the ICO community about the issues, that they may face in nearest future. But we had some great news recently - it has became known that in 2018, ICO-projects raised $ 9.29 billion, which is more than double than total for the previous year. The corresponding data is reported by CoinSchedule. It is worth noting that, unlike many other ratings, CoinSchedule takes into account Telegram ($ 1.7 billion) and Venezuelan El Petro ($ 735 million). These projects are the leaders in terms of investment.In each month of the current year, more than $ 1 billion was collected, and at the expense of Telegram, March became the leader - $ 3.8 billion.

Upcoming ICO

Today we have prepared for you the best and most interesting ICOs, that will start offering coins next week. 

Don’t forget to read to the bottom and take part in our poll about upcoming ICOs. 

1. CrowdPrecision 

Hype.Codes rate  92

CrowdPrecision offers higher quality results at lower cost and faster. We decided against a solely decentralized platform. Our experiences show that there are always cases that can not be clarified automatically. Therefore, our platform has a group of experts who serve as a point of arbitration and take into account both, the interests of employees and employers in a neutral way. CrowdPrecision tackles two of the most significant challenges in current Crowdsourcing applications - quality control of the work submitted and fast and cost-effective payment mechanisms. 

Vote for this ICO

Sales dates: Jul 22nd - Aug 19th
Accepted currencies. ETH
Soft cap 7.5k ETH
Hard cap 30k ETH
Website and Whitepaper 

Back to the quick navigation list

2. InsCoin for Knox Project

Hype.Codes rate 83

"InsCoin for Knox Project" aims to establish the first insurance company that will accept a Crypto (INSC) for the payment of insurance premiums, and the first that, with the help of the blockchain, will solve the problem of falsification of insurance policies. The KNOX project will be the first insurance company that merges the real world with the digital one using Blockchain technology, creating the most efficient and advanced structure in the sector, to find a solution to the problem of certification and anti-forgery of insurance policies. It will be the first ever to emit insurance policies both in smart-contract and traditional paper form. With the smart contract the spread of false insurance policies is avoided because it is the same system that issues them after receiving the payment. With the smart contract the company won't have delay in collecting credits, as the policy is issued only after receiving the payment.

Vote for this ICO

Sales dates. Jul 23rd - Aug 30th 
Accepted currencies. ETH
Soft cap 4k ETH
Hard cap 39 444 ETH
Website and Whitepaper

3. METOKEN

Hype.Codes rate 91

Optimized for all users, Style.me is a shoppable, Instagram-like fashion experience. Style.me monetarily incentivises quality content creation from influencers and brands while rewarding users for opting in to receive targeted advertisements. The platform connects and rewards fashion influencers, consumers, and brands. For example, Influencers are able to post brands’ outfits on the platform. Users can like and share such posts, while both parties are rewarded for content creation and engagement. Using Style.me’s patented virtual fitting room, shoppers can try on the outfit, and even purchase directly. Fashion brands are happy due to a satisfied customer and a valued influencer.

Vote for this ICO

Sales dates. Jul 23rd - Aug 22nd
Accepted currencies. ETH, BTC
Soft cap $10M
Hard cap $30M
Website and Whitepaper

4. Vanig

Hype.Codes rate 89

Vanig is the world’s first integrated E-Commerce platform and Supply Chain ecosystem powered by the blockchain. Vanig Patent Pending solution addresses several significant Supply Chain and E-Commerce challenges and inefficiencies, providing a higher level of brand experience. Our Supply Chain ecosystem leverages the latest in blockchain technology through HyperLedger’s Sawtooth Lake technology. We simplify the E-Commerce experience and its embedded Supply Chain, eliminating intermediaries and manual processes as it ushers in a new level of transparency. The Vanig platform is safe, secure, and user-friendly, benefiting all members of the ecosystem and embraces cryptocurrency payments. It shortens recall process and timelines for manufacturers and retailers, providing real-time product visibility through to the consumer. Provenance information on products, increasingly an essential consumer ask, is fully integrated.

Vote for this ICO

Sales dates. Jul 23rd - Sep 25th
Accepted currencies. ETH, BTC, LTC, USD
Soft cap $2M
Hard cap $20M
Website and Whitepaper

5. Codex

Hype.Codes rate 86

Codex is the leading decentralized asset registry for the $2 trillion arts & collectibles (“A&C”) ecosystem, which includes art, fine wine, collectible cars, antiques, decorative arts, coins, watches, jewelry, and more. Powered by the CodexCoin native token, the Codex Protocol is open source, allowing third-party players in the A&C ecosystem to build applications and utilize the registry. These applications, built with Codex’s partners, will make buying, selling, insurance, asset-backed loans and shipping and logistics easier for everyone. Codex’s first application, Biddable, is a title-escrow system built on the Codex Protocol, which solves long-standing challenges in auctions: non-performing bidders, lack of privacy, and bidder access. It is already live with the Codex Consortium, a group of major stakeholders in the A&C space who facilitate over $6 Billion in sales to millions of bidders across tens of thousands of auctions from 5,000 auction houses in over 50 countries.

Vote for this ICO

Sales dates. Jul 15th - Aug 15th
Accepted currencies. ETH, BTC
Hard cap $25M
Website and Whitepaper

6. Plentix

Hype.Codes rate 89

The advent of cryptocurrencies and the tokenized economy makes it possible to re-imagine the entire value chain of consumer, products, and producers from a referral perspective. We present Plentix, a tokenized platform that enables users to refer other users to a business entity and enables business entities to leverage existing APIs for industry specific referrals and allows for safe, secure, trustless value exchange to take place. Unlike other referral platforms, Plentix unleashes the potential of a new global ecosystem to monetize referrals for every stakeholder, from the producer to the consumer.

Vote for this ICO

Sales dates. Jul 11th - Jul 24th
Accepted currencies. ETH, LTC, BTC, USD
Soft cap $3M
Hard cap $24M
Website and Whitepaper

7. WAR FIELD

Hype.Codes rate 85

WAR FIELD is a fully-functional, action-packed multiplayer first-person shooter game with a blockchain-driven gaming economy that uses tradeable Ethereum-based cryptographic GLDR Tokens you can buy, sell, trade, and win for skilful play.

Vote for this ICO

Sales dates. Jul 26th - Nov 15th
Accepted currencies. BTC, ETH, LTC
Hard cap $3M
Hard cap $12M
Website and Whitepaper

What is Hype.Codes Rate? 

Hype.codes team works everyday to bring you the best reader’s experience. We are trying to add some new cool features every day. Hype.Codes Rate is average, abstract ranking of ICO, that we give to every upcoming ICO. It depends on such criteria:

  • Landing webpage design
  • Completeness of information provided on the landing webpage
  • Convenience of information search on the landing webpage
  • The concept itself
  • Whitepaper
  • Reputation and accessibility of information about the project team, their experience
  • Project activity on social networks
  • And many other

We hope that you like the idea of Hype.Codes ICO ranking and maybe it will help to navigate through the stormy sea of blockchain-based start-ups. 

Learn about the best ICOs of recent weeks in this articles:

Voting for the best upcoming ICO 22.07 - 28.07

We are constantly updating the list of top upcoming ICO and we would like you to share some thoughts on which upcoming Token Sale from 22nd to 27th of July a is the most appealing to you. Which one seems interesting for you to invest your funds, and which one, in your opinion, will bring the most profit? Please, select one of the options below.