当前位置:网站首页>Solidity from introduction to practice (V)
Solidity from introduction to practice (V)
2022-06-22 08:53:00 【Rookie counter attack】
Solidity From introduction to practice ( 5、 ... and )
Be careful : This column mainly refers to https://www.bilibili.com/video/BV1St411a7Pk?p=11&spm_id_from=pageDriver Study notes and https://blog.csdn.net/weixin_45067603/article/details/105751748
Constructors
- Automatically call once when the contract is deployed , And can only be called once
- There are two ways to use it :
① new ( recommend ):constructor( parameter list ) {}
② old type :function Contract name ( parameter list ) {}
If you pass in parameters , You also need to input parameters during deployment- effect : Can be used to declare , Assignment variable ( It is often used to get the address of the contract caller ) wait
- Multiple contracts can be written in one program
// Use here 0.4.16 Version will have compilation errors , An error occurred because the constructor does not match the compiler version , So I'm going to use 0.5.0
pragma solidity ^0.5.0;
contract gouzao2Test{
address public owner;
uint public a;
constructor() public{
//a=100;
owner = msg.sender;// Get the address of the contract caller
}
}
contract gouzaoTest{
uint public a; // A contract can only have zero or one constructor
// The constructor is executed as soon as the contract is deployed
//function gouzaoTest(){
// a=100;
//}
// Constructors can have parameters
// function gouzaoTest(uint _a,uint _b) {
// a=_a;
// }
}

modifier function
- Application scenarios : Make a judgment , Assignment and so on
- The main role : Make code reusable
Case study 1
pragma solidity ^0.5.0;
contract modifierTest{
address public owner;
uint public num =0;
constructor()public {
// Address of the contract deployer
owner = msg.sender;
}
// Definition modifer
modifier OnlyOwner{
// Determine whether the current login address is the deployer of the contract , If so , Execute the following statement , otherwise , Roll back
require(msg.sender == owner);
_;
}
// additional modifer, Execute first require(msg.sender == owner), After judging success , Will execute num = _num;
function changeIt(uint _num)public OnlyOwner {
num = _num;
}
}
When require(msg.sender == owner) When judging success

When require(msg.sender == owner) When judgment fails
Case study 2
Reform the previous registered case , Because there is a problem that an account can be registered multiple times
pragma solidity ^0.4.16;
contract mappingTest{
// Definition mapping idmapping Representative address ==》id Mapped together ,namemapping representative id==> Names are mapped together
mapping(address => uint) idmapping;
mapping(uint => string) namemapping;
// Define the total number of registrations
uint public sum =0;
// Definition modifer
modifier control{
// If at present idmapping[msg.sender]==0, Indicates that the user is a new user , Allow the following operations
require(idmapping[msg.sender]==0);
_;
}
// Register function
function register(string name) control{
// Get the caller address of the current contract
address account = msg.sender;
sum++;
// Match the address of the caller of the contract with the total registered amount id Connect
idmapping[account]= sum;
// Will the current user's id Bound to the user's name
namemapping[sum] =name;
}
// Get the bound to the user through the address id value
function getIdByAddress(address are) view public returns(uint){
return idmapping[are];
}
// adopt id Value to get the name it is bound to
function gerNameById(uint id) view public returns(string){
return namemapping[id];
}
}
New users register for the first time
New users register again
Case study 3
modifer There can be parameters
pragma solidity ^0.4.16;
contract mappingTest2{
uint public level =9;
string public name;
uint public DNA;
// Definition modifier, There can be parameters , It improves the reusability and extensibility of the code
modifier contrlLevel(uint needLevel){
require(level >= needLevel);
_;
}
function changeName() contrlLevel(2){
name =" Wu Yanzu ";
}
function changeDNA() contrlLevel(10){
DNA = 999;
}
}

Case study 4
Multiple modifier Execution order of
pragma solidity ^0.4.16;
contract mulmodifierTest{
uint public a =0;
modifier mod1{
a=1;
_; // take mod2 Embedded in
a=2;
}
modifier mod2{
a=3;
_;
a=4;
}
// Execution order :a=1,a=3,a=100,a=4,a=2;
function test() mod1 mod2{
a=100;
}
}

