Create Contract in Ethereum Blockchain

Posted By : Md Imroz Alam | 12-Dec-2016

create contract in Ethereum Blockchain

First setup the Ethereum blockchain(private/public) 

start Ethereum Client by following command

Public blockchain with testnet

 



geth --rpc --rpcaddr "127.0.0.1" --rpcport "8545" --datadir ~/.ethereum-testnet --testnet --rpcapi="db,eth,net,web3,personal,web3" --rpc console
 

Private blockchain



geth --datadir ~/myBlockChain --mine --minerthreads 3 --networkid 1300 --rpcaddr "127.0.0.1" --rpcport 8000 --port 30301 --rpcapi eth,web3,personal --rpc --maxpeers 0 --nodiscover console
 

Step 1. 
Connection with Ethereum Virtual machine(EVM)

var Web3=require('web3');

 global.web3;

 web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8000"));

 if (!web3.isConnected()) {

       console.log("ethereum network connected");

     } else {

       Logger.info("ethereum connected");

 }

Step 2. 
Ethereum Support three language(Solidity,Serprent,LLL) to Write Contract.
----------------- Contract Code in Solidity Language -------------------



contract Authentication {

    address admin;

    event message(string str);

    function Authentication() {

        admin=msg.sender;

    }

    function isAdmin(){

       if(msg.sender==admin){

        message('Welcome admin');

    }

    else

    {

        message('Sorry, You are not authorized');

    }

    }



}

// Save file as "demoContract.sol", ".sol" is extension of solidity code.
for more detail -->https://solidity.readthedocs.io/en/develop/contracts.html

 

Step 3. 
// contract code compilation and get contract abi(arbitrary binary definiton)
for reference --> https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

var convertToAbi=function(cb) {
        var fs=require('fs');
            fs.readFile(__dirname + '/demoContract.sol', 'utf8', function(err, solidityCode) {
                if (err) {
                    console.log("error in reading file: ", err);
                    return;
                } else {
            var solc=require('solc');
                    var compiled = solc.compile(solidityCode, 1).contracts.Authentication;
                    var abi = JSON.parse(compiled.interface);
                    var bytecode = compiled.bytecode;
                    var contractInstance = web3.eth.contract(abi);
                    cb(bytecode, contractInstance, abi);
                }
            });
}

Step 4.

var unlockAccount=function(owner, password, duration, cb) {
       web3.personal.unlockAccount(owner, password, 120, function(error, result) {
             cb(error, result);
        });

}

Step 5.

var estimateGas=function(account, bytecode, cb) {                 web3.eth.estimateGas({                     from: account,                     data: bytecode                 }, function(error, gas) {                    cb(error, gas);                 }); }

 

Step 6.

create contract and deploy to ethereum blockchain

var createContract=function(contractInstance, owner, bytecode, gas, abi, callback) {
            var ss = contractInstance.new({
                from: owner,
                data: bytecode,
                gas: gas
               }, (err, contract) => {
                if (err) {
                    callback(err,err);
                    return;
                } else if (contract.address) {
                   var arr = {};
                    arr.contractAddress = contractAddress;
                     arr.transactionHash = transactionHash;
                    arr.gasUsed = gas;
                     callback(null, arr);
                } else {
                    Logger.info("A transmitted, waiting for mining...");
                }
            });
}

Step Last: 
All Combined Code:

var smartContract=function(req, res, callback) {
        // account and their password( etherbase account)
            var owner = req.body.owner; 
            var password = req.body.password;
            // call a function to covert abi(arbitray binary definition) of contract
            convertToAbi((bytecode, contractInstance, abi) => {
                console.log("Unlocking account -----------");
               unlockAccount(owner, password, 30, (error, result) => {
                    if (error) {
                        callback(error, result);
                        return;
                    } else {
            // estimate gas of contract 
                        estimateGas(owner, bytecode, (error, gas) => {
                            if (error) {
                                callback(error, gas);
                                return;
                            } else {
                                createContract(contractInstance, owner, bytecode, gas, abi, callback);
                            }
                        });
                    }
                });
            });
}

 

------------Execute/Run Contract method --------------------

var contractAddress = req.body.contractAddress; // ethereum account  and password 
var accountAddress = req.body.accountAddress; 
var password = req.body.password; 
var method = req.body.method; 
var contractInstance = web3.eth.contract(abi); 
var contractCaller = contractInstance.at(contractAddress);
                 Logger.info("Unlock Account ----------------");
                 unlockAccount(adminAddress, password, 30, (error, result) => { 
                    if (error) {                         callback(error, result);                         return;                     } else {                         estimateGas(adminAddress, bytecode, (error, gas) => {                             if (error) {                                 callback(error, gas);                                 return;                          } else {                 contractMethod(method,contractCaller,accountAddress,callback);                                                              }                         });                     }  }); var contractMethodCall=function(method,contractCaller,accountAddress,callback){ switch(method){ case "isAdmin":    contractCaller.isAdmin(accountAddress, action, {                             from: adminAddress,                             gas: gas                         }, (err, data) => {                             callEvent(contractCaller,callback,data);                         });                         break;                          } }






var callEvent=function(contractCaller, callback, data) {         
var event = contractCaller.usersLog(function(error, result) {             
if (!error) {             
var arr = {};                 
arr.transactionHash = data;                 
arr.result = result.args;                 
callback(error, arr);                 
event.stopWatching();             
} else {                 
callback(error, result);                 
event.stopWatching();             
}         
}); }

I hope, this will be helpul

Thanks 

About Author

Author Image
Md Imroz Alam

Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.

Request for Proposal

Name is required

Comment is required

Sending message..