Blockchain "smart contracts" from basic to entry - mastering this article is enough! ! !

Creation is not easy, if it is helpful to you, your Sanlian is the greatest support and encouragement to the author (Xiao K).
Reprint: Please note the original link! ! !

1. Development environment:

(1)Remix

——It may be necessary to climb over the wall, which is relatively slow, but it is convenient to use directly

(2)WeBASE-Front

——The code is bright and beautiful, easy to use, but you need to build your own environment

2. Overview of Solidity

insert image description here

  • Smart Contract: A set of computer protocols designed to inform, verify or enforce contracts
  • Ethereum Virtual Machine: A lightweight virtual machine for running smart contracts on the network. The EVM is built to simulate operations that can be performed by a physical CPU, and is also responsible for many of Ethereum's key functions
  • Solidity: Ethereum launches programming language for writing smart contracts

Three, the basic type

(1)Int

  • Use intx and uintx to declare, where x is a multiple of 8 between 8-256, indicating how many bits there are. Such as int8, uint32.
  • Comparison: <=, <, ==, !=, >=, >
  • Bitwise operations: &, |, ^, ~, <<, >>
  • Numerical operations: addition, subtraction, multiplication and division, % remainder, ** exponent.0 to the power of 0 is equal to 1
  • type(x).min and type(x).max give the upper and lower bounds for the type
  • overflow will be truncated

(2)address

Can be a contract address or an account address

  • address and address payable: Store 160-bit long information, which is an address.
  • address payable can be more than addressTransfer money to this addressfunction
  • .balance gives the amount of the address
  • .transfer() and .send() for an address payable on behalf of transferring money to it
