Showing posts with label Smart Contract. Show all posts
Showing posts with label Smart Contract. Show all posts

Ethereum Solidity Compiler


Ethereum contracts are written in the high level language called Solidity and compiled into bytecode using the Solidity compiler. This bytecode is then uploaded on to the blockchain.

As mentioned in the previous blog, Visual Studio Code and several editors provide integrated environment to compile the code. If you want to manually run the compiler then here are the steps for compiling a smart contract.

Download the compiler from the GitHub release site
Based on your platform download the corresponding bits

Open the command line and run the below command to compile our 0xService or any smart contract
%path%\solc.exe --bin --abi --overwrite -o bin Service.sol

As you see in the above we are passing bin and abi arguments to specify to the compiler to create the bin and abi file. The generated files are created in the bin folder as mentioned by the other bin attribute. The overwrite flag is used to overwrite the previously generated abi and bytecodes.

Hello World Ethereum Smart Contract with VS Code and Solidity


In my previous blog we have created our first Hello world app using Remix Solidity IDE.

In this blog, I will go over how to use Visual Studio Code to compile the Hello World contract and deploy the contract on a private chain and Rinkeby chain. Please refer to my other related blogs for setting up Visual Studio Code, Private Chain and connecting to Rinkeby Testnet.

Let’s start by opening Visual Studio Code and open a folder in VS Code. If required create the folder. The folder is required because VS code compiles the code and creates the abi and bytecode here.

Create a new file in this folder called HelloWorld.sol with the below code:
pragma solidity ^0.4.11;

contract HelloWorld {

    function greet() public constant returns (string) {
        return "Hello World!";
    }
}

