Note: The operating environment of this article is MacOS.

1

The installation

brew tap ethereum/ethereum brew install ethereum

When done, verify with the following command:

geth version
Copy the code

2

run

Running means running a node and joining the Ethereum network, which has two options: the public chain and the test chain, both of which are on the Internet.

2.1 male chain

Geth –fast –cache=512 –datadir console

2.2 test chain

Geth –testnet –fast –cache=512 –datadir console

Both methods require synchronized blocks, which are stored in the directory specified by the Datadir, so make sure you have enough space.

3

Set up the chain of private

Setting up a private chain is mainly for testing purposes. It is not recommended to set up a private chain for operation purposes. The whole process is as follows:

**3.1 Write genesis. Json to define initial information. ** The following is an example:

{

    "config": {

        "chainId": 20."homesteadBlock": 0."eip155Block": 0."eip158Block": 0}."alloc": {

        "0xeb680f30715f347d4eb5cd03ac5eced297ac5046": {

            "balance":"100000000000000000000000000000000"}},"coinbase": "0x0000000000000000000000000000000000000000"."difficulty": "0x01"."extraData": "0x777573686f756865"."gasLimit": "0xffffffff"."nonce": "0x0000000000000001"."mixhase": "0x0000000000000000000000000000000000000000000000000000000000000000"."parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"."timestamp": "0x00"

}
Copy the code

3.2 the initialization

geth --datadir "your dir" init genesis.json
Copy the code

3.3 Start, see the small hammer, indicating that mining has begun.

geth --datadir "Your Catalogue"-- RPC -- rpcADDR =0.0.0.0 --rpcport 8545 -- rpcCorsDomain"*" --rpcapi "eth,net,web3,personal,admin,shh,txpool,debug,miner" --nodiscover --maxpeers 30 --networkid 1981 --port 30303 --mine --minerthreads 1 --etherbase "0xeb680f30715f347d4eb5cd03ac5eced297ac5046" console
Copy the code

Note that ctrl-c on this command line does not terminate the process. To terminate the run, enter exit on the command line.

Geth also provides a console that can be accessed by typing the following command:

Geth –datadir “Attach your directory” ipc: Attach your directory /geth.ipc

The console provides interfaces including: accounts, transactions, contract calls, and blocks.

4

Intelligent contract

This section briefly describes the development process of smart contract using VScode as IDE and GEth-CLI.

4.1 Environment Preparations

Install language pack

brew install solidity

Preparing the IDE plug-in

https://github.com/juanfranblanco/vscode-solidity, enter the “extension”, search “solidity”, is the first.

4.2 Contract Development

Edit (simpledata.sol) as follows:

Pragma solidity ^ 0.4.23; contract SimpleData { uint data;function set(uint x) public{

        data = x;

    }

    function get() view public returns (uint) {

        returndata; }}Copy the code

compile

echo “var output=solc --optimize --combined-json abi,bin,interface simpledata.sol” > simpledata.js

Deployment (using the private chain built earlier)

  • Start the private chain

  • Enter the console, all the following steps are completed in the console, using JS syntax.

  • Loading compiled js:

loadScript(‘… /simpledata.js’)

  • Gets the parameters required for deployment, where output is the output defined in the “compile” step above:
var contractAbi = output.contracts['simpledata.sol:SimpleData'].abi

var contract = eth.contract(JSON.parse(contractAbi))

var binCode = "0x" + output.contracts['simpledata.sol:SimpleData'].bin
Copy the code
  • Create a user with a balance in their account (deployment also costs money) :
personal.newAccount("123456") // Set the password to miner.setetherbase (eth. Accounts [0]) // Set the user to be miner web3.fromwei (eth. GetBalance (eth. Accounts [0]),"ether") // Check the balanceCopy the code
  • release
var deployTx = { from: eth.accounts[0], data: binCode, gas: 1000000}; var instance = contract.new(deployTx) var contractAddress = The eth. GetTransactionReceipt (instance. TransactionHash). ContractAddress/address/contractCopy the code

Call (still on the same private chain, also executed on the console)

Var simpleData = contract.at(contractAddress) simpledata.get.call () personal. UnlockAccount (eth. Accounts [0]) // This step is required simpleData.set.sendTransaction(33, {from: eth.accounts[0], gas: 100000}) simpleData.get.call()Copy the code

Two things to note here:

  • On-chain changes are made through transactions, while contracts are executed at a cost, namely gas, which is a big departure from traditional development. This is why the user was created before deployment and set to miner to get the balance.

    Note: Gas and ETH are not the same thing, and the final amount of ETH consumed by the contract is determined by: step and gasPrice.

  • The account needs to be unlocked before executing the transaction, which is similar to the “withdrawal password” we need to enter before transferring money using online banking. At the same time, the unlock has a time limit, to avoid frequent unlock can use the following statement:

Personal. UnlockAccount (eth. Accounts [0], password, time limit)

There is a transaction, so there is a security issue:

  • All transactions on Ethereum are publicly viewable, and all transaction history can be seen with Etherscan.

  • All transaction executions are signed with the originator’s private key, so as long as the private key is kept properly, there should be no major problem. Signing with the private key did not occur in the above steps because the account itself is created by the console, and the corresponding public and private keys are created along with the creation.

