Source code

Introduction to Smart Contract - Overview (I)

Smart contract Smart Contract is a very popular concept at present, but it has been used by non famous computer scientists more than 20 years ago Nick Szabo It describes a smart contract as a computer protocol that spreads, verifies, or executes the contract in an information-based way. It can allow trusted transactions without a third party, and these transactions are untraceable and irreversible.

A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. Smart contracts allow the performance of credible transactions without third parties. These transactions are trackable and irreversible.

 2018-04-11-smart-contract.jpg

Bitcoin, the originator of blockchain, has achieved distributed consistency through POW, used the UTXO model to store and manage the underlying data structure, realized decentralized distributed ledger, and realized the feature of "programmable" to a certain extent, but its basic mechanism is very simple, just a Stack based scripting language It not only has no function function, but also is not Turing complete, unable to realize complex logic.

Ethereum is generally regarded as a blockchain 2.0 project today. Unlike Bitcoin, Ethereum platform implements Turing's complete programming language, so that we can write and deploy smart contracts on Ethereum, and use the programming language Solidity and API supported by Ethereum to realize some complex functions.

Solidity

It is hard to leave when writing smart contracts mentioned on Ethereum Solidity This programming language. If you want to learn Solidity systematically and in detail, you should read the relevant Official Documents , this article will not introduce how to write smart contracts in detail, but will focus on how the programming language is designed.

 2018-04-11-solidity.png

Although many basic chains currently use Solidity as the programming language supported by the platform, there are also some basic chains. For example, EOS provides the C++API for writing smart contracts, which is just a choice and trade-off made by different platforms for different purposes. However, in this article, we will take Solidity on Ethereum as an example.

form

Solidity is a Contract oriented And Turing's complete programming language, which includes four different important elements, Contract, Variable, Function and Event.

 2018-04-11-solidity-composition.png

Among them, contract is the core concept in Solidity. We all know that Ethereum implements the underlying logic and design data structure according to the account balance model. There are two types of accounts, one is the external account controlled by the private key, which is very similar to the address in Bitcoin, and the other is the account controlled by the contract code, These codes deployed in Ethereum contracts are written using Solidity, and finally deployed to the entire network.

The code in each contract account is a contract, which is very similar to the concept of class in object-oriented programming. Both the contract and the class can have variables and functions, but the class can be instantiated. The contract does not have the function of instantiation. Its variables and functions can be directly accessed or called on the contract itself.

 2018-04-11-solidity-contract.png

In fact, variables, functions and events belong to a certain contract. These elements together form the whole content of a contract. The functions of variables and functions do not need to be explained too much. People with a little programming experience will know their functions. Events are special elements in contract oriented programming languages.

event

Before the advent of blockchain applications, most of the code ran in an instance or node. If a service wants to send notification to the outside world when certain events occur, it often needs to send messages to the message queue, and subscribers can subscribe to the corresponding topics and process them.

 2018-04-11-message-queue.png

The design of Pub/Sub in Ethereum is around events. Events are elements that are supported at the language level in the contract oriented programming paradigm. When we use other programming languages, such as C++and Golang, we can also define some events within the language through existing elements and send notifications to relevant parties of some events, Because the contract needs to keep the logic as simple as possible and reduce the computation consumption, many operations are not suitable for direct execution on the chain, so the contract supports events at the language level, and can directly notify interested parties for processing when the expected event occurs. Developers who do not need the contract repeatedly implement the same logic.

In the following contract, we define a new event Deposit:

 pragma solidity ^0.4.0; contract ClientReceipt {     event Deposit(         address indexed _from,         bytes32 indexed _id,         uint _value     );     function deposit(bytes32 _id) public payable {         emit Deposit(msg.sender, _id, msg.value);     } }

When a transaction calls the deposit function in the contract ClientReceipt, the contract will issue the Deposit event, which can be detected by the Javascript API:

 var abi = /* abi as generated by the compiler */; var ClientReceipt = web3.eth.contract(abi); var clientReceipt = ClientReceipt.at("0x1234...ab67" /* address */); var event = clientReceipt. Deposit(function(error, result) {     if (!error)         console.log(result); });

When an event is triggered by a function in the contract, the parameters in the event will be stored in the transaction log as a special data structure, but these logs cannot be accessed inside the smart contract. In Ethereum's Pub/Sub model composed of events, the contract itself is like a message queue. All transactions (or messages) that call the contract and trigger events are producers. The Javascript API that listens to events can be understood as consumers.

 2018-04-11-ethereum-events.png

ERC20 contract

The most common contract in Ethereum should be the contract that follows the ERC20 interface. The implementation of the ERC20 contract is also very mature now. The cost of issuing a new token in Ethereum may be less than tens of dollars.

 2018-04-11-erc20-interface.png

Here, we can briefly look at a simple implementation of ERC20 protocol:

 contract EIP20 is EIP20Interface {     mapping (address => uint256) public balances;     string public name;     uint8 public decimals;     string public symbol;     function EIP20(uint256 _initialAmount, string, uint8 _decimalUnits, string _tokenSymbol) public {         balances[msg.sender] = _initialAmount;         totalSupply = _initialAmount;         name = _tokenName;         decimals = _decimalUnits;         symbol = _tokenSymbol;     }     function transfer(address _to, uint256 _value) public returns (bool success) {         require(balances[msg.sender] >= _value);         balances[msg.sender] -= _value;         balances[_to] += _value;         Transfer(msg.sender, _to, _value);         return true;     }          function balanceOf(address _owner) public view returns (uint256 balance) {         return balances[_owner];     }     // ... }

A lot of functions specified in the ERC20 interface are omitted here. Let's take a look at the two simplest and commonly used functions, balanceOf, which accept an address parameter and store the balance corresponding to the balance variable balances address from the contract. The implementation of the transfer function is also very simple. The sender of the current transaction is guaranteed to have enough balance by requiring, Then subtract the sender's value from the balances and increase the receiver's value. Finally, issue the Transfer event and return.

summary

The function of Solidity, a contract oriented programming language, is very simple, but many of its concepts are designed according to the characteristics of blockchain networks. For experienced developers, learning and writing Solidity will not be a particularly difficult and complex thing.

It should be noted that as an on blockchain contract or DApp, once deployed, it cannot be updated and upgraded like other applications, so once a bug occurs in the contract, it is a very serious problem. When writing the contract, you must carefully consider the loopholes in it to avoid writing complex code and logic, Important contracts can only be deployed and released after formal verification to ensure that there are no defects in the program.

Reference

About pictures and reprints

This work adopts Knowledge Sharing Attribution 4.0 International License Agreement Licensing. Please indicate the original link when reprinting. Please keep all the contents of the picture when using the picture. You can zoom appropriately and attach the article link where the picture is located at the quotation. The picture is drawn using Sketch.

About comments and notes

If this article Introduction to Smart Contract - Overview (I) If you have any questions about the content of, please leave a message in the comment system below. Thank you.

Original link: Simple Introduction to Smart Contracts - Overview (I) · Faith oriented Programming

Follow: Draveness · GitHub

fabulous ( zero )

This article is written by Contributors Author, article address: https://blog.isoyu.com/archives/qianruqianchuzhinengheyue-gaishuyi.html
use Knowledge Sharing Attribution 4.0 International License Agreement. Unless the reprint/source is indicated, they are all original or translated by this website. Please sign your name before reprinting. Last editing time: April 14, 2018 at 02:49 am

Popular articles

Post reply

[Required]

I am a human?

Please wait three seconds after submission to avoid unsubmission and repetition