Ethereum: How To Create a Hello World Smart Contract based on a Private Blockchain

Looking at the ethereum's official Hello World tutorial -- https://www.ethereum.org/greeter, I discovered several annoyances.
  • The example is not simple enough to be qualified as "Hello World".
  • geth sync process is lengthy and error-prone.
  • Network connectivity is essential to leverage. 
How we can circumvent those to pave a way for an easy start in the Ethereum world? The following tutorial will provide a example to sort out those issues.

In order to create and deploy a smart contract, we must have a blockchain network. Apart from the well-known main and test nets, alternatively, we can build a private blockchain that's only visible and serves locally.

Prerequisites 

First things first is to install some tools to carry out development tasks.
  • install geth client.
 sudo apt-get install software-properties-common  
 sudo add-apt-repository -y ppa:ethereum/ethereum  
 sudo apt-get update  
 sudo apt-get install ethereum  
  • install solidity compiler.
 sudo apt-get install solc  

These commands are based on Ubuntu, you can also find other instructions for other platforms.

Build a Private Blockchain

When you learn and test some smart contracts, using main net can lose money and using test net, the sync process would be rather tedious. Furthermore, they're both difficult to mine to get some ethers to spend and network connectivity is essential. Therefore, a private blockchain that's only for test purpose can be a very good rescue. The following steps are the way to build one:
  • create a folder to store the blockchain.
 mkdir my-private-blockchain  
 cd my-private-blockchain  
  • use your favorite editor to create a genesis file(e.g. myGenesis.json)
 {  
   "config": {  
    "chainId": 1994,  
    "homesteadBlock": 0,  
    "eip155Block": 0,  
    "eip158Block": 0,  
    "byzantiumBlock": 0  
   },  
   "difficulty": "400",  
   "gasLimit": "2000000",  
   "alloc": {  
    "7b684d27167d208c66584ece7f09d8bc8f86ffff": {  
      "balance": "100000000000000000000000"  
    },  
    "ae13d41d66af28380c7af6d825ab557eb271ffff": {  
      "balance": "120000000000000000000000"  
    }  
   }  
 }  
  • create your data directory.
 geth --datadir ./myDataDir init ./myGenesis.json  
  • launch your geth client which connects to your private blockchain, you can use any number for networkid.
 geth --datadir ./myDataDir --networkid 1114 console 2>> myEth.log  

That's pretty much a private blockchain you're currently residing on.

Write up a Hello World Smart Contract

After the blockchain infrastructure is ready, we need to create a simple smart contract to deploy onto it. The simplest smart contract could be as follows:

 pragma solidity ^0.4.24;  
 contract HelloWorld {  
   uint public value;  
   constructor(uint _value) public {   
     value = _value;  
   }   
 }  

We can save it as HelloWorld.sol. This smart contract merely generates a state on the blockchain and through the constructor, the state can be initialized, next, we need to compile it and generate Application Binary Interface.
  • compile smart contract.
 solc --bin HelloWorld.sol  
The output would be something as follows:

 ======= HelloWorld.sol:HelloWorld =======  
 Binary:   
 608060405234801561001057600080fd5b506040516020806100e7833981018060405281019080805190602001909291905050508060008190555050609e806100496000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633fa4f245146044575b600080fd5b348015604f57600080fd5b506056606c565b6040518082815260200191505060405180910390f35b600054815600a165627a7a72305820f31a1aba5f5e591995e29233f34a17d390b60e560e7dbf75898abd5d7cc5b4610029  
  • generate Application Binary Interface.
 solc --abi HelloWorld.sol  