Inherit
Inheritance without permission
pragma solidity ^0.4.16;
contract grandfarther{
uint public gudong =2000;
function zhongdi() public returns(string){
return "zhongdi";
}
}
contract father is grandfarther{
uint public money =10000;
function dahan() public returns(string){
return "dahan";
}
}
//son Inherited father,father Inherited grandfarther,son You can inherit all their properties and functions
contract son is father{
function getMoney() public view returns(uint){
return money;
}
function getGudong()public view returns(uint){
return gudong;
}
function test01() public view returns(string){
return zhongdi();
}
function test02() public view returns(string){
return dahan();
}
}

Inheritance with permission
pragma solidity ^0.4.16;
contract father {
//1. uint money=10000; Without any modifiers , Can be inherited
//2. uint public money=10000; add public, Can be inherited
//3. uint internal money=10000; add internal, Can be inherited
//4. uint external money=10000; Compiler error , No, external Property modifier
uint private money =10000;// Compiler error , Only the father has the right to change , uninheritable
function dahan() public returns(string){
return "dahan";
}
}
contract son is father{
function getMoney() public view returns(uint){
return money;
}
}
Function inheritance
pragma solidity ^0.4.16;
contract father {
//public、internal、external Functions can be inherited ,external Function inheritance is different , This is shown in the following code
//private Smart contracts are used independently , Cannot be inherited
function dahan() public pure returns(string){
return "dahan";
}
}
contract son is father{
function test() public pure returns(string){
return dahan();
}
}
pragma solidity ^0.4.16;
contract father {
function dahan() external pure returns(string){
return "dahan";
}
}
contract son is father{
function test() public pure returns(string){
//external Function inheritance
this.dahan();
}
}
Be careful :
- internal Can only be called inside the contract , Not outside the contract ;
- external Can only be called outside the contract , Not inside the contract ;
The so-called external and internal , With remix give an example , Internally, this function can be called inside the contract , Externally, the function button can be seen on the side after the contract is deployed .
As shown in the figure below ,farther Only... Is displayed externally test1(), But you can call dahan() This function .

As shown in the figure below ,external Calling in the contract as shown in the following figure will cause errors
pragma solidity ^0.4.16;
contract father {
function dahan() external pure returns(string){
return "dahan";
}
//external Decorated functions cannot be called internally
// function test1() public view {
// dahan();
// }
}
contract son is father{
//external Decorated functions cannot be called inside inherited contracts
function test() public view returns(string){
return dahan();
}
}

external Can be invoked outside the contract

that , How to achieve contract internal call external The effect of the function ? There are two ways , In essence, it is called indirectly through external contracts
- Use this. Function name call
- Declare another contract , Create or reference the contract within the new contract
// To achieve the effect the teacher said , choice 0.4.0 edition , Compiler selection 0.4.23 edition
pragma solidity ^0.4.0;
contract father {
function dahan() external pure returns(string){
return "dahan";
}
// Indirectly call... Within the contract , Input this.
function test1() public view {
this.dahan();
}
}
contract son is father{
function test() public view returns(string){
this.dahan();
}
}

// To achieve the effect the teacher said , choice 0.4.0 edition , Compiler selection 0.4.23 edition
pragma solidity ^0.4.0;
contract father {
function dahan() external pure returns(string){
return "dahan";
}
function test1() public view returns(string) {
return this.dahan();
}
}
// contract son is father{
// function test() public view returns(string){
// this.dahan();
// }
// }
// The second way to call , The address where the contract is created or referenced within another contract “ Address .” To call
contract externalTest {
father f =new father();
function externalTestIt() public view returns(string){
return f.dahan();
}
}

Function summary
- private Cannot be inherited 、 Cannot call... Externally 、 Can be called internally ;
- internal Can be called internally , Cannot call... Externally 、 Can be inherited ;
- external Cannot call... Internally , Can only be called externally , If forced to call , adopt " Address ." Way to call ;
- public Maximum authority , Can be called externally and internally , Can be inherited ;
- pure Will not read global variables , And it won't modify global variables , A fixed input will have a fixed output , Don't consume gas;
- constant In the function , And view identical , In global variables , Used only for byte1–byte32,uint,int,string Representative data cannot be modified ;
- view Read only the values of global variables , Do not modify the value , Don't consume gas;
- payable The keywords that must be added when transferring money
- Functions can have multiple return values
getter Use
Case study 1
pragma solidity ^0.4.0;
//1.public Modifiers generate by default get Method , For our external calls
contract getter{
uint public num =100;
//2. It is equivalent to this function , When we write this function , The default function will disappear
//3. Default generated get The function is external The powers of the , Cannot be invoked inside a contract
function num() external view returns(uint){
return num;
}
function test(){
this.num();
}
}

