Write your first smart contract in Remix

A smart contract is simply:A contract or a set of instructions deployed on a decentralized blockchain. When this contract or this set of instructions is deployed, it It cannot be changed and will be executed automatically. Everyone can see the terms in the contract. A deeper understanding is that these codes will be executed in a decentralized manner, just like a group of people running a certain software, which means that no one person or subject can modify these contracts or change them. terms.

1. Smart contract industry applications

DeFi: stands for decentralized finance, which allows users to participate in the financial market without going through a centralized intermediary.
For example, Robinhood, you no longer need to trust Robinhood to continue to provide you with services and allow you to access the market. On the contrary, you can directly check the smart contract, yes, so you can enter the market. Or during the 2008 financial crisis, you no longer have to trust that these groups and institutions will provide you with correct information in the background. You can see everything on the blockchain and they are all transparent. You can participate in many things, such as currency markets and complex financial products, simply, safely and efficiently. As of 2022, there will be approximately US$200 billion in assets under management in DeFi, and it is still growing rapidly.
Dao: Decentralized Autonomous Organization, is another application. Dao is a completely decentralized organization. They are managed by a set of instructions or a smart contract on the blockchain. This management method is very advantageous. Participation is simpler, the rules are clear and black, and you can directly log in on the chain. See all things. Voting and governance use completely decentralized technology, and blockchain is one of the important technologies that allows us to promote the advancement of governance technology. It makes governance more efficient, fair and reasonable.
NFT: Non-fungible token, which is to some extent an electronic artwork or a unique asset. Projects like Bored Ape and Cryptopunk have revolutionized the way people get paid by working, showing creativity and status

2.Remix introduction

Remix is ​​a powerful tool because it has many functions to help us view and interact with smart contracts. Although we will gradually leave Remix and use a local development environment, Remix is ​​very helpful for learning the basics of smart contracts.< /span> When you enter the Remix page, you will find that there are many things and many Plugins, because we have to use Solidity, which is the language of smart contracts. . Remix official website

Insert image description here

3.Solidity data type

Solidity has multiple basic data types. The four most basic data types are boolean, uint, int and address. There are also arrays, structures, and mappings, or bytes, which are lower-level data types.
boolean defines true and false;
uint is an unsigned integer, which means that this number cannot be positive or negative, but can only be a positive number; uint is special, we can Determine the space allocated to it. This number can be as large as uint256, and uint defaults to uint256. In general, it is a good practice to write out the allocated space explicitly.
int can represent a positive or negative number; similarly, we can also decide the space allocated to the int variable.
address represents the address, just like the address seen in MetaMask.
The specific variable type codes defined in Remix are as follows:

// SPDX-License-Identifier: MIT
// 定义solidity的版本 此处允许0.8.8以上的版本,但不允许0.9.0以上的版本
pragma solidity ^0.8.8 <0.9.0;

contract SimpleStorage{
    bool hasFavoriteNumber = false;
    //uint允许分配的空间只能以byte的速度增长 uint8 uint16...uint256 最大只能到uint256
    uint256 favoriteNumber = 123;
    int64 favoriteInt = -5;
    string favoriteNumberInText = "five";//string类型变量只允许存储文本
    address myAddress = 0x993CC624c1350D52cCbe32F77652362F82fc4D41;
}

4.Solidity function

Function or method refers to an independent module, which will execute certain instructions when we call it. Defining functions in Solidity is similar to that in JavaScript, just use the function keyword.
Function variables have four visibility identifiers:
public: Visible both externally and internally, anyone interacting with the contract Everyone can see variables and functions modified by public. Adding the public modifier to a variable or function actually creates a getter function for it and creates a function that returns its value.
private: private means that only this contract can call this function, private means that it is only visible inside the contract;
external The specific solidity code for function implementation is as follows: respectively. If a function is modified by view, it means that we will only read The status of this contract. The function modified by view is not allowed to modify any state, and you cannot modify any state in its function. Similarly, the pure function is not allowed to modify the state, and the pure function is not allowed to read blockchain data. Pure functions are typically used to perform mathematical operations or other calculations that do not involve changes to state. are view and pure In addition, there are two keywords in solidity that can be used Modified function, the call of the identifying function does not need to consume gas, The default value of the modifier of a general variable or function is internal, which means it is only visible to this contract and inherited contracts: internal means that only this contract or contracts that inherit it can be read
internal: external means that it is only visible outside the contract


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8 <0.9.0;

