19th Lecture | Get started with your own smart contract

Source: Internet
Author: User

We talked about the blockchain smart contract, I mainly introduced the concept of smart contracts, but did not provide you with the actual operation of the smart contract case, then today, we will write a smart contract, and introduce the Smart Contract standard template, for you to reference learning, and build up their own smart contract.

This article will be based on Ethereum as a basic knowledge, this article for the people without any intelligent Contract foundation, so equipped with more illustrations and operation commands, if you are listening to audio, you can click on the document view, hope to read this article can help you get started smart contract.

Build a smart Contract

  Before we actually operate the smart contract, we'll start by looking at Ethereum, or Ethereum, which is also known as Ethereum wallet. Ethereum Wallets offer a number of general functions including account management, Ethereum transfer, DAPP deployment and use.

The Ethereum community offers clients and development libraries in a variety of languages, most of which support the json-rpc2.0 standard, currently supported by the Go-ethereum (Go language), Parity (Rust), Cpp-ethereum (c + + language), Ethereum-lib (Javascript), ETHERERUMJ (Java language), Pyethapp (Python language), basically covers the mainstream programming language.

Photo from Ethereum official documents

The official recommended version is Go-ethererum, which is the Go Language implementation version, also known as the Geth client.

To remind you that the implementation of the client language here is not to require users to familiarize themselves with the programming language, where the user refers to Dapp developers, such as the operation of the Geth client, the user does not need to understand the go language.

1. Download and install Geth

This article uses Geth to test, first of all we want to get Geth client, if the user is using the Ubuntu environment, can be installed directly from the PPA.

# apt-get install software-properties-Common # Add-apt-repository-y ppa:ethereum/ethereum # apt< /c2>-get  Update # apt-get install Ethereum

After the installation is successful, we can view the Geth version.

Indicates that we have successfully installed, of course you can also compile the installation, because space is limited, you can search for additional information to try.

2. Building Ethereum Private Chain

It would be unwise to run and develop a test intelligence contract on the Ethereum main network, because it would consume the real etheric currency, but we could use Geth to build an ethereum blockchain that belongs to the Ethereum chain.

How to build it? In fact, it is very simple, only need to modify the configuration file and some operating parameters.

   {"Config": {    "Chainid":98,    "Homesteadblock":0,    "Eip155block":0,    "Eip158block":0},"Difficulty":"200000000","Gaslimit":"2100000","Alloc": {    "7df9a875a174b3bc565e6424a0050ebc1b2d1d82": {"Balance":"300000" },    "F41c74c9ae680c1aa78f42e5647a62f353b7bdde": {"Balance":"400000" }}}

Then execute:

    $ geth--datadir/root/geth-test/init Genesis.json

In this way, we initialize our own creation block information.

Next we create an account, because it is the user's private chain mining, only you dig mine, so using the CPU mining is completely free of problems.

We enter the Geth command line interaction page with the following command:

98 Console

Run through, as shown.

Personal.newaccount ()

We created a new account, which is the EOA account, and the balance of the current address is obtained by Eth.getbalance, which is displayed as 0.

Enter Exit exit, we start with mining mode, here we'd better record our address:

"0xf8f7ff845596f0bab1e973859bfcaec6cd2a82ab"

We use the following command to start mining, pay attention to fill in etherbase place the above address:

98 --mine--minerthreads=1 --etherbase=0xf8f7ff845596f0bab1e973859bfcaec6cd2a82ab

The POW mining algorithm in Ethereum is a memory-difficult one, which requires a DAG to be built, which depends on the performance of your device, takes a while, and waits patiently as shown, we can see that Dag generation is very time consuming.

It took me 6 and a half minutes to get to my remote development machine, and after a 4 minute, I dug in the first block, as shown.

The load of the machine during this period is as follows.

Can see the CPU and memory consumption is very high, I use the test machine here is 2Core 4GB Ubuntu16.04.

