Create your first Ethereum Dapp from Scratch
Blockchain is the new Internet Hype. Cryptocurrencies like Bitcoin and Dogecoin have all been in news lately because of their rapid fluctuating market.
Ethereum, while also boast a Crypto known as Ether, wasn’t born to replace the existing financial system but instead bring a revolution with its Distributed Application (Dapp) deployment methodology. The apps on Ethereum run on Ethereum Virtual Machine or EVM which are hosted on a peer-2-peer community node running the Ethereum client.
In this blog post, I am gonna show you how you can create your own private Ethereum Network and deploy your own Dapp and start mining (though you won’t get any reward for it!). It is important to test our Dapps in a private network before deploying on the actual mainnet.
A lot of work is borrowed from this article, while old, it was indeed helpful. I am using Arch Linux host but any Linux based host would work just fine.
PART 1: Creating Private Test Network
Install Geth
Geth is the eth client written in Go. Arch Linux provides all go-eth tools under the package name go-ethereum. Install it with pacman.
# pacman -Sy go-ethereum
Create Data Directory Structure
In this tutorial, we will be using a virtual private network of three Ethereum nodes.
$ mkdir blockchain$ cd blockchainblockchain$ mkdir node1 node2 node3
Create Node Accounts
blockchain$ geth —datadir node1/ account new
Choose any random password. Since this is a private network, security is not a concern. (Remember (— ) is a double hyphen, medium.com won’t just let me use it!)
Create Node2 and Node3 accounts similarly.
Save Credentials
We need to store the public address and password for future use.
Create Genesis Block file
The go-ethereum package contains all the required tools for setup as well as mining. It comes with puppeth, the Ethereum Private Network Manager, which will help us in creating the genesis block file interactively.
blockchain$ puppeth
Specify chain ID.
Since this is the first time we are using puppeth, it will show option to configure new genesis. Choose 2nd option.
We want to create new genesis block so choose 1st option
We will be using Proof of Authority (PoA) to save our CPU usage. This is also the default option provided.
Choose mining time. You can choose anything as we will be changing it later.
Add accounts to be sealed in the network. We will add all the three accounts.
Add accounts to get free Ethers. (You can’t trade it on exchange though!)
The Genesis block configuration has been created and now its time to export it.
It will show some errors, just ignore them. Press Ctrl+C to exit from interactive puppeth.
Configure Genesis file
Now you will have 2 more files created in your data directory. Rename 1515.json to genesis.json for simple identification.
And Edit the Clique period to “0” in the same file.
Initialize the nodes
We need to initialize each node with the same genesis block.
blockchain$ geth —datadir node1/ init genesis.json
Similarly initialize other 2 nodes as well.
Start the nodes
Now its time to start running our virtual private nodes. There are some parameters that you must pass while starting these nodes as explained here.
blockchain/node1$ geth —nousb —datadir=$PWD —syncmode ‘full’ —port 3030 —miner.gasprice 0 —miner.gastarget 470000000000 —http —http.addr ‘localhost’ —http.port 8545 —http.api admin,eth,miner,net,txpool,personal,web3 —mine —allow-insecure-unlock —unlock “0xCaA5e7834B7CC7e73bA06Dd8E3b71fFedEE1398A” —password password
Let me explain what this command actually means,
- —nousb Disables monitoring for and managing USB hardware wallets.
- —datadir=$PWD Data directory for the databases and keystore.
- —syncmode ‘full’ Enables full chain sync (default: “fast”).
- —port 3030 assign port geth process.
- —miner.gasprice 0 On private network we don’t want to pay anything, so make it zero.
- —miner.gastarget 470000000000 use same as the genesis file. However, actual gaslimit is dynamic for new block and depends on the previous block.
- —http Enable the HTTP-RPC server.
- —http.addr ‘localhost’ HTTP-RPC server listening interface (default: “localhost”).
- —http.port 8545 HTTP-RPC server listening port (default: 8545).
- —http.api Bunch of apis to be used over RPC calls.
- —mine Enable mining.
- —allow-insecure-unlock Allow insecure account unlocking when account-related RPCs are exposed by http.
- —unlock “0xCaA5e7834B7CC7e73bA06Dd8E3b71fFedEE1398A” Account to unlock, we’ll use the address of node1.
- —password password Password file to use for non-interactive password input
Just stop the node when it says Looking for peers, we need to configure rest 2 before it can find it.
Additionally, note down the enode output from “Started P2P networking” line.
Repeat same for rest of the two nodes. Remember to change the ports in the command for these two nodes e.g. from 3010 & 8545 to 3011 & 8546 respectively and the public address as well.
Create Node configuration
We will provide static configuration to geth to connect to other nodes in our private network though Geth has the ability to connect to peers in more ways.
Create a static-nodes.json file and add the enode lines in it like this.
Copy this configuration file in other two node folders as well.
Now just use above commands for starting nodes followed by ‘&’ to fork it as background process. You can also run all the three peers in three different terminals to see debug output.
Now if you didn’t fork the processes in background, you would see output like this.
If you forked the process in background, you need to attach the IPC output to geth to see if it is connected to other nodes or not.
blockchain/node3$ geth attach geth.ipc
> net.peerCount
Our Test Network is ready now. Now we will deploy our code in one of these nodes that will be automatically synced with other nodes. Keep these nodes running in their terminal sessions.
PART 2: Creating Dapp
Install Solidity
On Arch Linux, Solidity package is available in official repository so simply fire pacman.
# pacman -Sy solidity
Writing the Code
This part is actually even simpler since we have already got our environment set and running. Let’s see our first Solidity code.
pragma solidity >=0.8.0;
contract stateChangeTest {
uint storedData;
function store(uint data) public {
storedData = data * 10;
}
function fetch() public view returns (uint ret) {
return storedData;
}
}
Let’s understand each line.
- The first line starting with pragma defines the solidity compiler version to be used. I am currently using the latest available version 0.8.6. The operator >= actually implies to use any compiler after v0.8.0.
- Second part is the contract declaration. Just grasp it as synonym to classes in C++ or Java.
- Then we have State variables or simply class variables whose validity is within the entire contract. Read more on this.
- Function declaration in solidity is like JavaScript with one added feature that you must define the scope of the function.
- Functions in Solidity require you to declare the return type using “returns (type)” syntax since it is statically typed language like C++. Furthermore you also need to define the type of function, if it is only reading a state variable then declare it as “view”. Read more on this.
You can write the code using any of your favorite IDE. I used nano Btw. Save it as stateChangeTest.sol.
Compiling the Code
Use solc compiler to get the optimized abi and bin output that we will use in later steps.
blockchain $ solc -o ./out —optimize —abi —bin stateChangeTest.sol
Ignore warnings, if you get any.
Copy the contents of both *.abi and *.bin file.
Deploying the code
Change to one of the node directory, say node1.
- Paste the contents of *.abi file in variable t1ContractAbi.
Similarly paste the contents of *.bin file in variable t1CodeBin.
2. Get the contract in geth object format (from json).
> t1Contract = eth.contract(JSON.parse(t1ContractAbi))
3. Deploy Contract
> var t1ContractInstance = t1Contract.new({from: eth.accounts[0], data: t1CodeBin, gas: 2000000})
Get the transaction Receipt to communicate with it.
> eth.getTransactionReceipt(t1ContractInstance.transactionHash)
Note down the contractAddress from this output to identify the contract on the network while calling later.
Testing the Code
Deployment was successful and now its time to test our smart contract.
Get the smart contract instance in a variable using its address.
> t1 = t1Contract.at(“0x95b94926e770fd30eee076f6d0fa8d2705a9dd8d”)
Now call the fetch function.
> t1.fetch.call()
You will notice that there are no debug log in the node instances. This is because invoking a function to read state variables isn’t a transaction but merely a call so it doesn’t require mining.
Let’s update our data. Send transaction using store function.
> t1.store.sendTransaction(5, {from: eth.accounts[0], gas: 100000})
Call the fetch function again.
If you see 50 in output, then Congratulations, you have successfully deployed and tested your first Ethereum Dapp. While this is merely a update variable code, it is a good beginning.
You will also notice that the nodes running in background have generated debug logs of “mining”. Since we set the mining period as 0 in our configuration, the results are outputted almost instantaneously.
Play with the code now.
Join Coinmonks Telegram Channel and learn about crypto trading and investing
Also, Read
- What is Margin Trading | Dollar-Cost Averaging
- BigONE Exchange Review | Grid Trading Bot
- 3Commas Review | Pionex Review | Coinrule review
- Ledger vs Ngrave | Ledger nano s vs x | Binance Review
- Bybit Exchange Review | Bityard Review | CoinSpot Review
- 3Commas vs Cryptohopper | Earn crypto interest
- The Best Bitcoin Hardware wallet | BitBox02 Review
- BlockFi vs Celsius | Hodlnaut Review | KuCoin Review
- Bitsgap review | Quadency Review | Bitbns Review
- Crypto Copy Trading Platforms | Coinmama Review
- Crypto exchanges in India | Bitcoin Savings Account
- CoinDCX Review | Crypto Margin Trading Exchanges
- CoinLoan Review | YouHodler Review | BlockFi Review
- CoinFLEX Review | AEX Exchange Review | UPbit Review
- AscendEx Margin Trading | Bitfinex Staking | bitFlyer Review
- AscendEx Staking | Bot Ocean Review | Best Bitcoin Wallets
- Huobi Review | OKEx Margin Trading | Futures Trading
- Sparrow Exchange Review | Nash Exchange Review
- The Best Crypto Tax Software | CoinTracking Review
- Stackedinvest Review | Kraken Review | Futures Trading Bots
- Best Crypto Lending Platforms | Leveraged Token