contract SimpleStorage{
    //uint允许分配的空间只能以byte的速度增长 uint8 uint16...uint256 最大只能到uint256
    uint256 public favoriteNumber = 123;//设置公开可见
    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }

    function getFavoriteNumber() public view returns(uint256){
        return favoriteNumber;
    }
    function testPure() pure public returns(uint){
        return (1+1);
    }
}

5.Mapping mapping

Using mapping is more efficient than array traversal to find elements, and can reach O(1) level, while array traversal is O(n) level;
You can simply think of mapping as A dictionary is a set of key-value pairs. Each key returns a certain value associated with the key. The way we create a mapping variable is exactly the same as the way we create all other variables; the details are as follows:

mapping(string => uint256) public nameToFavoriteNumber

The specific definition of mapping and the operation of adding elements are as follows:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8 <0.9.0;

contract SimpleStorage{
    //uint允许分配的空间只能以byte的速度增长 uint8 uint16...uint256 最大只能到uint256
    uint256 public favoriteNumber = 123;//设置公开可见
    struct People{
        string name;
        uint256 favoriteNumber;
    }//定义结构体
    //定义映射
    mapping(string => uint256) public nameToFavoriteNumber;
    People[] public people;//定义结构体数组(存储多个结构体的数组)

    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }
    //这里被view修饰的函数调用不消耗gas 表示只读函数 不修改或改变区块链已有的状态
    function getFavoriteNumber() public view returns(uint256){
        return favoriteNumber;
    }
    //定义添加数组元素的函数
    function addPerson(string memory _name,uint _favoriteNumber) public{
        //这里由于string底层数bytes数组,因为需要使用memory关键字
        people.push(People(_name,_favoriteNumber));
        nameToFavoriteNumber[_name] = _favoriteNumber;
    }
}

It should be noted here that the code contains the definition and implementation of arrays and structures. Since it is similar to Java and C++, readers can understand it by analogy, so it is not elaborated in detail.

6.EVM introduction

All the contract codes we wrote through solidity were compiled on EVM (Ethereum Virtual Machine).
EVM (Ethereum Virtual Machine) is a standard for deploying smart contracts on the Ethereum blockchain, and you can deploy solidity code on any blockchain that implements some kind of EVM. For example, Avalanche, Fantom, and Polygon are all compatible with EVM, which means that we can deploy the solidity code we write to these blockchains.
Review the entire smart contract:
The first thing you have to do in the smart contract is to tell solidity which version of solidity you are using, and you have to Add // SPDX-License-Identifier: MIT in the first line, to eliminate the warning message, and then you need to use the keyword contract to create your contract object And name it, the contract in solidity is similar to the class class in other object-oriented languages, and everything within the curly braces {} is a component of the contract.
There are many different data types in solidity, such as unsigned integer uint, boolean, string, and bytes (bytes32) and so on. If you want to create a new type, you can create a so-called struct. You can also create an array or a list. You can also create a dictionary or mapping. When you When you give it a key, it returns the value corresponding to that key. We can also create functions in solidity to modify the status of the blockchain.The function is modified with view and pure to indicate that it is a function that does not modify the status of the blockchain, we can also specify different data locations in the function. The meaning of calldata and memory is that the data is only temporary data. They only exist during the running of the function. The storage variable exists permanently, and the function parameters are temporary variables. Therefore, storage variables cannot be used. When we write the solidity code and compile it at the Remix point, it will compile the code according to the format of the Ethereum Virtual Machine.
After writing the smart contract code, you can directly use the shortcut key Ctrl+S to compile in Remix. After successful compilation, a small green icon will appear in the sidebar, and then click the fourth one on the side icon to enter the deployment interface, first select the virtual account, because we are deploying to the virtual machine that comes with Remix, then set the gas limit limit, and then click the deploy button. After the deployment is successful, you can see that a contract account is automatically generated. At this point, you have completed your first smart contract.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_51447436/article/details/133677407