Blockchain Development (Part 2) Deploy and run the first Ethereum smart contract

Blockchain Development (Part 2) Deploy and run the first Ethereum smart contract

Blockchain Development (Part 2) Deploy and run the first Ethereum smart contract

There are many articles on the Internet about deploying smart contracts, but they all have one thing in common, which is that they are deployed using the command line. First, the SOLC compilation environment is established, then the Geth or Eth node is deployed, and then the wallet, ABI, and contract address are generated step by step for deployment. This is difficult for beginners to understand and prone to failure. This article mainly introduces how to deploy and call smart contracts with one click in a graphical interface.

1. Overview of Smart Contracts and DAPP

1. Basic concepts of smart contracts

A smart contract is a collection of code and data that can be deployed and run on the Ethereum network. If we use an analogy, a smart contract is more like a JAVA program. A JAVA program interprets the code into bytes for execution through the JAVA virtual machine (JVM). Ethereum's smart contracts are interpreted into bytecodes for execution through the Ethereum virtual machine (EVM). If you have learned assembly, you will find that the compiled bytecodes are very similar to assembly. At the same time, smart contracts have their own accounts and can automatically execute some functions driven by time or events, such as transmitting information between each other and modifying the status of the blockchain, such as account information. The biggest feature of Ethereum's smart contracts is Turing completeness. In layman's terms, it can completely simulate everything a computer can do. The well-known Bitcoin can actually execute some simple scripts, but it is not Turing complete. For example, Bitcoin cannot execute loop instructions.

Ethereum Virtual Machine (EVM)

The Ethereum Virtual Machine (EVM) is the runtime environment for smart contracts in Ethereum. It is not only encapsulated in a sandbox, but in fact it is completely isolated, which means that the code running inside the EVM cannot access the network, file system or other processes, and even there are only limited calls between smart contracts.

2. Basic Concepts of DAPP

Beginners often confuse smart contracts with DAPPs. The Ethereum community calls applications based on smart contracts decentralized apps. The goal of DApps is to give your smart contracts a friendly interface, plus some extra things that are beneficial to users. A typical DApp example consists of an HTML interface, a web3 runtime, a piece of JS code, and a smart contract deployed on the blockchain. Unlike general CS-architecture websites, DApps cannot run on ordinary servers. DApps must run on a server that can interact with Ethereum nodes, or on any Ethereum node. DApps interact with the corresponding smart contracts by submitting transactions to the blockchain network, and read important data from the blockchain network instead of centralized databases such as (MYSQL databases). Unlike the typical BS-architecture user login system, Ethereum users are represented as a hexadecimal address and all user data and other data are stored locally, which is very different from the current web application architecture.

3. Smart contract high-level language

It is impossible for users to write Ethereum Virtual Machine (EVM) bytecode directly, so Ethereum provides several high-level languages ​​for writing smart contracts.

Solidity: Similar to JavaScript, this is the flagship language recommended by Ethereum and the most popular smart contract language. For specific usage, please refer to the Solidity documentation at: https://solidity.readthedocs.io/en/latest/

Serpent: Similar to Python style, document address: https://github.com/ethereum/wiki/wiki/Serpent

LLL: Lisp-like style, currently discontinued.

You can choose different high-level languages ​​according to different habits. The most popular one is Solidity.

2. Deploy the first smart contract on the Ethereum private chain

The smart contract in this article uses the official Ethereum sample contract, which is used to store a number on the blockchain and be able to read it out. The code is as follows:

contract SimpleStorage {

uint storedData;

function set(uint x) {

storedData = x;

}

function get() constant returns (uintretVal) {

return storedData;

}

}

Even if you have not learned Solidity language, you can roughly see that the contract set function stores a number in the X variable, and the get function reads the number from the X variable. The following is the deployment of this contract:

1. Start a private chain

Start the Ethereum private chain Geth and Ethereum-Wallet graphical interface (this article uses Geth 1.41 version, Ethereum-Wallet 0.8.1 version). If you don’t know how to start, please refer to my previous article "Blockchain Development (I) Building a Private Chain Environment Based on Ethereum". After starting, the interface is as follows, and Ethereum-Wallet will display a red PRIVATE-NET mark.

  2. Create two wallets