The output would be something as follows:

 ======= HelloWorld.sol:HelloWorld =======  
 Contract JSON ABI   
 [{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_value","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]

We should save both outputs to a place for the later usage.

Deploy Smart Contract to the Blockchain

Alright, we have a private blockchain and a simple smart contract which is processed ready. Let's head back to the geth console to deploy, the console looks like this:

 Welcome to the Geth JavaScript console!  
 instance: Geth/v1.8.10-stable-eae63c51/linux-amd64/go1.10.1  
 coinbase: 0xbe7001811a49343615d5a764c70c958933777c01  
 at block: 25888 (Sat, 02 Jun 2018 12:19:07 NZST)  
  datadir: /home/xxxx/xxxxx/xxxx/my-private-blockchain/myDataDir  
  modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0  
 >   

You can run all sorts of javascript functions inside this console.

To begin with, we need to create a personal account to do following tasks.

 personal.newAccount("<YOUR_PASSPHRASE>")  

You can leave the password as empty because it's just for the test purpose. The output would be something like "0xe1ee1713532d69db681effd23a0443402ac996eb", which is account address, next, let's check the balance in this account.

 eth.getBalance("<YOUR_CREATED_ACCOUNT_ADDRESS>")  

The output would be 0, we have to get some ethers in order to do operations on blockchain, including deploying contracts. The easiest way to get ethers on a private blockchain is via mining by ourselves.

 miner.start()  

After a while, check the balance again. This time, the created account should get some ethers. Let's stop the mining once we get enough ethers to spend because the mining process is quite resource-exhausting.

  miner.stop()  

The following javascript can be used to deploy the contract:

 personal.unlockAccount(eth.coinbase)   
 var primaryAddress = eth.coinbase  
 var abi = [{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_value","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]  
 var HelloWorldFactory = eth.contract(abi)   
 var helloWorld = HelloWorldFactory.new(1000, {from: primaryAddress, data: "0x608060405234801561001057600080fd5b506040516020806100e7833981018060405281019080805190602001909291905050508060008190555050609e806100496000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633fa4f245146044575b600080fd5b348015604f57600080fd5b506056606c565b6040518082815260200191505060405180910390f35b600054815600a165627a7a72305820f31a1aba5f5e591995e29233f34a17d390b60e560e7dbf75898abd5d7cc5b4610029", gas: 500000})   

Note the abi is from the previous section's generated Application Binary Interface and data in the last line is from the previous section's compiled smart contract. Also, we initialize the contract with value 1000. You can type all those lines one by one inside the geth console. A new transaction to deploy contract will be generated after the above commands executed. Yet, we still need to mine to include this transaction to the blockchain, let's resume the mining again.

 miner.start()  

After a while, let's inspect the helloWorld variable.

 helloWorld  

You would be able to get something as follows:

 {  
  abi: [{  
    constant: true,  
    inputs: [],  
    name: "value",  
    outputs: [{...}],  
    payable: false,  
    stateMutability: "view",  
    type: "function"  
  }, {  
    inputs: [{...}],  
    payable: false,  
    stateMutability: "nonpayable",  
    type: "constructor"  
  }],  
  address: "0x943ccc2f765c16f1964a1f07af7e15983a996be1",  
  transactionHash: "0x14617cd9592c326d3556beccc15e6daad77cbc56c08dc0315eb9fcf549c4a38a",  
  allEvents: function(),  
  value: function()  
 }  

The address inside the JSON object is the address of the newly deployed contract, let's verify the deployed contract by using this command:

  eth.getCode("<CONTRACT_ADDRESS>")  

You should get some binary code:

 "0x608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633fa4f245146044575b600080fd5b348015604f57600080fd5b506056606c565b6040518082815260200191505060405180910390f35b600054815600a165627a7a72305820f31a1aba5f5e591995e29233f34a17d390b60e560e7dbf75898abd5d7cc5b4610029"  

At present, your Hello World smart contract is just deployed! Remember stop the mining to save resource usage.

Testing the Smart Contract

The function of our contract is fairly simple, it sets a state and assigns a value to the state, so let's verify if this function is working as expected.

 helloWorld.value()  

In that there's a public variable of this contract called value, correspondingly, value() function is available to access it, you should get the initialized value -- 1000.

Well done! We've successfully built a private blockchain and deployed a smart contract on it.

Comments

  1. Radiologex is a next-gen medical network that is web accessible and downloadable as an APP on any device, MAC, PC, IOS, and Android. It is powered by blockchain technology and RDGX AI, allowing medical professionals all across the globe to connect, communicate, collaborate, transact, access content, and perform services on one comprehensive and complete medical ECOSYSTEM. It’s more intuitive, easier to operate, requires ZERO hardware purchases, and is equipped with leading security features—all for less cost. It’s the Evolution of Telemedicine AND Teleradiology.

    At the core, Radiologex is galvanized by a blockchain powered state-of-the art content delivery network (CDN) that is designed to not only replace redundant and unnecessary multiple platforms, both software and hardware, but to connect you with the global Medical community in an all-in-one platform that will drive all communication, business (buy/sell/network), with powerful medical imaging technology (PACS) and RIS/CIS capabilities. Unplug yourself from redundant hardware and various software and applications, usernames passwords and hassle, function seamlessly, with no intermediaries. The future of Enterprise Imaging and True Telemedicine™️ have arrived. With the renowned efficiency, security, decentralization of data, elimination of software fail points, transparency, and transparency and traceability of blockchain technology, Radiologex takes this core architecture to the next level to deliver a new way for the Medical Industry to interact and perform service.

    join : https://t.me/RadiologexOfficialGroup

    ReplyDelete

Post a Comment

Popular posts from this blog

A trick for connecting spring security oauth2 and wso2 api manager

How to use bitcoinj to implement multisig transactions

How to develop Tomcat-based WebSocket application on Heroku