Compile this smart contract by pressing F5 key. This creates a bin folder with abi and bin (bytecode). Here are the contents of the abi and bin file:
abi:
[{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]

bin(bytecode):
6060604052341561000c57fe5b5b6101498061001c6000396000f300606060405263ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cfae3217811461003a575bfe5b341561004257fe5b61004a6100ca565b604080516020808252835181830152835191928392908301918501908083838215610090575b80518252602083111561009057601f199092019160209182019101610070565b505050905090810190601f1680156100bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100d261010b565b5060408051808201909152600c81527f48656c6c6f20576f726c6421000000000000000000000000000000000000000060208201525b90565b604080516020810190915260008152905600a165627a7a723058205168b085c257b42e405c11a8e900935fd85bd351767a3ed78211b54b7c6df2e10029

Now let’s start the private chain as mentioned in my blog Ethereum Dev Chain - Private Chain

Here are the steps to be followed in the JavaScript console to deploy the contract:
  • Unlock the account so that Ether can be used for gas
> personal.unlockAccount(eth.accounts[0], "password")
true
In the above command I am using the first account. If required you can specify any other account
  • Define the abi & bytecode variables. Prefix the bytecode with “0x”
var abi = [{ abi generated by the compiler }]
var bytecode = “0x<bytecode generated by compiler>”
  • Deploy the contract
> var contract = eth.contract(abi)
  • Find the gas estimate for deploying the contract
eth.estimateGas({ data: bytecode} )
This gives the gas required to deploy the contract. Currently it’s value is 138902. Specify this value in the next step while creating an instance of this contract
  • Now create an instance of this contract.
> var instance = contract.new({
......    from:eth.accounts[0],
......    data:bytecode,
......    gas:138902}, function(err, contractInstance){
......     if(!err) {
.........        if(!contractInstance.address) {
............            console.log("Tx Hash: " + contractInstance.transactionHash) // The hash of the transaction
............        } else {
............            console.log("Address: " + contractInstance.address) // the contract address
............        }
.........     }
...... else {
......... console.log(err)
......... }
...... });
Tx Hash: 0x57228ccd8013aa17b134c3f76147a1c5a74f40f98c7bc352e484f42581e30355
undefined
> Address: 0x44408814564648d05d4cfcf12397151cfee0af52
The contract creation is an asynchronous function. Once the contract is mined, the call back function returns the transaction hash and address at which the contract is deployed.
  • Wait till the contract is mined and address is shown in the console
  • Now invoke the greet function
> instance.greet()
"Hello World!"

With above steps we successfully deployed the contract onto a private chain and invoked it. Here is the complete JavaScript console code:
personal.unlockAccount(eth.accounts[0], "password")
var abi = [{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]
var bytecode = "0x6060604052341561000c57fe5b5b6101498061001c6000396000f300606060405263ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cfae3217811461003a575bfe5b341561004257fe5b61004a6100ca565b604080516020808252835181830152835191928392908301918501908083838215610090575b80518252602083111561009057601f199092019160209182019101610070565b505050905090810190601f1680156100bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100d261010b565b5060408051808201909152600c81527f48656c6c6f20576f726c6421000000000000000000000000000000000000000060208201525b90565b604080516020810190915260008152905600a165627a7a723058205168b085c257b42e405c11a8e900935fd85bd351767a3ed78211b54b7c6df2e10029"

var contract = eth.contract(abi)
var gas = eth.estimateGas({ data: bytecode} )

var instance = contract.new({
   from:eth.accounts[0],
   data:bytecode,
   gas:gas}, function(err, contractInstance){
    if(!err) {
       if(!contractInstance.address) {
           console.log("Tx Hash: " + contractInstance.transactionHash) // The hash of the transaction
       } else {
           console.log("Address: " + contractInstance.address) // the contract address
       }
    }
    else {
        console.log(err)
    }
});

//wait for the mining to be completed
instance.greet()

I generally use Rinkeby during the UAT environment. Let’s run the above script in the Rinkeby environment and check it. Please refer to my other blog on how to connect to Rinkeby chain, Setting up Ethereum Rinkeby Testnet

I deployed the contract on Rinkeby network and here is the screenshot of this contract:


Setting up Ethereum Rinkeby Testnet

Rinkeby is the public testnet for Ethereum. This testnet can be used during development, testing and pre-production scenarios. I personally use private net during development and use Rinkeby for demos.

Refer to my other blog on setting up a development private chain: Ethereum Dev Network

Here are the steps for setting up and connecting to Rinkeby test chain:

Step 1: Download the latest Geth from the below URL

As I am using a windows machine, I downloaded the windows version. Install the Geth on your machine as per the installation guide.

Step 2: Create a folder called Rinkeby which keeps the chain data.

Step 3: Run the following command to connect to the Rinkeby testnet
geth.exe --rinkeby --syncmode "fast" --datadir=devchain --rpc --rpccorsdomain "*" --rpcapi "eth,web3,personal,net,miner,admin,debug" --verbosity 0 console

Step 4: Wait for the sync to complete. The sync will be completed based number of blocks. With the current block number 586,326 it took about 20 mins to sync. You can check the sync status with the following command:
eth.syncing

The above command returns either false (if syncing has not stated or completed) or current block number. Wait for the syncing to be completed.

Step 5: Create the user account using the javascript console. Run personal.newAccount() and provide password when prompted

The console shows the address of the new account created.

Step 6: Verify that your account is created in the Rinkeby by using the Rinkeby Etherscan


Step 7: Request Ether(ETH) for your newly created account. As you see above the current ETH balance is 0. Rinkeby uses Proof of Authority for mining. Hence you need to request Rinkeby to provide you ether. Rinkeby has a faucet which can provide you ether. You need to periodically request Ether using this faucet.

To prevent spam, Rinkeby faucet requires people requesting funds have a GitHub account and create a GitHub Gist. Let’s create a GitHub Gist with the account number as shown below:

Once the Gist is created go to the Rinkeby faucet (https://faucet.rinkeby.io/) and request funds

Once the account is funded with your requested ethers, go to the Etherscan and verify that the account is credited with the requested ethers.

With these above seven steps, our Rinkeby testnet is setup and ready to deploy smart contracts and send transactions.


Smart Contracts (Solidity) coding using Visual Studio Code


Visual Studio Code is the open source editor with powerful developer tooling. It works on Windows, Linux and Mac. Visual Studio Code is also a great editor for developing of smart contracts with Solidity. VS Code provides syntax highlighting, compilation of current contract and all contracts.

If you haven’t downloaded Visual Studio Code, download and install code from the below link.

For developing Solidity using Visual Studio Code you first need to install the Solidity Extension. For that open Visual Studio Code and using menu click View -> Extensions and search for Solidity and click install. Once the extension is installed you can start coding solidity smart contracts.

To compile the contract click F5. If there are no error messages, you will get the success message as shown below:

If there is a compile error then the error is highlighted as shown below

Overall Visual Studio Code is a good editor for developing smart contracts for Ethereum.

Hello World Ethereum Solidity Smart Contract


As we typically start every programming language with “Hello, World”, let start our first Ethereum Dapp with the same customary Hello World appp.

Ethereum uses Solidity to create smart contracts. As per definition “Solidity is a contract-oriented, high-level language whose syntax is similar to that of JavaScript and it is designed to target the Ethereum Virtual Machine (EVM)”

Here is our first Hello World smart contract
pragma solidity ^0.4.11;

contract FirstContract {

    function Greet() public constant returns (string) {
        return "Hello, World";
    }
}


We can execute our very first contract using web based Remix Solidity IDE. Go to the below URL

Delete the default contract that comes with Remix. Create a new contract and write our first contract. Your browser should look like this:

Now click on the “Create” button. Remix will compile and deploy the contract. It will also shows you the output of our contract, which is “Hello, World” as shown below:

So we complete our traditional Hello World app using the browser based Remix Solidity IDE
Remis IDE is good for quick prototyping. If you need to build smart contracts and Dapps, you need the following tools. Please see my other blogs on this:

  • Visual Studio Code for compiling Contracts
  • Deploying and transacting with contracts using JavaScript Console
  • Development Test Chain during development phase
  • Rinkeby Test Chain for full node testing



Ethereum Solidity Compiler

Ethereum contracts are written in the high level language called Solidity and compiled into bytecode using the Solidity compiler. This ...