2、 Learning foundation smart contract

Time:2020-10-27

Lesson 1 Introduction

1. What is a smart contract?

Smart contract is not a common contract in reality, but a piece of program code that exists on the blockchain and can be triggered to execute. These codes implement certain predetermined rules and are “autonomous agents” existing in the execution environment of blockchain. If the smart contract is triggered, the code will execute. If it is not triggered, its state will always remain in a state, and the deployed smart contract will not be modified. The syntax of smart contract language is very similar to JS scripting language, so partners who have JS development experience will learn it quickly.

2. Introduction of programming tools.

We all know the truth that “to do well in advance, we must first sharpen the tools”. In reality, weaving requires a loom to complete weaving. Similarly, our smart contract learning also requires the use of programming tools. We will use Remix as the programming tool to explain the course. Remix is the loom in our hands. It depends on us programmers who use Remix.
The address is( http://remix.ethereum.org/ )Can be developed directly in the browser, very convenient, as long as there is a Google Chrome Google browser can be developed.

Remix has several main commonly used panels, which are file panel, compiler, runner, and the most important part of the text editor.

File panel: we can create files, select files and manage files in this panel.
Compiler: we can compile the sol file. If the compilation fails, the contract will not be executed, and we can get the code.json as well as abi.json 。 We can run them on a public chain that supports sol.
Runner: the sol smart contract can be deployed on the ETH chain, and the contract method can be called.
Text editor: our code is written in this location. You will face this page most of the time.

3. My first smart contract app

The following smart contract is our first contract program, so we named it“ FirstContract.sol ”File name

pragma solidity ^0.6.0;

// first contract
contract FirstContract {
    // first method
    function firstMethod() public pure returns (string memory) {
        return 'I am first method !!!';
    }
}

Many of the above code partners should not understand what the meaning, do not understand it does not matter, I will give you a line by line explanation.
pragma solidity ^0.6.0;
This line indicates that it is written in solidity version 0.6.0 and can run on versions between 0.6.0 and 0.7.0.
contract FirstContract {
This sentence defines a contract called firstcontract.
function firstMethod() public pure returns (string memory){
This line defines a method called firstmethod, which has a return value of type string.

    return 'I am first method !!!';

The line is that this method will return “I am first method!”.

It seems that there may still be some partners who don’t understand, but we only teach so much about what is string. String is the meaning of string. String can be regarded as any ABCDE, and the punctuation marks are written in single quotation marks or double quotation marks. This is the most easy to understand string interpretation, friends, you can try to customize some strings to let him return.

Smart contract structure

In solidness, contracts are a bit like classes in object-oriented languages. Each contract contains statements of state variables, functions, function variables, function modifiers, events, structures, and enumeration classes. Contracts can also inherit other contracts. You may not know much about the concept of class and structure in class. I will give you a simple example. A class can be compared to a car. The oil in the car is a variable, and then the throttle, brake, etc. are functions. When we step on the accelerator, we call the functions in the class. When the car moves, the oil decreases, which means that the variable value changes.

Let’s write a car contract according to the above description. First use Remix to create a carcontract1. Sol file, and then set a contract named carcontract1. If you have a car, you need to have a fuel tank and set a variable_ Gasoline, as a fuel tank. Then we add a throttle to the car and write a startup function as the throttle. Now that you have a tank, but you don’t know how much oil there is, add the gatgasoline function as a dashboard. We only have the fuel tank, and the car can’t run without oil. We are adding a refueling interface to refuel the car. We use the addgasoline function to refuel. Here is our complete car code.

CarContract1.sol

pragma solidity ^0.6.0;

contract CarContract1 {
    uint256 _gasoline;
    
    function startUp() public {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline = _gasoline + gasoline;
    }
    
}

1. State variable

In the car contract_ Gasoline is the state variable defined by us, and its type is uint256. The variable is stored in the chain, that is, its data is saved and every change is recorded. Therefore, when we call the addgasoline function, we will refuel the car successfully_ The value of gasoline will change. Similarly, when we call the startup function_ The gasoline value also changes.

2. Function

In carcontract1 car, startup(), getgasoline(), addgasoline (uint256 gasoline) are all functions. Some of these functions have no parameters, which are also called nonparametric functions, such as startup(), getgasoline(). Some functions with parameters are called parametric functions, such as addgasoline (uint256 gasoline). Some of these functions have return values and some have no return values. Depending on the specific scenarios, call operations generally have return values, and call operations will not change the contract status. Only the send operation will change the status of the contract.

3. Function variable
We all know that adding different types of gasoline will have different effects. Let’s change different types of gasoline to the car, and we put a bucket on the car named_ Bucket, used to hold another model of gasoline. If one of our two containers is empty, we can switch to gasoline directly. But when we have oil in both containers, it is obvious that the two containers can not exchange gasoline. At this time, we need to borrow a bucket from Lao Li next door__ In this way, the three containers can be converted. The gasoline in the tank is replaced with the gasoline in the barrel. After the change, the barrel is returned.

We are building a new car named carcontract2. Add a bucket and set the variable to_ Bucket, as a bucket. It is also necessary to record the oil type of the current car. Setting variables_ Gasolinetype is the current oil type, and the default is type 1. Set a function changegasolinetype to exchange gasoline type. Set a function to view the current car type getgasolinetype. So far, our car has been upgraded successfully.

CarContract2.sol

pragma solidity ^0.6.0;

contract CarContract2 {
    uint256 _gasoline;
    uint256 _bucket;
    int _gasolineType = 1;
    
    function startUp() public {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline += gasoline;
    }
    
    function changeGasolineType() public {
        require(_gasoline != 0 || _bucket != 0, "can not change");
        
        if (_gasoline == 0) {
            _gasoline = _bucket;
            _bucket = 0;
        } else if (_bucket == 0) {
            _bucket = _gasoline;
            _gasoline = 0;
        } else {
            uint256 __tempBucket = _gasoline;
            _gasoline = _bucket;
            _bucket = __tempBucket;
        }
        
        _gasolineType = -1 * _gasolineType;
    }
    
    function getGasolineType() public view returns(int gasolineType) {
        return _gasolineType;
    }
    
}

The above car generation 2 is officially released. Let me tell you about the upgrades we have made. First of all, we have defined the change gasolinetype internally__ Tempbucket variable, which is a function variable, is temporarily created and will not be recorded in the chain. That is, we will return it to Lao Li next door when we use it up, and the bucket is empty when we return it.

4. Function modifier

Our car is still very simple. We are adding something to it, which stipulates that the door must be closed if the car wants to start.

Let’s modify our car again and add one_ The doorstatus variable is used as our door status. Add the functions getdoorstatus(), changedoorstatus(), which are used to control the door opening / closing and view the door status. And add a when doorclose() as our judge.

pragma solidity ^0.6.0;

contract CarContract3 {
    uint256 _gasoline;
    uint256 _bucket;
    int _gasolineType = 1;
    
    bool _doorStatus;
    
    modifier whenDoorClose() {
        require(!_doorStatus, "door is not close");
        _;
        
    }
    
    function startUp() public whenDoorClose {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline += gasoline;
    }
    
    function changeGasoline() public {
        require(_gasoline != 0 || _bucket != 0, "can not change");
        
        if (_gasoline == 0) {
            _gasoline = _bucket;
            _bucket = 0;
        } else if (_bucket == 0) {
            _bucket = _gasoline;
            _gasoline = 0;
        } else {
            uint256 __tempBucket = _gasoline;
            _gasoline = _bucket;
            _bucket = __tempBucket;
        }
        
        _gasolineType = -1 * _gasolineType;
    }
    
    function getGasolineType() public view returns(int gasolineType) {
        return _gasolineType;
    }
    
    
    function getDoorStatus() public view returns(bool doorStatus) {
        return _doorStatus;
    }
    
    function changeDoorStatus() public {
        _doorStatus = ! _doorStatus;
    }
}

The above three generations of cars have been completed. When doorclose() is defined by our function modifier using modifier.

5. Events

Every time we go to refuel when there is no fuel, we add a function. When the fuel level is less than 5, we need to give an early warning.

We add a gasolinealarm event, which has a parameter, the current oil quantity. In this way, we add the call of this event to the start function to judge whether the oil volume after this use is less than or equal to 5. If yes, call the event

pragma solidity ^0.6.0;

contract CarContract4 {
    uint256 _gasoline;
    uint256 _bucket;
    int _gasolineType = 1;
    
    bool _doorStatus;
    
    modifier whenDoorClose() {
        require(!_doorStatus, "door is not close");
        _;
        
    }
    
    event gasolineAlarm(uint256 gasoline);
    
    function startUp() public whenDoorClose {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
        if (_gasoline <= 5) {
            emit gasolineAlarm(_gasoline);
        }
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline += gasoline;
    }
    
    function changeGasoline() public {
        require(_gasoline != 0 || _bucket != 0, "can not change");
        
        if (_gasoline == 0) {
            _gasoline = _bucket;
            _bucket = 0;
        } else if (_bucket == 0) {
            _bucket = _gasoline;
            _gasoline = 0;
        } else {
            uint256 __tempBucket = _gasoline;
            _gasoline = _bucket;
            _bucket = __tempBucket;
        }
        
        _gasolineType = -1 * _gasolineType;
    }
    
    function getGasolineType() public view returns(int gasolineType) {
        return _gasolineType;
    }
    
    function getDoorStatus() public view returns(bool doorStatus) {
        return _doorStatus;
    }
    
    function changeDoorStatus() public {
        _doorStatus = ! _doorStatus;
    }
}

We have updated to the fourth generation car. The gasoline alarm of the fourth generation car is the event defined by us. An event will be recorded on the virtual machine. We can get the event content by querying the log.

6. Structure

Our car feels mature. At this time, we should give our car some features, such as color, such as the number of wheels, such as the number of doors and so on.

We add carinfo structure to the car, which can define color color, wheelnum wheel number, etc., and then we add the set and get functions: setcarinfo(), getcarinfo(), so that our car has some parameters.

pragma solidity ^0.6.0;

contract CarContract5 {
    uint256 _gasoline;
    uint256 _bucket;
    int _gasolineType = 1;
    bool _doorStatus;
    
    struct CarInfo {
        string color;
        uint8 wheelNum;
    }
    
    CarInfo _carInfo;
    
    modifier whenDoorClose() {
        require(!_doorStatus, "door is not close");
        _;
        
    }
    
    event gasolineAlarm(uint256 gasoline);
    
    function startUp() public whenDoorClose {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
        if (_gasoline <= 5) {
            emit gasolineAlarm(_gasoline);
        }
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline += gasoline;
    }
    
    function changeGasoline() public {
        require(_gasoline != 0 || _bucket != 0, "can not change");
        
        if (_gasoline == 0) {
            _gasoline = _bucket;
            _bucket = 0;
        } else if (_bucket == 0) {
            _bucket = _gasoline;
            _gasoline = 0;
        } else {
            uint256 __tempBucket = _gasoline;
            _gasoline = _bucket;
            _bucket = __tempBucket;
        }
        
        _gasolineType = -1 * _gasolineType;
    }
    
    function getGasolineType() public view returns(int gasolineType) {
        return _gasolineType;
    }
    
    
    function getDoorStatus() public view returns(bool doorStatus) {
        return _doorStatus;
    }
    
    function changeDoorStatus() public {
        _doorStatus = ! _doorStatus;
    }
    
    function setCarInfo(string memory color, uint8 wheelNum) public {
        _carInfo.color = color;
        _carInfo.wheelNum = wheelNum;
        
        //_carInfo = CarInfo(color, wheelNum);

    }
    
    function getCarInfo() public view returns(string memory color, int wheelNum) {
        color = _carInfo.color;
        wheelNum = _carInfo.wheelNum;
    }
}

Carinfo is added to our 5th generation car, which is the structure. The initial value cannot be set in the structure. We can classify a class of attributes into the structure, which can serve as our data model.

7. Enumeration class

To open the door of our car, we need to open the lock. The lock is a state, on / off.

We add the enumeration class doorswitch to define two states, open and close. Define when doorswitch function modifier and make judgment.

pragma solidity ^0.6.0;

contract CarContract6 {
    uint256 _gasoline;
    uint256 _bucket;
    int _gasolineType = 1;
    bool _doorStatus;
    
    enum DoorSwitch{ open, close }
    
    DoorSwitch _doorSwitch;
    
    struct CarInfo {
        string color;
        uint8 wheelNum;
    }
    
    CarInfo _carInfo;
    
    modifier whenDoorClose() {
        require(!_doorStatus, "door is not close");
        _;
        
    }
    
    modifier whenDoorSwitch() {
        if (!_doorStatus) {
            require(_doorSwitch == DoorSwitch.open, "door switch is close");
        }
        _;
    }
    
    event gasolineAlarm(uint256 gasoline);
    
    function startUp() public whenDoorClose {
        require(_gasoline >= 1, "gasoline is not haved");
        _gasoline = _gasoline - 1;
        if (_gasoline <= 5) {
            emit gasolineAlarm(_gasoline);
        }
    }
    
    function getGasoline() public view returns(uint256 gasoline) {
        return _gasoline;
    }
    
    function addGasoline(uint256 gasoline) public {
        _gasoline += gasoline;
    }
    
    function changeGasoline() public {
        require(_gasoline != 0 || _bucket != 0, "can not change");
        
        if (_gasoline == 0) {
            _gasoline = _bucket;
            _bucket = 0;
        } else if (_bucket == 0) {
            _bucket = _gasoline;
            _gasoline = 0;
        } else {
            uint256 __tempBucket = _gasoline;
            _gasoline = _bucket;
            _bucket = __tempBucket;
        }
        
        _gasolineType = -1 * _gasolineType;
    }
    
    function getGasolineType() public view returns(int gasolineType) {
        return _gasolineType;
    }
    
    
    function getDoorStatus() public view returns(bool doorStatus) {
        return _doorStatus;
    }
    
    function changeDoorStatus() public {
        _doorStatus = ! _doorStatus;
    }
    
    function setCarInfo(string memory color, uint8 wheelNum) public {
        _carInfo.color = color;
        _carInfo.wheelNum = wheelNum;
        
        //_carInfo = CarInfo(color, wheelNum);
    }
    
    function getCarInfo() public view returns(string memory color, int wheelNum) {
        color = _carInfo.color;
        wheelNum = _carInfo.wheelNum;
    }
    
    function setDoorSwitch(DoorSwitch doorSwitch) public {
        _doorSwitch = doorSwitch; 
    }
}

We have updated to the 6th generation of cars. In the 6th generation of cars, we have added the door switch of doorswitch, which is defined by enumeration. In the actual project, the enumeration definition is generally used in the definition of state and type, which is convenient for management.

By now, our car has been completed and has been updated for 6 generations. I believe you will have a better understanding of this course. The state variables, functions, function variables, function modifiers, events, structures and enumeration classes contained in smart contracts have been used in car building and upgrading.

Lesson 3 data types

In solidity, there are special data types. What is the data type? We can think that the number is the type, whether it is the type, the address is the type, etc. In solidness, there are the following common types: uint / int, bool, address, mapping, bytes, string, fixed / ufixed.

pragma solidity ^0.6.0;


contract Test {
    uint v1 = 1;
    int v2 = -2;
    bool v3 = true;
    address v4 = 0x8a5fa31F2bf83812ECd8E5Ef1878dD12bBaDb40C;
    mapping(uint => uint) v5;
    bytes v6 = "0x123"; 
    string v7 = "asd";
    fixed v8 = 1.3;
    ufixed v9 = 1.2;
}

1. Uint / int type

Uint / int types are all integers, that is, they are integers. 1. 2, 3 and 4 have no decimal point. The difference is that uint has no sign. Look at the code V1 is an unsigned integer, V2 is a signed integer. The default is 0

2、bool

Bool is a boolean type in Chinese, indicating yes / No. V3 is a bool type. There are only two values of true / false. The default value is false

3、address

Address is the address type, storage address, account address, contract address, etc.

4、mapping

The code in the mapping type example is not very complete. Let me explain it. In fact, it is a key value model, that is, a key corresponds to a value. For example, if we say Xiaoming, we are going to Xiaoming. That’s why.

5、bytes

Fixed length array, that is to say, its length is fixed and can not be changed. It is set as many as possible.

6、string

String type, can put string, length is 255 bit binary number.

7、fixed/ufixed

Floating point type, i.e. values with decimal point, such as 1.2, 1.4 and 1.9. It is also divided into signed items.

Lesson 4 control sentences

In solidness, we can use the following control structures: if, else, while, for, break, continue, return,?: let’s introduce these structures.

1. If else statement

You must be curious about what an if else statement is. He is what we say if not. That is to say, if I am what I am, I am not. Note that else can only be used with if. Let’s take a look at the following code:

pragma solidity ^0.6.0;


contract Test {
    uint256 temp;
    
    function test1(bool doorSwitch) public {
        if (doorSwitch) {
            temp = 1;
        }
    }
    
    function test2(bool doorSwitch) public {
        if (doorSwitch) {
            temp = 1;
        }
        temp = 2;
    }
    
    function test3(bool doorSwitch) public {
        if (doorSwitch) {
            temp = 1;
        } else {
            temp = 2;
        }
    }
    
    function getTemp() public view returns(uint256){
        return temp;
    }
}

In the above code, we define three test methods and a method to get the temp value. The first test method indicates that if the doorswitch we pass in is true and the door is open, then temp is equal to 1. Otherwise, if doorswitch is equal to false, the value of temp will not change. The second test method indicates that if the doorswitch we pass in is true and the door is open, then temp is equal to 1 first and then to 2. Otherwise, if doorswitch is equal to false, then temp is directly equal to 2. The third test method indicates that if the doorswitch passed in is true and the door is open, then temp is equal to 1; otherwise, if doorswitch is equal to false, then temp is equal to 2.

2. While statement

The while statement is a loop statement, which means that the loop will continue when the conditions are met. Generally, we will use it with break. When a certain situation is reached, the loop body can automatically end the loop.

pragma solidity ^0.6.0;


contract Test {
    function test1() public {
        int a = 1;
        while(true) {
            if (a == 5) {
                break;
            }
            a++;
        }
    }
    
    function test2() public {
        int a = 1;
        while(a != 5) {
            
            a++;
        }
    }
}

There is a loop inside the two functions above. In fact, the effect of the two loops is the same. There are some subtle differences, which need to be analyzed according to the specific business scenarios. It is not recommended to use while. If you are not careful, the loop will not be fun.

3. For loop

For loop concept directly on the code, you can understand some.

pragma solidity ^0.6.0;


contract Test {
    function test1() public {
        for(uint8 i = 0; i < 10; i ++) {
            ...
        }
    }
}

The above is a common way to use the for loop, which circulates the content of “…” 10 times.

4. Continue statement

The continue statement is to skip this loop and enter the next loop. See the code:

pragma solidity ^0.6.0;


contract Test {
    function test1() public {
        for(uint8 i = 0; i < 10; i ++) {
            if (i == 3) {
                continue;
            }
            
            ...
        }
    }
}

If I = 3 after this loop.

5. Return statement

Return is the command to return. When return is encountered, it means the end. Look at the code:

pragma solidity ^0.6.0;


contract Test {
    function test1() public {
        for(uint8 i = 0; i < 10; i ++) {
            if (i == 3) {
                return;
            }
            
            ...
        }
    }
}

The above code shows that when I = 3, the program ends directly.

6. End

This is the end of our basic study of control statements. These concepts are similar in every language, so they are important. Practice more partners!

end

After learning the above course, we have basically studied the smart contract, but we still lack the use of it. We just know what we have and when to use it. At this time, we need to exercise and write more small things.

Recommended Today

What black technology does the real-time big data platform use behind the glory of the king?

Hello everyone, I’m Xu Zhenwen. Today’s topic is “Tencent game big data service application practice based on Flink + servicemesh”, which is mainly divided into the following four parts: Introduction to background and Solution Framework Real time big data computing onedata Data interface service onefun Microservice & servicemesh 1、 Introduction to the solution framework and […]