A brief introduction to smart contracts

I have studied blockchain courses this semester, and the homework is a report after studying smart contracts:

 

1 Simple understanding of smart contracts

1.1 What is a smart contract

A smart contract is an event-driven, stateful computer program deployed on a shared distributed database, often using IF-THEN statements. In a narrow sense, a smart contract is a program code that designs relevant business logic and algorithms, and codes the complex relationship between people, laws, and networks; in a broad sense, a smart contract is a computer protocol that can realize self-execution and self-verification. At first glance, it looks quite similar to a trigger in a database.

In short, a smart contract is a contract that uses computer language instead of legal language to record terms. Smart contracts can be automatically executed by a computing system, which can be regarded as a digital version of traditional contracts.

If the blockchain is compared to a database, the smart contract is the application layer that enables blockchain technology to be applied to real life. Smart contracts are computer programs that run on a blockchain database and can execute automatically when conditions written in their source code are met. After the smart contract is written, it can be trusted by users, and the terms of the contract cannot be changed, so the contract cannot be changed.

1.2 Technical characteristics of smart contracts

1.2.1 Data transparency

All data on the blockchain is open and transparent, so the data processing of smart contracts is also open and transparent, and any party can view its code and data during runtime.

1.2.2 Immutable

All data in the blockchain itself cannot be tampered with, so the smart contract code deployed on the blockchain and the data output generated by the operation are also tamper-proof. Nodes running smart contracts do not have to worry about other nodes maliciously modifying code and data.

1.2.3 Permanent operation

The number of nodes supporting the blockchain network often reaches hundreds or even thousands, and the failure of some nodes will not lead to the cessation of the smart contract. Its reliability is theoretically close to permanent operation, which ensures that the smart contract can be like a paper contract Works all the time.

 

2 Preliminary learning of Solidity language

2.1  Use of IDE

I used the online IDE during the learning process . The screenshot of the ide on this machine is as follows . The left side is the list of files , and the middle area can quickly create new files .

 

2.2 The  first smart contract helloworld

2.2.1 Create  a project _ _

Create a new file named Helloworld.sol , the source code is as follows , and the functions of related functions are written in the comments :

pragma solidity ^0.4;//版本指令为0.4
contract HelloWorld {//合约创建
function sayHelloWorld() public returns(string){//定义函数,public意味着任何一方 (或其它合约) 都可以调用你合约里的函数。
return ("hello world");
}
}

2.2.2 Compile and run

Compile in the compile tab, you can click compilation Details to understand the specific details of the compilation. There is no error reported here, and a green hook graphic appears to indicate that the compilation is successful.

 After the compilation is successful, we can deploy the contract in the run tab

 Clicking deploy is to deploy this contract, and the function of this contract will appear below, click to run the function of this contract, the log will output the corresponding record, it can be seen that helloworld has returned.

 

 

2.3 The  second smart contract

The contract of a simple bank model has been studied and compiled. The understanding of the model is written in the code in the form of comments. Through this contract, the functions of saving money, withdrawing money, and checking the balance can be realized:

2.3.1 Initialization section

Here, a simple model of a bank is created, a mapping variable is declared to represent the balance, and some values ​​and variables are initialized.

2.3.2 Construction method

  

2.3.3 Ways to save money

2.3.4 Methods of withdrawing money

2.3.5 How to check the balance

2.3.6 Run the contract

Like the helloworld contract, click deploy after the compilation is successful, and there are four methods to choose from.

 

We clicked balance and owner to realize the function of displaying user information and balance respectively. The deposit function can also run successfully, but the withdraw method reports an error because the balance of this account is 0. In the code, we use the require function to restrict . If the withdrawal amount is greater than the account balance, an error will be reported, and the withdrawal cannot be realized, so an error will be reported.

2.3.7 Others

Because currency transactions are implemented here, there will be a prompt to charge a handling fee. Gas is the concept of handling fee in virtual currency. The more gas, the faster the transaction will be.

 

 2.3.8 Source code:

pragma solidity 0.6.6;

contract SimpleBank { //创建一个简单银行模型的合约
    
    mapping (address => uint) private balances;//声明了一个mapping类型的变量balance表示余额,这是一个key-value类型,key是address类型,value是uint类型。
//owner用来表示合约持有者的地址。
    address public owner;//address是一种比较特殊的类型,它有20个字节长度,一般用来表示地址或者账户的公钥信息。需要注意的是,虽然看起来它是一个数字的类型,但是它不支持任何的算术运算操作。

    event LogDepositMade(address accountAddress, uint amount);//事件 是合约和区块链通讯的一种机制。你的前端应用“监听”某些事件,并做出反应,通过emit触发事件的执行。

    constructor() public {//构造方法
        owner = msg.sender;//把owner变量赋值为msg.sender,后者是一个约定的内部变量,表示的是方法的调用者。在这里指合约的创建人。
    }


    function deposit() public payable returns (uint) {//deposit表示存钱的方法。被payable关键字修饰的方法可以在调用的时候接收ETH(以太币)。
                                                      //这个方法的首先检查发送的ETH值要必须大于0,然后更新余额,出发日志事件,最后返回余额。
        require((balances[msg.sender] + msg.value) >= balances[msg.sender]);//require使得函数在执行过程中,当不满足某些条件时抛出错误,并停止执行。这边通过该函数判定存入的钱大于0.

        balances[msg.sender] += msg.value;//余额增加

        emit LogDepositMade(msg.sender, msg.value); // 对应上方的event,触发该监听

        return balances[msg.sender];//更新余额
    }


    function withdraw(uint withdrawAmount) public returns (uint remainingBal) {//表示取钱的方法。
        require(withdrawAmount <= balances[msg.sender]);//判定取出的钱小于账户余额。

        
        balances[msg.sender] -= withdrawAmount;//取钱

        msg.sender.transfer(withdrawAmount);//转账一定数量(以wei为单位)的以太币到指定的地址,该地址为调用该函数的人的地址

        return balances[msg.sender];
    }

    function balance() view public returns (uint) {//返回余额的方法。view表示是一个只读的方法,不消耗gas费。
        return balances[msg.sender];
    }
}

Guess you like

Origin blog.csdn.net/hmysn/article/details/128339946