This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August

Solidity is a high-level language for smart contracts that runs on top of the Ethereum Virtual Machine (EVM). Solidity is ethereum’s preferred language. It has all the features of Serpent built in. Its syntax is close to Javascript and it is an object-oriented language, which lowers the barrier to learning and is easy to master and use as Javascript is a common language for Web developers. Solidity therefore takes full advantage of the fact that millions of programmers already know JavaScript.

Ethereum smart contract programming language, simple syntax, but immature imperfect, buggy, no multithreading

Matters needing attention

Compiler selection

The Remix IDE compiler is not friendly to Chinese. Make a joke!

Some instructions

  1. acontractInside is a contract, there is no main function, as long as the contract deployment can be run
  2. Be sure to include a header version number:Pragma solidity 0.4.24;
  3. Each line should end with a semicolon(;)The end of the

Note: Chinese must be written on the outside and then copied, not directly in the inside to write Chinese notes! Very unfriendly to Chinese!


1. The variable

1.1 State Variables

Variables defined within the contract but outside the function are called state variables, which are uploaded to the blockchain and are private by default, and can be decorated with public and private

pragma solidity 0.424.; 

contract HelloWorld{
    string public name;   // This is the state variable, using the public modifier
    function hello(string memory text) public pure returns(string memory) {
        returntext; }}Copy the code

1.2 Local variables

Local variables cannot use public within a contract, within a function

pragma solidity 0.424.;

contract Hello{

    function hello(string memory text) public pure returns(string memory) {
        string name = "FanOne";   // This is the local variable
        returntext; }}Copy the code

State variables are private by default and can be decorated with public

2. Data type

2.1 value type

2.1.1 Booleans:

True or false. The default is false

! Logic of logic && and | | = = equal to or logical! = is not equal to

pragma solidity 0.424.;

contract DataType {

    // bool public ok = true;
    bool public ok;  // def is false

    function test() returns(string) {if (ok) {
            return "this is true";
        }else {
            return "this is false"; }}}Copy the code

2.1.2 Integers:

Int /uint: indicates a signed and unsigned integer with different digits

The 8-bit interval includes int8, int16, int24… , int256, int The default is int256, uint the same

int8 num;
int256 total = 120;
Copy the code

Example: the result of adding two numbers