Case study 2
pragma solidity ^0.4.0;
contract getter{
uint public num =100;
mapping(uint =>string) public map;
//mapping The type is very special , The following function will be generated by default ,
//function map(uint key)external returns(string){
//}
function test(){
this.num();
}
function test2(){
map[2] =" Wu Yanzu ";
}
function test3()returns(string){
return this.map(2);
}
}

Case study 3
pragma solidity ^0.4.0;
contract getter{
mapping(uint =>mapping(uint =>mapping(uint =>string))) public map;
function test(){
map[0][1][2]= " Wu Yanzu ";
}
}

Override of inherited functions
pragma solidity ^0.4.0;
contract father{
uint public money =10000;
function dahan() returns(string){
return " Snore ";
}
}
contract son is father {
// Override the father's value
uint public money =200000;
function getMoney()returns(uint){
return money;
}
function dahan()returns(string){
return " Snore loudly ";
}
function test() view returns(string){
// The way to cover the father
return dahan();
}
}

multiple inheritance
pragma solidity ^0.4.0;
contract father{
uint public money =10000;
function test() returns(string){
return "A";
}
}
contract mother{
uint public heignt =180;
function test()returns(string){
return "B";
}
}
contract son is father,mother {
// according to father,monther Inherit in the order of
uint public money =200000;
uint public heignt =190; // Override property values
function test() returns(string){
// Rewriting methods
return "son";
}
function getHeight() returns(uint){
return heignt;
}
}

Contract destruction
pragma solidity ^0.4.0;
contract destruct{
address owner;
uint public money =0;
constructor(){
owner = msg.sender;
}
function increment(){
money +=10;
}
function kill(){
if(msg.sender == owner){
// If it is the caller of the current contract , Carry out the destruction contract
selfdestruct(owner);
}
}
}

边栏推荐
- My first go program
- Flask blog practice - user management
- Golang 开发 常用的第三方库 没有最全只有更全
- CF1267G Game Relics
- Spark yard memory resource calculation and analysis (Reference) -- optimized configuration of executor cores, nums and memory
- Win10 add group policy command
- Eureka的InstanceInfoReplicator类(服务注册辅助工具)
- Some mathematical operation functions in LabVIEW
- Web Knowledge 1 (server +servlet)
- Navicat for MySQL连接MySQL数据库时各种错误解决
猜你喜欢

报告:在技术领域,男性更有可能获得工作面试的机会

07 适配器模式

Yolov5 export GPU inference model export

Hashtable source code analysis, collections Synchronizedmap parsing

Third party services (file and picture storage)

10.file/io stream -bite

Fastcorrect: speech recognition fast error correction model RTC dev Meetup

面试突击59:一个表中可以有多个自增列吗?

Deep learning - (1) RESNET implementation
![[path planning] auxiliary points and multi segment Bessel smoothing RRT](/img/0c/74055c93a11b9be18dfec1058796c2.jpg)
[path planning] auxiliary points and multi segment Bessel smoothing RRT
随机推荐
一文彻底搞懂My SQL索引知识点
Nouvelle éclosion de Coronavirus
Introduction to MySQL database Basics
The dream of "getting rich overnight" is broken. Beware of virtual currency investment scams!!!
Hashtable source code analysis, collections Synchronizedmap parsing
07 适配器模式
19 备忘录模式
luogu P4557 [JSOI2018]战争
Win11 mongodb installation tutorial
What is defi and what mode is defi?
A simple - timed task component (quartz) -demo
Flask blog practice - create background management application
Detailed sorting of Oracle and MySQL pages
14 职责链模式
Top ten of the year! Saining network security was once again shortlisted in the top 100 report on China's digital security
Flask blog practice - display the navigation menu and home page data of the whole site
Do not use primitive types in new code during the use of generic types
Installation and use of Jupiter notebook
[conda]conda switch to source of China University of science and technology
20 状态模式


