Solidity writing smart Contracts (Getting started)

Source: Internet
Author: User

A simple smart contract

Start with a very basic example, and don't worry that you don't know it at all, and we'll get to know more details.

Store
contract SimpleStorage {    uint storedData;    function set(uint x) {        storedData = x;    }    function get() constant returns (uint retVal) {        return storedData;    }}

In solidity, a contract consists of a set of code (the function of the contract) and the data (the state of the contract). The contract is located at a special address on the Ethereum blockchain. UINT Storeddata; This line of code declares a state variable named Storeddata with the type UINT (256bits unsigned integer). You can think of it as a storage unit in a database that, like the management database, can be queried and modified by calling functions. In Ethereum, it is usually only the owner of the contract to do so. In this example, the function set and get are used to modify and query the value of the variable respectively.

As with many other languages, you do not need to add this before accessing a state variable. Such a prefix.

The contract is not yet able to do much (subject to ethereum infrastructure), just allowing anyone to store a number. And anyone in the world can access this number without a (reliable) way to protect the numbers you publish. Anyone can call the set method to set a different number to overwrite the number you publish. But your numbers will remain in the history of the blockchain. Later we will learn how to add an access limit so that only you can modify this number.

Examples of tokens

The next contract will implement one of the simplest forms of crypto currency. The sky is no longer a magic trick, of course, only the person who created the contract can do it (it is very simple to use the other currency distribution mode, only to achieve the difference in details). And anyone can send money to other people, do not need to register a user name and password, as long as there is a pair of ethereum public private key.

Attention
This is not a good example of an online solidity environment. If you use the online solidity environment to try this example. When a function is called, the From address cannot be changed. So you can only play the role of a mint, casting money and sending it to others, rather than playing the role of other people. This online solidity environment will be improved in the future.