Now let's check the balance of the address that etherbase points to.

You can see that there are already 5 etheric coins, the smallest unit of Wei, so 5 after 18 zeros represents 5 etheric coins.

3. Write and deploy your own smart contract

The development of intelligent contract and wallet is independent, users can use the IDE to debug and other operations, the current dapp of the IDE is not many, common there are truffle, Embark, remix several;

In this article, I do not use the IDE, just give some sample code, that is, classic Hello Word, if you want to try to write your own smart contract, you can use the online IDE.

https://ethereum.github.io/browser-solidity/.

First we want to get the solidity compiler, install it via the Apt-get install SOLC.

After the installation is successful, we create a new solidity source file, named Helloword.sol, and write the code as follows.

pragma solidity ^0.4.  One ; contract HelloWorld {function Renderhelloworld () returns (stringreturn  helloWorld';}}

Executes the SOLC--bin Helloword.sol to obtain the EVM binary code.

The compiler warns us to ignore it, and next we need to generate the ABI deployment parameters, using the command Solc--abi Helloword.sol.

Start deployment, we enter the console,

Define the code and ABI two variables as follows, note that the value of code is preceded by 0x, and the binary data is in hexadecimal notation.

>code="0x6060604052341561000f57600080fd5b6101578061001e6000396000f300606060405260043610610041576000357c010000000000000000000 0000000000000000000000000000000000000900463ffffffff168063942ae0a714610046575b600080fd5b341561005157600080fd5b6100596100d4 565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009957808201518184015260208101905 061007e565b50505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b50925050506040518091 0390f35b6100dc610117565b6040805190810160405280600a81526020017f68656c6c6f576f726c64000000000000000000000000000000000000000 00000815250905090565b6020604051908101604052806000815250905600a165627a7a72305820fcce0b6910e479539e4796b7d56620a6f90e03ba47 449c843bec54958f68bf700029">abi=[{"constant":false,"Inputs":[],"name":"Renderhelloworld","outputs":[{"name":"","type":"string"}],"payable":false,"statemutability":"nonpayable","type":"function"}]

You can do it separately in the console, because the results are longer and are not released here.

     >personal.unlockaccount ("0xf8f7ff845596f0bab1e973859bfcaec6cd2a82ab " )   //  Use the ABI variables defined above to generate contract information   >myhelloworld=eth.contract (ABI)   //  inject code information to activate contract >contract=myhelloworld. New ({from:"0xf8f7ff845596f0bab1e973859bfcaec6cd2a82ab", Data:code,gas:  1000000})   

The results of the final execution are as follows.

We can check for unconfirmed transactions through Txpool.

The next step is to wait for the block, and your contract will become a normal contract, otherwise the contract may not be invoked.

Since I am very slow to dig out locally, I have tried the remix IDE and we can get the following results after running.

At this point a simple Helloword smart contract is generated, but it is very expensive to run, so we strongly recommend using it in some convenient virtual environments.

Smart Contract Standard Template

  When anyone can write code to customize the business logic, it also means that a set of criteria is needed to reduce the development threshold and standardize the interface to enable collaboration between the products. So let's talk about the three smart contract standard templates on Ethereum.

All three of these templates are related to tokens. So first of all, we will distinguish between the concept of digital currency and token, the digital currency generally refers to a blockchain project platform tokens, such as Ethereum on the Ethereum, the meta-world ETP is the base token.

Tokens often represent an asset that runs on top of existing blockchain, and assets can be traded like commodities, such as consumer points and game virtual assets. Tokens are also closer to specific blockchain applications, as the project side of the blockchain application is usually the issuer of the token.

Currently the most widely used three token standards are based on Ethereum, which are ERC20, ERC223, ERC721, respectively. The ERC here represents Ethereum request for Comments, which translates to the Ethereum opinion request.

1.erc20

In November 2015, V God submitted the technical standard for ERC20 tokens on GitHub, and then from 2016 to 2017, a large number of blockchain projects used ERC20 as a tool for ICO. This makes ERC20 the token standard in the entire blockchain industry, and it can be seen that the impact of this standard is large.

In fact, ERC20 tokens are a kind of smart contracts that run on the Ethereum blockchain, except that the contract codes follow certain specifications, which are ERC20 standards, which stipulate cross-dapp transfer tokens, token transactions, and some usage interfaces.

ERC20 altogether defines 6 functions and two trigger events, all written in solidity language.

6 functions describe how to transfer and how the relevant data of the token is accessed, and 99% of the ERC20 tokens on the market can find these 6 functions. 2 events provide formatted output for approve and transfer.

Let's take a look at the interface of ERC20.

 // --------------------------------------------- //ERC Token Standard #20 Interface// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // -------------------------------------------contract Erc20interface {functionTotalsupply () public constant Returns (UINT); functionBalanceof (address Tokenowner) public constant Returns (UINTbalance); functionAllowance (address Tokenowner, address spender) public constant Returns (UINTremaining); functionTransfer (address to,UINTTokens) Public Returns (BOOLsuccess); functionApprove (Address spender,UINTTokens) Public Returns (BOOLsuccess); functionTransferfrom (address from, address to,UINTTokens) Public Returns (BOOLsuccess); Event Transfer (address indexed from, address indexed to,UINTtokens); Event Approval (address indexed Tokenowner, address indexed spender,UINTtokens);}

Allowance: Allows a one-way transaction between two different addresses to be created multiple times, the owner of the token can extract tokens from this smart contract;

Approve: This function needs to refer to allowance, as the name implies, it defines that the owner of the token agrees to create a transaction of its own, which requires two parameters as input, namely the address of the consumer, and the amount to be sent;

Balanceof: Defines the interface for querying the account balance of the target address;

Transfer and Transferfrom: Defines how tokens are transferred and the transfer process is performed;

Totalsupply: Defines the maximum issuance of this token.

Above we briefly introduce the interface of ERC20 standard contract, let's take a look at the upgrade version of ERC20.

2.erc223

In some cases, ERC20 also has some drawbacks. For example, if someone uses ERC20 to send 100 tokens to another account, if the target account is a contract account, what if the target account's contract code is incompatible with the ERC20 standard?

This is very likely, because the contract code does not recognize the transaction, so the transaction will be rejected.

We know that Ethereum is not using utxo, which means that the contract does not meet acid, then unfortunately the sender of the 100 tokens are permanently lost.

To solve this problem, unofficial community developers have submitted ERC223 templates to solve this problem, and users need to upgrade their existing ERC20 contracts to ERC223 contracts.

3.erc721

In early 2018, there was a blockchain game fire, called Ethereum Cat game, this game is also a smart contract. It is based on the ERC721 standard, which is actually a token standard.

The biggest difference between ERC721 and ERC20 is that ERC721 defines that each token is unique and that it has a unique identity. For example, mango and rice are two different properties of the asset, from the physical world, they can not be directly mixed together, we can not add mango to rice.

In this way, the meaning of token in ERC721 has also turned into a document of property ownership, which is no longer a homogeneous asset in ERC20.

Summarize

  Today we introduced Ethereum wallets, taught you to build an ethereum private chain, and told you how to compile and deploy smart contracts, and finally I introduced three popular smart contract templates to help you get started and understand smart contracts in depth.

Reference Links:

    1. Http://www.ethdocs.org/en/latest/ethereum-clients/go-ethereum/index.html
    2. Https://github.com/ethereum/wiki/wiki/JSON-RPC
    3. http://remix.ethereum.org
    4. Https://github.com/ethereum/go-ethereum/wiki/Private-network
    5. Https://theethereum.wiki/w/index.php/ERC20_Token_Standard

19th Lecture | Get started with your own smart contract

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.