pragma solidity 0.424.;
contract Add {
  int8 i1 = 10;
  int16 i2 = 11;
  function add() returns (int8) {return i1 + int8(i2); // Type strong}}Copy the code

2.1.3 Fixed Point Numbers:

Fixed/uFIXED: fixed bit floating point numbers with and without signs

Not fully supported, it can be used to declare variables, but not to assign values

2.1.4 Fixed-size Byte Arrays

Keywords: bytes1, bytes2, bytes3… , bytes32. Byte indicates bytes1. Bytes1 stores 1 byte, that is, 8 bits, and bytes2 stores 2 bytes, incremented by 1 byte. Length: indicates the length of this byte array (read only), which returns the length of the fixed-length byte array type, not the length of the value. Length cannot be modified

pragma solidity 0.424.;

contract TestBytes {
    bytes1 public b0;  / / byte: 0 x00
    bytes1 public b1 = "f";  // 0x66
    bytes2 public b2 = "fa";  // 0x6661
    bytes6 public b6 = "fanone";  
    bytes32 public b32 = "FanOne";
    function getLen() returns(int256){
        return b32.length;
    }
    function getByIndex() returns(bytes1){
        return b1[0]; }}Copy the code

2.1.5 Rational and Integer Literals (Rational and Integer Literals)

Numeric constants that appear directly in expressions:

Integers, decimals, and scientific counting are supported (9e30:6 *200^10)

2.1.6 enumeration (Enums)

A custom type should have at least one element, the default bit uint8, and don’t forget the curly braces

enum Gender {
 	Male, 
 	FeMale 
 }
Copy the code

// Gender is a custom type. Set the default value

Gender default = Gender.Male 
Copy the code

2.1.7 Function Types

  • State variables: The default is private
  • Function: The default is public

The modifier

View/constant: The function reads but does not modify any of the contract’s state variables. Pure: The function does not apply to the state variable ‘payable’ of any contract: the call to the function requires payment, and the money is paid to the account of the smart contract. Returns: External is used in the function declaration: only external to the contract can be called; internal is called with this: Only internal and inherited contracts can be called

You can have more than one modifier preceding the DECLARATION of RETURNS

The difference between View, Constant, and Pure is for state variables

Call the state variable, but don’t modify it, use view or constant if you don’t use the state variable, use pure if you access the state variable and then modify it, don’t modify it. The compiler does not report an error when modifying a constant state variable, but fails to do so.

payable

To transfer money, the modifier ‘payable’ must be ‘

‘payable’ modifier, the money is transferred into the contract

function setMoney(string str) public payable returns(string) {
    return str;
}
Copy the code

The amount of money in the contract has been reduced. Note the unit of the amount of money in the contract, otherwise you will see no big change in the amount of money in the contract

function getMoney() public view returns(uint256){
     return this.balance;
}
Copy the code

This represents the current contract itself, and balance gets the balance of the current contract

The function definitions

Function Function name (optional) Modifier Return value {function body}

Ex. :

function Add(a int8) public view returns(int8) {return a
}
Copy the code

Function return value

  • Use RETURNS to specify the type to be returned

  • Return value declarations must come last

  • Multiple return values using tuples: parentheses ()

The constructor

Enter the contract on execution, generally set some initialization after invariable data

constractor() public {
    owner = msg.sender;
}
Copy the code

View /constant: the state variable is used, but the state variable is not modified. Pure can only be modified: We don’t use the state variable, we can only decorate the function ‘payable’ : we can only decorate the function ‘payable’, we have to use ‘payable’ for transfers, the money comes in from the account, the money goes to the contract returns: at the end of the function, the value is returned

Do not use the (view\constant\pure) modifier when state variables are modified in functions

2.1.8 Address Type (Address)

Basic knowledge of

Addresses are the basis of all contracts, and all contracts inherit address objects

The function in the contract can be called through the address string of the contract, which is essentially uint160. It can be added or subtracted and requires strong transformation

If the balance of the contract is not enough, you need to handle it manually. There will be no error. Call the contract inside, call the underlying code, do not use callcode: Call underlying code, don’t delegatecall: Call underlying code, don’t call this to the contract itself

Address (this), if you use this, you will get a warningCopy the code

Account –> account: not supported account — contract: paybable contract — account: Transfer contract — contract: transfer contract: 1ether = 10**18wei (10^18

transfer

pragma solidity 0.424.;

contract TransferDemo {
    uint256 public a;
    function constractGetMoney() public payable{
        
    }
    function getConstractBalance() public {
        a = address(this).balance;
    }
    address to_addr = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
    function trans() public {
        to_addr.transfer(5 * 10支那18 );  //define is wei
        //need to transfer eth}}Copy the code

There are many addresses to choose from

Where the money goes: Transfer is invoked with the person to whom the money is transferred

Where the money comes from: the money in the contract (payable), an error will be reported when the money in the contract is not enough to transfer

2.2 Reference Types

2.2.1 string

  1. Index not supported
  2. The length and push methods are not supported
  3. This can be modified using a bytes conversion
string me = "fanone";
Copy the code

Go to bytes, and you can use the bytes feature

bytes(me).length;
Copy the code

Bytes to turn the string

string(bytes)
Copy the code

Arrays of indeterminate bytes: bytes:

  • Length, push (append at the end) methods are supported
  • You can modify
  • Index support, if not allocated space (new allocated space), using subscript will be reported corner index out of bounds, the other will automatically allocate space
  • Assign values in hexadecimal format
bytes me = "fanone"
name.push("666")
Copy the code

2.2.2 array

  • Built-in arrays: String, bytes, bytes1… bytes32

  • User-defined array of fixed length: immutable length, length is supported, push is not supported

uint256[5] public nums = [1.2.3.4.5];
Copy the code
  • User-defined array: variable length, content can be modified, support length, push method
uint256[] public nums = [1.2.3.4.5];
nums.push(6)
delete nums;
Copy the code
  • Function uses new to allocate space
uint8[] memory aa = new uint8[] (10);// 10 lengths of space
Copy the code

2.2.3 Structure:

Functions do not support returning struct objects. Values can be returned in tuples.

structStruct name {type field name; }Copy the code
 struct Person {
    string name;
    uint age;
}

// Specify the field name, which must be enclosed in () and curly braces
Person public p1 = Person({name:"hallen",age:18});
// Initialize the values in sequence, with parentheses () instead of curly braces {}
Person public p2 = Person("hallen".18);
// Struct indeterminate array
Person[] persons;
// The type must be a struct initializer object
persons.push(p1);
Copy the code

2.2.4 Mapping:

You cannot determine whether a key does not support length

mapping(string= >string) map_data;
// Assign a value to the function
map_data["name"] = "hallen";
// Get the value of the specified key
string storage aa = map_data["name"];
Copy the code

2.2.5 storage and memory

Storage: Data is stored forever and references are passed. Only variables of the reference type can display the declaration as storage.

Memory: The value is stored in the memory and will be reclaimed. Data will expire and be lost

Bytes1, bytes, string are converted to each other

Bytes1 to string goes through the middle bytes

Use uint256 type for corner labels, otherwise there will be type mismatch

The last

Xiao Sheng Fan Yi, looking forward to your attention.