contract Coin {

//关键字“public”使变量能从合约外部访问。    address public minter;    mapping (address => uint) public balances;//事件让轻客户端能高效的对变化做出反应。    event Sent(address from, address to, uint amount);//这个构造函数的代码仅仅只在合约创建的时候被运行。    function Coin() {        minter = msg.sender;    }    function mint(address receiver, uint amount) {        if (msg.sender != minter) return;        balances[receiver] += amount;    }    function send(address receiver, uint amount) {        if (balances[msg.sender] < amount) return;        balances[msg.sender] -= amount;        balances[receiver] += amount;        Sent(msg.sender, receiver, amount);    }}

This contract introduces some new concepts, let's take a look at it one by one.

address public minterThis line of code declares a publicly accessible state variable of type address. The address type has a value size of bits and does not support any arithmetic operations. Applies to the address of the storage contract or the public private key of another person. The Public keyword automatically generates an Access function for the state variable it modifies. Variables that do not have the public keyword will not be accessible by other contracts. In addition, only the code in this contract can be written. The automatically generated functions are as follows:

function minter() returns (address) { return minter; }

Of course it doesn't work to add an access function of our own. The compiler will report an error stating that this function has the same name as a state variable.

The next line mapping (address => uint) public balances of code creates a public state variable, but its type is more complex. This type maps some address to an unsigned integer. Mapping can be considered a hash table, each possible key corresponding to the value of the virtual initialized to the full 0. This analogy is not very rigorous, and for a mapping, you cannot get a linked list of all of its keys or value. So we have to remember to add something to the mapping. A better way is to maintain a list of these, or use other more advanced data types. Or just use mapping in scenes that are not affected by this flaw, as in this example. The access functions generated by the Public keyword in this example will be more complex, with the following code:

function balances(address _account) returns (uint balance) {    return balances[_account];}

We can easily use this function to query the balance of a particular account.

event Sent(address from, address to, uint value)This line of code declares an "event". Triggered by the last line of code for the Send function. The client (which is also applicable to the service-side application) can listen to these blockchain-triggered events at a very low cost. When the event is triggered, the listener will receive the From,to,value parameter values at the same time, which can be conveniently used for tracking transactions. To listen to this event, you can use the following code:

Coin.Sent().watch({}, ‘‘, function(error, result) {    if (!error) {        console.log("Coin transfer: " + result.args.amount +            " coins were sent from " + result.args.from +            " to " + result.args.to + ".");        console.log("Balances now:\n" +            "Sender: " + Coin.balances.call(result.args.from) +            "Receiver: " + Coin.balances.call(result.args.to));    }}

Note how the auto-generated balances function is called in the client.

Here's a very special function Coin. It is a constructor that runs when the contract is created and cannot be called. It will permanently store the address of the creator of the contract. MSG (as well as TX and block) is a magical global variable that contains some of the blockchain-linked attributes that can be accessed by contract code. Msg.sender always holds the address of the external caller of the current function.

Finally, the function that is used to complete the function of this contract is mint and send, which is actually called by the user or other contract. If someone other than the contract creator calls Mint, nothing will happen. Send can be called by anyone (with a certain amount of tokens), sending some coins to other people. Note that when you send some tokens to an address through the contract, you will not see anything in the Blockchain browser when you query the address. Because the balance changes caused by sending tokens are only stored in the data store of the token contract. Through events we can easily create a "blockchain browser" that can track your SGD transactions and balances.

Blockchain Basics

For programmers, the concept of blockchain is not difficult to understand. Because some of the hardest things to understand (mining, hashing, elliptic curve encryption, point-to-point networking, and so on) are just to provide a range of features and guarantees. You just have to accept these existing features and don't need to be concerned with their underlying technology. Just like you. If you just want to use Amazon's AWS, you don't need to know how it works inside.

Transactions/Transactions

A blockchain is a globally shared, transactional database. This means that every person involved in the network can read the records. If you want to modify something in this database, you must create a transaction and get confirmation from everyone else. The word transaction means that the changes you want to make (if you want to change two values at the same time) can only be implemented completely or not at all.

In addition, when your transaction is applied to the database, other transactions cannot modify the database.

For example, imagine a table that lists the balance of all accounts in an electronic currency. When a transfer request takes place from one account to another, the transaction characteristics of the database ensure that the amount lost from one account is added to the other account. If, for some reason, the amount added to the target account is not available, the amount of the source account will not be changed.

In addition, a transaction is cryptographic signed by the sender (the creator). This is an intuitive measure that adds access protection to specific modifications to the database. In the case of electronic money, a simple check ensures that only the person holding the account key can transfer money out of the account.

Block

One of the major challenges to be solved in blockchain is called "double-flower attack" in Bitcoin. What happens when there are two transactions on the network that spend the money in one account? A conflict?

The simple answer is that you don't need to be concerned about the problem. These transactions are sorted and packaged as "chunks" and then executed and distributed by all participating nodes. If the two deals collide, the sorted trades are rejected and the chunks are removed.

These chunks are sorted by time into a linear sequence. This is also the origin of the word "blockchain". Chunks are added to the chain at a fairly regular interval. For Ethereum, this interval is roughly 17 seconds.

As part of the sequential selection mechanism (often referred to as mining), a chunk of blockchain may be rolled back from time to time. But this happens only at the end of the chain. The more chunks involved in rollbacks, the smaller the probability of their occurrence. So your trades may be rolled back and even removed from the blockchain. But the longer you wait, the less likely it is to happen.

Ethereum Virtual Machine Overview

Ethereum virtual Machine (EVM) is the operating environment of the smart contract in Ethereum. Not only is it encapsulated in a sandbox, it is actually completely isolated, meaning that code running within EVM does not have access to the network, file system, or other processes. Even smart contracts have limited contact with other smart contracts.

Account

There are two types of accounts in Ethereum, which share the same address space. External accounts, which are controlled by the public-private key pair (human). Contract account, which is controlled by the code stored in the account.

The address of the external account is determined by the public key, and the address of the contract account is determined when the contract is created (this address is calculated from the address of the contract creator and the number of transactions issued at that address, and the number of transactions issued by the address is also referred to as "nonce")

The contract account stores the code, and the external account does not, except that the two types of accounts are the same for EVM.

Each account has a key-value form of persistent storage. Where the length of key and value is 256bit, the name is storage.

In addition, each account has an ethereum balance (in "Wei"), which can be changed by sending it a transaction with an Ethernet currency.

Transaction

A transaction is a message that is sent from one account to another (probably the same account or 0 account, see below). Transactions can contain binary data (payload) and etheric currency.

If the target account contains code, the code executes and payload is the input data.

If the target account is a 0 account (the account address is 0), the transaction will create a new contract. As mentioned above, this contract address is not a 0 address, but is calculated by the address of the contract creator and the number of transactions (known as Nonce) issued by the address. The payload that created the contract transaction is executed as an EVM bytecode. The executed output is permanently stored as the contract code. This means that in order to create a contract, you do not need to send a real contract code to the contract, but rather send the code that returns the real code.

Gas

Each transaction on the Ethereum will be charged a certain amount of gas,gas to limit the amount of work required to execute the exchange and to pay for the execution. When EVM executes a trade, gas is gradually consumed by specific rules.

Gas price, the ether currency, is set by the creator of the transaction, and the transaction fee required to send the account is paid in advance = gas prices * Gas amount. If there is gas remaining at the end of execution, the gas will be returned to the sending account.

No matter where it is executed, once gas is exhausted (such as a negative value), a Out-of-gas exception is triggered. All state modifications made by the current call frame will be rolled back.

Storage, main memory and stacks

Each account has a piece of persistent memory area called storage. The length of the form Key-value,key and value is 256 bits. In the contract, the storage of the account cannot be traversed. Compared to the other two, the stored read operation is relatively expensive and modifies storage more. A contract can only read and write to its own storage.

The second memory area is called main storage. Each time the contract executes a message, there is a new, erased main memory. Main memory can be addressed in byte granularity, but the read-write granularity is 32 bytes (256 bits). The overhead of manipulating main memory becomes larger as it grows (the square level).

EVM is not a register-based, but a stack-based virtual machine. So all calculations are performed in a region called a stack. The stack has a maximum of 1024 elements, 256 bits per element. Access to the stack is limited to its top, by allowing one of the top 16 elements to be copied to the top of the stack, or the top element of the swap stack and one of the 16 elements below. All other operations can only take the top two (or one, or more, depending on the specific action) element and press the result on top of the stack. Of course, the elements on the stack can be placed in storage or main memory. However, it is not possible to access only the element of the specified depth on the stack, and before that, all elements above the specified depth must be removed from the stack.

Instruction Set

EVM's instruction set is deliberately kept to a minimum size to avoid possible error implementations that could lead to consensus issues. All instructions are for 256-bit operation of this basic data type. With the usual arithmetic, bit, logic and comparison operations. can also be achieved conditional and unconditional jump. In addition, the contract can access the relevant properties of the current chunk, such as its number and timestamp.

Message invocation

Contracts can be invoked by means of a message to invoke other contracts or to send an etheric currency to a non-contract account. Message invocation and trading are very similar, they all have a source, a target, data payload, ether currency, gas and return data. In fact each transaction can be thought of as a top-level message call, which in turn produces more message calls.

A contract can determine the distribution of the remaining gas. For example, how much gas is used for internal message invocation, or how much gas is expected to be retained. If an Out-of-gas exception (or other exception) occurs when an internal message is called, the contract is notified and an error code is pressed on the stack. This is only the gas exhaustion of the internal message call. In solidity, in this case, the contract initiating the call triggers a manual exception by default. This exception will print out the call stack.

As I said before, the called contract (the same as the contract that initiates the call) will have a new main memory and be able to access the payload of the call. The call payload is stored in a separate area known as Calldata. After the call execution finishes, the returned data is stored in the caller's pre-allocated chunk of memory.

The number of call tiers is limited to 1024, so for more complex operations, we should use loops instead of recursion.

Code calls and libraries

There is a special type of message call, called Callcode. It is almost exactly the same as a message invocation, except that the code that loads the destination address will run in the contract context in which the call originated.

This means that a contract can dynamically load code from another address at run time. Store, both the current address and the balance point to the contract that originated the call, and only the code is fetched from the called address.

This allows the solidity to implement "libraries". Reusable library code can be applied to the storage of a contract and can be used to implement complex data structures.

Log

At the block level, data can be stored in a special, indexable structure. This feature is called a log, and solidity uses it to implement events. The log data cannot be accessed after the contract is created, but the data can be accessed efficiently from outside the blockchain. Because part of the log data is stored in the Bron filter (Bloom filter), we can search the log efficiently and securely, so those network nodes (light clients) that do not download the entire blockchain can also find these logs.

Create

Contracts can even create other contracts with a special directive (not a simple call to a 0 address). The call to create a contract differs from a normal message invocation in that the result of the execution of the payload data is treated as code, and the caller/creator gets the address of the new contract on the stack.

Self-destruct

The contract code is removed from the blockchain only if the contract on an address is performing a self-destruct operation. The remaining etheric currency on the contract address is sent to the specified target, and then its storage and code is removed.

Note that even if the code for a contract does not contain self-destruct instructions, you can still perform this operation through code calls (Callcode).

Solidity writing smart Contracts (Getting started)

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.