5

Truffle framework

As you can see, the whole process is quite tedious, and Truffle is designed to solve these problems.

The installation

npm install -g truffle
Copy the code

Development and deployment

  • mkdir dapp

  • cd dapp

  • truffle init

  • Enter the directory for contracts and create the following files

Pragma solidity ^ 0.4.23; contract Storage { uint256 storageData;function set(uint256 data) public {

        storageData = data;

    } 

   function get() view public returns (uint256) {

        returnstorageData; }}Copy the code
  • truffle compile

  • Contract deployment is done through Migration, which should be familiar if you’ve used a DBMigration tool such as Liquidbase. Go to the migrations directory and create a file that starts with a number _, for example, 2_deploy_storage.js. As follows:

var Storage = artifacts.require("Storage");

module.exports = function(deployer) {

   deployer.deploy(Storage);
}
Copy the code
  • Build a test chain for development, Ganache, because its speed is faster than the previous self-built private chain.

NPM install -g ganache-cli //

Ganache cli / / run

  • Before deployment, modify the truffle.js content (where networks can define various networks, which objectively act as an “environment”) :
module.exports = {

  networks: {

    development: {

      host: "127.0.0.1",

      port: 8545,

      network_id: "*" // Match any network id

    }

  }

};
Copy the code
  • truffle migrate

Now that the deployment is complete, let’s test it manually.

6

The contract is invoked manually using JSON-RPC

The JSON-RPC interface can be done with curl. If this is a bit of a mouthful, think of it as using Java Reflection to call a class’s methods.

To invoke the above contract, we first need to get the signature of the contract methods (get and set) :

The get method

curl -X POST -i http://localhost:8545 --data '{" jsonrpc ":" 2.0 ", "method" : "web3_sha3", "params:" [] "the get ()", "id" : 1}'

**set** curl -x POST -i http://localhost:8545 --data'{" jsonrpc ":" 2.0 ", "method" : "web3_sha3", "params" : [] "set (uint256)", "id" : 1}'
Copy the code

The method signature is obtained using “web3_sha3”, whose signature is 8 bits after 0x of the return value. The results of the above two calls are as follows:

  • The get: 6 d4ce63c

  • Set: 60 fe47b1

Calling the contract requires the address of the contract, which can be obtained from the Ganache terminal. Look for a statement in its terminal output similar to the following, where the address follows created.

Contract created: 0x59322f0c1235719b4c0044b0c67f2437674b8c69
Copy the code

The rest is the contract call (where the from account directly uses the account initialized when Ganache starts, and to is the contract address) :

The get method

curl -X POST -i http://localhost:8545 --data '{" jsonrpc ":" 2.0 ", "method" : "eth_call", "params" : [{" from ":" 0 x2fe84a7fb107ade77adfeb351b92615597b68f52 ", "to":"0x59322f0c1235719b4c0044b0c67f2437674b8c69", "data":"0x6d4ce63c0000000000000000000000000000000000000000000000000000000000000000" }, "latest" ], "id":1 }'
Copy the code

Set method

curl -X POST -i http://localhost:8545 --data '{" jsonrpc ":" 2.0 ", "method" : "eth_sendTransaction", "params" : [{" from ":" 0 x2fe84a7fb107ade77adfeb351b92615597b68f52 ", "to":"0x59322f0c1235719b4c0044b0c67f2437674b8c69", "gas":"0xc350", "gaslimit":"0xc350", "data":"0x60fe47b10000000000000000000000000000000000000000000000000000000000000005" } ], "id":1 }'
Copy the code

Notice the difference in “method” between the two calls. Meanwhile, the first 8 bits after 0x in the “data” parameter are the signature of the corresponding method, followed by the data actually passed into the corresponding method.

7

Programming interface (API)

If you want to interact with smart contracts in a JS file, you need the corresponding package:

  • Web3. js, which encapsulates the JSON-RPC interface

  • Truffle-contract module, the contract abstraction of truffle

8

Automated testing

Truffle supports two types of automated tests: using javascript and using solidity. Both are fairly simple and I won’t go over them here. Test files are stored in the test directory. Test commands:

truffle test// All truffle teststestFile // single testCopy the code

9

Package management

Js package with ordinary NPM, omitted

Smart contract package ethpm

Truffle install Package name Truffle publish package name

10

reference

Truffle (https://truffleframework.com/)

Solidity (https://solidity.readthedocs.io/en/v0.4.24/)

“Blockchain Development Practice: Key Technologies and Case Analysis of Ethereum”, part of the content is outdated, such as TestRPC has been replaced by Ganache.

HiBlock Blockchain Technology Evangelist Group – Hu Jian

Originally published in Jane’s book

The original link: https://www.jianshu.com/p/bec173e6cf73

Add wechat baobaotalk_com to join the technical evangelist group

Recommendation of offline activities

Technical workshop | how to utilize the ERC875 agreement block chain development World Cup tickets? (Beijing)