Click the "ADD ACCOUNT" button to add a wallet. The program will pop up a dialog box and prompt you to enter your password twice. After entering the password, the account is successfully created. Create other accounts with the same operation. From the screenshot above, you can see that there are three accounts, one is MAIN ACCOUNT, one is ACCOUNT2, and one is ACCOUNT3.

3. Mining to get some ether

After the account is created, there is no Ethereum yet, so you need to mine on the private chain. Switch to the Geth interface and enter

miner.start(1)

The 1 in the brackets of the miner command means using one thread for mining. If it is not configured, the CPU will run at full speed, affecting the use of the computer.

After running for a while, the main account will obtain a lot of Ethereum. At this time, the screen will refresh quickly. Don't worry about it. Enter the command miner.stop() to stop mining.

4. Transferring Ethereum from one wallet to another

First click on the ACCOUNT2 account to enter the account details interface, click "COPY address" on the right, and copy the address of ACCOUNT2. The system will prompt you that you are now in a test network and do not transfer real Ethereum to this account.

Click the "SEND" button in the wallet to transfer a certain amount of ether from MAINACCOUNT to ACCOUNT2. At the same time, you can see that the fee for executing this transaction is 0.00042 ether.

 

     

After clicking Send, you will be prompted to enter the password, but it has not been sent successfully yet. According to the transaction rules of the blockchain, it needs the confirmation of the miners, and each transaction needs to confirm 12 blocks, and one block takes 16 seconds to generate. Switch to the Geth program and enter the mining command until 100 ethers are displayed on ACCOUNT2, then stop mining.

5. Deploy smart contracts

Click "CONTRACTS" to enter the smart contract management interface, click "DEPOLY NEW CONTRACT" to start deploying the smart contract, select the account to deploy the smart contract, and enter the smart contract code, as shown below

After entering the information, click “DEPLOY”. The system will prompt you to enter your account and password, because deploying smart contracts requires fees.

          

At this time, you cannot see the deployed smart contract. Switch to the Geth interface and start mining. After 12 blocks, the smart contract will be confirmed and displayed.

3. Running Smart Contracts

1. Run smart contracts on this node

Click "CONTRACTS" to enter the smart contract interface, you can see the smart contract "SimpleStorage" just deployed, click to enter the smart contract, enter the details interface, which has the smart contract write area and read area, first start Geth mining, then select the corresponding smart contract function SET in the write area, enter the value you want to set in the value input box below, after running for a while, you can see the return value of Retval in the smart contract function GET in the read area has changed.

The operation of other smart contracts is the same, except that there are more functions and more inputs.

 

2. Run smart contracts on other nodes

At this point, the smart contract can only be seen by yourself, and others cannot see or run it. If others want to run the smart contract you deployed, they need to provide some information, which is the ABI and address of the smart contract mentioned in other tutorials.

Enter the "SimpleStorage" smart contract interface that has just been deployed. There are four buttons on the right.

A. "Deposit Eher": Send Ether to the smart contract

B. “Copy address”: copy the address of the smart contract

C. “Show QR Code”: Display a QR code. If you scan it with a mobile phone, it will show the address of the smart contract.

D. “Show Interface”: Display the JSON interface of the smart contract, that is, the ABI

First, we click "Copy address" to copy the address of the smart contract, then click "Show Interface" to copy all the JSON interfaces of the smart contract, open Ethereum-Wallet on another node that needs to run the smart contract, open the "CONTRACTS" interface and click "WATCH CONTRACTS" to add a smart contract.

As shown in the figure above, fill in CONTRACT NAME at random, fill in the smart contract address in CONTRACT ADDRESS, and fill in the content just copied in "Show Interface" in JSON INTERFACE. After clicking OK, you can see this smart contract and run it.

4. Deployment Principles of Smart Contracts

1. Smart Contract Deployment Architecture

Although the deployment of the smart contract introduced in this article is compiled and executed in the graphical interface, it actually mainly relies on the node running Geth in the background. At this time, Geth provides an RPC interface to provide blockchain information to the wallet in the graphical interface.

