[Ethereum Tutorial]Depoly contract on the private chain

版权声明:本文为博主原创文章,转载请注明出处与作者! https://blog.csdn.net/weixin_40401264/article/details/78136346

[Ethereum Tutorial]Depoly contract on the private chain


Introduction:

This tutorial shows you how to write contracts, compile contracts, and deploy contracts to your own private chain and call contract function.


Environment Setup:


Write a simple contract:

Create a new text file, type the following code in this file:

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) {
        storedData = x;
    }

    function get() constant returns (uint) {
        return storedData;
    }

}

The first line of code is used to declare to the compiler that the current contract is written in 0.4 Solidity syntax.The purpose of this statement is to ensure that the contract is backward compatible with the new version of the compiler.The following code is the contract body.Declaring a “State Variable” called the storedData type is uint, which is recorded in the blockchain database.The “State Variables” in the contract are similar to static member variables in c+ +.The two functions, set and get, are then declared to set and get the “state variable” values that are declared above。

Save this text file and rename it SimpleStorage.sol.
这里写图片描述


Compile the contract:

Open the Windows command line and enter the following commands:

echo var contractContent = > SimpleStorage.js
solc --combined-json abi,bin,interface SimpleStorage.sol >> SimpleStorage.js

The main purpose of this step is to generate a javascript script that initializes a contractContent variable, which records the compiled contract script in string form.The second command is to use solidity compiler to compile our contract, SimpleStorage, and generate ABI, contract bytecode, and interface description.Wrap this information in json format.

After running the above command.We got a javascript script, SimpleStorage.js
这里写图片描述

This script will be executed later in geth, so that the compiled contract script can be cleverly uploaded to the geth console.
This step is mainly due to the deprecate of the compiler function of eth.compile.Solidity after geth1.6.


Deploy the contract:

Start the geth console.Enter the following command in the Windows command line:

geth --datadir "E:\EthDBSpace\PrivChain" --jspath "D:\workspace\solidity\" console      

–datadir option is used to specify the eth data path, which specifies the path of the private chain data we built before.For how to build a private chain, see the previous lesson on “how to create a private chain”(http://blog.csdn.net/weixin_40401264/article/details/78095222)。
–jspath option is used to specify the javascript storage directory.Here we specify the directory where we just compiled SimpleStorage.js.
console command is used to open the geth command line

After a few seconds of initialization, enter the geth command line.The results are as follows:
这里写图片描述

Load the compiled contract in the geth command line:

loadScript("SimpleStorage.js")

This command loads and executes SimpleStorage.js.The result is a new variable, contractContent, which records the compiled contract.

To see if the compiled contract is successful, type the variable name directly into the geth command line to view the variable contents

contractContent

The results are as follows, loaded successfully.
这里写图片描述

Create a contract object.Type the following command on the geth command line:

var contractTemplate=web3.eth.contract(JSON.parse(contractContent.contracts["SimpleStorage.sol:SimpleStorage"].abi))

The meaning of the code above is: Use the ABI of contractContent “SimpleStorage. Sol: SimpleStorage” to create a contract object of the contract.The contract object can be understood as a contract template that will be used to create the contract instance.

Before the contract is deployed, gas estimates for the deployed contract are required.Type in the geth command line:

var gasValue = eth.estimateGas({data:"0x"+contractContent.contracts["SimpleStorage.sol:SimpleStorage"].bin})

You need to unlock your account before you deploy the contract, because you will use the money in your account.Type in the geth command line:

personal.unlockAccount(eth.accounts[0])

Deploy the contract.Type in the geth command line

var contractInst = contractTemplate.new({ from: eth.accounts[0], data: "0x" + contractContent.contracts["SimpleStorage.sol:SimpleStorage"].bin,gas:gasValue},
      function (e, contract) {
            console.log(e, contract);
           if (typeof contract.address !== 'undefined') {
              console.log('Contract mined! address: ' + contract.address + 'transactionHash: ' + contract.transactionHash);
           }
      }
);

The code above means: call the contract.new function to deploy the contract, and return a contract instance object.
The signature of the new function is:contract.new([arg0][,arg1]…[,transactionObject][,callback]).The preceding parameters are constructor parameters.The second parameter fills the transaction description.For the purpose of the deployment contract, from is the account of the deployment contract.to parameter is not needed.data parameter fill in the bytecode text of the compiled contract. gas is the gas estimate of the contract.The third parameter is the asynchronous callback.This callback function is invoked after the deployment contract is successful.The callback function here is to print the address and transaction hash of the contract on the console after the contract is deployed.In solidity, the js callback uses a callback in the form of error-first callback, similar to node.js.
See for error-first-callback.
http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

After the contract deployment command executes successfully, the console displays that the transaction has been submit.
这里写图片描述

The contract is deployed to the private chain block through mining.

miner.start()

After the successful deployment of the contract.The results are as follows:

这里写图片描述

We can see that our callbacks are called and print out the address of the contract:

0x171d64d78f753d2c95f4efba6799a0cc6dc8c5a7

Stop mining:

miner.stop()

Call the contract function:

Next, we call the set function to assign values to the state variable, storedData.Because our set function is to write the data on the chain, we need to use sendTransaction to call it.To use the sendTransaction to call the contract on the chain, we first need to get the Function Selector for the signature of the Function.You need to pass the function signature to the sha3 function to generate a hash256, the first four bytes of the hash that is the value of the function selector.

In the geth command line, enter the following command to get the set function hash:

web3.sha3("set(uint256)")

In the parameter list of the function signature, you can only fill in the parameter type, the parameter type is separated by a comma, and the parameter list should not contain Spaces.
The parameter type must contain the word length.For example, the current contract’s storedData variable is uint, and the uint type in solidity is the same as uint256, so fill uint256 here.

The result of the set function hash is as follows:
这里写图片描述

The hash value is

0x60fe47b16ed402aae66ca03d2bfc51478ee897c26a1158669c7058d5f24898f4

So the function selector for the set function is 0x60fe47b1.

Enter the following command at the geth command:

eth.sendTransaction({from:eth.accounts[0], to:contractInst.address, value:0, data:"0x60fe47b10000000000000000000000000000000000000000000000000000000000001234"})

from: account of the caller.
to: contract address
value: since the purpose of this call is not to transfer money, this value is 0.
data: describes the function to call and what parameters to use.The first four bytes are the function selector.This is to call the set function so 0x60fe47b1, followed by the parameter.Since the set function has only one uint (uint 256) parameter, the word length is 32 bytes.The value set here is 0x1234.

After the command is successful, it will show:

这里写图片描述

Function calls are performed by mining.Enter the geth command line:

miner.start()

Stop mining after successful execution:

miner.stop()

Query the result of the set function execution:

eth.getStorageAt(contractInst.address,0)

The first parameter is the contract address, and the second parameter is the state variable index, because our contract currently has only one state variable so it’s zero.

The results are as follows:

这里写图片描述

The return value is 0x1234, indicating that the call set function is successful!


Query call result:

We can also query the state variable storedData by calling the get function in the contract.Because the get function is constant, you can call locally.In the geth command line, enter the following command:

contractInst.get.call()

The results are as follows:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40401264/article/details/78136346
今日推荐