address payable x = address(0x123);
address myAddress = address(this);
if(x.balance < 10 && myAddress.balance >= 10){
    
    
	x.transfer(10);// or x.send(10)

Declare a transfer-acceptable address x
with address 0x123 Get the address of the current contract myAddress
Determine whether the account balance of x is less than 10 and the address of the current contract is greater than or equal to 10
x.transfer(10) represents the transfer of the current contract to x

(3)Bool

  • declare with bool x
  • operator! , &&, ||, ==, ! =
  • The && operation and the || operation areshort circuit operation

(4) Array

  • Fixed-length array: bytes1, bytes3, … bytes32 means an array that stores 1, 2, … 32 bytes
  • bytes32 x: can be accessed with subscripts
  • with bit operations
  • Regular arrays are similar to C++: int a[10]
  • You can also declare a moving-length array:int a[]. The moving array hasa.lengthreturns the length,a.push(x)Add a new element x at the end and return the new length

(5)Char and String

  • Use char to declare character variables
  • string is equivalent to an array of char, but the current version does not support the use of .length and subscript access, it needs to be converted to bytes to access the content in the form of bytes
string s;
bytes(s).length
bytes(s)[7] = 'x'

(6)Mapping

  • Use mapping(_keytype => _valuetype), which is basically a hash table
	mapping(address => uint) public balance;
	function update(uint newBalance) public {
    
    
		balances[msg.sender] = newBalance;
	}

The value uint that declares a uint mapped from the address of a balance is
not specified. The default is uint256 to
declare a function (described in detail later)
On the whole, a smart contract is not a finished program that needs to be called by others to achieve real actions
msg.sender is the caller's address (will be introduced in detail later)
balance[address] = uint256 (specific problems, specific analysis)

(7)Struct

struct Voter{
    
    //投票者
	uint weight;//权重
	bool voted;//是否投过票
	address delegate;//地址
	uint vote;//票数
	}

4. Predefined variables

(1)block

Information about the block

  • block.blockhash(uint blockNumber) retruns(bytes32) specifies the block hash of the block, not recommended, it is recommended to use blockhash(uint blockNumber) instead
  • block.coinbase(address): The address of the miner that mined the current block
  • block.difficulty(uint): current block difficulty
  • block.gaslimit(uint): current block gas limit
  • block.number(uint): current block number
  • block.timestamp(uint): timestamp of the current block in seconds since uinx epoch

(2)msg

  • msg.data(bytes): complete calldata
  • msg.gas(uint): remaining gas, not recommended, it is recommended to use gasleft() instead
  • msg.sender(address): The sender of the message currently called
  • msg.sig(bytes4): the first 4 bytes of calldata (that is, the function identifier)
  • msg.value(uint): the amount of wei sent with the message

5. Event

  • Used to trigger log records in EVM, use the following statement to declare and use
event X(<parameter types>) //定义
emit X(<parameter>) //使用
event Send(address sender, address receive, uint amount); //事件

function sent() public payable{
    
    
	//....
	emit Send(msg.sender, msg.receive,msg.value);//触发事件
	}

Calling the send function will trigger the Send event and
return an event: who transferred how much to whom

6. Control structure

  • Most of the structures in C++/js are available, including if, else, while, do, for, break, continue, return, ? :
  • no goto
  • In soldity, other types are not automatically converted to bool, so if(1){} is illegal

7. Units

(1)EtherUnits

  • wei,szabo,finney,ether
  • 1 ether = 1000 finney = 106 szabo = 1018 wei

(2) TimeUnits

  • A value followed by seconds, minutes, hours, days, weeks is a time unit, the default is seconds (1 == 1seconds)

How to convert a variable to a unit, similar to x * ether

8. Contracts

  • Contract Contract is the basic part of a code, similar to class
  • A Contract will containState variables, functions, function decorators and events
  • Contract also hasInheritance and Polymorphism

(1) State variable

  • Information stored in the contract, such as total amount, individual balance, etc.
contract C1{
    
    
	uint data; //State Variable
	}

data is a state variable

(2) Function

function (<parameter types>) [internal | external | public] [pure | view | payable] [returns (<return types>)]
{
    
    }
  • view: a function can be declared as view if it does not change state (including send ether)
  • pure: a function can be declared pure if it is a view and does not read data from the state
  • If a function does not return anything, it is equivalent to the void function in C++ without writing returns.
  • reutrn can return a tuple, enclosed in parentheses
  • internal | external | public is not optional and must be written
  • pure | view | payable is optional and can be omitted
  • returns is optional and can be omitted

(3)Payable

  • Indicates that a currency can be sent when calling
  • msg.sender is the issuing address, msg.value is the quantity
function deposit() payable returns(address addr,uint amount,bool success){
    
    
	return(msg.sender,msg.value,this.send(msg.value));
	}

No visibility is declared, the default is public to return the
sender's address, how many tokens have been sent, and whether the sending is successful .

(4)visibility

  • Functions have four types of visibility: external, public, internal, private
  • external means that it can only be called from the outside, if you want to call from the inside, you must use this.f
  • public means both inside and outside
  • internal can be called by itself or derived classes
  • private can only be called by itself
  • The visibility of the variable cannot be external

internal , private is only for external contracts, and the
visibility of related data can still be viewed outside the blockchain. The default is public.

(5) Constructor

A contract has at most one constructor, which is executed once during construction

Contract A{
    
    
	bytes32 name;
	constructor(bytes32 _name)public{
    
    
		name = _name;
		}
	}

(6)Receive Ether

  • A contract has at most one Receive ether function, declared with the following statement.
  • receive() external payable{…}
  • no function keyword
  • Executed when ether is received (.send() and .transfer())
//This contract keeps all Ether sent to it with no way 
//to get it back
contract Sink{
    
    
	event Received(address, uint);
	receive() external payable{
    
    
		emit Received(msg.sender, msg.value);
	}
}

contract Source{
    
    
	function sending(uint amount) internal payable {
    
    
		address payable x = address(Sink);
		x.transfer(10); // will call receive
	}
}

(7)fallback

  • A contract has at most one fallback function. The fallback function is the default function. When a function that does not exist in the contract is called, the fallback will be executed.
  • Use the following statement to declare, also without the function keyword
  • fallback() external [payable]

(8)require

  • predefined function
  • require(bool condition)
  • require(bool condition,string message)
  • Changes (including transfers) will be reversed if the conditions are not met

Require that a certain condition must be
met. If it is not met, it will not be executed, and all operations will be rolled back (undo)

(9) function modifier function modifier

contract owned{
    
    
	address owner;
	mapping(address => bool) registeredAddresses;
	uint price;
	
	constructor()public {
    
    
		owner = msg.sender;
	}
	
	modifier onlyOwner{
    
    
		require(msg.sender == owner);
		_;//如果满足上述条件,函数将会在这里接着执行
	}
	
	modifier costs(uint price) {
    
    //modifier可以接受参数
		if(msg.value >= price){
    
    
			_;//满足条件,函数将会在这里接着执行
		}
	}
	
	function register() public payable costs(price){
    
    
		registeredAddressed[msg.sender] =true;
	}
	
	function changePrice(uint _price) public onlyOwner{
    
    
		price = _price;
	}
	
}
			

At _ in modifier, the modified function will be executed here

(10) Inheritance

  • Use is to implement contract inheritance
  • Inherited child contracts will inherit all non-private things of the parent contract, including modifiers
  • Contract A{…}
  • Contract B is A {…}
  • If you want to override a function, you must add the virtual keyword when the overridden function is declared, and add override after the overridden function
  • If you want to be overridden here, also add the virtual keyword
  • The function defaults to calling the function defined by the most derived class
  • If you want to call the function of the parent class, use super.f()
  • When the function overrides, it must maintain the same visibility, or change from external to public
  • Another parameter can only become more strict, that is, non-payable (that is, no parameters) can be overridden as view, and view can become pure. payable is special and must remain payable
contract Base{
    
    
	function foo() virtual external view{
    
    }
}

contract Middle is Base{
    
    }

contract Inherited is Middle{
    
    
	function foo() virtual override public pure{
    
    }
}

external -> public
view -> pure
conforms to the function modification after override

(11)Abstract Contracts

  • Abstract contracts areUnimplemented Contract. Can be used as parent class
  • What function is used to use, the broader parent class
abstract contract A{
    
    
	function num() public pure virtual returns(uint);
}

contract B is A{
    
    
	function num() public pure override returns(uint){
    
    
		return 0;
	}
}

(12)Interface

  • Similar to Abstract Contract, but a little stricter
  • cannot implement any function
  • Constructor cannot be defined
  • cannot define any variables
  • cannot be inherited (can be inherited)

Guess you like

Origin blog.csdn.net/weixin_43402353/article/details/118447078