RPC Interface

Geth provides a JSON RPC API on port 8545. Data transmission uses the JSON format and can execute various commands of the Web3 library, such as providing blockchain information to the front end, such as mist and other graphical clients. The default access address is http://localhost:8545.

When we deploy a smart contract, Ethereum-Wallet first calls the SOLC smart contract compiler to compile the code into EVM bytecode, and then sends the EVM bytecode to the Ethereum network through Geth's RPC interface. After verification by the entire network, it is written to each blockchain managed by Geth at the same time. The architecture is as follows

         

2. Deployment data flow

First, the code is compiled into binary code by SOLC, and then a smart contract is created through a transaction. The transaction contains several key information such as the creator's account, smart contract content, and smart contract address. The smart contract address is generated by the creator's account and the number of transactions sent as random number inputs, and a new address is created as the account through the Kecca-256 encryption algorithm.

 

During the deployment process, transactions are required for deployment, and data needs to be stored on the blockchain, which requires the use of GAS.

  Transactions

A transaction is a message sent from one account to another. Transactions can contain binary data (payload) and ether.

If the target account contains code, the code and input data will be executed.

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

Gas

Each transaction on Ethereum will be charged a certain amount of gas. The purpose of gas is to limit the amount of work required to execute the transaction and to pay for the execution. When the EVM executes a smart contract, gas will be gradually consumed according to specific rules. In fact, GAS is a relatively small unit of Ethereum. If Ethereum is compared to 100 yuan, then GAS can be regarded as 1 cent. If there is only Ethereum, there will be problems. Ethereum needs to be bought and sold by everyone, and the market will have price fluctuations. There may be a situation like Bitcoin, which falls 50% and rises 50% in one day. This is unacceptable for the cost of calculation. For example, it costs ten yuan to do an addition today, and one hundred yuan to do an addition tomorrow. So gas is introduced here to decouple. Decouple the market fluctuations and the cost of calculation, that is, there is an exchange rate between Ethereum and gas. It doesn’t matter if Ethereum rises, as long as the gas price drops. It must ensure that I do the same calculation and the legal currency consumed is consistent.

The gas price (in ether) is set by the creator of the transaction. The sending account needs to prepay the transaction fee = gas price * gas amount. If there is gas left after the execution, the gas will be returned to the sending account.

As mentioned in the previous article, deploying the smart contract used 0.00042 ether, which is equivalent to 21,000 gas.

No matter where the execution is, once the gas is exhausted (for example, it drops to a negative value), an out-of-gas exception will be triggered. All state modifications made by the current call frame will be rolled back.

5. How Smart Contracts Work

Smart contracts are codes deployed on the blockchain. The blockchain itself cannot execute codes. Code execution is in the local EVM. In fact, the code deployed on the blockchain is the code that can generate the original smart contract code locally. The blockchain can be understood as a database, and the client reads the stored running code from the database, runs it locally, and writes the result to the blockchain database.

In essence, Ethereum wallet is also an application of smart contract. Ethereum is a platform for writing various applications. In the next article, we will describe in detail how to develop, write and debug smart contracts.


<<:  Ripple Labs CTO changes attitude towards blockchain technology

>>:  Counting the top 5 countries with the strictest Bitcoin regulations

Recommend

What are the facial features of people who always blindly follow the crowd?

Everyone wants different results, so it is destin...

Facial features that are destined to be rich and powerful

China is a country with a profound and extensive ...

What does it mean when the marriage line forks upwards?

The marriage line is one of the important lines b...

What is the fortune of boys with beautiful eyebrows?

If some people have beautiful eyebrows and eyes, ...

What are the characteristics of a woman who is loved by everyone?

If a woman is the kind that everyone loves, then ...

Analysis of the palmistry characteristics of good women

What are the characteristics of a good woman'...

India's gold import ban proposal drives up Bitcoin trading searches

Rage Commentary : In order to combat the black ma...

What kind of face is willful when you have money?

There is a saying that I believe everyone has hea...

Analysis of the facial features of outstanding women

Analysis of the facial features of outstanding wo...

Teach you how to tell your fortune from your face

Face reading is closely related to our fortune. W...